create-crust 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,39 +16,51 @@ bun create crust@latest my-cli
16
16
  deno run -A npm:create-crust@latest my-cli
17
17
  ```
18
18
 
19
- The initializer collects the destination, any required overwrite decision, runtime, dependency installation choice, and Git initialization choice. Explicit flags skip the corresponding prompts; prompts can also use defaults without rendering non-interactively. The package name is inferred from the directory name.
19
+ The initializer collects the destination, any required overwrite decision, runtime, build output, dependency installation choice, and Git initialization choice. Explicit flags skip the corresponding prompts; prompts can also use defaults without rendering non-interactively. The package name is inferred from the directory name.
20
20
 
21
21
  ## Options
22
22
 
23
23
  ```text
24
- create-crust [directory] [--runtime bun|node|deno] [--install|--no-install] [--git|--no-git] [--overwrite|--no-overwrite]
24
+ create-crust [directory] [--runtime bun|node|deno] [--artifact package|binary] [--install|--no-install] [--git|--no-git] [--overwrite|--no-overwrite]
25
25
  ```
26
26
 
27
27
  - `directory` sets the destination; otherwise the directory prompt defaults to `my-cli`. Its basename (the current directory's for `.`) becomes the package and command name, so it must use only letters, digits, `.`, `_`, `~`, and `-`, not starting with `.` or `-`; anything else is rejected before any file is written.
28
28
  - `--runtime` selects the runtime the project develops and builds for: `bun`, `node`, or `deno`. The default is `bun`.
29
- - `--install` / `--no-install` installs or skips dependencies. The default is to install. Deno projects install with `deno install`; the other runtimes use the detected package manager.
29
+ - `--artifact` selects the build output independently of the runtime: `package` for a JavaScript bundle requiring the user's selected runtime, or `binary` for a standalone executable embedding that runtime. Defaults: `binary` for Bun/Deno, `package` for Node.js. Deno runtime-package bundling is experimental.
30
+ - `--install` / `--no-install` installs or skips dependencies. The default is to install. Deno projects install with `deno install`; the other runtimes use the detected package manager. If installation is skipped, the next steps include the install command.
30
31
  - `--git` / `--no-git` initializes or skips a Git repository when the destination is not already inside one. The default is to initialize.
31
32
  - When the destination requires an overwrite decision, `--overwrite` overwrites conflicting files without confirmation; `--no-overwrite` aborts without prompting. The default is not to overwrite.
32
33
 
33
- Generated projects use the single-file starter (`src/cli.ts`).
34
+ Generated projects use the single-file starter (`src/cli.ts`). The generated README and next steps use the detected package manager for script commands (`bun run`, `npm run`, `pnpm run`, or `yarn run`), independently of the selected runtime. Detection checks the destination's lockfiles first, then the invoking package manager's user-agent, and defaults to npm. Deno projects always use `deno task`.
34
35
 
35
36
  Every generated project includes:
36
37
 
37
38
  - `src/cli.ts` — entry point with a sample command
38
- - `package.json` — configured for the selected runtime, with `$schema` pointing at the `crust` block schema shipped by `@crustjs/crust` for editor completion
39
+ - `package.json` — configured for the selected runtime and artifact, with `$schema` pointing at the `crust` block schema shipped by `@crustjs/crust` for editor completion
39
40
  - `tsconfig.json` — strict TypeScript config
40
41
  - `README.md` — getting started instructions
41
42
  - `.gitignore` — sensible defaults for Node/Bun projects
42
43
 
43
- Every project has the same scripts: `build` (`crust build`) stages the publishable npm package(s) in `.crust/`, `start` runs the built CLI from `.crust/root/bin/<name>.js`, and `release` (`crust publish`) publishes them. The runtime decides how the project runs in development and what `build` puts in `.crust/`:
44
+ Every project has the same scripts: `build` (`crust build`) stages the publishable npm package(s) in `.crust/`, `start` runs the built CLI from `.crust/root/bin/<name>.js`, and `release` (`crust publish`) publishes them. The runtime decides how the project runs in development; the `crust.artifact` setting decides what `build` puts in `.crust/`. All six combinations are selectable; the defaults preserve each runtime's established output:
44
45
 
45
- | Runtime | `dev` | `build` output |
46
- | ------- | ------------------------ | ----------------------------------------------------------------------------------- |
47
- | `bun` | `bun run src/cli.ts` | A root package with a Node launcher plus one standalone binary package per platform |
48
- | `node` | `node src/cli.ts` | A root package containing one JavaScript bundle that needs Node 22.18+ |
49
- | `deno` | `deno run -A src/cli.ts` | A root package with a Node launcher plus one standalone binary package per platform |
46
+ | Runtime | `dev` | `build` output (`crust.artifact`) |
47
+ | ------- | ------------------------ | --------------------------------------------------------------------------------------------- |
48
+ | `bun` | `bun run src/cli.ts` | `binary`: a root package with a Node launcher plus one standalone binary package per platform |
49
+ | `node` | `node src/cli.ts` | `package`: a root package containing one JavaScript bundle that needs Node 22.18+ |
50
+ | `deno` | `deno run -A src/cli.ts` | `binary`: a root package with a Node launcher plus one standalone binary package per platform |
50
51
 
51
- Every runtime puts the Crust packages your code imports (`@crustjs/core`, `@crustjs/extensions`) in `dependencies` and the build tool (`@crustjs/crust`) in `devDependencies`, and sets `"crust": { "runtime": ... }` in `package.json` so `crust build` picks the runtime without flags. See [Build and distribution](https://crustjs.com/docs/guide/build-and-distribution).
52
+ Every runtime puts the Crust packages your code imports (`@crustjs/core`, `@crustjs/extensions`) in `dependencies` and the build tool (`@crustjs/crust`) in `devDependencies`, and writes your selections to `"crust": { "runtime": ..., "artifact": ... }` in `package.json` so `crust build` needs no additional flags.
53
+
54
+ For example, scaffold a Node binary or an experimental Deno runtime package:
55
+
56
+ ```sh
57
+ npx create-crust@latest my-node-cli --runtime node --artifact binary
58
+ npx create-crust@latest my-deno-cli --runtime deno --artifact package
59
+ ```
60
+
61
+ Node binaries need Node 26+ and Bun at build time; Node runtime packages do not need the Node executable compiler. Deno packages need Deno 2.5+ to bundle. The wizard does not install or pin compilers. See [Build and distribution](https://crustjs.com/docs/guide/build-and-distribution) for complete requirements.
62
+
63
+ Artifact choice is separate from distribution channel. `release` publishes to npm, but npm is optional: standalone executables plus adjacent assets can be shipped as downloads or through Homebrew/Scoop without a separate JavaScript runtime. The npm binary launcher requires Node.js. The generated README links to [custom distribution](https://crustjs.com/docs/guide/build-and-distribution#custom-distribution); the wizard does not generate installer definitions.
52
64
 
53
65
  ## Documentation
54
66
 
@@ -1,22 +1,67 @@
1
1
  #!/usr/bin/env node
2
- import{existsSync as En,readdirSync as yi}from"node:fs";import{basename as In,join as vi,resolve as Ue}from"node:path";import{dirname as Wi,join as Ui,posix as Vi,resolve as Yn,win32 as qi}from"node:path";import{existsSync as qe,statSync as Nn}from"node:fs";import{dirname as Ge,isAbsolute as Ni,join as kn,resolve as An}from"node:path";function He(e){let t=An(e);if(qe(t)&&!Nn(t).isDirectory())t=Ge(t);while(!0){if(qe(kn(t,"package.json")))return t;let n=Ge(t);if(n===t)return null;t=n}}import{realpathSync as Tn}from"node:fs";import{dirname as _n,join as se,resolve as Fn}from"node:path";import{fileURLToPath as Pn}from"node:url";var Dn="CRUST_INTERNAL_BUILD_OUT_DIR";function Rn(){let{Bun:e,Deno:t}=globalThis,n=e?.main??"";return n.startsWith("/$bunfs/")||/^[A-Za-z]:[\\/]~BUN[\\/]/.test(n)||t?.build?.standalone===!0}function ie(e){if(e===""||e==="."||e===".."||/[\\/]/.test(e))throw Error(`Artifact name must be a single directory name, got ${JSON.stringify(e)}.`);if(Rn())return se(_n(process.execPath),e);return Fn(Pn(import.meta.url),"..","..",e)}import{AsyncLocalStorage as Mn}from"node:async_hooks";import{Writable as Bn}from"node:stream";var Ln=Symbol.for("crustjs.terminal.io"),zn=Symbol.for("crustjs.terminal.ambient-callbacks"),Wn=globalThis,Un=globalThis,V=Wn[Ln]??=new Mn,Ke=Un[zn]??=new WeakMap;function ae(e,t){let n=V.getStore();return V.run({input:e.input??n?.input,output:e.output??n?.output},t)}function q(){return V.getStore()}function Vn(e){let t="",n=new Bn({decodeStrings:!1,write(r,o,s){t+=r.toString();let i=t.indexOf(`
2
+ import{existsSync as Wn,readdirSync as ia}from"node:fs";import{basename as Vn,dirname as Un,join as aa,resolve as qn}from"node:path";import{dirname as ja,join as ka,posix as Na,resolve as gr,win32 as Aa}from"node:path";import{existsSync as et,statSync as Hn}from"node:fs";import{dirname as tt,isAbsolute as ha,join as Kn,resolve as Yn}from"node:path";function nt(e){let t=Yn(e);if(et(t)&&!Hn(t).isDirectory())t=tt(t);while(!0){if(et(Kn(t,"package.json")))return t;let n=tt(t);if(n===t)return null;t=n}}import{realpathSync as Jn}from"node:fs";import{dirname as Xn,join as de,resolve as Zn}from"node:path";import{fileURLToPath as Qn}from"node:url";var rt="CRUST_INTERNAL_BUILD_OUT_DIR",er="crustjs.packagedBuild",tr=Symbol.for(er);function me(){return globalThis[tr]===!0}function nr(){let{Bun:e,Deno:t}=globalThis,n=e?.main??"";return n.startsWith("/$bunfs/")||/^[A-Za-z]:[\\/]~BUN[\\/]/.test(n)||t?.build?.standalone===!0||process.getBuiltinModule?.("node:sea")?.isSea()===!0}function ge(e){if(e===""||e==="."||e===".."||/[\\/]/.test(e))throw Error(`Artifact name must be a single directory name, got ${JSON.stringify(e)}.`);if(nr())return de(Xn(process.execPath),e);return me(),Zn(Qn(import.meta.url),"..","..",e);let t=process.env[rt];if(t)return de(t,e);let n=process.argv[1],r=n;if(n)try{r=Jn(n)}catch(o){throw Error(`Could not resolve artifact "${e}": could not resolve source entrypoint "${n}".`,{cause:o})}let s=r?nt(r):null;if(!s)throw Error(`Could not resolve artifact "${e}": no package.json was found above ${n?`entrypoint "${n}"`:"process.argv[1] (unset)"}.`);return de(s,".crust","root",e)}import{AsyncLocalStorage as rr}from"node:async_hooks";import{Writable as sr}from"node:stream";var or=Symbol.for("crustjs.terminal.io"),ir=Symbol.for("crustjs.terminal.ambient-callbacks"),ar=globalThis,cr=globalThis,q=ar[or]??=new rr,st=cr[ir]??=new WeakMap;function pe(e,t){let n=q.getStore();return q.run({input:e.input??n?.input,output:e.output??n?.output},t)}function G(){return q.getStore()}function lr(e){let t="",n=new sr({decodeStrings:!1,write(r,s,o){t+=r.toString();let i=t.indexOf(`
3
3
  `);while(i!==-1)e.stderr(t.slice(0,i)),t=t.slice(i+1),i=t.indexOf(`
4
- `);s()}});return Ke.set(n,e),n}function ce(e,t){let n=V.getStore();return ae({input:n?.input,output:n?.output&&!Ke.has(n.output)?n.output:Vn(e)},t)}import{parseArgs as Jn}from"node:util";import{isPromise as Xn}from"node:util/types";function Ye(e){let t=Number(e);return Number.isNaN(t)?void 0:t}function le(e){return e==="true"||e==="1"}import{homedir as Zn}from"node:os";function qn(e){return typeof e==="number"}function Gn(e){return e.map((t,n)=>qn(t)?`[${t}]`:n>0?`.${String(t)}`:String(t)).join("")}function Hn(e){return typeof e==="object"&&e!==null&&"key"in e}function Kn(e){if(!e)return[];return e.map((t)=>Hn(t)?t.key:t)}function Je(e,t=[]){return e.map((n)=>{let r=Kn(n.path),o=[...t,...r];return{message:n.message,path:Gn(o)}})}var h=class extends Error{code;details;cause;constructor(e,t,...n){super(t);this.name="CrustError",this.code=e,this.details=n[0]}is(e){return Object.is(this.code,e)}withCause(e){return this.cause=e,this}toJSON(){return{code:this.code,message:this.message,details:this.details}}};function ue(e,t){if(e==="")throw new h("DEFINITION",`Flag ${t} spellings must be non-empty`,{subject:"flag",name:e,reason:"empty-spelling"});if(t!=="short"&&e.startsWith("no-"))throw new h("DEFINITION",`Flag ${t} "${e}" must not start with "no-"; the prefix is reserved for boolean negation`,{subject:"flag",name:e,reason:"reserved-no-prefix"});if(e==="__proto__")throw new h("DEFINITION",`Flag ${t} "__proto__" is a reserved spelling`,{subject:"flag",name:e,reason:"reserved-spelling"})}function nt(e,t){return[e,...t.short===void 0?[]:[t.short],...t.aliases??[]]}function rt(e){return e.type==="boolean"&&e.noNegate!==!0}function ot(e){if(e.choices&&e.default!==void 0){let t="multiple"in e&&e.multiple?e.default:[e.default];for(let n of t)if(!e.choices.includes(n))throw new h("DEFINITION","default must be one of choices")}return Object.freeze({...e,..."aliases"in e&&e.aliases?{aliases:Object.freeze([...e.aliases])}:{},...e.choices?{choices:Object.freeze([...e.choices])}:{},..."env"in e&&e.env?{env:Object.freeze({name:e.env.name,delimiter:e.env.delimiter})}:{},..."multiple"in e&&e.multiple&&Array.isArray(e.default)?{default:Object.freeze([...e.default])}:{}})}function Qn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&"name"in e&&typeof e.name==="string"&&(!("delimiter"in e)||e.delimiter===void 0||typeof e.delimiter==="string")}function st(e,t){if(ue(e,"canonical"),t.short!==void 0)ue(t.short,"short");for(let r of t.aliases??[])ue(r,"alias");let n=nt(e,t);if(new Set(n).size!==n.length)throw new h("DEFINITION",`Flag "${e}" repeats one of its own spellings`,{subject:"flag",name:e,reason:"flag-collision"});if(t.short!==void 0&&t.short.length!==1)throw new h("DEFINITION","Short flags must be one character");if(t.env!==void 0&&!Qn(t.env))throw new h("DEFINITION",`Flag "${e}" env must be an object with a string name and optional string delimiter`,{subject:"flag",name:e,reason:"invalid-env"});if(t.env?.name==="")throw new h("DEFINITION",`Flag "${e}" env variable name must be non-empty`,{subject:"flag",name:e,reason:"empty-env"});for(let[r,o]of[["delimiter",t.delimiter],["env.delimiter",t.env?.delimiter]]){if(o===void 0)continue;if(!t.multiple)throw new h("DEFINITION",`Flag "${e}" ${r} requires multiple: true`,{subject:"flag",name:e,reason:"delimiter-without-multiple"});if(o==="")throw new h("DEFINITION",`Flag "${e}" ${r} must be non-empty`,{subject:"flag",name:e,reason:"empty-delimiter"})}return ot(t)}function it(e){if(e.name==="")throw new h("DEFINITION","Argument names must be non-empty",{subject:"argument",name:e.name,reason:"empty-name"});return ot(e)}var er=Symbol("crust.defining");function K(e){return e[er]}var at=Symbol.for("crust.contextSources");function Y(e,t){let n=new Set(e.map((s)=>s.name)),r=new Set,o=(s)=>{if(r.has(s))return;r.add(s);let i="contextName"in s?s.contextName:s.name;if(!n.has(i))throw new h("DEFINITION",`No provider for Context "${i}"`,{subject:"context",name:i,reason:"missing-context"});for(let a of s.uses)o(a)};for(let s of t)o(s)}function tr(e){return typeof e==="function"}var nr=class{#e=[];#t=!1;#n(){if(this.#t)throw ReferenceError("AsyncDisposableStack is already disposed")}use(e){this.#n();let t=or(e)?e[Symbol.asyncDispose]:e[Symbol.dispose];return this.#e.push(()=>t.call(e)),e}defer(e){if(this.#n(),!tr(e))throw TypeError("defer callback is not callable");this.#e.push(e)}async[Symbol.asyncDispose](){if(this.#t)return;this.#t=!0;let e=[];for(let t=this.#e.length-1;t>=0;t--)try{await this.#e[t]()}catch(n){e.push(n)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Disposal failed")}},rr=globalThis.AsyncDisposableStack??nr;function or(e){return typeof e[Symbol.asyncDispose]==="function"}function sr(e){if(e===null||typeof e!=="object"&&typeof e!=="function")return!1;let t=e;return typeof t[Symbol.asyncDispose]==="function"||typeof t[Symbol.dispose]==="function"}function ir(e,t,n){if(!sr(e)||n.has(e))return;n.add(e),t.use(e)}function ar(e,t,n,r){let o=new Map(e.map((m)=>[m.name,m])),s=new Map,i=new WeakSet,a,c=!0,l=!1;n.defer(()=>{l=!0});let u=(m,p,v=new Set)=>{if(m.name===p)return[m.name];if(v.has(m.name))return;v.add(m.name);for(let O of m.waitingOn){let S=s.get(O);if(!S)continue;let I=u(S,p,v);if(I)return[m.name,...I]}},f=(m)=>{try{let p=new Set;for(let v=m;v!=null&&!p.has(v);v=v.cause)if(p.add(v),v instanceof h&&v.code==="DEFINITION"&&v.details?.reason==="flags-before-validation")return!0;return!1}catch{return!1}};function d(m){let p=Promise.reject(m);return p.catch(()=>{}),p}let b=(m)=>(p)=>{let v=m?` (pulled while constructing Context "${m.name}")`:"";if(l)return d(new h("DEFINITION",`Context "${p}" cannot be pulled from onError because invocation Contexts have already been disposed.`,{subject:"context",name:p,reason:"context-after-disposal"}));let O=o.get(p);if(!O)return d(new h("DEFINITION",`No provider for Context "${p}". Add .provide(${p}(...)) to the app or an ancestor command.${v}`,{subject:"context",name:p,reason:"missing-context"}));if(!c&&!s.has(p))return d(new h("DEFINITION",`Context "${p}" cannot be constructed during invocation cleanup. Read it while setting up the Context whose cleanup needs it.`,{subject:"context",name:p,reason:"context-during-disposal"}));if(a===void 0&&Object.keys(O.ownedFlags).length>0)return d(new h("DEFINITION",`Context "${p}" owns flags and cannot be pulled before flag validation${v}. Pull it from an action or a postRun hook after a validated invocation.`,{subject:"context",name:p,reason:"flags-before-validation"}));let S=s.get(p);if(!S){let I=Promise.withResolvers();I.promise.catch(()=>{}),S={name:p,promise:I.promise,resolve:I.resolve,reject:I.reject,waitingOn:new Set,settled:!1},s.set(p,S);let x=S;(async()=>{try{let C=Object.fromEntries(Object.keys(O.ownedFlags).map((E)=>[E,a?.[E]])),j=await O.setup({...t,signal:r,flags:C,ctx:g(O.uses,x),defer(E){if(x.settled)throw new h("DEFINITION",`Context "${p}" cannot register cleanup after its setup has finished.`,{subject:"context",name:p,reason:"context-defer-after-setup"});n.defer(E)}});ir(j,n,i),x.resolve(j)}catch(C){if(f(C))s.delete(p);x.reject(C)}finally{x.settled=!0}})()}if(m&&!S.settled){let I=u(S,m.name);if(I)return d(new h("DEFINITION",`Context dependency cycle: ${[m.name,...I].map((x)=>`"${x}"`).join(" -> ")}`,{subject:"context",name:m.name,reason:"context-cycle"}));return m.waitingOn.add(p),S.promise.finally(()=>m.waitingOn.delete(p))}return S.promise},g=(m,p)=>{let v={},O=(S)=>{let I="contextName"in S?S.contextName:S.name;if(Object.hasOwn(v,I))return;Object.defineProperty(v,I,{enumerable:!0,get:()=>b(p)(I)});for(let x of S.uses??[])O(x)};for(let S of m)O(S);return Object.defineProperty(v,at,{value:Object.freeze([...m])}),Object.freeze(v)};return{bag:(m)=>g(m,null),setValidatedFlags(m){a=m},async settle(){for(;;){let m=[...s.values()].filter((p)=>!p.settled);if(m.length===0){c=!1;return}await Promise.allSettled(m.map((p)=>p.promise))}}}}var cr=Object.freeze({[Symbol("crust.finished")]:!0});function me(){return cr}function ct(e){return{meta:{name:e},localFlags:{},ownedFlags:{},effectiveFlags:{},flagSpellings:new Map,args:[],subCommands:{},contexts:[],demands:[],extensions:[],run:void 0}}function A(e,t,n,r){n=st(t,n);let o=nt(t,n),s=Object.hasOwn(e.effectiveFlags,t)?t:o.map((a)=>e.flagSpellings.get(a)?.canonicalName).find((a)=>a!==void 0);if(s!==void 0)throw new h("DEFINITION",`Flag "${t}" collides with existing flag "${s}" on command "${e.meta.name}"`,{subject:"flag",name:t,reason:"flag-collision"});(r==="local"?e.localFlags:e.ownedFlags)[t]=n,e.effectiveFlags[t]=n;let i={canonicalName:t,def:n,negatable:rt(n)};if(e.flagSpellings.set(t,{...i,kind:"canonical"}),n.short!==void 0)e.flagSpellings.set(n.short,{...i,kind:"short"});for(let a of n.aliases??[])e.flagSpellings.set(a,{...i,kind:"alias"})}function lt(e,t,n,r){if(A(e,t,n,"owned"),!r)return;for(let o of Object.values(e.subCommands))lt(o,t,n,!0)}function lr(e,t,n){for(let r of t.commands??[])e.subCommands[r.name]=n(r,e,t.id)}function ur(e,t){for(let[n,r]of Object.entries(t.flags??{})){let{recursive:o=!0,...s}=r;lt(e,n,s,o)}}function J(e){return{localFlags:{...e.localFlags},ownedFlags:{...e.ownedFlags},effectiveFlags:{...e.effectiveFlags},flagSpellings:new Map(e.flagSpellings)}}function M(e){let t={};for(let[n,r]of Object.entries(e.subCommands))t[n]=M(r);return{...e,meta:{...e.meta},...J(e),args:[...e.args],subCommands:t,contexts:e.contexts.map((n)=>({...n})),demands:[...e.demands],extensions:[...e.extensions],run:e.run}}function fr({subject:e,name:t}){return new h("DEFINITION",`${e==="command"?"Command":"Extension"} "${t}" contains invalid documentation sections`,{subject:e,name:t,reason:"invalid-sections"})}function ut(e,t){let{title:n,body:r,only:o,except:s}=e;if(!n.trim()||/[\r\n]/.test(n)||!r.trim()||o?.length===0||s?.length===0||o!==void 0&&s!==void 0)throw fr(t);let i=(a)=>Object.freeze(a.map((c)=>typeof c==="string"?c:c.id));return Object.freeze({title:n,body:r,...o?{only:i(o)}:s?{except:i(s)}:{}})}function he(e,t){return t.map((n)=>ut(n,{subject:"command",name:e}))}function dr(e,t,n){let r=e;for(let o of t){let s=Object.hasOwn(r.subCommands,o)?r.subCommands[o]:void 0;if(!s)throw new h("DEFINITION",`Extension "${n.id}" section target "${t.join(" ")}" is not a canonical command path`,{subject:"extension",name:n.id,reason:"invalid-section-path"});r=s}return r}function mr(e,t,n){if(!t.sections)return;let r={subject:"extension",name:t.id},o=t.sections(n);for(let s of o){let i=ut(s,r),a=dr(e,s.command,t);a.meta.sections=[...a.meta.sections??[],i]}}function ft(e,t,n){let r=M(e),o=new Set(t.flatMap((i)=>!n.has(i.id)&&e.extensions.includes(i)?[i.id]:[])),s=(i)=>{i.contexts=i.contexts.filter((u)=>u.extensionId===void 0||o.has(u.extensionId));let a=Object.keys(i.effectiveFlags),c=i.localFlags,l={};for(let{instance:u}of i.contexts)Object.assign(l,u.ownedFlags);i.localFlags={},i.ownedFlags={},i.effectiveFlags={},i.flagSpellings=new Map;for(let u of a){let f=Object.hasOwn(l,u)?"owned":"local",d=f==="owned"?l:c;if(Object.hasOwn(d,u))A(i,u,d[u],f)}for(let u of Object.values(i.subCommands))s(u)};s(r);for(let i of t){if(o.has(i.id))continue;let a=i.provides??[];if(a.length===0)continue;let c=(l,u)=>{let f=a.filter((g)=>!u.has(g.name)),d=f.map((g)=>({instance:g,extensionId:i.id}));l.contexts.push(...d);for(let g of f)for(let[m,p]of Object.entries(g.ownedFlags))A(l,m,p,"owned");let b=new WeakSet(l.contexts.map(({instance:g})=>g));for(let g of Object.values(l.subCommands)){let m=new Set(u);for(let{instance:p}of g.contexts)if(!b.has(p))m.add(p.name);c(g,m)}};c(r,new Set)}return r}function gr(e){try{return new URL(e)}catch{throw new h("PARSE",`Invalid URL "${e}"${/^[a-z][a-z0-9+.-]*:/i.test(e)?"":" (missing protocol — e.g. https://example.com)"}`)}}function G(e){if(e==="")throw new h("PARSE","Path cannot be empty");let t=e.replace(/^~(?=\/|$)/,Zn());return Yn(process.cwd(),t)}function pr(e){try{return JSON.parse(e)}catch(t){throw new h("PARSE",`Invalid JSON: ${t instanceof Error?t.message:String(t)}. Tip: wrap JSON in single quotes on the command line, e.g. --flag '{"k":1}'`)}}function hr(e){let t={};for(let[n,r]of e){if(r.kind==="short")continue;let o={type:r.def.type==="boolean"?"boolean":"string"};if(r.def.multiple)o.multiple=!0;if(r.kind==="canonical"&&r.def.short)o.short=r.def.short;t[n]=o}return t}function dt(e,t,n){if(t==="number"){let r=Ye(e);if(r===void 0)throw new h("PARSE",`Expected number for ${n}, got "${e}"`);return r}if(t==="boolean")return le(e);if(t==="url")return gr(e);if(t==="path")return G(e);if(t==="json")return pr(e);return e}function be(e,t,n){if(!t.includes(e))throw new h("PARSE",`Invalid value "${e}" for ${n}. Expected one of: ${t.join(", ")}`)}function R(e,t,n,r){let o=r===void 0?n:`${n} element [${r}]`,s;try{if(s=e(t),Xn(s))throw s.catch(()=>{}),Error("parse must be synchronous")}catch(i){throw new h("PARSE",`Failed to parse ${o}: ${i instanceof Error?i.message:String(i)}`).withCause(i)}return s}function mt(e,t){let{default:n,parse:r}=e;if(n===void 0)return;if(r){if(Array.isArray(n))return n.map((o,s)=>R(r,String(o),t,s));return R(r,String(n),t)}if(e.type==="path"){if(Array.isArray(n))return n.map((o)=>G(String(o)));return G(String(n))}return"multiple"in e&&e.multiple&&Array.isArray(n)?[...n]:n}function br(e,t,n){if(n.kind==="boolean")return n.value;let r=`--${e}`,o=(s,i)=>{if(t.choices)be(s,t.choices,r);if(t.parse)return R(t.parse,s,r,i);return dt(s,t.type,r)};return Array.isArray(n.value)?n.value.map(o):o(n.value)}function wr(e,t){let n={};for(let r of e){if(r.kind!=="option")continue;let{canonicalName:o,def:s}=t.get(r.name),i=n[o];if(s.type==="boolean"){let a=!r.rawName.startsWith("--no-");if(s.multiple&&i?.kind==="boolean"&&Array.isArray(i.value))i.value.push(a);else n[o]={kind:"boolean",value:s.multiple?[a]:a}}else{let a=r.value;if(s.multiple&&i?.kind==="string"&&Array.isArray(i.value))i.value.push(a);else n[o]={kind:"string",value:s.multiple?[a]:a}}}return n}function gt(e,t){if(t===void 0)return[...e];return e.flatMap((n)=>n.split(t)).filter((n)=>n!=="")}function yr(e,t,n){let r=t.multiple?gt([n],t.env?.delimiter):[n];if(t.multiple&&r.length===0)return;if(t.type!=="boolean")return{kind:"string",value:t.multiple?r:n};let o=r.map(le);if("noNegate"in t&&t.noNegate&&o.includes(!1))throw new h("PARSE",`Flag "--${e}" does not support negation (from ${t.env?.name})`);return{kind:"boolean",value:t.multiple?o:o[0]}}function vr(e,t,n){let r={};for(let[o,s]of Object.entries(e)){let i=Object.hasOwn(t,o)?t[o]:void 0;if(i!==void 0){if(s.delimiter!==void 0&&i.kind==="string"&&Array.isArray(i.value)){let c=gt(i.value,s.delimiter);r[o]=c.length===0?void 0:{kind:"string",value:c}}else r[o]=i;continue}if(s.env===void 0||!Object.hasOwn(n,s.env.name))continue;let a=n[s.env.name];if(a!==void 0)r[o]=yr(o,s,a)}return r}function Sr(e,t,n){let r={};for(let o of Object.keys(t))if(!Object.hasOwn(e,o)&&t[o]!==void 0)throw new h("PARSE",`Unknown flag "--${o}"`,{flag:o,reason:"unknown-flag"});for(let[o,s]of Object.entries(e)){let i=Object.hasOwn(t,o)?t[o]:void 0;if(!(i===void 0||s.multiple&&Array.isArray(i)&&i.length===0)){r[o]=n(o,s,i);continue}r[o]=mt(s,`--${o}`)}return r}function xr(e,t){for(let[n,r]of Object.entries(e))if(r.required===!0&&r.default===void 0){if(t[n]===void 0)throw new h("VALIDATION",`Missing required flag "--${n}"`)}}function Or(e,t,n,r){if(e.schema)return t;if(e.choices)be(t,e.choices,n);if(e.parse)return R(e.parse,t,n,r);return dt(t,e.type,n)}function $r(e,t,n){let r={},o=0;for(let s of e){let{name:i}=s,a=`<${i}>`;if(Object.defineProperty(r,i,{value:void 0,writable:!0,enumerable:!0,configurable:!0}),s.variadic)r[i]=t.slice(o).map((c,l)=>n(s,c,a,l)),o=t.length;else if(o<t.length)r[i]=n(s,t[o],a),o++;else r[i]=mt(s,a)}return{args:r,consumed:o}}function Cr(e,t){for(let n of e){if(n==="--")return;if(!n.startsWith("--no-"))continue;let r=n.indexOf("="),o=r===-1?n.slice(5):n.slice(5,r),s=t.get(o);if(!s||s.def.type!=="boolean"||s.negatable)continue;throw new h("PARSE",`Flag "--${s.canonicalName}" does not support negation ("--no-${o}")`)}}function Er(e,t){let n=e.flagSpellings,r=hr(n);Cr(t,n);let o;try{o=Jn({args:t,options:r,strict:!0,allowPositionals:!0,allowNegative:!0,tokens:!0})}catch(c){if(c instanceof Error){let l=c.message.match(/Unknown option '(.+?)'/);if(l)throw new h("PARSE",`Unknown flag "${l[1]}"`).withCause(c);if("code"in c&&c.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"&&c.message.length>0)throw new h("PARSE",c.message).withCause(c)}throw new h("PARSE","Failed to parse command arguments").withCause(c)}let s=[],i=[],a=!1;for(let c of o.tokens){if(c.kind==="option-terminator"){a=!0;continue}if(c.kind==="positional")(a?s:i).push(c.value)}return{positionals:i,flagValues:wr(o.tokens,n),rawArgs:s}}function Ir(e,t,n){let r=e.schema?e.type==="boolean"?"boolean":"string":e.type,o;if(r==="url")o=t instanceof URL;else if(r==="json"){let s=[t],i=new Set;o=!0;while(s.length>0){let a=s.pop();if(a instanceof URL){o=!1;break}if(Array.isArray(a)&&!i.has(a))i.add(a),s.push(...a)}}else o=typeof t===(r==="path"?"string":r);if(!o)throw new h("PARSE",`Expected ${r} for ${n}`);if(t===!1&&"noNegate"in e&&e.noNegate)throw new h("PARSE",`Flag "${n}" does not support negation`)}function ge(e,t,n,r){if(Ir(e,t,n),e.choices)be(String(t),e.choices,n);if(e.parse)return R(e.parse,String(t),n,r);if(e.type==="path")return G(String(t));return t}function jr(e,t,n){let r=`--${e}`;if(t.multiple){if(!Array.isArray(n))throw new h("PARSE",`Expected an occurrence array for ${r}`);return n.map((o,s)=>ge(t,o,r,s))}return ge(t,n,r)}function pt(e,t,n,r,o){let s=Sr(e.effectiveFlags,n,o);return{...$r(e.args,t,r),flags:s}}function Nr(e,t,n=process.env){let{positionals:r,flagValues:o,rawArgs:s}=Er(e,t),{args:i,flags:a,consumed:c}=pt(e,r,vr(e.effectiveFlags,o,n),Or,br);return{args:i,flags:a,excessArgs:r.slice(c),rawArgs:s}}function kr(e,t){let{args:n,flags:r,raw:o}=t,s=[],i;for(let l of e.args){let u=n&&Object.hasOwn(n,l.name)?n[l.name]:void 0;if(u===void 0){i=l.name;continue}if(i!==void 0)throw new h("PARSE",`Argument <${l.name}> cannot be provided after omitted argument <${i}>`,{argument:l.name,reason:"positional-gap"});if(l.variadic){if(!Array.isArray(u))throw new h("PARSE",`Expected an occurrence array for <${l.name}>`);s.push(...u)}else s.push(u)}for(let l of Object.keys(n??{}))if(!e.args.some((u)=>u.name===l)&&n?.[l]!==void 0)throw new h("PARSE",`Unknown argument "${l}"`,{argument:l,reason:"unknown-argument"});let{args:a,flags:c}=pt(e,s,r??{},ge,jr);return{args:a,flags:c,excessArgs:[],rawArgs:[...o??[]]}}function Ar(e,t){let{args:n,effectiveFlags:r}=e,{args:o,flags:s}=t;if(t.excessArgs.length>0)throw new h("VALIDATION",`Unexpected positional argument${t.excessArgs.length===1?"":"s"}: ${t.excessArgs.map((i)=>JSON.stringify(i)).join(", ")}`);for(let i of n){let{name:a}=i,c=`argument "<${a}>"`,l=o[a];if(i.required===!0&&i.default===void 0){if(i.variadic){if(!Array.isArray(l)||l.length===0)throw new h("VALIDATION",`Missing required ${c}`)}else if(l===void 0)throw new h("VALIDATION",`Missing required ${c}`)}}xr(r,s)}async function Xe(e,t,n,r){let o=await e["~standard"].validate(t);if(o.issues)return r.push(...Je(o.issues,n)),{ok:!1};return{ok:!0,value:o.value}}async function Tr(e,t){let n=[],r=new Map(Object.entries(t.args)),o=new Map(Object.entries(t.flags));for(let s of e.args){if(s.schema===void 0)continue;let i=await Xe(s.schema,r.get(s.name),["args",s.name],n);if(i.ok)r.set(s.name,i.value)}for(let[s,i]of Object.entries(e.effectiveFlags)){if(i.schema===void 0)continue;let a=await Xe(i.schema,o.get(s),["flags",s],n);if(a.ok)o.set(s,a.value)}if(n.length>0)throw new h("VALIDATION",`Invalid input:
5
- ${n.map((s)=>` - ${s.path}: ${s.message}`).join(`
6
- `)}`,{issues:n});return{args:Object.fromEntries(r),flags:Object.fromEntries(o)}}function ht(e){return e.meta.hidden!==!0}function H(e){for(let t of Object.keys(e))if(e[t]===void 0)delete e[t];return Object.freeze(e)}function we(e){if(e instanceof URL)return e.href;if(Array.isArray(e))return Object.freeze(e.map(we));return e}function _r(e){return H({name:e.name,type:e.type,description:e.description,required:e.required,variadic:e.variadic,choices:e.choices?Object.freeze([...e.choices]):void 0,default:we(e.default)})}function Fr(e){return H({type:e.type,description:e.description,short:e.short,aliases:e.aliases?Object.freeze([...e.aliases]):void 0,required:e.required,multiple:e.multiple,negatable:rt(e),noNegate:"noNegate"in e?e.noNegate:void 0,choices:e.choices?Object.freeze([...e.choices]):void 0,default:we(e.default),env:e.env?H({name:e.env.name,delimiter:e.env.delimiter}):void 0,delimiter:e.delimiter})}function N(e){let t={};for(let[r,o]of Object.entries(e.effectiveFlags))t[r]=Fr(o);let n={};for(let[r,o]of Object.entries(e.subCommands))n[r]=N(o);return Object.freeze({meta:H({name:e.meta.name,description:e.meta.description,version:e.meta.version,usage:e.meta.usage,sections:e.meta.sections?Object.freeze(e.meta.sections.map((r)=>Object.freeze({...r}))):void 0,aliases:e.meta.aliases?Object.freeze([...e.meta.aliases]):void 0,hidden:e.meta.hidden}),hasAction:e.run!==void 0,args:Object.freeze(e.args.map(_r)),flags:Object.freeze(t),subCommands:Object.freeze(n)})}function Pr(e,t){for(let[n,r]of Object.entries(e)){let o=r.meta.aliases;if(!o)continue;if(o.includes(t))return{canonicalName:n,node:r}}return null}function Ze(e,t){if(t==="--")return null;if(t.startsWith("--")){let r=t.indexOf("="),o=r===-1?t.slice(2):t.slice(2,r),s=e.get(o);if(s)return{consumesValue:s.def.type!=="boolean"&&r===-1};if(o.startsWith("no-")){if(e.get(o.slice(3))?.negatable)return{consumesValue:!1}}return null}let n=t.slice(1);if(n.length===0)return null;for(let r=0;r<n.length;r++){let o=e.get(n[r]);if(!o)return null;if(o.def.type!=="boolean")return{consumesValue:r===n.length-1}}return{consumesValue:!1}}function bt(e,t){let n=[e.meta.name],r=e,o=t,s=[],i=[],a=(c,l)=>{if(i.length===0)return;let u=c.flagSpellings;for(let{token:f,consumesValue:d}of i){let b=Ze(u,f);if(b!==null&&b.consumesValue===d)continue;throw new h("PARSE",`Flag "${f}" cannot be used before subcommand "${l}" because "${l}" does not accept it.`,{flag:f,reason:"flag-not-forwardable"})}};while(o.length>0){let c=r.subCommands;if(Object.keys(c).length===0)break;let l=o[0];if(!l)break;if(l.startsWith("-")){let d=Ze(r.flagSpellings,l);if(!d)break;s.push(l),i.push({token:l,consumesValue:d.consumesValue}),o=o.slice(1);let b=o[0];if(d.consumesValue&&b!==void 0)s.push(b),o=o.slice(1);continue}if(Object.hasOwn(c,l)&&c[l]){a(c[l],l),r=c[l],n.push(l),o=o.slice(1);continue}let u=Pr(c,l);if(u){a(u.node,l),r=u.node,n.push(u.canonicalName),o=o.slice(1);continue}if(r.run)break;let f=N(r);throw new h("COMMAND_NOT_FOUND",`Unknown command "${l}".`,{input:l,available:Object.entries(f.subCommands).flatMap(([d,b])=>ht(b)?[d]:[]),commandPath:[...n],parentCommand:f})}return{command:r,argv:[...s,...o],commandPath:n}}function Dr(){var e=typeof SuppressedError=="function"?SuppressedError:function(o,s){var i=Error();return i.name="SuppressedError",i.error=o,i.suppressed=s,i},t={},n=[];function r(o,s){if(s!=null){if(Object(s)!==s)throw TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(o)var i=s[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(i===void 0&&(i=s[Symbol.dispose||Symbol.for("Symbol.dispose")],o))var a=i;if(typeof i!="function")throw TypeError("Object is not disposable.");a&&(i=function(){try{a.call(s)}catch(l){return Promise.reject(l)}}),n.push({v:s,d:i,a:o})}else o&&n.push({d:s,a:o});return s}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var s,i=this.e,a=0;function c(){for(;s=n.pop();)try{if(!s.a&&a===1)return a=0,n.push(s),Promise.resolve().then(c);if(s.d){var u=s.d.call(s.v);if(s.a)return a|=2,Promise.resolve(u).then(c,l)}else a|=1}catch(f){return l(f)}if(a===1)return i!==t?Promise.reject(i):Promise.resolve();if(i!==t)throw i}function l(u){return i=i!==t?new e(u,i):u,c()}return c()}}}var Qe=()=>{};function et(e,t){let n=()=>{if(e.listenerCount("error")===0)e.once("error",Qe)};try{n(),e.write(`${t}
7
- `,(r)=>{if(r)n()})}catch{}finally{e.removeListener("error",Qe)}}var Rr={stdout:(e)=>et(process.stdout,e),stderr:(e)=>et(process.stderr,e)};var D=130;function fe(e){if(!(e instanceof Error))return!1;return e.name==="AbortError"}function wt(e){return yt(e)&&"error"in e&&"suppressed"in e&&e.name==="SuppressedError"}function yt(e){return typeof e==="object"&&e!==null}function pe(e,t="Error"){let n=[],r=new Set,o=256,s=!1,i=(c)=>{if(s)return;if(o===0){s=!0,n.push("[additional failures omitted]");return}o--;let l;try{l=c()}catch{n.push("[unreadable failure]");return}a(l)},a=(c)=>{try{if(yt(c)){if(r.has(c))return;r.add(c)}let l=n.length;if(wt(c)){if(i(()=>c.error),i(()=>c.suppressed),n.length>l)return}else if(c instanceof AggregateError){let u=c.errors;if(Array.isArray(u)){for(let f=0;f<u.length;f++)if(i(()=>u[f]),s)break;if(n.length>l)return}}n.push(String(c instanceof Error&&c.message||c))}catch{n.push("[unreadable failure]")}};return i(()=>e),n.map((c)=>`${t}: ${c}`).join(`
8
- `)}function vt(e){if(Object.freeze(e),Object.freeze(e.localFlags),Object.freeze(e.ownedFlags),Object.freeze(e.effectiveFlags),e.meta.sections)Object.freeze(e.meta.sections);Object.freeze(e.meta),Object.freeze(e.contexts),Object.freeze(e.extensions),Object.freeze(e.args);for(let t of Object.values(e.subCommands))vt(t);Object.freeze(e.subCommands)}function Mr(e){return typeof e==="symbol"}var tt=new WeakMap;function Br(e,t){let n=M(e),r=Object.freeze([...e.extensions]);for(let o of r)lr(n,o,t);for(let o of r)ur(n,o);return{rootNode:n,extensions:r}}function Lr(e,t){if(t.some((n)=>n.sections!==void 0)){let n=N(e);for(let r of t)mr(e,r,n)}return vt(e),e}function B(e,t){let n=tt.get(e);if(n)return n;let r=Br(e,t);return Lr(r.rootNode,r.extensions),tt.set(e,r),r}function zr(e,t){let n=bt(e,[...t]);return{argv:t,route:n,parsed:Nr(n.command,n.argv)}}function ye(e,t){let n=bt(e,[...t]);if(n.argv.length>0){let r=n.argv[0],o=N(n.command);throw new h("COMMAND_NOT_FOUND",`Unknown command "${r}".`,{input:r,available:Object.entries(o.subCommands).flatMap(([s,i])=>ht(i)?[s]:[]),commandPath:n.commandPath,parentCommand:o})}return n}function Wr(e,t,n){let r=ye(e,t);return{argv:t,route:r,parsed:kr(r.command,n)}}async function St(e,t,n,r,o,s){try{var i=Dr();let{rootNode:a,extensions:c}=t,{argv:l,route:u,parsed:f}="argv"in e?zr(a,e.argv):Wr(a,e.path,e.input),d=u.command,b=i.a(new rr),g=d.contexts.map(({instance:C})=>C),m=ar(g,n,b,r),p=N(a),v=p;for(let C of u.commandPath.slice(1))v=v.subCommands[C];let O=Object.freeze({argv:[...l],rootCommand:p,command:v,commandPath:Object.freeze([...u.commandPath]),args:f.args,flags:f.flags,rawArgs:f.rawArgs,signal:r,ctx:m.bag(c.flatMap((C)=>C.uses??[])),finish:me,stdout:n.stdout,stderr:n.stderr});o?.(O);let S=async()=>{Ar(d,f);let C=await Tr(d,f);if(m.setValidatedFlags(C.flags),!d.run)return;let j={args:C.args,flags:C.flags,ctx:m.bag(g),rawArgs:f.rawArgs,signal:r,command:O.command,rootCommand:p,stdout:n.stdout,stderr:n.stderr};return await d.run(j)},I,x={status:"completed"};try{try{for(let E of c)if(await E.hooks?.preRun?.(O)===me()){x={status:"finished",by:E.id};break}if(x.status!=="finished")I=await S()}catch(E){let T=await s?.(E,O);x={status:"failed",error:E,...T===void 0?{}:{by:T}}}Object.freeze(x);let C=!1,j;for(let E of c.toReversed())try{await E.hooks?.postRun?.(O,x)}catch(T){if(x.status!=="failed"&&!C)C=!0,j=T}if(x.status==="failed")throw x.error;if(C)throw j}finally{await m.settle()}return x.status==="finished"?{status:"finished",by:x.by}:{status:"completed",result:I}}catch(a){i.e=a}finally{await i.d()}}async function de(e,t,n,r,o,s,i=!1){let a=()=>{if(i)return;r.stderr(pe(e))};function c(f){return Promise.reject(new h("DEFINITION",`Context "${String(f)}" cannot be pulled from onError because invocation Contexts have already been disposed.`,{subject:"context",name:String(f),reason:"context-after-disposal"}))}let l=new Proxy({},{get:(f,d)=>d==="then"||Mr(d)?void 0:c(d)}),u=s;if(!u){let f=N(n.rootNode);u=Object.freeze({argv:[...t],rootCommand:f,command:f,commandPath:Object.freeze([n.rootNode.meta.name]),args:Object.freeze({}),flags:Object.freeze({}),rawArgs:[],signal:o,finish:me,stdout:r.stdout,stderr:r.stderr,ctx:l})}try{for(let f of n.extensions)if(await f.hooks?.onError?.(e,u))return f.id}catch{}a()}function Ur(e){return e!==void 0&&Object.keys(e).length>0}async function ve(e,t,n,r){let o=[],s=[];try{let{signal:i=new AbortController().signal,...a}=n??{},c={stdout(l){o.push(l),a.stdout?.(l)},stderr(l){s.push(l),a.stderr?.(l)}};return{...await ce(c,async()=>await St(t,B(e,r),c,i)),stdout:o.join(`
9
- `),stderr:s.join(`
10
- `)}}catch(i){return{status:"failed",error:i,stdout:o.join(`
11
- `),stderr:s.join(`
12
- `)}}}async function xt(e,t,n){let r=t?.argv??process.argv.slice(2),o={...Rr,...t?.io},s=new AbortController,i=t?.signal?AbortSignal.any([t.signal,s.signal]):s.signal,a=void 0,c=async()=>{let l;try{l=B(e,n)}catch(g){if(fe(g))return process.exitCode=D,D;return o.stderr(pe(g)),process.exitCode=1,1}let u=()=>{if(!s.signal.aborted){s.abort(new DOMException("Interrupted by SIGINT.","AbortError"));return}if(process.removeListener("SIGINT",u),process.listenerCount("SIGINT")===0)process.kill(process.pid,"SIGINT")};process.on("SIGINT",u);let f,d=!1,b;try{await St({argv:r},l,o,i,(g)=>{f=g},async(g,m)=>{d=!0,b=g;let p=fe(g);return process.exitCode=p?D:1,de(g,r,l,o,i,m,p)})}catch(g){let m;try{if(d&&!Object.is(g,b)&&wt(g)&&Object.is(g.suppressed,b))m={error:g.error}}catch{}if(m)o.stderr(pe(m.error,"Cleanup failed"));if(fe(g)){if(!d)await de(g,r,l,o,i,f,!0);return process.exitCode=D,D}if(process.exitCode=1,!d)await de(g,r,l,o,i,f);return 1}finally{process.removeListener("SIGINT",u)}return 0};return await(Ur(t?.io)?ce(o,c):c())}var xe=Symbol.for("crust.commandDefinition");function _(e,t,n){let r=e[xe],o=e.name,s=n?`Extension "${n}" command "${o}"`:`Command "${o}"`,i=(u)=>({subject:n?"extension":"command",name:n??o,reason:u}),a=new X(o);for(let[u,f]of Object.entries(t.ownedFlags))A(a._node,u,f,"owned");a._node.contexts=t.contexts.map((u)=>({...u}));let c=r.recipe(a);if(!(c instanceof X)||c._ancestorOwnedFlags!==a._ancestorOwnedFlags)throw new h("DEFINITION",`${s} definition must return the same command builder it received`,i("foreign-command-builder"));if(c._node.extensions.length>0)throw new h("DEFINITION",`${s} cannot register Extensions inside command definitions`,i("nested-command-extension"));let l=M(c._node);return Y(l.contexts.map(({instance:u})=>u),l.demands),l.meta={name:o,...r.meta},l}function Se(e,t=[]){if(e.trim()==="")throw new h("DEFINITION","Command name must be a non-empty string",{subject:"command",name:e,reason:"empty-name"});if(e==="__proto__")throw new h("DEFINITION",'Command name "__proto__" is reserved',{subject:"command",name:e,reason:"reserved-name"});if(t.includes(e))throw new h("DEFINITION",`Command "${e}" must not list its own canonical name as an alias`,{subject:"command",name:e,reason:"alias-collision"});return e}function Vr(e){return typeof e==="function"}function qr(e,t,n){let r=!Vr(t),o=r?t:{},s=r?n:t,i=Se(e,o.aliases);for(let b of o.aliases??[])if(b===""||/[ \t\n\r\v\f]/.test(b)||b.startsWith("-"))throw new h("DEFINITION",`Command "${i}" has an invalid alias "${b}"`);let{sections:a,version:c,...l}=o,u={...l,...o.aliases?{aliases:[...o.aliases]}:{},...a?{sections:he(i,a)}:{}},f={name:i,recipe:s,meta:u},d=(b)=>Object.freeze({name:b,as:(g)=>d(Se(g,u.aliases)),[xe]:Object.freeze({...f,name:b})});return d(i)}function Gr(e){return e.filter((t,n)=>e.findLastIndex((r)=>r.id===t.id)===n)}var X=class{_node;_ancestorOwnedFlags;constructor(e,...t){let n=t[0]??{},r=Se(e);if(this._node=ct(r),n.description!==void 0)this._node.meta.description=n.description;if(n.version!==void 0)this._node.meta.version=n.version;if(n.usage!==void 0)this._node.meta.usage=n.usage;if(n.sections!==void 0)this._node.meta.sections=he(r,n.sections);this._ancestorOwnedFlags={}}_clone(e){let t=Object.create(Object.getPrototypeOf(this));return t._node={...this._node,...e},t._ancestorOwnedFlags=this._ancestorOwnedFlags,t}flags(...e){let t=this._clone(J(this._node));for(let n of e){let{name:r,...o}=n;A(t._node,r,o,"local")}return t}args(...e){let t=[...this._node.args,...e.map(it)],n=new Set;for(let[r,o]of t.entries()){if(n.has(o.name))throw new h("DEFINITION",`Argument name "${o.name}" is already defined`,{subject:"argument",name:o.name,reason:"duplicate-arg"});if(n.add(o.name),o.variadic===!0&&r!==t.length-1)throw new h("DEFINITION",`Only the last positional argument can be variadic; "${o.name}" is not last`,{subject:"argument",name:o.name,reason:"variadic-position"})}return this._clone({args:t})}use(...e){return this._clone({demands:[...this._node.demands,...e.map(K)]})}provide(...e){let t=e.map(K);Y([...this._node.contexts.map(({instance:r})=>r),...t],t);let n=this._clone({...J(this._node),contexts:[...this._node.contexts,...t.map((r)=>({instance:r}))]});for(let r of t)for(let[o,s]of Object.entries(r.ownedFlags))A(n._node,o,s,"owned");return n}action(e){return this._clone({run:e})}extend(...e){let t=e.map(K),n=Gr([...this._node.extensions,...t]),r=ft(this._node,n,new Set(t.map((o)=>o.id)));return Y(r.contexts.map(({instance:o})=>o),n.flatMap((o)=>[...o.uses,...o.provides??[]])),this._clone({...r,extensions:n})}add(...e){return this._addDefinitions(e)}command(e,t){let n=qr(e,t);return this._addDefinitions([n])}_addDefinitions(e){let t={...this._node.subCommands};for(let n of e){let r=[n.name,...n[xe].meta.aliases??[]];for(let s of Object.values(t))if([s.meta.name,...s.meta.aliases??[]].some((i)=>r.includes(i)))throw new h("DEFINITION",`Command name "${n.name}" is already registered on this command`,{subject:"command",name:n.name,reason:"command-collision"});let o=_(n,this._node);t[n.name]=o}return this._clone({subCommands:t})}async snapshot(){return N(B(this._node,_).rootNode)}async run(e,...t){let n=t[0]??{},r=t[1];return await ve(this._node,{path:e,input:n},r,_)}at(e){ye(B(this._node,_).rootNode,e);let t=this._node,n=Object.freeze([...e]);return{path:n,async run(...r){let o=r[0]??{},s=r[1];return await ve(t,{path:n,input:o},s,_)}}}async execute(e){return await xt(this._node,e,_)}};import{existsSync as Ce,lstatSync as Ft,mkdirSync as kt,readFileSync as ao,readdirSync as Pt,realpathSync as Dt,statSync as Rt,writeFileSync as At}from"node:fs";import{dirname as Mt,join as F,resolve as Tt,sep as co}from"node:path";import{fileURLToPath as lo}from"node:url";function Ot(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"}import{isAbsolute as Hr,relative as Kr,sep as Yr}from"node:path";function $t(e,t){let n=Kr(e,t);return n===""||!Hr(n)&&n!==".."&&!n.startsWith(`..${Yr}`)}import{spawn as uo,spawnSync as fo}from"node:child_process";import{once as mo}from"node:events";import{accessSync as Ct,constants as Et,statSync as It}from"node:fs";import{delimiter as Jr,extname as Xr,join as Zr,resolve as Qr,sep as eo,win32 as to}from"node:path";import{spawn as no}from"node:child_process";import{once as ro}from"node:events";import{text as jt}from"node:stream/consumers";function Nt(e){if(e?.startsWith("bun"))return"bun";if(e?.startsWith("pnpm"))return"pnpm";if(e?.startsWith("yarn"))return"yarn";if(e?.startsWith("npm"))return"npm";return null}var oo=/[\0\r\n"%!^`<>&|]/,Oe=/([()\][%!^"`<>&|;, *?])/g;function so(e){let t=e.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\"");return t=t.replace(/(?=(\\+?)?)\1$/g,"$1$1"),t=`"${t}"`.replace(Oe,"^$1"),t.replace(Oe,"^$1")}function io(e,t,n,r=process.platform){if(n||r!=="win32"||!/\.(cmd|bat)$/i.test(e))return null;let o=to.normalize(e);for(let[i,a]of[o,...t].entries())if(oo.test(a)){let c=i===0?"command":`argument ${i}`;throw Error(`Windows command shim ${c} ${JSON.stringify(a)} contains unsafe shell characters`)}let s=[o.replace(Oe,"^$1"),...t.map(so)].join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${s}"`],windowsVerbatimArguments:!0}}async function L(e,t=[],n={}){let r=io(e,t,n.shell),o=(n.stdio??"collect")==="collect",s=o&&n.stdout!=="ignore",i=no(r?.command??e,r?.args??t,{cwd:n.cwd,env:n.env,shell:n.shell,stdio:o?["ignore",s?"pipe":"ignore","pipe"]:"inherit",windowsVerbatimArguments:r?.windowsVerbatimArguments}),[a,c,[l]]=await Promise.all([s?jt(i.stdout):"",o?jt(i.stderr):"",ro(i,"close")]);return{exitCode:l,stdout:a,stderr:c}}function $e(e){if(e.includes(eo)||e.includes("/")){try{if(Ct(e,Et.X_OK),It(e).isFile())return e}catch{}return null}let t=process.platform==="win32"&&!Xr(e)?(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";"):[""];for(let n of process.env.PATH?.split(Jr)??[])for(let r of t){let o=Qr(Zr(n,e+r));try{if(Ct(o,Et.X_OK),It(o).isFile())return o}catch{}}return null}function go(e,t){return e.replace(/\{\{\s*(\w+)\s*\}\}/g,(n,r)=>Object.hasOwn(t,r)?t[r]??n:n)}function po(e){let t=Mt(e),n=e.slice(t==="."?0:t.length+1);if(n.startsWith("_")&&!n.startsWith("__")){let r=`.${n.slice(1)}`;return t==="."?r:F(t,r)}return e}function ho(e){if(!Ce(e))return!1;if(!Rt(e).isDirectory())return!1;return Pt(e).length>0}function bo(e,t){let n=e;for(let r of t.split(co)){n=F(n,r);let o;try{o=Ft(n).isSymbolicLink()}catch(i){if(Ot(i)&&i.code==="ENOENT")return;throw i}if(!o)continue;let s;try{s=Dt(n)}catch{}if(s===void 0||!$t(e,s))throw Error(`Destination path "${n}" is a symlink${s===void 0?" to a missing target":` to "${s}"`} outside the destination "${e}". Remove the link or choose another destination.`)}}async function Ee(e){let{template:t,dest:n,context:r,conflict:o="abort"}=e,s=t instanceof URL?lo(t):Tt(t),i=Tt(n);if(!Ce(s))throw Error(`Template directory "${s}" does not exist (from template: "${String(t)}").`);if(!Rt(s).isDirectory())throw Error(`Template path "${s}" is not a directory (from template: "${String(t)}").`);if(o==="abort"&&ho(i))throw Error(`Destination directory "${i}" already exists and is non-empty. Use conflict: "overwrite" to proceed.`);let a=Pt(s,{recursive:!0,encoding:"utf8"}).filter((f)=>Ft(F(s,f)).isFile());kt(i,{recursive:!0});let c=Dt(i),l=a.map((f)=>({relFromTemplate:f,destRelPath:po(f)}));for(let{destRelPath:f}of l)bo(c,f);let u=[];for(let{relFromTemplate:f,destRelPath:d}of l){let b=F(s,f),g=F(c,d);kt(Mt(g),{recursive:!0});let m=ao(b);if(m.subarray(0,8192).includes(0))At(g,m);else{let p=go(m.toString("utf-8"),r);At(g,p,"utf-8")}u.push(d)}return{files:u}}var wo=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];function yo(e){let t=e??process.cwd();for(let[n,r]of wo)if(Ce(F(t,n)))return r;return Nt(process.env.npm_config_user_agent)??"npm"}function Bt(e){try{return fo("git",["rev-parse","--is-inside-work-tree"],{cwd:e??process.cwd(),stdio:"ignore"}).status===0}catch{return!1}}async function Ie(e,t){for(let n of e)switch(n.type){case"install":await vo(t);break;case"git-init":await So(t,n.commit);break;case"open-editor":await xo(t);break;case"command":await Oo(n.cmd,n.cwd??t)}}async function vo(e){let t=yo(e),n=$e(t);if(!n)throw Error(`Package manager "${t}" was not found on PATH. Install ${t} and try again.`);let{exitCode:r}=await L(n,["install"],{cwd:e,stdio:"inherit"});if(r!==0)throw Error(`"${t} install" exited with code ${r}`)}async function So(e,t){let n=$e("git");if(!n)throw Error('"git" was not found on PATH. Install Git and try again.');if(await z([n,"init"],e,"git init"),t)await $o(e,n),await z([n,"add","."],e,"git add"),await z([n,"commit","-m",t],e,"git commit")}async function xo(e){let t=process.env.EDITOR||"code";try{let n=uo(t,[e],{stdio:"ignore",shell:process.platform==="win32"});n.unref();let r=await Promise.race([mo(n,"close").then(([o])=>({kind:"exited",code:o})),new Promise((o)=>setTimeout(()=>o({kind:"timeout"}),500))]);if(r.kind==="exited"&&r.code!==0)console.warn(`Warning: could not open editor "${t}" (exit code ${r.code})`)}catch{console.warn(`Warning: could not open editor "${t}"`)}}async function Oo(e,t){let{exitCode:n}=await L(e,[],{cwd:t,shell:!0,stdio:"inherit"});if(n!==0)throw Error(`Command "${e}" exited with code ${n}`)}async function $o(e,t){let n=await _t(t,"user.name",e)===0,r=await _t(t,"user.email",e)===0;if(!n)await z([t,"config","user.name","Crust"],e,"git config user.name");if(!r)await z([t,"config","user.email","crust@scaffolded.project"],e,"git config user.email")}async function _t(e,t,n){let{exitCode:r}=await L(e,["config",t],{cwd:n,stdio:"collect",stdout:"ignore"});return r}async function z(e,t,n){let{exitCode:r,stderr:o}=await L(e[0],e.slice(1),{cwd:t,stdio:"collect",stdout:"ignore"});if(r!==0)throw Error(`"${n}" failed with exit code ${r}${o?`: ${o.trim()}`:""}`)}var Lt=Object.defineProperty,Co=(e,t)=>{let n={};for(var r in e)Lt(n,r,{get:e[r],enumerable:!0});if(!t)Lt(n,Symbol.toStringTag,{value:"Module"});return n},Eo=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Io=/[\p{Cc}\p{Cf}\p{Mn}\p{Me}]/u,jo=/\p{Emoji_Presentation}|\p{Emoji}\uFE0F/u,No=new RegExp([String.raw`(?:\x1b\[|\x9b)[^\x1b\x18\x1a\x9c\x40-\x7e]*[\x40-\x7e\x18\x1a\x9c]?`,String.raw`(?:\x1b\]|\x9d)[^\x07\x1b\x18\x1a\x9c]*(?:\x07|\x1b\\|[\x18\x1a\x9c])?`,String.raw`(?:\x1b[PX^_]|[\x90\x98\x9e\x9f])[^\x1b\x18\x1a\x9c]*(?:\x1b\\|[\x18\x1a\x9c])?`,String.raw`\x1b[\x20-\x2f][^\x1b]?`,String.raw`\x1b[\x18\x1a\x9c\x30-\x7e]?`].join("|"),"g");function ko(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=94176&&e<=111355||e>=127488&&e<=127743||e>=131072&&e<=262141)}function Ao(e){return Io.test(String.fromCodePoint(e))||e>=4448&&e<=4607||e>=55216&&e<=55295}function To(e){if(!/[^\x20-\x7e]/.test(e))return e.length;let t=0;for(let{segment:n}of Eo.segment(e.replace(No,""))){if(jo.test(n)){let r=n.codePointAt(0);t+=n.length===2&&r>=127462&&r<=127487?1:2;continue}for(let r of n){let o=r.codePointAt(0);if(Ao(o))continue;t+=ko(o)?2:1;break}}return t}function Vt(e){return globalThis.Bun?.stringWidth(e,{countAnsiEscapeCodes:!1})??To(e)}var _o=Co({bgBlack:()=>rs,bgBlue:()=>as,bgBrightBlack:()=>fs,bgBrightBlue:()=>ps,bgBrightCyan:()=>bs,bgBrightGreen:()=>ms,bgBrightMagenta:()=>hs,bgBrightRed:()=>ds,bgBrightWhite:()=>ws,bgBrightYellow:()=>gs,bgCyan:()=>ls,bgGreen:()=>ss,bgMagenta:()=>cs,bgRed:()=>os,bgWhite:()=>us,bgYellow:()=>is,black:()=>zo,blue:()=>qo,bold:()=>Fo,brightBlue:()=>Qo,brightCyan:()=>ts,brightGreen:()=>Xo,brightMagenta:()=>es,brightRed:()=>Jo,brightWhite:()=>ns,brightYellow:()=>Zo,cyan:()=>Ho,dim:()=>Po,gray:()=>Yo,green:()=>Uo,hidden:()=>Bo,inverse:()=>Mo,isModifierName:()=>qt,italic:()=>Do,magenta:()=>Go,red:()=>Wo,strikethrough:()=>Lo,styleMethodNames:()=>Ne,underline:()=>Ro,white:()=>Ko,yellow:()=>Vo});function y(e,t){return{open:`\x1B[${e}m`,close:`\x1B[${t}m`}}var Fo=y(1,22),Po=y(2,22),Do=y(3,23),Ro=y(4,24),Mo=y(7,27),Bo=y(8,28),Lo=y(9,29),zo=y(30,39),Wo=y(31,39),Uo=y(32,39),Vo=y(33,39),qo=y(34,39),Go=y(35,39),Ho=y(36,39),Ko=y(37,39),Yo=y(90,39),Jo=y(91,39),Xo=y(92,39),Zo=y(93,39),Qo=y(94,39),es=y(95,39),ts=y(96,39),ns=y(97,39),rs=y(40,49),os=y(41,49),ss=y(42,49),is=y(43,49),as=y(44,49),cs=y(45,49),ls=y(46,49),us=y(47,49),fs=y(100,49),ds=y(101,49),ms=y(102,49),gs=y(103,49),ps=y(104,49),hs=y(105,49),bs=y(106,49),ws=y(107,49),Ne=Object.freeze(["bold","dim","italic","underline","inverse","hidden","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite","bgBlack","bgRed","bgGreen","bgYellow","bgBlue","bgMagenta","bgCyan","bgWhite","bgBrightBlack","bgBrightRed","bgBrightGreen","bgBrightYellow","bgBrightBlue","bgBrightMagenta","bgBrightCyan","bgBrightWhite"]),ys=new Set(["bold","dim","italic","underline","inverse","hidden","strikethrough"]);function qt(e){return ys.has(e)}function W(e,t,n){return e!==void 0&&t in e?e[t]:n}function Gt(e){return W(e,"isTTY",process.stdout?.isTTY)??!1}function Ht(e){return W(e,"forceColor",process.env.FORCE_COLOR)}function Kt(e){return e==="0"||e==="false"}function vs(e){let t=e.toLowerCase();return t.includes("24bit")||t.includes("truecolor")||t.endsWith("-direct")}function Yt(e,t){if(e!==void 0){let n=e.toLowerCase();if(n==="truecolor"||n==="24bit")return!0}return t!==void 0&&vs(t)}function zt(e,t){if(Yt(e,t))return"truecolor";if(t!==void 0&&t.toLowerCase().includes("256color"))return"256";return"16"}function Ss(e,t){if(e==="never")return"none";if(e==="always")return"truecolor";let n=W(t,"colorTerm",process.env.COLORTERM),r=W(t,"term",process.env.TERM),o=Ht(t);if(o!==void 0){if(Kt(o))return"none";if(o==="1")return"16";if(o==="2")return"256";if(o==="3")return"truecolor";return zt(n,r)}if(!Gt(t))return"none";let s=W(t,"noColor",process.env.NO_COLOR);if(s!==void 0&&s!=="")return"none";if(r!==void 0&&r.toLowerCase()==="dumb"&&!Yt(n,r))return"none";return zt(n,r)}function xs(e,t){if(e==="always")return!0;if(e==="never")return!1;let n=Ht(t);if(n!==void 0)return!Kt(n);return Gt(t)}var Jt={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function ke(e,t){if(e==null)return"";let n=String(e);if(n==="")return"";let{open:r,close:o}=t;if(n.includes(o))n=n.replaceAll(o,o+r);return r+n+o}var Os="\x1B[39m",$s="\x1B[49m",Cs="\x1B[38;",Es="\x1B[48;";function Is(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function js(e){return Object.hasOwn(Jt,e)}function Ae(e){if(Array.isArray(e)){if(e.length===3&&e.every((t)=>Number.isInteger(t)&&t>=0&&t<=255))return[e[0],e[1],e[2]]}else if(typeof e==="string"){let t=e.toLowerCase();if(js(t))return Jt[t];let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t)?.[1];if(n){let o=n.length===3?n.split("").map((s)=>s+s).join(""):n;return[Number.parseInt(o.slice(0,2),16),Number.parseInt(o.slice(2,4),16),Number.parseInt(o.slice(4,6),16)]}let r=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.exec(t)??/^rgb\(\s*(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})\s*\)$/.exec(t);if(r){let o=[Number(r[1]),Number(r[2]),Number(r[3])];if(o.every((s)=>s<=255))return o}}throw TypeError(`Invalid color input: ${Is(e)}`)}function Ns(e,t,n){let r=[0,95,135,175,215,255],o=(f)=>r.reduce((d,b,g)=>Math.abs(b-f)<Math.abs(r[d]-f)?g:d,0),[s,i,a]=[o(e),o(t),o(n)],c=Math.min(23,Math.max(0,Math.round(((e+t+n)/3-8)/10))),l=8+c*10,u=(f,d,b)=>(e-f)**2+(t-d)**2+(n-b)**2;return u(l,l,l)<u(r[s],r[i],r[a])?232+c:16+36*s+6*i+a}function Xt(e,t,n){let r=Math.round(Math.max(e,t,n)/127.5);if(r===0)return 30;let o=30+((Math.round(n/255)<<2|Math.round(t/255)<<1|Math.round(e/255))&7);if(r===2)o+=60;return o}function Zt(e,t){let[n,r,o]=Ae(e);if(t==="16")return`\x1B[${Xt(n,r,o)}m`;if(t==="256")return`\x1B[38;5;${Ns(n,r,o)}m`;return`\x1B[38;2;${n};${r};${o}m`}function ks(e,t){if(t==="16"){let[n,r,o]=Ae(e);return`\x1B[${Xt(n,r,o)+10}m`}return Zt(e,t).replace(Cs,Es)}function Te(e,t,n){if(n==="none")return Ae(t),{open:"",close:""};return{open:e==="fg"?Zt(t,n):ks(t,n),close:e==="fg"?Os:$s}}function Qt(e,t){return Te("fg",e,t)}function en(e,t){return Te("bg",e,t)}function tn(e,t,n,r){let o=Te(e,n,r);return r==="none"?t:ke(t,o)}function As(e,t,n="truecolor"){return tn("fg",e,t,n)}function Ts(e,t,n="truecolor"){return tn("bg",e,t,n)}var nn="\x1B]",rn="\x1B\\",_s=`${nn}8;;${rn}`;function on(e,t,n,r=""){if(!n.test(e))throw TypeError(`Invalid ${t}: ${JSON.stringify(e)} must contain only printable ASCII characters${r}.`)}function Fs(e){let t=e?.id;if(t===void 0||t==="")return"";if(on(t,"hyperlink id",/^[\x20-\x7e]*$/),t.includes(":")||t.includes(";"))throw TypeError('Invalid hyperlink id: ":" and ";" are reserved by the OSC 8 format.');return`id=${t}`}function sn(e,t){on(e,"hyperlink URL",/^[\x21-\x7e]*$/," without spaces");let n=Fs(t);return{open:`${nn}8;${n};${e}${rn}`,close:_s}}function Ps(e,t,n){return ke(e,sn(t,n))}var an=[["fg",Qt,As],["bg",en,Ts]],Ds=_o;function Rs(e){return e.kind==="named"&&qt(e.name)}function je(e,t){if(e.kind==="named")return Ds[e.name];return e.kind==="fg"?Qt(e.input,t):en(e.input,t)}function Wt(e,t,n){if(e==null)return"";let r=String(e);if(r==="")return r;let o=n(),{modifiersEnabled:s,colorsEnabled:i}=o;for(let a=t.length-1;a>=0;a--){let c=t[a];if(c===void 0)continue;if(Rs(c)?!s:!i)continue;r=ke(r,je(c,o.colorDepth))}return r}function Ms(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)}function Bs(e,t){let n=new Map,r=t?"truecolor":e().colorDepth;function o(s){let i=s.map((f)=>f.kind==="named"?f.name:`~${je(f,"truecolor").open}`).join("|"),a=n.get(i);if(a)return a;let c=(f,...d)=>{if(Ms(f)){let b="";for(let g=0;g<f.length;g++)if(b+=f[g]??"",g<d.length)b+=String(d[g]);return Wt(b,s,e)}return Wt(f,s,e)};if(n.size>=1024)n.delete(n.keys().next().value);n.set(i,c);for(let f of Ne)Object.defineProperty(c,f,{configurable:!1,enumerable:!0,get(){return o([...s,{kind:"named",name:f}])}});for(let[f,d]of an)Object.defineProperty(c,f,{configurable:!1,enumerable:!0,value:(b)=>(d(b,"truecolor"),o([...s,{kind:f,input:b}])),writable:!1});let l="",u="";for(let f of s){let d=je(f,r);l+=d.open,u=d.close+u}return Object.defineProperty(c,"open",{value:l,writable:!1,configurable:!1,enumerable:!0}),Object.defineProperty(c,"close",{value:u,writable:!1,configurable:!1,enumerable:!0}),Object.freeze(c)}return o}function Ls(e){let t={};for(let n of Ne)t[n]=e([{kind:"named",name:n}]);return t}function Ut(e){let t=e?.mode??"auto",n=xs(t,e?.overrides),r=Ss(t,e?.overrides);return{modifiersEnabled:n,colorDepth:r,colorsEnabled:r!=="none",trueColorEnabled:r==="truecolor"}}function zs(e,t){let n=t?Ut:(()=>{let i=Ut(e);return()=>i})(),r=Bs(n,t),o=Ls(r),s={get enabled(){let{modifiersEnabled:i,colorsEnabled:a}=n();return i||a},get colorsEnabled(){return n().colorsEnabled},get trueColorEnabled(){return n().trueColorEnabled},get colorDepth(){return n().colorDepth},link(i,a,c){if(n().modifiersEnabled)return Ps(i,a,c);return sn(a,c),i},...Object.fromEntries(an.map(([i,a,c])=>[i,(...l)=>{let u=n();if(l.length===1)return a(l[0],"truecolor"),r([{kind:i,input:l[0]}]);return c(l[0],l[1],u.colorDepth)}])),...o};return Object.freeze(s)}var w=zs(void 0,!0),{black:Ca,red:Z,green:Q,yellow:Ea,blue:Ia,magenta:cn,cyan:U,white:ja,gray:Na,brightRed:ka,brightGreen:Aa,brightYellow:Ta,brightBlue:_a,brightMagenta:Fa,brightCyan:Pa,brightWhite:Da,bgBlack:Ra,bgRed:Ma,bgGreen:Ba,bgYellow:La,bgBlue:za,bgMagenta:Wa,bgCyan:Ua,bgWhite:Va,bgBrightBlack:qa,bgBrightRed:Ga,bgBrightGreen:Ha,bgBrightYellow:Ka,bgBrightBlue:Ya,bgBrightMagenta:Ja,bgBrightCyan:Xa,bgBrightWhite:Za,bold:ee,dim:te,italic:Qa,underline:ec,inverse:tc,hidden:nc,strikethrough:rc,link:oc,fg:sc,bg:ic}=w;var ln={spinner:cn,message:ee,success:Q,error:Z},Pe="\x1B[",Ws=`${Pe}?25l`,un=`${Pe}?25h`,dn=`${Pe}2K`,mn="\r",fn={dots:{frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],interval:80},line:{frames:["-","\\","|","/"],interval:130},arc:{frames:["◐","◓","◑","◒"],interval:100},bounce:{frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"],interval:120}},Us="✓",Vs="✗";function qs(e){if(e===void 0)return fn.dots;if(typeof e==="string")return fn[e];if(e.frames.length===0)throw Error("A custom spinner requires at least one frame");return e}function _e(e,t){let n=e[t];if(n===void 0)throw Error("Spinner frame index is out of bounds");return n}function Fe(e,t,n){return`${dn}${mn}${n.spinner(e)} ${n.message(t)}`}function Gs(e,t,n,r){let o=n==="success"?Us:Vs,s=`${(n==="success"?t.success:t.error)(o)} ${t.message(e)}
13
- `;return r?dn+mn+s:s}function Hs(e){let t=e.sink??q()?.output??process.stderr,n=e.theme?{...ln,...e.theme}:ln,r=t.isTTY??!1,{frames:o,interval:s}=qs(e.spinner),i=e.sigint??"exit",a=e.message,c=0,l=!1,u=!1,f,d;function b(){if(f!==void 0)clearInterval(f),f=void 0;if(d)process.removeListener("SIGINT",d),d=void 0}return{start(){if(l||u)return;if(l=!0,!r)return;if(t.write(Ws),t.write(Fe(_e(o,0),a,n)),f=setInterval(()=>{c=(c+1)%o.length,t.write(Fe(_e(o,c),a,n))},s),i==="exit")d=()=>{if(b(),u=!0,t.write(un),process.listenerCount("SIGINT")===0)process.kill(process.pid,"SIGINT")},process.once("SIGINT",d)},updateMessage(g){if(u)return;if(a=g,l&&r)t.write(Fe(_e(o,c),a,n))},stop(g="success",m){if(u)return;if(u=!0,m!==void 0)a=m;if(b(),t.write(Gs(a,n,g,l&&r)),l&&r)t.write(un)}}}function De(e){let t=Hs(e),{task:n}=e;if(!n)return t;return t.start(),Promise.resolve().then(()=>n(t)).then((r)=>(t.stop("success"),r),(r)=>{throw t.stop("error"),r})}import*as k from"node:readline";var gn={prefix:U,message:ee,placeholder:te,cursor:U,selected:U,unselected:te,error:Z,success:Q,hint:te,filterMatch:U};function re(e){let t=q();return{input:e?.input??t?.input??process.stdin,output:e?.output??t?.output??process.stderr}}var Be=Symbol("submit");function Le(e){return{[Be]:e}}var Re=new WeakSet,Me=new WeakSet,hn="\x1B[",Ks=`${hn}?25l`,Ys=`${hn}?25h`;function pn(e,t){let n=e.split(`
14
- `),r=0;for(let o of n){let s=Vt(o);r+=s===0?1:Math.ceil(s/t)}return r}var Js=class extends Error{constructor(e){super(e??"Prompts require an interactive terminal (TTY).");this.name="NonInteractiveError"}};function bn(e=re().input){return!!e.isTTY}function Xs(e=re().input){if(!bn(e))throw new Js}function Zs(e){return typeof e==="object"&&e!==null&&Be in e}function ze(e,t){let{render:n,handleKey:r,initialState:o,renderSubmitted:s}=e,i=e.theme?{...gn,...e.theme}:gn,{input:a,output:c}=re(t),l=c;return new Promise((u,f)=>{if(Re.has(a)||Me.has(c)){f(Error("Cannot run multiple prompts concurrently on the same input or output stream. Await each prompt before starting the next."));return}Xs(a),Re.add(a),Me.add(c);let d=o,b=0,g=!1,m=!1;function p(){if(g)return;if(g=!0,Re.delete(a),Me.delete(c),a.removeListener("keypress",C),m)a.setRawMode?.(!1);a.pause(),c.write(Ys)}function v(j){let E=c.columns||80;if(b>0)k.cursorTo(l,0),k.moveCursor(l,0,-(b-1)),k.clearScreenDown(l);c.write(j),b=pn(j,E)}let O=Promise.resolve(),S=null;function I(){if(S!==null)return;S=setTimeout(()=>{if(S=null,g)return;try{v(n(d,i))}catch(j){p(),f(j)}},0)}function x(){if(S!==null)clearTimeout(S),S=null}function C(j,E){if(E?.ctrl&&E.name==="c"){x(),c.write(`
15
- `),p(),f(new DOMException("Prompt was cancelled.","AbortError"));return}let T={char:j??"",name:E?.name??"",ctrl:E?.ctrl??!1,meta:E?.meta??!1,shift:E?.shift??!1};O=O.then(async()=>{if(g)return;try{let P=await r(T,d);if(g)return;if(Zs(P)){x();let Ve=P[Be];if(s)v(s(d,Ve,i));c.write(`
16
- `),p(),u(Ve)}else d=P,I()}catch(P){x(),p(),f(P)}})}try{if(k.emitKeypressEvents(a),a.setRawMode)a.setRawMode(!0),m=!0;a.resume(),c.write(Ks);let j=n(d,i);c.write(j),b=pn(j,c.columns||80),a.on("keypress",C)}catch(j){p(),f(j)}})}async function ne(e,t,n){if(e.initial!==void 0)return{shortCircuited:!0,value:n?await n(e.initial,"initial"):e.initial};let r=re(t);if(!bn(r.input)&&e.default!==void 0)return{shortCircuited:!0,value:n?await n(e.default,"default"):e.default};return{shortCircuited:!1,promptIO:r}}function We(e,t,n){let r=[e];if(t)r.push(t);if(n)r.push(n);return r.join(" ")}function wn(e,t,n,r){let o=t?`${e} ${t}`:e,s=r??"";if(t)return`${o}${s}
17
- ${n}`;return`${o}${s} ${n}`}function Qs(e,t,n,r,o){let s=Math.min(e.length,n),i=[];if(t>0)i.push(o("..."));for(let a=t;a<t+s;a++){let c=e[a];if(c===void 0)break;i.push(r(c,a))}if(t+s<e.length)i.push(o("..."));return i}function yn(e,t,n,r){let o=Math.min(n,r);if(e<t)return e;if(e>=t+o)return e-o+1;return t}function ei(e,t,n,r,o){let s=n===-1?e<=0?t-1:e-1:e>=t-1?0:e+1;return{cursor:s,scrollOffset:yn(s,r,t,o)}}function ti(e){return e.map((t)=>{if(typeof t==="string")return{label:t,value:t};return t})}function ni(e,t){if(e.name==="return")return Le(t.value);if(e.name==="left"||e.name==="right"||e.name==="tab")return{value:!t.value};if(e.name==="h"||e.char==="y"||e.char==="Y")return{value:!0};if(e.name==="l"||e.char==="n"||e.char==="N")return{value:!1};return t}var ri=" · ";function oi(e,t,n,r,o){let s=t.prefix("┃"),i=t.message(n??"Are you sure?"),a=e.value?`${t.selected("●")} ${t.selected(r)}`:`${t.unselected("○")} ${t.unselected(r)}`,c=e.value?`${t.unselected("○")} ${t.unselected(o)}`:`${t.selected("●")} ${t.selected(o)}`;return wn(s,i,`${a}${ri}${c}`)}function si(e,t,n,r,o,s){let i=n.success("✓"),a=n.message(r??"Are you sure?"),c=t?o:s;return We(i,a,n.success(c))}async function oe(e,t){let n=await ne(e,t);if(n.shortCircuited)return n.value;let{promptIO:r}=n,o=e.active??"Yes",s=e.inactive??"No";return ze({initialState:{value:e.default??!0},theme:e.theme,render:(i,a)=>oi(i,a,e.message,o,s),handleKey:ni,renderSubmitted:(i,a,c)=>si(i,a,c,e.message,o,s)},r)}async function ii(e,t,n){let r=await ne(e,n);if(r.shortCircuited)return r;let o=ti(e.choices),s=e.maxVisible??10,i=e.default===void 0?[]:t==="multiple"?e.default:[e.default],a=new Set(i.flatMap((u)=>{let f=o.findIndex((d)=>d.value===u);return f===-1?[]:[f]})),c=i.length===0?-1:o.findIndex((u)=>u.value===i[0]),l=c===-1?0:c;return{shortCircuited:!1,choices:o,maxVisible:s,cursor:l,scrollOffset:yn(l,0,o.length,s),selected:a,promptIO:r.promptIO}}async function vn(e,t,n){if(t){let r=await t["~standard"].validate(e),o=r.issues?.[0];if(o)return{ok:!1,error:o.message||"Validation failed"};if("value"in r)return{ok:!0,value:r.value};return{ok:!1,error:"Validation failed"}}if(n)try{await n(e)}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Validation failed"}}return{ok:!0,value:e}}async function ai(e,t,n){let r=await vn(t,e,void 0);if(!r.ok)throw Error(`${n} value rejected by schema: ${r.error}`);return r.value}function ci(e,t,n,r){if(e==="")return r?n.placeholder(r):n.cursor("│");return`${e.slice(0,t)}${n.cursor("│")}${e.slice(t)}`}function li(e,t,n){if(e.name==="backspace"){if(n===0)return{text:t,cursorPos:n};return{text:t.slice(0,n-1)+t.slice(n),cursorPos:n-1}}if(e.name==="delete"){if(n>=t.length)return{text:t,cursorPos:n};return{text:t.slice(0,n)+t.slice(n+1),cursorPos:n}}if(e.name==="left"){if(n===0)return{text:t,cursorPos:n};return{text:t,cursorPos:n-1}}if(e.name==="right"){if(n>=t.length)return{text:t,cursorPos:n};return{text:t,cursorPos:n+1}}if(e.name==="home")return{text:t,cursorPos:0};if(e.name==="end")return{text:t,cursorPos:t.length};if(e.char.length===1&&!e.ctrl&&!e.meta){let r=t.slice(0,n),o=t.slice(n);return{text:r+e.char+o,cursorPos:n+1}}return null}function ui(e,t,n){return async(r,o)=>{if(r.name==="return"){let i=await vn(o.value===""&&n!==void 0?n:o.value,e,t);return i.ok?Le(i.value):{...o,error:i.error}}let s=li(r,o.value,o.cursorPos);return s?{value:s.text,cursorPos:s.cursorPos,error:null}:o}}function fi(e,t,n,r,o){let s=t.prefix("┃"),i=t.message(n??"Enter a value"),a=r??o,c=o!==void 0&&r!==void 0&&e.value===""?` ${t.hint(`(${o})`)}`:"",l=wn(s,i,ci(e.value,e.cursorPos,t,a),c);if(e.error!==null)l+=`
18
- ${t.error(e.error)}`;return l}function di(e,t,n,r){return We(n.success("✓"),n.message(r??"Enter a value"),n.success(String(t)))}async function Sn(e={},t){if(e.schema!==void 0&&e.validate!==void 0)throw Error('input() cannot combine "schema" with "validate"');let n=e.schema,r=n?await ne(e,t,(s,i)=>ai(n,s,i)):await ne(e,t);if(r.shortCircuited)return r.value;let{promptIO:o}=r;return ze({initialState:{value:"",cursorPos:0,error:null},theme:e.theme,render:(s,i)=>fi(s,i,e.message,e.placeholder,e.default),handleKey:ui(e.schema,e.validate,e.default),renderSubmitted:(s,i,a)=>di(s,i,a,e.message)},o)}function mi(e){return(t,n)=>{let r=n.choices.length;if(t.name==="return"){let o=n.choices[n.cursor];if(o)return Le(o.value);return n}if(["up","down","k","j"].includes(t.name)){let o=t.name==="up"||t.name==="k"?-1:1;return{...n,...ei(n.cursor,r,o,n.scrollOffset,e)}}return n}}function gi(e,t,n,r){let o=[`${t.prefix("┃")} ${t.message(n??"Pick an option")}`];return o.push(...Qs(e.choices,e.scrollOffset,r,(s,i)=>{let a=s.hint?` ${t.hint(s.hint)}`:"";return i===e.cursor?`${t.cursor("›")} ${t.selected(s.label)}${a}`:` ${t.unselected(s.label)}${a}`},t.hint)),o.join(`
19
- `)}function pi(e,t,n,r){let o=n.success("✓"),s=n.message(r??"Pick an option"),i=e.choices[e.cursor],a=i?i.label:"";return We(o,s,n.success(a))}async function xn(e,t){let n=await ii(e,"single",t);if(n.shortCircuited)return n.value;let{choices:r,cursor:o,maxVisible:s,promptIO:i,scrollOffset:a}=n;return ze({initialState:{cursor:o,choices:r,scrollOffset:a},theme:e.theme,render:(c,l)=>gi(c,l,e.message,s),handleKey:mi(s),renderSubmitted:(c,l,u)=>pi(c,l,u,e.message)},i)}var On={name:"@crustjs/core",version:"0.4.1",description:"Core library for the Crust CLI framework",type:"module",sideEffects:!1,license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/core"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","command","framework","parser","bun","typescript"],files:["dist"],types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./tooling":{types:"./dist/tooling.d.ts",import:"./dist/tooling.js"}},publishConfig:{access:"public"},scripts:{build:"tsdown",dev:"tsdown --watch","check:types":"tsc --noEmit",test:"bun test",prepack:"cp ../../LICENSE LICENSE",postpack:"rm -f LICENSE"},dependencies:{"@crustjs/utils":"workspace:^"},devDependencies:{"@crustjs/config":"workspace:*",tsdown:"catalog:"},peerDependencies:{typescript:"^7.0.0"},peerDependenciesMeta:{typescript:{optional:!0}},engines:{bun:">=1.4.0",node:">=22",deno:">=2.8"}};var $n={name:"@crustjs/crust",version:"0.4.1",description:"CLI tooling for the Crust framework",type:"module",license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/crust"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","build","compile","standalone","bun","typescript"],publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},crust:{include:["schema","dist"]},bin:{crust:"src/cli.ts"},scripts:{build:"tsdown && bun src/cli.ts build",release:"bun src/cli.ts publish",dev:"bun src/cli.ts",start:"bun .crust/root/bin/crust.js","check:types":"tsc --noEmit",test:"bun test"},dependencies:{"@crustjs/core":"workspace:^","@crustjs/extensions":"workspace:^","@crustjs/style":"workspace:^"},peerDependencies:{"@crustjs/core":"^0.4.0"},devDependencies:{"@arethetypeswrong/core":"^0.18.5","@crustjs/config":"workspace:*","@crustjs/testing":"workspace:*","@crustjs/utils":"workspace:*",publint:"^0.3.24",tsdown:"catalog:"},engines:{bun:">=1.4.0"}};var Cn={name:"@crustjs/extensions",version:"0.4.1",description:"Official Extensions for the Crust CLI framework",type:"module",sideEffects:!1,license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/extensions"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","extension","help","version","completion","did-you-mean","bun","typescript"],files:["dist"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},publishConfig:{access:"public"},scripts:{build:"tsdown",dev:"tsdown --watch","check:types":"tsc --noEmit",test:"bun test",prepack:"cp ../../LICENSE LICENSE",postpack:"rm -f LICENSE"},dependencies:{"@crustjs/store":"workspace:^","@crustjs/style":"workspace:^","@crustjs/utils":"workspace:^"},devDependencies:{"@crustjs/config":"workspace:*","@crustjs/core":"workspace:*",tsdown:"catalog:"},peerDependencies:{"@crustjs/core":"workspace:^",typescript:"^7.0.0"},peerDependenciesMeta:{typescript:{optional:!0}},engines:{bun:">=1.4.0",node:">=22",deno:">=2.8"}};var Si={bun:{run:"bun run",shebang:"#!/usr/bin/env bun",tsLib:'"ESNext"',tsTypes:'"bun"'},node:{run:"npm run",shebang:"#!/usr/bin/env node",tsLib:'"ESNext"',tsTypes:'"node"'},deno:{run:"deno task",shebang:"#!/usr/bin/env -S deno run -A",tsLib:'"ESNext", "deno.window"',tsTypes:""}},xi={crustCoreVersion:On.version,crustExtensionsVersion:Cn.version,crustCliVersion:$n.version},Oi=/^[A-Za-z0-9_~][A-Za-z0-9._~-]*$/;function jn(e){if(e==="__proto__"||!Oi.test(e))throw Error(`Project name ${JSON.stringify(e)} is not safe for the generated project.
20
- The directory basename becomes the package and command name: use letters, digits, ".", "_", "~", and "-", not starting with "." or "-"; "__proto__" is reserved.`)}var $i=/[<>:"|?*\\]/;function Ci(e){if(!e)throw Error("Project directory cannot be empty");if($i.test(e))throw Error(`Project directory contains invalid characters: ${e}`);jn(In(Ue(e)))}var Ei=new X("create-crust",{description:"Scaffold a new Crust CLI project"}).flags({name:"runtime",type:"string",choices:["bun","node","deno"],description:'Runtime to develop and build for ("bun", "node", or "deno")'},{name:"install",type:"boolean",description:"Install dependencies after scaffolding"},{name:"git",type:"boolean",description:"Initialize a git repository after scaffolding"},{name:"overwrite",type:"boolean",description:"Overwrite the destination directory if it already exists"}).args({name:"directory",type:"string",description:"Project directory to scaffold into"}).action(async({args:e,flags:t})=>{let n=e.directory??await Sn({message:"Project directory",default:"my-cli",validate:Ci}),r=Ue(process.cwd(),n),o=In(r);jn(o);let s=t.runtime,i=n==="."?yi(r).length>0:En(r),a=!1;if(i){if(a=await oe({message:n==="."?"Current directory is not empty. Overwrite conflicting files?":`Directory "${o}" already exists. Overwrite?`,default:!1,...t.overwrite!==void 0?{initial:t.overwrite}:{}}),!a){console.log("Aborted.");return}}let c=await xn({message:"Runtime",choices:[{label:"Bun (recommended)",value:"bun",hint:"standalone binaries per platform, published as npm packages"},{label:"Node.js",value:"node",hint:"one JavaScript bundle, published as a single npm package"},{label:"Deno",value:"deno",hint:"standalone binaries per platform, published as npm packages"}],default:"bun",...s!==void 0?{initial:s}:{}}),l=await oe({message:"Install dependencies?",default:!0,...t.install!==void 0?{initial:t.install}:{}}),u=En(r)?r:Ue(r,".."),d=Bt(u)?!1:await oe({message:"Initialize a git repository?",default:!0,...t.git!==void 0?{initial:t.git}:{}}),b=o,g=(p)=>vi(ie("templates"),p),m={name:b,...Si[c],...xi};if(await De({message:"Scaffolding project...",task:async()=>{await Ee({template:g("base"),dest:r,context:m,...a?{conflict:"overwrite"}:{}}),await Ee({template:g(`runtime/${c}`),dest:r,context:m,conflict:"overwrite"})}}),l)await Ie([c==="deno"?{type:"command",cmd:"deno install"}:{type:"install"}],r);if(d)await De({message:"Initializing git repository...",task:()=>Ie([{type:"git-init",commit:"chore: initial commit"}],r)});if(console.log(`
4
+ `);o()}});return st.set(n,e),n}function he(e,t){let n=q.getStore();return pe({input:n?.input,output:n?.output&&!st.has(n.output)?n.output:lr(e)},t)}import{parseArgs as pr}from"node:util";import{isPromise as hr}from"node:util/types";function ot(e){let t=Number(e);return Number.isNaN(t)?void 0:t}function be(e){return e==="true"||e==="1"}import{homedir as br}from"node:os";function ur(e){return typeof e==="number"}function fr(e){return e.map((t,n)=>ur(t)?`[${t}]`:n>0?`.${String(t)}`:String(t)).join("")}function dr(e){return typeof e==="object"&&e!==null&&"key"in e}function mr(e){if(!e)return[];return e.map((t)=>dr(t)?t.key:t)}function it(e,t=[]){return e.map((n)=>{let r=mr(n.path),s=[...t,...r];return{message:n.message,path:fr(s)}})}var h=class extends Error{code;details;cause;constructor(e,t,...n){super(t);this.name="CrustError",this.code=e,this.details=n[0]}is(e){return Object.is(this.code,e)}withCause(e){return this.cause=e,this}toJSON(){return{code:this.code,message:this.message,details:this.details}}};function we(e,t){if(e==="")throw new h("DEFINITION",`Flag ${t} spellings must be non-empty`,{subject:"flag",name:e,reason:"empty-spelling"});if(t!=="short"&&e.startsWith("no-"))throw new h("DEFINITION",`Flag ${t} "${e}" must not start with "no-"; the prefix is reserved for boolean negation`,{subject:"flag",name:e,reason:"reserved-no-prefix"});if(e==="__proto__")throw new h("DEFINITION",`Flag ${t} "__proto__" is a reserved spelling`,{subject:"flag",name:e,reason:"reserved-spelling"})}function dt(e,t){return[e,...t.short===void 0?[]:[t.short],...t.aliases??[]]}function mt(e){return e.type==="boolean"&&e.noNegate!==!0}function gt(e){if(e.choices&&e.default!==void 0){let t="multiple"in e&&e.multiple?e.default:[e.default];for(let n of t)if(!e.choices.includes(n))throw new h("DEFINITION","default must be one of choices")}return Object.freeze({...e,..."aliases"in e&&e.aliases?{aliases:Object.freeze([...e.aliases])}:{},...e.choices?{choices:Object.freeze([...e.choices])}:{},..."env"in e&&e.env?{env:Object.freeze({name:e.env.name,delimiter:e.env.delimiter})}:{},..."multiple"in e&&e.multiple&&Array.isArray(e.default)?{default:Object.freeze([...e.default])}:{}})}function wr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&"name"in e&&typeof e.name==="string"&&(!("delimiter"in e)||e.delimiter===void 0||typeof e.delimiter==="string")}function pt(e,t){if(we(e,"canonical"),t.short!==void 0)we(t.short,"short");for(let r of t.aliases??[])we(r,"alias");let n=dt(e,t);if(new Set(n).size!==n.length)throw new h("DEFINITION",`Flag "${e}" repeats one of its own spellings`,{subject:"flag",name:e,reason:"flag-collision"});if(t.short!==void 0&&t.short.length!==1)throw new h("DEFINITION","Short flags must be one character");if(t.env!==void 0&&!wr(t.env))throw new h("DEFINITION",`Flag "${e}" env must be an object with a string name and optional string delimiter`,{subject:"flag",name:e,reason:"invalid-env"});if(t.env?.name==="")throw new h("DEFINITION",`Flag "${e}" env variable name must be non-empty`,{subject:"flag",name:e,reason:"empty-env"});for(let[r,s]of[["delimiter",t.delimiter],["env.delimiter",t.env?.delimiter]]){if(s===void 0)continue;if(!t.multiple)throw new h("DEFINITION",`Flag "${e}" ${r} requires multiple: true`,{subject:"flag",name:e,reason:"delimiter-without-multiple"});if(s==="")throw new h("DEFINITION",`Flag "${e}" ${r} must be non-empty`,{subject:"flag",name:e,reason:"empty-delimiter"})}return gt(t)}function ht(e){if(e.name==="")throw new h("DEFINITION","Argument names must be non-empty",{subject:"argument",name:e.name,reason:"empty-name"});return gt(e)}function bt(e){return e.meta.hidden!==!0}var yr={command:"Command",context:"Context",extension:"Extension"};function vr({subject:e,name:t}){let n=yr[e];return new h("DEFINITION",`${n} "${t}" contains invalid documentation sections`,{subject:e,name:t,reason:"invalid-sections"})}function wt(e,t){let{title:n,body:r,only:s,except:o}=e;if(!n.trim()||/[\r\n]/.test(n)||!r.trim()||s?.length===0||o?.length===0||s!==void 0&&o!==void 0)throw vr(t);let i=(a)=>Object.freeze(a.map((c)=>typeof c==="string"?c:c.id));return Object.freeze({title:n,body:r,...s?{only:i(s)}:o?{except:i(o)}:{}})}function Ee(e,t,n="command"){return t.map((r)=>wt(r,{subject:n,name:e}))}var xr=Symbol("crust.defining");function Y(e){return e[xr]}var yt=Symbol.for("crust.contextSources");function J(e,t){let n=new Set(e.map((o)=>o.name)),r=new Set,s=(o)=>{if(r.has(o))return;r.add(o);let i="contextName"in o?o.contextName:o.name;if(!n.has(i))throw new h("DEFINITION",`No provider for Context "${i}"`,{subject:"context",name:i,reason:"missing-context"});for(let a of o.use)s(a)};for(let o of t)s(o)}function Sr(e){return typeof e==="function"}var $r=class{#e=[];#t=!1;#n(){if(this.#t)throw ReferenceError("AsyncDisposableStack is already disposed")}use(e){this.#n();let t=Er(e)?e[Symbol.asyncDispose]:e[Symbol.dispose];return this.#e.push(()=>t.call(e)),e}defer(e){if(this.#n(),!Sr(e))throw TypeError("defer callback is not callable");this.#e.push(e)}async[Symbol.asyncDispose](){if(this.#t)return;this.#t=!0;let e=[];for(let t=this.#e.length-1;t>=0;t--)try{await this.#e[t]()}catch(n){e.push(n)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Disposal failed")}},Or=globalThis.AsyncDisposableStack??$r;function Er(e){return typeof e[Symbol.asyncDispose]==="function"}function Ir(e){if(e===null||typeof e!=="object"&&typeof e!=="function")return!1;let t=e;return typeof t[Symbol.asyncDispose]==="function"||typeof t[Symbol.dispose]==="function"}function Cr(e,t,n){if(!Ir(e)||n.has(e))return;n.add(e),t.use(e)}function _r(e,t,n,r){let s=new Map(e.map((g)=>[g.name,g])),o=new Map,i=new WeakSet,a,c=!0,l=!1;n.defer(()=>{l=!0});let u=(g,p,w=new Set)=>{if(g.name===p)return[g.name];if(w.has(g.name))return;w.add(g.name);for(let S of g.waitingOn){let x=o.get(S);if(!x)continue;let C=u(x,p,w);if(C)return[g.name,...C]}},f=(g)=>{try{let p=new Set;for(let w=g;w!=null&&!p.has(w);w=w.cause)if(p.add(w),w instanceof h&&w.code==="DEFINITION"&&w.details?.reason==="flags-before-validation")return!0;return!1}catch{return!1}};function d(g){let p=Promise.reject(g);return p.catch(()=>{}),p}let m=(g)=>(p)=>{let w=g?` (pulled while constructing Context "${g.name}")`:"";if(l)return d(new h("DEFINITION",`Context "${p}" cannot be pulled from onError because invocation Contexts have already been disposed.`,{subject:"context",name:p,reason:"context-after-disposal"}));let S=s.get(p);if(!S)return d(new h("DEFINITION",`No provider for Context "${p}". Add .provide(${p}(...)) to the app or an ancestor command.${w}`,{subject:"context",name:p,reason:"missing-context"}));if(!c&&!o.has(p))return d(new h("DEFINITION",`Context "${p}" cannot be constructed during invocation cleanup. Read it while setting up the Context whose cleanup needs it.`,{subject:"context",name:p,reason:"context-during-disposal"}));if(a===void 0&&Object.keys(S.ownedFlags).length>0)return d(new h("DEFINITION",`Context "${p}" owns flags and cannot be pulled before flag validation${w}. Pull it from an action or a postRun hook after a validated invocation.`,{subject:"context",name:p,reason:"flags-before-validation"}));let x=o.get(p);if(!x){let C=Promise.withResolvers();C.promise.catch(()=>{}),x={name:p,promise:C.promise,resolve:C.resolve,reject:C.reject,waitingOn:new Set,settled:!1},o.set(p,x);let O=x;(async()=>{try{let E=Object.fromEntries(Object.keys(S.ownedFlags).map((I)=>[I,a?.[I]])),_=await S.setup({...t,signal:r,flags:E,ctx:b(S.use,O),defer(I){if(O.settled)throw new h("DEFINITION",`Context "${p}" cannot register cleanup after its setup has finished.`,{subject:"context",name:p,reason:"context-defer-after-setup"});n.defer(I)}});Cr(_,n,i),O.resolve(_)}catch(E){if(f(E))o.delete(p);O.reject(E)}finally{O.settled=!0}})()}if(g&&!x.settled){let C=u(x,g.name);if(C)return d(new h("DEFINITION",`Context dependency cycle: ${[g.name,...C].map((O)=>`"${O}"`).join(" -> ")}`,{subject:"context",name:g.name,reason:"context-cycle"}));return g.waitingOn.add(p),x.promise.finally(()=>g.waitingOn.delete(p))}return x.promise},b=(g,p)=>{let w={},S=(x)=>{let C="contextName"in x?x.contextName:x.name;if(Object.hasOwn(w,C))return;Object.defineProperty(w,C,{enumerable:!0,get:()=>m(p)(C)});for(let O of x.use??[])S(O)};for(let x of g)S(x);return Object.defineProperty(w,yt,{value:Object.freeze([...g])}),Object.freeze(w)};return{bag:(g)=>b(g,null),setValidatedFlags(g){a=g},async settle(){for(;;){let g=[...o.values()].filter((p)=>!p.settled);if(g.length===0){c=!1;return}await Promise.allSettled(g.map((p)=>p.promise))}}}}var jr=Object.freeze({[Symbol("crust.finished")]:!0});function xe(){return jr}function vt(e){return{meta:{name:e},localFlags:{},ownedFlags:{},effectiveFlags:{},flagSpellings:new Map,args:[],subCommands:{},contexts:[],providedContexts:[],demands:[],extensions:[],run:void 0}}function N(e,t,n,r){n=pt(t,n);let s=dt(t,n),o=Object.hasOwn(e.effectiveFlags,t)?t:s.map((a)=>e.flagSpellings.get(a)?.canonicalName).find((a)=>a!==void 0);if(o!==void 0)throw new h("DEFINITION",`Flag "${t}" collides with existing flag "${o}" on command "${e.meta.name}"`,{subject:"flag",name:t,reason:"flag-collision"});(r==="local"?e.localFlags:e.ownedFlags)[t]=n,e.effectiveFlags[t]=n;let i={canonicalName:t,def:n,negatable:mt(n)};if(e.flagSpellings.set(t,{...i,kind:"canonical"}),n.short!==void 0)e.flagSpellings.set(n.short,{...i,kind:"short"});for(let a of n.aliases??[])e.flagSpellings.set(a,{...i,kind:"alias"})}function xt(e,t,n,r){if(N(e,t,n,"owned"),!r)return;for(let s of Object.values(e.subCommands))xt(s,t,n,!0)}function kr(e,t,n){for(let r of t.commands)e.subCommands[r.name]=n(r,e,t.id)}function Nr(e,t){for(let[n,r]of Object.entries(t.flags)){let{recursive:s=!0,...o}=r;xt(e,n,o,s)}}function X(e){return{localFlags:{...e.localFlags},ownedFlags:{...e.ownedFlags},effectiveFlags:{...e.effectiveFlags},flagSpellings:new Map(e.flagSpellings)}}function M(e){let t={};for(let[n,r]of Object.entries(e.subCommands))t[n]=M(r);return{...e,meta:{...e.meta},...X(e),args:[...e.args],subCommands:t,contexts:e.contexts.map((n)=>({...n})),providedContexts:[...e.providedContexts],demands:[...e.demands],extensions:[...e.extensions],run:e.run}}function Ar(e,t,n){let r=e;for(let s of t){let o=Object.hasOwn(r.subCommands,s)?r.subCommands[s]:void 0;if(!o)throw new h("DEFINITION",`Extension "${n.id}" section target "${t.join(" ")}" is not a canonical command path`,{subject:"extension",name:n.id,reason:"invalid-section-path"});r=o}return r}function Tr(e,t,n){if(!t.sections)return;let r={subject:"extension",name:t.id},s=t.sections(n);for(let o of s){let i=wt(o,r),a=Ar(e,o.command,t);a.meta.sections=[...a.meta.sections??[],i]}}function Fr(e,t){let n=(r,s,o)=>{let i=[...new Map(o.map((a)=>[a.name,a])).values()];if(i.some((a)=>a.sections.length>0)){let a=new Set((r.meta.sections??[]).map(({title:c})=>c));for(let c of i){for(let{title:l}of c.sections)if(a.has(l))throw new h("DEFINITION",`Context "${c.name}" section "${l}" duplicates a section on command "${s}"`,{subject:"context",name:c.name,reason:"duplicate-section"});for(let{title:l}of c.sections)a.add(l)}r.meta.sections=[...r.meta.sections??[],...i.flatMap((c)=>c.sections)]}for(let[a,c]of Object.entries(r.subCommands))n(c,`${s} ${a}`,c.providedContexts)};n(e,e.meta.name,[...e.providedContexts,...t.flatMap((r)=>r.provide)])}function St(e,t,n){let r=M(e),s=new Set(t.flatMap((i)=>!n.has(i.id)&&e.extensions.includes(i)?[i.id]:[])),o=(i)=>{i.contexts=i.contexts.filter((u)=>u.extensionId===void 0||s.has(u.extensionId));let a=Object.keys(i.effectiveFlags),c=i.localFlags,l={};for(let{instance:u}of i.contexts)Object.assign(l,u.ownedFlags);i.localFlags={},i.ownedFlags={},i.effectiveFlags={},i.flagSpellings=new Map;for(let u of a){let f=Object.hasOwn(l,u)?"owned":"local",d=f==="owned"?l:c;if(Object.hasOwn(d,u))N(i,u,d[u],f)}for(let u of Object.values(i.subCommands))o(u)};o(r);for(let i of t){if(s.has(i.id))continue;let a=i.provide;if(a.length===0)continue;let c=(l,u)=>{let f=a.filter((b)=>!u.has(b.name)),d=f.map((b)=>({instance:b,extensionId:i.id}));l.contexts.push(...d);for(let b of f)for(let[g,p]of Object.entries(b.ownedFlags))N(l,g,p,"owned");let m=new WeakSet(l.contexts.map(({instance:b})=>b));for(let b of Object.values(l.subCommands)){let g=new Set(u);for(let{instance:p}of b.contexts)if(!m.has(p))g.add(p.name);c(b,g)}};c(r,new Set)}return r}function Pr(e){try{return new URL(e)}catch{throw new h("PARSE",`Invalid URL "${e}"${/^[a-z][a-z0-9+.-]*:/i.test(e)?"":" (missing protocol — e.g. https://example.com)"}`)}}function H(e){if(e==="")throw new h("PARSE","Path cannot be empty");let t=e.replace(/^~(?=\/|$)/,br());return gr(process.cwd(),t)}function Rr(e){try{return JSON.parse(e)}catch(t){throw new h("PARSE",`Invalid JSON: ${t instanceof Error?t.message:String(t)}. Tip: wrap JSON in single quotes on the command line, e.g. --flag '{"k":1}'`)}}async function at(e,t,n,r){let s=await e["~standard"].validate(t);if(s.issues)return r.push(...it(s.issues,n)),{ok:!1};return{ok:!0,value:s.value}}async function Dr(e,t){let n=[],r=new Map(Object.entries(t.args)),s=new Map(Object.entries(t.flags));for(let o of e.args){if(o.schema===void 0)continue;let i=await at(o.schema,r.get(o.name),["args",o.name],n);if(i.ok)r.set(o.name,i.value)}for(let[o,i]of Object.entries(e.effectiveFlags)){if(i.schema===void 0)continue;let a=await at(i.schema,s.get(o),["flags",o],n);if(a.ok)s.set(o,a.value)}if(n.length>0)throw new h("VALIDATION",`Invalid input:
5
+ ${n.map((o)=>` - ${o.path}: ${o.message}`).join(`
6
+ `)}`,{issues:n});return{args:Object.fromEntries(r),flags:Object.fromEntries(s)}}function Mr(e){let t={};for(let[n,r]of e){if(r.kind==="short")continue;let s={type:r.def.type==="boolean"?"boolean":"string"};if(r.def.multiple)s.multiple=!0;if(r.kind==="canonical"&&r.def.short)s.short=r.def.short;t[n]=s}return t}function $t(e,t,n){if(t==="number"){let r=ot(e);if(r===void 0)throw new h("PARSE",`Expected number for ${n}, got "${e}"`);return r}if(t==="boolean")return be(e);if(t==="url")return Pr(e);if(t==="path")return H(e);if(t==="json")return Rr(e);return e}function Ie(e,t,n){if(!t.includes(e))throw new h("PARSE",`Invalid value "${e}" for ${n}. Expected one of: ${t.join(", ")}`)}function D(e,t,n,r){let s=r===void 0?n:`${n} element [${r}]`,o;try{if(o=e(t),hr(o))throw o.catch(()=>{}),Error("parse must be synchronous")}catch(i){throw new h("PARSE",`Failed to parse ${s}: ${i instanceof Error?i.message:String(i)}`).withCause(i)}return o}function Se(e,t){let{default:n,parse:r}=e;if(n===void 0)return;if(r){if(Array.isArray(n))return n.map((s,o)=>D(r,String(s),t,o));return D(r,String(n),t)}if(e.type==="path"){if(Array.isArray(n))return n.map((s)=>H(String(s)));return H(String(n))}return"multiple"in e&&e.multiple&&Array.isArray(n)?[...n]:n}function Br(e,t,n){if(n.kind==="boolean")return n.value;let r=`--${e}`,s=(o,i)=>{if(t.choices)Ie(o,t.choices,r);if(t.parse)return D(t.parse,o,r,i);return $t(o,t.type,r)};return Array.isArray(n.value)?n.value.map(s):s(n.value)}function Lr(e,t){let n={};for(let r of e){if(r.kind!=="option")continue;let{canonicalName:s,def:o}=t.get(r.name),i=n[s];if(o.type==="boolean"){let a=!r.rawName.startsWith("--no-");if(o.multiple&&i?.kind==="boolean"&&Array.isArray(i.value))i.value.push(a);else n[s]={kind:"boolean",value:o.multiple?[a]:a}}else{let a=r.value;if(o.multiple&&i?.kind==="string"&&Array.isArray(i.value))i.value.push(a);else n[s]={kind:"string",value:o.multiple?[a]:a}}}return n}function Ot(e,t){if(t===void 0)return[...e];return e.flatMap((n)=>n.split(t)).filter((n)=>n!=="")}function zr(e,t,n){let r=t.multiple?Ot([n],t.env?.delimiter):[n];if(t.multiple&&r.length===0)return;if(t.type!=="boolean")return{kind:"string",value:t.multiple?r:n};let s=r.map(be);if("noNegate"in t&&t.noNegate&&s.includes(!1))throw new h("PARSE",`Flag "--${e}" does not support negation (from ${t.env?.name})`);return{kind:"boolean",value:t.multiple?s:s[0]}}function Wr(e,t,n){let r={};for(let[s,o]of Object.entries(e)){let i=Object.hasOwn(t,s)?t[s]:void 0;if(i!==void 0){if(o.delimiter!==void 0&&i.kind==="string"&&Array.isArray(i.value)){let c=Ot(i.value,o.delimiter);r[s]=c.length===0?void 0:{kind:"string",value:c}}else r[s]=i;continue}if(o.env===void 0||!Object.hasOwn(n,o.env.name))continue;let a=n[o.env.name];if(a!==void 0)r[s]=zr(s,o,a)}return r}function Ur(e,t,n){let r={};for(let s of Object.keys(t))if(!Object.hasOwn(e,s)&&t[s]!==void 0)throw new h("PARSE",`Unknown flag "--${s}"`,{flag:s,reason:"unknown-flag"});for(let[s,o]of Object.entries(e)){let i=Object.hasOwn(t,s)?t[s]:void 0;if(!(i===void 0||o.multiple&&Array.isArray(i)&&i.length===0)){r[s]=n(s,o,i);continue}r[s]=Se(o,`--${s}`)}return r}function Vr(e,t){for(let[n,r]of Object.entries(e))if(r.required===!0&&r.default===void 0){if(t[n]===void 0)throw new h("VALIDATION",`Missing required flag "--${n}"`)}}function qr(e,t,n,r){if(e.schema)return t;if(e.choices)Ie(t,e.choices,n);if(e.parse)return D(e.parse,t,n,r);return $t(t,e.type,n)}function Gr(e,t,n){let r={},s=0;for(let o of e){let{name:i}=o,a=`<${i}>`;if(Object.defineProperty(r,i,{value:void 0,writable:!0,enumerable:!0,configurable:!0}),o.variadic){let c=t.slice(s);r[i]=c.length===0&&o.default!==void 0?[Se(o,a)]:c.map((l,u)=>n(o,l,a,u)),s=t.length}else if(s<t.length)r[i]=n(o,t[s],a),s++;else r[i]=Se(o,a)}return{args:r,consumed:s}}function Hr(e,t){for(let n of e){if(n==="--")return;if(!n.startsWith("--no-"))continue;let r=n.indexOf("="),s=r===-1?n.slice(5):n.slice(5,r),o=t.get(s);if(!o||o.def.type!=="boolean"||o.negatable)continue;throw new h("PARSE",`Flag "--${o.canonicalName}" does not support negation ("--no-${s}")`)}}function Kr(e,t){let n=e.flagSpellings,r=Mr(n);Hr(t,n);let s;try{s=pr({args:t,options:r,strict:!0,allowPositionals:!0,allowNegative:!0,tokens:!0})}catch(c){if(c instanceof Error){let l=c.message.match(/Unknown option '(.+?)'/);if(l)throw new h("PARSE",`Unknown flag "${l[1]}"`).withCause(c);if("code"in c&&c.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"&&c.message.length>0)throw new h("PARSE",c.message).withCause(c)}throw new h("PARSE","Failed to parse command arguments").withCause(c)}let o=[],i=[],a=!1;for(let c of s.tokens){if(c.kind==="option-terminator"){a=!0;continue}if(c.kind==="positional")(a?o:i).push(c.value)}return{positionals:i,flagValues:Lr(s.tokens,n),rawArgs:o}}function Yr(e,t,n){let r=e.schema?e.type==="boolean"?"boolean":"string":e.type,s;if(r==="url")s=t instanceof URL;else if(r==="json"){let o=[t],i=new Set;s=!0;while(o.length>0){let a=o.pop();if(a instanceof URL){s=!1;break}if(Array.isArray(a)&&!i.has(a))i.add(a),o.push(...a)}}else s=typeof t===(r==="path"?"string":r);if(!s)throw new h("PARSE",`Expected ${r} for ${n}`);if(t===!1&&"noNegate"in e&&e.noNegate)throw new h("PARSE",`Flag "${n}" does not support negation`)}function $e(e,t,n,r){if(Yr(e,t,n),e.choices)Ie(String(t),e.choices,n);if(e.parse)return D(e.parse,String(t),n,r);if(e.type==="path")return H(String(t));return t}function Jr(e,t,n){let r=`--${e}`;if(t.multiple){if(!Array.isArray(n))throw new h("PARSE",`Expected an occurrence array for ${r}`);return n.map((s,o)=>$e(t,s,r,o))}return $e(t,n,r)}function Et(e,t,n,r,s){let o=Ur(e.effectiveFlags,n,s);return{...Gr(e.args,t,r),flags:o}}function Xr(e,t,n=process.env){let{positionals:r,flagValues:s,rawArgs:o}=Kr(e,t),{args:i,flags:a,consumed:c}=Et(e,r,Wr(e.effectiveFlags,s,n),qr,Br);return{args:i,flags:a,excessArgs:r.slice(c),rawArgs:o}}function Zr(e,t){let{args:n,flags:r,raw:s}=t,o=[],i;for(let l of e.args){let u=n&&Object.hasOwn(n,l.name)?n[l.name]:void 0;if(u===void 0){i=l.name;continue}if(i!==void 0)throw new h("PARSE",`Argument <${l.name}> cannot be provided after omitted argument <${i}>`,{argument:l.name,reason:"positional-gap"});if(l.variadic){if(!Array.isArray(u))throw new h("PARSE",`Expected an occurrence array for <${l.name}>`);o.push(...u)}else o.push(u)}for(let l of Object.keys(n??{}))if(!e.args.some((u)=>u.name===l)&&n?.[l]!==void 0)throw new h("PARSE",`Unknown argument "${l}"`,{argument:l,reason:"unknown-argument"});let{args:a,flags:c}=Et(e,o,r??{},$e,Jr);return{args:a,flags:c,excessArgs:[],rawArgs:[...s??[]]}}function Qr(e,t){let{args:n,effectiveFlags:r}=e,{args:s,flags:o}=t;if(t.excessArgs.length>0)throw new h("VALIDATION",`Unexpected positional argument${t.excessArgs.length===1?"":"s"}: ${t.excessArgs.map((i)=>JSON.stringify(i)).join(", ")}`);for(let i of n){let{name:a}=i,c=`argument "<${a}>"`,l=s[a];if(i.required===!0&&i.default===void 0){if(i.variadic){if(!Array.isArray(l)||l.length===0)throw new h("VALIDATION",`Missing required ${c}`)}else if(l===void 0)throw new h("VALIDATION",`Missing required ${c}`)}}Vr(r,o)}function K(e){for(let t of Object.keys(e))if(e[t]===void 0)delete e[t];return Object.freeze(e)}function Ce(e){if(e instanceof URL)return e.href;if(Array.isArray(e))return Object.freeze(e.map(Ce));return e}function es(e){return K({name:e.name,type:e.type,description:e.description,required:e.required,variadic:e.variadic,choices:e.choices?Object.freeze([...e.choices]):void 0,default:Ce(e.default)})}function ts(e){return K({type:e.type,description:e.description,short:e.short,aliases:e.aliases?Object.freeze([...e.aliases]):void 0,required:e.required,multiple:e.multiple,negatable:mt(e),noNegate:"noNegate"in e?e.noNegate:void 0,choices:e.choices?Object.freeze([...e.choices]):void 0,default:Ce(e.default),env:e.env?K({name:e.env.name,delimiter:e.env.delimiter}):void 0,delimiter:e.delimiter})}function j(e){let t={};for(let[r,s]of Object.entries(e.effectiveFlags))t[r]=ts(s);let n={};for(let[r,s]of Object.entries(e.subCommands))n[r]=j(s);return Object.freeze({meta:K({name:e.meta.name,description:e.meta.description,version:e.meta.version,usage:e.meta.usage,sections:e.meta.sections?Object.freeze(e.meta.sections.map((r)=>Object.freeze({...r}))):void 0,aliases:e.meta.aliases?Object.freeze([...e.meta.aliases]):void 0,hidden:e.meta.hidden}),hasAction:e.run!==void 0,args:Object.freeze(e.args.map(es)),flags:Object.freeze(t),subCommands:Object.freeze(n)})}function ns(e,t){for(let[n,r]of Object.entries(e)){let s=r.meta.aliases;if(!s)continue;if(s.includes(t))return{canonicalName:n,node:r}}return null}function ct(e,t){if(t==="--")return null;if(t.startsWith("--")){let r=t.indexOf("="),s=r===-1?t.slice(2):t.slice(2,r),o=e.get(s);if(o)return{consumesValue:o.def.type!=="boolean"&&r===-1};if(s.startsWith("no-")){if(e.get(s.slice(3))?.negatable)return{consumesValue:!1}}return null}let n=t.slice(1);if(n.length===0)return null;for(let r=0;r<n.length;r++){let s=e.get(n[r]);if(!s)return null;if(s.def.type!=="boolean")return{consumesValue:r===n.length-1}}return{consumesValue:!1}}function It(e,t){let n=[e.meta.name],r=e,s=t,o=[],i=[],a=(c,l)=>{if(i.length===0)return;let u=c.flagSpellings;for(let{token:f,consumesValue:d}of i){let m=ct(u,f);if(m!==null&&m.consumesValue===d)continue;throw new h("PARSE",`Flag "${f}" cannot be used before subcommand "${l}" because "${l}" does not accept it.`,{flag:f,reason:"flag-not-forwardable"})}};while(s.length>0){let c=r.subCommands;if(Object.keys(c).length===0)break;let l=s[0];if(!l)break;if(l.startsWith("-")){let d=ct(r.flagSpellings,l);if(!d)break;o.push(l),i.push({token:l,consumesValue:d.consumesValue}),s=s.slice(1);let m=s[0];if(d.consumesValue&&m!==void 0)o.push(m),s=s.slice(1);continue}if(Object.hasOwn(c,l)&&c[l]){a(c[l],l),r=c[l],n.push(l),s=s.slice(1);continue}let u=ns(c,l);if(u){a(u.node,l),r=u.node,n.push(u.canonicalName),s=s.slice(1);continue}if(r.run)break;let f=j(r);throw new h("COMMAND_NOT_FOUND",`Unknown command "${l}".`,{input:l,available:Object.entries(f.subCommands).flatMap(([d,m])=>bt(m)?[d]:[]),commandPath:[...n],parentCommand:f})}return{command:r,argv:[...o,...s],commandPath:n}}function rs(){var e=typeof SuppressedError=="function"?SuppressedError:function(s,o){var i=Error();return i.name="SuppressedError",i.error=s,i.suppressed=o,i},t={},n=[];function r(s,o){if(o!=null){if(Object(o)!==o)throw TypeError("using declarations can only be used with objects, functions, null, or undefined.");if(s)var i=o[Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose")];if(i===void 0&&(i=o[Symbol.dispose||Symbol.for("Symbol.dispose")],s))var a=i;if(typeof i!="function")throw TypeError("Object is not disposable.");a&&(i=function(){try{a.call(o)}catch(l){return Promise.reject(l)}}),n.push({v:o,d:i,a:s})}else s&&n.push({d:o,a:s});return o}return{e:t,u:r.bind(null,!1),a:r.bind(null,!0),d:function(){var o,i=this.e,a=0;function c(){for(;o=n.pop();)try{if(!o.a&&a===1)return a=0,n.push(o),Promise.resolve().then(c);if(o.d){var u=o.d.call(o.v);if(o.a)return a|=2,Promise.resolve(u).then(c,l)}else a|=1}catch(f){return l(f)}if(a===1)return i!==t?Promise.reject(i):Promise.resolve();if(i!==t)throw i}function l(u){return i=i!==t?new e(u,i):u,c()}return c()}}}var lt=()=>{};function ut(e,t){let n=()=>{if(e.listenerCount("error")===0)e.once("error",lt)};try{n(),e.write(`${t}
7
+ `,(r)=>{if(r)n()})}catch{}finally{e.removeListener("error",lt)}}var ss={stdout:(e)=>ut(process.stdout,e),stderr:(e)=>ut(process.stderr,e)};var R=130;function ye(e){if(!(e instanceof Error))return!1;return e.name==="AbortError"}function Ct(e){return _t(e)&&"error"in e&&"suppressed"in e&&e.name==="SuppressedError"}function _t(e){return typeof e==="object"&&e!==null}function Oe(e,t="Error"){let n=[],r=new Set,s=256,o=!1,i=(c)=>{if(o)return;if(s===0){o=!0,n.push("[additional failures omitted]");return}s--;let l;try{l=c()}catch{n.push("[unreadable failure]");return}a(l)},a=(c)=>{try{if(_t(c)){if(r.has(c))return;r.add(c)}let l=n.length;if(Ct(c)){if(i(()=>c.error),i(()=>c.suppressed),n.length>l)return}else if(c instanceof AggregateError){let u=c.errors;if(Array.isArray(u)){for(let f=0;f<u.length;f++)if(i(()=>u[f]),o)break;if(n.length>l)return}}n.push(String(c instanceof Error&&c.message||c))}catch{n.push("[unreadable failure]")}};return i(()=>e),n.map((c)=>`${t}: ${c}`).join(`
8
+ `)}function jt(e){if(Object.freeze(e),Object.freeze(e.localFlags),Object.freeze(e.ownedFlags),Object.freeze(e.effectiveFlags),e.meta.sections)Object.freeze(e.meta.sections);Object.freeze(e.meta),Object.freeze(e.contexts),Object.freeze(e.extensions),Object.freeze(e.args);for(let t of Object.values(e.subCommands))jt(t);Object.freeze(e.subCommands)}function os(e){return typeof e==="symbol"}var ft=new WeakMap;function is(e,t){let n=M(e),r=Object.freeze([...e.extensions]);for(let s of r)kr(n,s,t);for(let s of r)Nr(n,s);return{rootNode:n,extensions:r}}function as(e,t){if(Fr(e,t),t.some((n)=>n.sections!==void 0)){let n=j(e);for(let r of t)Tr(e,r,n)}return jt(e),e}function B(e,t){let n=ft.get(e);if(n)return n;let r=is(e,t);return as(r.rootNode,r.extensions),ft.set(e,r),r}function cs(e,t){let n=It(e,[...t]);return{argv:t,route:n,parsed:Xr(n.command,n.argv)}}function _e(e,t){let n=It(e,[...t]);if(n.argv.length>0){let r=n.argv[0],s=j(n.command);throw new h("COMMAND_NOT_FOUND",`Unknown command "${r}".`,{input:r,available:Object.entries(s.subCommands).flatMap(([o,i])=>bt(i)?[o]:[]),commandPath:n.commandPath,parentCommand:s})}return n}function ls(e,t,n){let r=_e(e,t);return{argv:t,route:r,parsed:Zr(r.command,n)}}async function kt(e,t,n,r,s,o){try{var i=rs();let{rootNode:a,extensions:c}=t,{argv:l,route:u,parsed:f}="argv"in e?cs(a,e.argv):ls(a,e.path,e.input),d=u.command,m=i.a(new Or),b=d.contexts.map(({instance:E})=>E),g=_r(b,n,m,r),p=j(a),w=p;for(let E of u.commandPath.slice(1))w=w.subCommands[E];let S=Object.freeze({argv:[...l],rootCommand:p,command:w,commandPath:Object.freeze([...u.commandPath]),args:f.args,flags:f.flags,rawArgs:f.rawArgs,signal:r,ctx:g.bag(c.flatMap((E)=>E.use)),finish:xe,stdout:n.stdout,stderr:n.stderr});s?.(S);let x=async()=>{Qr(d,f);let E=await Dr(d,f);if(g.setValidatedFlags(E.flags),!d.run)return;let _={args:E.args,flags:E.flags,ctx:g.bag(b),rawArgs:f.rawArgs,signal:r,command:S.command,rootCommand:p,stdout:n.stdout,stderr:n.stderr};return await d.run(_)},C,O={status:"completed"};try{try{for(let I of c)if(await I.hooks?.preRun?.(S)===xe()){O={status:"finished",by:I.id};break}if(O.status!=="finished")C=await x()}catch(I){let A=await o?.(I,S);O={status:"failed",error:I,...A===void 0?{}:{by:A}}}Object.freeze(O);let E=!1,_;for(let I of c.toReversed())try{await I.hooks?.postRun?.(S,O)}catch(A){if(O.status!=="failed"&&!E)E=!0,_=A}if(O.status==="failed")throw O.error;if(E)throw _}finally{await g.settle()}return O.status==="finished"?{status:"finished",by:O.by}:{status:"completed",result:C}}catch(a){i.e=a}finally{await i.d()}}async function ve(e,t,n,r,s,o,i=!1){let a=()=>{if(i)return;r.stderr(Oe(e))};function c(f){return Promise.reject(new h("DEFINITION",`Context "${String(f)}" cannot be pulled from onError because invocation Contexts have already been disposed.`,{subject:"context",name:String(f),reason:"context-after-disposal"}))}let l=new Proxy({},{get:(f,d)=>d==="then"||os(d)?void 0:c(d)}),u=o;if(!u){let f=j(n.rootNode);u=Object.freeze({argv:[...t],rootCommand:f,command:f,commandPath:Object.freeze([n.rootNode.meta.name]),args:Object.freeze({}),flags:Object.freeze({}),rawArgs:[],signal:s,finish:xe,stdout:r.stdout,stderr:r.stderr,ctx:l})}try{for(let f of n.extensions)if(await f.hooks?.onError?.(e,u))return f.id}catch{}a()}function us(e){return e!==void 0&&Object.keys(e).length>0}async function je(e,t,n,r){let s=[],o=[];try{let{signal:i=new AbortController().signal,...a}=n??{},c={stdout(l){s.push(l),a.stdout?.(l)},stderr(l){o.push(l),a.stderr?.(l)}};return{...await he(c,async()=>await kt(t,B(e,r),c,i)),stdout:s.join(`
9
+ `),stderr:o.join(`
10
+ `)}}catch(i){return{status:"failed",error:i,stdout:s.join(`
11
+ `),stderr:o.join(`
12
+ `)}}}async function Nt(e,t,n){let r=t?.argv??process.argv.slice(2),s={...ss,...t?.io},o=new AbortController,i=t?.signal?AbortSignal.any([t.signal,o.signal]):o.signal;if(!me());let a=async()=>{let c;try{c=B(e,n)}catch(m){if(ye(m))return process.exitCode=R,R;return s.stderr(Oe(m)),process.exitCode=1,1}let l=()=>{if(!o.signal.aborted){o.abort(new DOMException("Interrupted by SIGINT.","AbortError"));return}if(process.removeListener("SIGINT",l),process.listenerCount("SIGINT")===0)process.kill(process.pid,"SIGINT")};process.on("SIGINT",l);let u,f=!1,d;try{await kt({argv:r},c,s,i,(m)=>{u=m},async(m,b)=>{f=!0,d=m;let g=ye(m);return process.exitCode=g?R:1,ve(m,r,c,s,i,b,g)})}catch(m){let b;try{if(f&&!Object.is(m,d)&&Ct(m)&&Object.is(m.suppressed,d))b={error:m.error}}catch{}if(b)s.stderr(Oe(b.error,"Cleanup failed"));if(ye(m)){if(!f)await ve(m,r,c,s,i,u,!0);return process.exitCode=R,R}if(process.exitCode=1,!f)await ve(m,r,c,s,i,u);return 1}finally{process.removeListener("SIGINT",l)}return 0};return await(us(t?.io)?he(s,a):a())}var Ne=Symbol.for("crust.commandDefinition");function T(e,t,n){let r=e[Ne],s=e.name,o=n?`Extension "${n}" command "${s}"`:`Command "${s}"`,i=(u)=>({subject:n?"extension":"command",name:n??s,reason:u}),a=new Z(s);for(let[u,f]of Object.entries(t.ownedFlags))N(a._node,u,f,"owned");a._node.contexts=t.contexts.map((u)=>({...u}));let c=r.recipe(a);if(!(c instanceof Z)||c._ancestorOwnedFlags!==a._ancestorOwnedFlags)throw new h("DEFINITION",`${o} definition must return the same command builder it received`,i("foreign-command-builder"));if(c._node.extensions.length>0)throw new h("DEFINITION",`${o} cannot register Extensions inside command definitions`,i("nested-command-extension"));let l=M(c._node);return J(l.contexts.map(({instance:u})=>u),l.demands),l.meta={name:s,...r.meta},l}function ke(e,t=[]){if(e.trim()==="")throw new h("DEFINITION","Command name must be a non-empty string",{subject:"command",name:e,reason:"empty-name"});if(e==="__proto__")throw new h("DEFINITION",'Command name "__proto__" is reserved',{subject:"command",name:e,reason:"reserved-name"});if(t.includes(e))throw new h("DEFINITION",`Command "${e}" must not list its own canonical name as an alias`,{subject:"command",name:e,reason:"alias-collision"});return e}function fs(e){return typeof e==="function"}function ds(e,t,n){let r=!fs(t),s=r?t:{},o=r?n:t,i=ke(e,s.aliases);for(let m of s.aliases??[])if(m===""||/[ \t\n\r\v\f]/.test(m)||m.startsWith("-"))throw new h("DEFINITION",`Command "${i}" has an invalid alias "${m}"`);let{sections:a,version:c,...l}=s,u={...l,...s.aliases?{aliases:[...s.aliases]}:{},...a?{sections:Ee(i,a)}:{}},f={name:i,recipe:o,meta:u},d=(m)=>Object.freeze({name:m,as:(b)=>d(ke(b,u.aliases)),[Ne]:Object.freeze({...f,name:m})});return d(i)}function ms(e){return e.filter((t,n)=>e.findLastIndex((r)=>r.id===t.id)===n)}var Z=class{_node;_ancestorOwnedFlags;constructor(e,...t){let n=t[0]??{},r=ke(e);if(this._node=vt(r),n.description!==void 0)this._node.meta.description=n.description;if(n.version!==void 0)this._node.meta.version=n.version;if(n.usage!==void 0)this._node.meta.usage=n.usage;if(n.sections!==void 0)this._node.meta.sections=Ee(r,n.sections);this._ancestorOwnedFlags={}}_clone(e){let t=Object.create(Object.getPrototypeOf(this));return t._node={...this._node,...e},t._ancestorOwnedFlags=this._ancestorOwnedFlags,t}flags(...e){let t=this._clone(X(this._node));for(let n of e){let{name:r,...s}=n;N(t._node,r,s,"local")}return t}args(...e){let t=[...this._node.args,...e.map(ht)],n=new Set;for(let[r,s]of t.entries()){if(n.has(s.name))throw new h("DEFINITION",`Argument name "${s.name}" is already defined`,{subject:"argument",name:s.name,reason:"duplicate-arg"});if(n.add(s.name),s.variadic===!0&&r!==t.length-1)throw new h("DEFINITION",`Only the last positional argument can be variadic; "${s.name}" is not last`,{subject:"argument",name:s.name,reason:"variadic-position"})}return this._clone({args:t})}use(...e){return this._clone({demands:[...this._node.demands,...e.map(Y)]})}provide(...e){let t=e.map(Y);J([...this._node.contexts.map(({instance:r})=>r),...t],t);let n=this._clone({...X(this._node),contexts:[...this._node.contexts,...t.map((r)=>({instance:r}))],providedContexts:[...this._node.providedContexts,...t]});for(let r of t)for(let[s,o]of Object.entries(r.ownedFlags))N(n._node,s,o,"owned");return n}action(e){return this._clone({run:e})}extend(...e){let t=e.map(Y),n=ms([...this._node.extensions,...t]),r=St(this._node,n,new Set(t.map((s)=>s.id)));return J(r.contexts.map(({instance:s})=>s),n.flatMap((s)=>[...s.use,...s.provide])),this._clone({...r,extensions:n})}add(...e){return this._addDefinitions(e)}command(e,t){let n=ds(e,t);return this._addDefinitions([n])}_addDefinitions(e){let t={...this._node.subCommands};for(let n of e){let r=[n.name,...n[Ne].meta.aliases??[]];for(let o of Object.values(t))if([o.meta.name,...o.meta.aliases??[]].some((i)=>r.includes(i)))throw new h("DEFINITION",`Command name "${n.name}" is already registered on this command`,{subject:"command",name:n.name,reason:"command-collision"});let s=T(n,this._node);t[n.name]=s}return this._clone({subCommands:t})}async snapshot(){return j(B(this._node,T).rootNode)}async run(e,...t){let n=t[0]??{},r=t[1];return await je(this._node,{path:e,input:n},r,T)}at(e){_e(B(this._node,T).rootNode,e);let t=this._node,n=Object.freeze([...e]);return{path:n,async run(...r){let s=r[0]??{},o=r[1];return await je(t,{path:n,input:s},o,T)}}}async execute(e){return await Nt(this._node,e,T)}};import{existsSync as Pe,lstatSync as Ut,mkdirSync as Bt,readFileSync as ks,readdirSync as Vt,realpathSync as Fe,statSync as qt,writeFileSync as Ns}from"node:fs";import{dirname as Gt,join as F,resolve as Lt,sep as As}from"node:path";import{fileURLToPath as Ts}from"node:url";function At(e){return e instanceof Error&&"code"in e&&typeof e.code==="string"}import{isAbsolute as gs,relative as ps,sep as hs}from"node:path";function Tt(e,t){let n=ps(e,t);return n===""||!gs(n)&&n!==".."&&!n.startsWith(`..${hs}`)}import{spawn as Fs,spawnSync as Ps}from"node:child_process";import{once as Rs}from"node:events";import{accessSync as Ft,constants as Pt,statSync as Rt}from"node:fs";import{delimiter as bs,extname as ws,join as ys,resolve as vs,sep as xs,win32 as Ss}from"node:path";import{spawn as $s,spawnSync as Os}from"node:child_process";import{once as Es}from"node:events";import{text as Dt}from"node:stream/consumers";function Mt(e){if(e?.startsWith("bun"))return"bun";if(e?.startsWith("pnpm"))return"pnpm";if(e?.startsWith("yarn"))return"yarn";if(e?.startsWith("npm"))return"npm";return null}var Is=/[\0\r\n"%!^`<>&|]/,Ae=/([()\][%!^"`<>&|;, *?])/g;function Cs(e){let t=e.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\"");return t=t.replace(/(?=(\\+?)?)\1$/g,"$1$1"),t=`"${t}"`.replace(Ae,"^$1"),t.replace(Ae,"^$1")}function _s(e,t,n,r=process.platform){if(n||r!=="win32"||!/\.(cmd|bat)$/i.test(e))return null;let s=Ss.normalize(e);for(let[i,a]of[s,...t].entries())if(Is.test(a)){let c=i===0?"command":`argument ${i}`;throw Error(`Windows command shim ${c} ${JSON.stringify(a)} contains unsafe shell characters`)}let o=[s.replace(Ae,"^$1"),...t.map(Cs)].join(" ");return{command:process.env.ComSpec??"cmd.exe",args:["/d","/s","/c",`"${o}"`],windowsVerbatimArguments:!0}}function js(e){if(e.pid===void 0)return;if(process.platform==="win32"){if(e.exitCode===null&&e.signalCode===null){let t=Os("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore",timeout:1e4});if(t.error||t.status!==0)e.kill("SIGKILL")}return}try{process.kill(-e.pid,"SIGKILL")}catch(t){if(t.code==="ESRCH")return;throw e.kill("SIGKILL"),t}}async function L(e,t=[],n={}){let r=_s(e,t,n.shell),s=(n.stdio??"collect")==="collect",o=s&&n.stdout!=="ignore",i=$s(r?.command??e,r?.args??t,{cwd:n.cwd,env:n.env,shell:n.shell,stdio:s?["ignore",o?"pipe":"ignore","pipe"]:"inherit",detached:n.timeout!==void 0&&process.platform!=="win32",windowsVerbatimArguments:r?.windowsVerbatimArguments}),a,c=new Promise((l,u)=>{if(n.timeout===void 0)return;let f=n.timeout;a=setTimeout(()=>{let d=Error(`${[e,...t].join(" ")} did not exit within ${f} ms and was killed.`);try{js(i)}catch(m){d=Error("Process-tree cleanup failed after timeout.",{cause:m})}i.stdout?.destroy(),i.stderr?.destroy(),u(d)},f)});try{let[l,u,[f]]=await Promise.race([Promise.all([o?Dt(i.stdout):"",s?Dt(i.stderr):"",Es(i,"close")]),c]);return{exitCode:f,stdout:l,stderr:u}}finally{clearTimeout(a)}}function Te(e){if(e.includes(xs)||e.includes("/")){try{if(Ft(e,Pt.X_OK),Rt(e).isFile())return e}catch{}return null}let t=process.platform==="win32"&&!ws(e)?(process.env.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";"):[""];for(let n of process.env.PATH?.split(bs)??[])for(let r of t){let s=vs(ys(n,e+r));try{if(Ft(s,Pt.X_OK),Rt(s).isFile())return s}catch{}}return null}function Ds(e,t){return e.replace(/\{\{\s*(\w+)\s*\}\}/g,(n,r)=>Object.hasOwn(t,r)?t[r]??n:n)}function Ms(e){let t=Gt(e),n=e.slice(t==="."?0:t.length+1);if(n.startsWith("_")&&!n.startsWith("__")){let r=`.${n.slice(1)}`;return t==="."?r:F(t,r)}return e}function Bs(e){if(!Pe(e))return!1;if(!qt(e).isDirectory())return!1;return Vt(e).length>0}function zt(e,t){if(Fe(e)!==e)throw Error(`Destination root "${e}" was redirected outside the destination.`);let n=e;for(let r of t.split(As)){n=F(n,r);let s;try{s=Ut(n).isSymbolicLink()}catch(i){if(At(i)&&i.code==="ENOENT")return;throw i}if(!s)continue;let o;try{o=Fe(n)}catch{}if(o===void 0||!Tt(e,o))throw Error(`Destination path "${n}" is a symlink${o===void 0?" to a missing target":` to "${o}"`} outside the destination "${e}". Remove the link or choose another destination.`)}}async function Ht(e){let{template:t,dest:n,context:r,conflict:s="abort",render:o=Ds}=e,i=t instanceof URL?Ts(t):Lt(t),a=Lt(n);if(!Pe(i))throw Error(`Template directory "${i}" does not exist (from template: "${String(t)}").`);if(!qt(i).isDirectory())throw Error(`Template path "${i}" is not a directory (from template: "${String(t)}").`);if(s==="abort"&&Bs(a))throw Error(`Destination directory "${a}" already exists and is non-empty. Use conflict: "overwrite" to proceed.`);let c=Vt(i,{recursive:!0,encoding:"utf8"}).filter((d)=>Ut(F(i,d)).isFile());Bt(a,{recursive:!0});let l=Fe(a),u=c.map((d)=>({relFromTemplate:d,destRelPath:Ms(d)}));for(let{destRelPath:d}of u)zt(l,d);let f=[];for(let{relFromTemplate:d,destRelPath:m}of u){let b=F(i,d),g=F(l,m),p=ks(b),w=p.subarray(0,8192).includes(0)?p:await o(p.toString("utf-8"),r);zt(l,m),Bt(Gt(g),{recursive:!0}),Ns(g,w,"utf-8"),f.push(m)}return{files:f}}var Ls=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];function Re(e){let t=e??process.cwd();for(let[n,r]of Ls)if(Pe(F(t,n)))return r;return Mt(process.env.npm_config_user_agent)??"npm"}function Kt(e){try{return Ps("git",["rev-parse","--is-inside-work-tree"],{cwd:e??process.cwd(),stdio:"ignore"}).status===0}catch{return!1}}async function De(e,t){for(let n of e)switch(n.type){case"install":await zs(t);break;case"git-init":await Ws(t,n.commit);break;case"open-editor":await Us(t);break;case"command":await Vs(n.cmd,n.cwd??t)}}async function zs(e){let t=Re(e),n=Te(t);if(!n)throw Error(`Package manager "${t}" was not found on PATH. Install ${t} and try again.`);let{exitCode:r}=await L(n,["install"],{cwd:e,stdio:"inherit"});if(r!==0)throw Error(`"${t} install" exited with code ${r}`)}async function Ws(e,t){let n=Te("git");if(!n)throw Error('"git" was not found on PATH. Install Git and try again.');if(await z([n,"init"],e,"git init"),t)await qs(e,n),await z([n,"add","."],e,"git add"),await z([n,"commit","-m",t],e,"git commit")}async function Us(e){let t=process.env.EDITOR||"code";try{let n=Fs(t,[e],{stdio:"ignore",shell:process.platform==="win32"});n.unref();let r=await Promise.race([Rs(n,"close").then(([s])=>({kind:"exited",code:s})),new Promise((s)=>setTimeout(()=>s({kind:"timeout"}),500))]);if(r.kind==="exited"&&r.code!==0)console.warn(`Warning: could not open editor "${t}" (exit code ${r.code})`)}catch{console.warn(`Warning: could not open editor "${t}"`)}}async function Vs(e,t){let{exitCode:n}=await L(e,[],{cwd:t,shell:!0,stdio:"inherit"});if(n!==0)throw Error(`Command "${e}" exited with code ${n}`)}async function qs(e,t){let n=await Wt(t,"user.name",e)===0,r=await Wt(t,"user.email",e)===0;if(!n)await z([t,"config","user.name","Crust"],e,"git config user.name");if(!r)await z([t,"config","user.email","crust@scaffolded.project"],e,"git config user.email")}async function Wt(e,t,n){let{exitCode:r}=await L(e,["config",t],{cwd:n,stdio:"collect",stdout:"ignore"});return r}async function z(e,t,n){let{exitCode:r,stderr:s}=await L(e[0],e.slice(1),{cwd:t,stdio:"collect",stdout:"ignore"});if(r!==0)throw Error(`"${n}" failed with exit code ${r}${s?`: ${s.trim()}`:""}`)}var Yt=Object.defineProperty,Gs=(e,t)=>{let n={};for(var r in e)Yt(n,r,{get:e[r],enumerable:!0});if(!t)Yt(n,Symbol.toStringTag,{value:"Module"});return n},Hs=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ks=/[\p{Cc}\p{Cf}\p{Mn}\p{Me}]/u,Ys=/\p{Emoji_Presentation}|\p{Emoji}\uFE0F/u,Js=new RegExp([String.raw`(?:\x1b\[|\x9b)[^\x1b\x18\x1a\x9c\x40-\x7e]*[\x40-\x7e\x18\x1a\x9c]?`,String.raw`(?:\x1b\]|\x9d)[^\x07\x1b\x18\x1a\x9c]*(?:\x07|\x1b\\|[\x18\x1a\x9c])?`,String.raw`(?:\x1b[PX^_]|[\x90\x98\x9e\x9f])[^\x1b\x18\x1a\x9c]*(?:\x1b\\|[\x18\x1a\x9c])?`,String.raw`\x1b[\x20-\x2f][^\x1b]?`,String.raw`\x1b[\x18\x1a\x9c\x30-\x7e]?`].join("|"),"g");function Xs(e){return e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=94176&&e<=111355||e>=127488&&e<=127743||e>=131072&&e<=262141)}function Zs(e){return Ks.test(String.fromCodePoint(e))||e>=4448&&e<=4607||e>=55216&&e<=55295}function Qs(e){if(!/[^\x20-\x7e]/.test(e))return e.length;let t=0;for(let{segment:n}of Hs.segment(e.replace(Js,""))){if(Ys.test(n)){let r=n.codePointAt(0);t+=n.length===2&&r>=127462&&r<=127487?1:2;continue}for(let r of n){let s=r.codePointAt(0);if(Zs(s))continue;t+=Xs(s)?2:1;break}}return t}function Qt(e){return globalThis.Bun?.stringWidth(e,{countAnsiEscapeCodes:!1})??Qs(e)}var eo=Gs({bgBlack:()=>Eo,bgBlue:()=>jo,bgBrightBlack:()=>To,bgBrightBlue:()=>Do,bgBrightCyan:()=>Bo,bgBrightGreen:()=>Po,bgBrightMagenta:()=>Mo,bgBrightRed:()=>Fo,bgBrightWhite:()=>Lo,bgBrightYellow:()=>Ro,bgCyan:()=>No,bgGreen:()=>Co,bgMagenta:()=>ko,bgRed:()=>Io,bgWhite:()=>Ao,bgYellow:()=>_o,black:()=>co,blue:()=>mo,bold:()=>to,brightBlue:()=>xo,brightCyan:()=>$o,brightGreen:()=>yo,brightMagenta:()=>So,brightRed:()=>wo,brightWhite:()=>Oo,brightYellow:()=>vo,cyan:()=>po,dim:()=>no,gray:()=>bo,green:()=>uo,hidden:()=>io,inverse:()=>oo,isModifierName:()=>en,italic:()=>ro,magenta:()=>go,red:()=>lo,strikethrough:()=>ao,styleMethodNames:()=>Me,underline:()=>so,white:()=>ho,yellow:()=>fo});function v(e,t){return{open:`\x1B[${e}m`,close:`\x1B[${t}m`}}var to=v(1,22),no=v(2,22),ro=v(3,23),so=v(4,24),oo=v(7,27),io=v(8,28),ao=v(9,29),co=v(30,39),lo=v(31,39),uo=v(32,39),fo=v(33,39),mo=v(34,39),go=v(35,39),po=v(36,39),ho=v(37,39),bo=v(90,39),wo=v(91,39),yo=v(92,39),vo=v(93,39),xo=v(94,39),So=v(95,39),$o=v(96,39),Oo=v(97,39),Eo=v(40,49),Io=v(41,49),Co=v(42,49),_o=v(43,49),jo=v(44,49),ko=v(45,49),No=v(46,49),Ao=v(47,49),To=v(100,49),Fo=v(101,49),Po=v(102,49),Ro=v(103,49),Do=v(104,49),Mo=v(105,49),Bo=v(106,49),Lo=v(107,49),Me=Object.freeze(["bold","dim","italic","underline","inverse","hidden","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","brightRed","brightGreen","brightYellow","brightBlue","brightMagenta","brightCyan","brightWhite","bgBlack","bgRed","bgGreen","bgYellow","bgBlue","bgMagenta","bgCyan","bgWhite","bgBrightBlack","bgBrightRed","bgBrightGreen","bgBrightYellow","bgBrightBlue","bgBrightMagenta","bgBrightCyan","bgBrightWhite"]),zo=new Set(["bold","dim","italic","underline","inverse","hidden","strikethrough"]);function en(e){return zo.has(e)}function W(e,t,n){return e!==void 0&&t in e?e[t]:n}function tn(e){return W(e,"isTTY",process.stdout?.isTTY)??!1}function nn(e){return W(e,"forceColor",process.env.FORCE_COLOR)}function rn(e){return e==="0"||e==="false"}function Wo(e){let t=e.toLowerCase();return t.includes("24bit")||t.includes("truecolor")||t.endsWith("-direct")}function sn(e,t){if(e!==void 0){let n=e.toLowerCase();if(n==="truecolor"||n==="24bit")return!0}return t!==void 0&&Wo(t)}function Jt(e,t){if(sn(e,t))return"truecolor";if(t!==void 0&&t.toLowerCase().includes("256color"))return"256";return"16"}function Uo(e,t){if(e==="never")return"none";if(e==="always")return"truecolor";let n=W(t,"colorTerm",process.env.COLORTERM),r=W(t,"term",process.env.TERM),s=nn(t);if(s!==void 0){if(rn(s))return"none";if(s==="1")return"16";if(s==="2")return"256";if(s==="3")return"truecolor";return Jt(n,r)}if(!tn(t))return"none";let o=W(t,"noColor",process.env.NO_COLOR);if(o!==void 0&&o!=="")return"none";if(r!==void 0&&r.toLowerCase()==="dumb"&&!sn(n,r))return"none";return Jt(n,r)}function Vo(e,t){if(e==="always")return!0;if(e==="never")return!1;let n=nn(t);if(n!==void 0)return!rn(n);return tn(t)}var on={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function Be(e,t){if(e==null)return"";let n=String(e);if(n==="")return"";let{open:r,close:s}=t;if(n.includes(s))n=n.replaceAll(s,s+r);return r+n+s}var qo="\x1B[39m",Go="\x1B[49m",Ho="\x1B[38;",Ko="\x1B[48;";function Yo(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Jo(e){return Object.hasOwn(on,e)}function Le(e){if(Array.isArray(e)){if(e.length===3&&e.every((t)=>Number.isInteger(t)&&t>=0&&t<=255))return[e[0],e[1],e[2]]}else if(typeof e==="string"){let t=e.toLowerCase();if(Jo(t))return on[t];let n=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t)?.[1];if(n){let s=n.length===3?n.split("").map((o)=>o+o).join(""):n;return[Number.parseInt(s.slice(0,2),16),Number.parseInt(s.slice(2,4),16),Number.parseInt(s.slice(4,6),16)]}let r=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/.exec(t)??/^rgb\(\s*(\d{1,3})\s+(\d{1,3})\s+(\d{1,3})\s*\)$/.exec(t);if(r){let s=[Number(r[1]),Number(r[2]),Number(r[3])];if(s.every((o)=>o<=255))return s}}throw TypeError(`Invalid color input: ${Yo(e)}`)}function Xo(e,t,n){let r=[0,95,135,175,215,255],s=(f)=>r.reduce((d,m,b)=>Math.abs(m-f)<Math.abs(r[d]-f)?b:d,0),[o,i,a]=[s(e),s(t),s(n)],c=Math.min(23,Math.max(0,Math.round(((e+t+n)/3-8)/10))),l=8+c*10,u=(f,d,m)=>(e-f)**2+(t-d)**2+(n-m)**2;return u(l,l,l)<u(r[o],r[i],r[a])?232+c:16+36*o+6*i+a}function an(e,t,n){let r=Math.round(Math.max(e,t,n)/127.5);if(r===0)return 30;let s=30+((Math.round(n/255)<<2|Math.round(t/255)<<1|Math.round(e/255))&7);if(r===2)s+=60;return s}function cn(e,t){let[n,r,s]=Le(e);if(t==="16")return`\x1B[${an(n,r,s)}m`;if(t==="256")return`\x1B[38;5;${Xo(n,r,s)}m`;return`\x1B[38;2;${n};${r};${s}m`}function Zo(e,t){if(t==="16"){let[n,r,s]=Le(e);return`\x1B[${an(n,r,s)+10}m`}return cn(e,t).replace(Ho,Ko)}function ze(e,t,n){if(n==="none")return Le(t),{open:"",close:""};return{open:e==="fg"?cn(t,n):Zo(t,n),close:e==="fg"?qo:Go}}function Qo(e,t){return ze("fg",e,t)}function ei(e,t){return ze("bg",e,t)}function ln(e,t,n,r){let s=ze(e,n,r);return r==="none"?t:Be(t,s)}function ti(e,t,n="truecolor"){return ln("fg",e,t,n)}function ni(e,t,n="truecolor"){return ln("bg",e,t,n)}var un="\x1B]",fn="\x1B\\",ri=`${un}8;;${fn}`;function dn(e,t,n,r=""){if(!n.test(e))throw TypeError(`Invalid ${t}: ${JSON.stringify(e)} must contain only printable ASCII characters${r}.`)}function si(e){let t=e?.id;if(t===void 0||t==="")return"";if(dn(t,"hyperlink id",/^[\x20-\x7e]*$/),t.includes(":")||t.includes(";"))throw TypeError('Invalid hyperlink id: ":" and ";" are reserved by the OSC 8 format.');return`id=${t}`}function mn(e,t){dn(e,"hyperlink URL",/^[\x21-\x7e]*$/," without spaces");let n=si(t);return{open:`${un}8;${n};${e}${fn}`,close:ri}}function oi(e,t,n){return Be(e,mn(t,n))}var gn=[["fg",ti],["bg",ni]],ii=eo;function ai(e){return e.kind==="named"&&en(e.name)}function Q(e,t){if(e.kind==="named")return ii[e.name];return e.kind==="fg"?Qo(e.input,t):ei(e.input,t)}function pn(e,t){let n={kind:e,input:t};return Q(n,"truecolor"),Array.isArray(t)?{kind:e,input:[t[0],t[1],t[2]]}:n}function Xt(e,t,n){if(e==null)return"";let r=String(e);if(r==="")return r;let s=n(),{modifiersEnabled:o,colorsEnabled:i}=s;for(let a=t.length-1;a>=0;a--){let c=t[a];if(c===void 0)continue;if(ai(c)?!o:!i)continue;r=Be(r,Q(c,s.colorDepth))}return r}function ci(e){return Array.isArray(e)&&"raw"in e&&Array.isArray(e.raw)}function li(e,t){let n=new Map,r=t?"truecolor":e().colorDepth;function s(o){let i=o.map((f)=>f.kind==="named"?f.name:`~${Q(f,"truecolor").open}`).join("|"),a=n.get(i);if(a)return a;let c=(f,...d)=>{if(ci(f)){let m="";for(let b=0;b<f.length;b++)if(m+=f[b]??"",b<d.length)m+=String(d[b]);return Xt(m,o,e)}return Xt(f,o,e)};if(n.size>=1024)n.delete(n.keys().next().value);n.set(i,c);for(let f of Me)Object.defineProperty(c,f,{configurable:!1,enumerable:!0,get(){return s([...o,{kind:"named",name:f}])}});for(let[f]of gn)Object.defineProperty(c,f,{configurable:!1,enumerable:!0,value:(d)=>s([...o,pn(f,d)]),writable:!1});let l="",u="";for(let f of o){let d=Q(f,r);l+=d.open,u=d.close+u}return Object.defineProperty(c,"open",{value:l,writable:!1,configurable:!1,enumerable:!0}),Object.defineProperty(c,"close",{value:u,writable:!1,configurable:!1,enumerable:!0}),Object.freeze(c)}return s}function ui(e){let t={};for(let n of Me)t[n]=e([{kind:"named",name:n}]);return t}function Zt(e){let t=e?.mode??"auto",n=Vo(t,e?.overrides),r=Uo(t,e?.overrides);return{modifiersEnabled:n,colorDepth:r,colorsEnabled:r!=="none",trueColorEnabled:r==="truecolor"}}function fi(e,t){let n=t?Zt:(()=>{let i=Zt(e);return()=>i})(),r=li(n,t),s=ui(r),o={get enabled(){let{modifiersEnabled:i,colorsEnabled:a}=n();return i||a},get colorsEnabled(){return n().colorsEnabled},get trueColorEnabled(){return n().trueColorEnabled},get colorDepth(){return n().colorDepth},link(i,a,c){if(n().modifiersEnabled)return oi(i,a,c);return mn(a,c),i},...Object.fromEntries(gn.map(([i,a])=>[i,(...c)=>{let l=n();if(c.length===1)return r([pn(i,c[0])]);return a(c[0],c[1],l.colorDepth)}])),...s};return Object.freeze(o)}var y=fi(void 0,!0),{black:mc,red:ee,green:te,yellow:gc,blue:pc,magenta:hn,cyan:U,white:hc,gray:bc,brightRed:wc,brightGreen:yc,brightYellow:vc,brightBlue:xc,brightMagenta:Sc,brightCyan:$c,brightWhite:Oc,bgBlack:Ec,bgRed:Ic,bgGreen:Cc,bgYellow:_c,bgBlue:jc,bgMagenta:kc,bgCyan:Nc,bgWhite:Ac,bgBrightBlack:Tc,bgBrightRed:Fc,bgBrightGreen:Pc,bgBrightYellow:Rc,bgBrightBlue:Dc,bgBrightMagenta:Mc,bgBrightCyan:Bc,bgBrightWhite:Lc,bold:ne,dim:re,italic:zc,underline:Wc,inverse:Uc,hidden:Vc,strikethrough:qc,link:Gc,fg:Hc,bg:Kc}=y;var bn={spinner:hn,message:ne,success:te,error:ee},Ve="\x1B[",di=`${Ve}?25l`,wn=`${Ve}?25h`,vn=`${Ve}2K`,xn="\r",yn={dots:{frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],interval:80},line:{frames:["-","\\","|","/"],interval:130},arc:{frames:["◐","◓","◑","◒"],interval:100},bounce:{frames:["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"],interval:120}},mi="✓",gi="✗";function pi(e){if(e===void 0)return yn.dots;if(typeof e==="string")return yn[e];if(e.frames.length===0)throw Error("A custom spinner requires at least one frame");return e}function We(e,t){let n=e[t];if(n===void 0)throw Error("Spinner frame index is out of bounds");return n}function Ue(e,t,n){return`${vn}${xn}${n.spinner(e)} ${n.message(t)}`}function hi(e,t,n,r){let s=n==="success"?mi:gi,o=`${(n==="success"?t.success:t.error)(s)} ${t.message(e)}
13
+ `;return r?vn+xn+o:o}function bi(e){let t=e.sink??G()?.output??process.stderr,n=e.theme?{...bn,...e.theme}:bn,r=t.isTTY??!1,{frames:s,interval:o}=pi(e.spinner),i=e.sigint??"exit",a=e.message,c=0,l=!1,u=!1,f,d;function m(){if(f!==void 0)clearInterval(f),f=void 0;if(d)process.removeListener("SIGINT",d),d=void 0}return{start(){if(l||u)return;if(l=!0,!r)return;if(t.write(di),t.write(Ue(We(s,0),a,n)),f=setInterval(()=>{c=(c+1)%s.length,t.write(Ue(We(s,c),a,n))},o),i==="exit")d=()=>{if(m(),u=!0,t.write(wn),process.listenerCount("SIGINT")===0)process.kill(process.pid,"SIGINT")},process.once("SIGINT",d)},updateMessage(b){if(u)return;if(a=b,l&&r)t.write(Ue(We(s,c),a,n))},stop(b="success",g){if(u)return;if(u=!0,g!==void 0)a=g;m();let p;try{t.write(hi(a,n,b,l&&r))}catch(w){p={error:w}}if(l&&r)try{t.write(wn)}catch(w){if(!p)throw w}if(p)throw p.error}}}function qe(e){let t=bi(e),{task:n}=e;if(!n)return t;return t.start(),Promise.resolve().then(()=>n(t)).then((r)=>(t.stop("success"),r),(r)=>{throw t.stop("error"),r})}import*as k from"node:readline";var Sn={prefix:U,message:ne,placeholder:re,cursor:U,selected:U,unselected:re,error:ee,success:te,hint:re,filterMatch:U};function oe(e){let t=G();return{input:e?.input??t?.input??process.stdin,output:e?.output??t?.output??process.stderr}}var Ke=Symbol("submit");function Ye(e){return{[Ke]:e}}var Ge=new WeakSet,He=new WeakSet,In="\x1B[",wi=`${In}?25l`,yi=`${In}?25h`;function $n(e,t){let n=e.split(`
14
+ `),r=0;for(let s of n){let o=Qt(s);r+=o===0?1:Math.ceil(o/t)}return r}var vi=class extends Error{constructor(e){super(e??"Prompts require an interactive terminal (TTY).");this.name="NonInteractiveError"}};function Cn(e=oe().input){return!!e.isTTY}function xi(e=oe().input){if(!Cn(e))throw new vi}function Si(e){return typeof e==="object"&&e!==null&&Ke in e}function Je(e,t){let{render:n,handleKey:r,initialState:s,renderSubmitted:o}=e,i=e.theme?{...Sn,...e.theme}:Sn,{input:a,output:c}=oe(t),l=c;return new Promise((u,f)=>{if(Ge.has(a)||He.has(c)){f(Error("Cannot run multiple prompts concurrently on the same input or output stream. Await each prompt before starting the next."));return}xi(a),Ge.add(a),He.add(c);let d=s,m=0,b=!1,g=!1;function p(){if(b)return;if(b=!0,Ge.delete(a),He.delete(c),a.removeListener("keypress",E),g)a.setRawMode?.(!1);a.pause(),c.write(yi)}function w(_){let I=c.columns||80;if(m>0)k.cursorTo(l,0),k.moveCursor(l,0,-(m-1)),k.clearScreenDown(l);c.write(_),m=$n(_,I)}let S=Promise.resolve(),x=null;function C(){if(x!==null)return;x=setTimeout(()=>{if(x=null,b)return;try{w(n(d,i))}catch(_){p(),f(_)}},0)}function O(){if(x!==null)clearTimeout(x),x=null}function E(_,I){if(I?.ctrl&&I.name==="c"){O(),c.write(`
15
+ `),p(),f(new DOMException("Prompt was cancelled.","AbortError"));return}let A={char:_??"",name:I?.name??"",ctrl:I?.ctrl??!1,meta:I?.meta??!1,shift:I?.shift??!1};S=S.then(async()=>{if(b)return;try{let P=await r(A,d);if(b)return;if(Si(P)){O();let Qe=P[Ke];if(o)w(o(d,Qe,i));c.write(`
16
+ `),p(),u(Qe)}else d=P,C()}catch(P){O(),p(),f(P)}})}try{if(k.emitKeypressEvents(a),a.setRawMode)a.setRawMode(!0),g=!0;a.resume(),c.write(wi);let _=n(d,i);c.write(_),m=$n(_,c.columns||80),a.on("keypress",E)}catch(_){p(),f(_)}})}async function se(e,t,n){if(e.initial!==void 0)return{shortCircuited:!0,value:n?await n(e.initial,"initial"):e.initial};let r=oe(t);if(!Cn(r.input)&&e.default!==void 0)return{shortCircuited:!0,value:n?await n(e.default,"default"):e.default};return{shortCircuited:!1,promptIO:r}}function Xe(e,t,n){let r=[e];if(t)r.push(t);if(n)r.push(n);return r.join(" ")}function _n(e,t,n,r){let s=t?`${e} ${t}`:e,o=r??"";if(t)return`${s}${o}
17
+ ${n}`;return`${s}${o} ${n}`}function $i(e,t,n,r,s){let o=Math.min(e.length,n),i=[];if(t>0)i.push(s("..."));for(let a=t;a<t+o;a++){let c=e[a];if(c===void 0)break;i.push(r(c,a))}if(t+o<e.length)i.push(s("..."));return i}function jn(e,t,n,r){let s=Math.min(n,r);if(e<t)return e;if(e>=t+s)return e-s+1;return t}function Oi(e,t,n,r,s){let o=n===-1?e<=0?t-1:e-1:e>=t-1?0:e+1;return{cursor:o,scrollOffset:jn(o,r,t,s)}}function Ei(e){return e.map((t)=>{if(typeof t==="string")return{label:t,value:t};return t})}function Ii(e,t){if(e.name==="return")return Ye(t.value);if(e.name==="left"||e.name==="right"||e.name==="tab")return{value:!t.value};if(e.name==="h"||e.char==="y"||e.char==="Y")return{value:!0};if(e.name==="l"||e.char==="n"||e.char==="N")return{value:!1};return t}var Ci=" · ";function _i(e,t,n,r,s){let o=t.prefix("┃"),i=t.message(n??"Are you sure?"),a=e.value?`${t.selected("●")} ${t.selected(r)}`:`${t.unselected("○")} ${t.unselected(r)}`,c=e.value?`${t.unselected("○")} ${t.unselected(s)}`:`${t.selected("●")} ${t.selected(s)}`;return _n(o,i,`${a}${Ci}${c}`)}function ji(e,t,n,r,s,o){let i=n.success("✓"),a=n.message(r??"Are you sure?"),c=t?s:o;return Xe(i,a,n.success(c))}async function ie(e,t){let n=await se(e,t);if(n.shortCircuited)return n.value;let{promptIO:r}=n,s=e.active??"Yes",o=e.inactive??"No";return Je({initialState:{value:e.default??!0},theme:e.theme,render:(i,a)=>_i(i,a,e.message,s,o),handleKey:Ii,renderSubmitted:(i,a,c)=>ji(i,a,c,e.message,s,o)},r)}async function ki(e,t,n){let r=await se(e,n);if(r.shortCircuited)return r;let s=Ei(e.choices),o=e.maxVisible??10,i=e.default===void 0?[]:t==="multiple"?e.default:[e.default],a=new Set(i.flatMap((u)=>{let f=s.findIndex((d)=>d.value===u);return f===-1?[]:[f]})),c=i.length===0?-1:s.findIndex((u)=>u.value===i[0]),l=c===-1?0:c;return{shortCircuited:!1,choices:s,maxVisible:o,cursor:l,scrollOffset:jn(l,0,s.length,o),selected:a,promptIO:r.promptIO}}async function kn(e,t,n){if(t){let r=await t["~standard"].validate(e),s=r.issues?.[0];if(s)return{ok:!1,error:s.message||"Validation failed"};if("value"in r)return{ok:!0,value:r.value};return{ok:!1,error:"Validation failed"}}if(n)try{await n(e)}catch(r){return{ok:!1,error:r instanceof Error?r.message:"Validation failed"}}return{ok:!0,value:e}}async function Ni(e,t,n){let r=await kn(t,e,void 0);if(!r.ok)throw Error(`${n} value rejected by schema: ${r.error}`);return r.value}function Ai(e,t,n,r){if(e==="")return r?n.placeholder(r):n.cursor("│");return`${e.slice(0,t)}${n.cursor("│")}${e.slice(t)}`}function On(e,t){return(e.codePointAt(t)??0)>65535?2:1}function En(e,t){return t>=2&&(e.codePointAt(t-2)??0)>65535?2:1}function Ti(e){let t=e.codePointAt(0);return t!==void 0&&e.length===(t>65535?2:1)&&(t<55296||t>57343)}function Fi(e,t,n){if(e.name==="backspace"){if(n===0)return{text:t,cursorPos:n};let r=n-En(t,n);return{text:t.slice(0,r)+t.slice(n),cursorPos:r}}if(e.name==="delete"){if(n>=t.length)return{text:t,cursorPos:n};let r=n+On(t,n);return{text:t.slice(0,n)+t.slice(r),cursorPos:n}}if(e.name==="left"){if(n===0)return{text:t,cursorPos:n};return{text:t,cursorPos:n-En(t,n)}}if(e.name==="right"){if(n>=t.length)return{text:t,cursorPos:n};return{text:t,cursorPos:n+On(t,n)}}if(e.name==="home")return{text:t,cursorPos:0};if(e.name==="end")return{text:t,cursorPos:t.length};if(Ti(e.char)&&!e.ctrl&&!e.meta){let r=t.slice(0,n),s=t.slice(n);return{text:r+e.char+s,cursorPos:n+e.char.length}}return null}function Pi(e,t,n){return async(r,s)=>{if(r.name==="return"){let i=await kn(s.value===""&&n!==void 0?n:s.value,e,t);return i.ok?Ye(i.value):{...s,error:i.error}}let o=Fi(r,s.value,s.cursorPos);return o?{value:o.text,cursorPos:o.cursorPos,error:null}:s}}function Ri(e,t,n,r,s){let o=t.prefix("┃"),i=t.message(n??"Enter a value"),a=r??s,c=s!==void 0&&r!==void 0&&e.value===""?` ${t.hint(`(${s})`)}`:"",l=_n(o,i,Ai(e.value,e.cursorPos,t,a),c);if(e.error!==null)l+=`
18
+ ${t.error(e.error)}`;return l}function Di(e,t,n,r){return Xe(n.success("✓"),n.message(r??"Enter a value"),n.success(String(t)))}async function Nn(e={},t){if(e.schema!==void 0&&e.validate!==void 0)throw Error('input() cannot combine "schema" with "validate"');let n=e.schema,r=n?await se(e,t,(o,i)=>Ni(n,o,i)):await se(e,t);if(r.shortCircuited)return r.value;let{promptIO:s}=r;return Je({initialState:{value:"",cursorPos:0,error:null},theme:e.theme,render:(o,i)=>Ri(o,i,e.message,e.placeholder,e.default),handleKey:Pi(e.schema,e.validate,e.default),renderSubmitted:(o,i,a)=>Di(o,i,a,e.message)},s)}function Mi(e){return(t,n)=>{let r=n.choices.length;if(t.name==="return"){let s=n.choices[n.cursor];if(s)return Ye(s.value);return n}if(["up","down","k","j"].includes(t.name)){let s=t.name==="up"||t.name==="k"?-1:1;return{...n,...Oi(n.cursor,r,s,n.scrollOffset,e)}}return n}}function Bi(e,t,n,r){let s=[`${t.prefix("┃")} ${t.message(n??"Pick an option")}`];return s.push(...$i(e.choices,e.scrollOffset,r,(o,i)=>{let a=o.hint?` ${t.hint(o.hint)}`:"";return i===e.cursor?`${t.cursor("›")} ${t.selected(o.label)}${a}`:` ${t.unselected(o.label)}${a}`},t.hint)),s.join(`
19
+ `)}function Li(e,t,n,r){let s=n.success("✓"),o=n.message(r??"Pick an option"),i=e.choices[e.cursor],a=i?i.label:"";return Xe(s,o,n.success(a))}async function Ze(e,t){let n=await ki(e,"single",t);if(n.shortCircuited)return n.value;let{choices:r,cursor:s,maxVisible:o,promptIO:i,scrollOffset:a}=n;return Je({initialState:{cursor:s,choices:r,scrollOffset:a},theme:e.theme,render:(c,l)=>Bi(c,l,e.message,o),handleKey:Mi(o),renderSubmitted:(c,l,u)=>Li(c,l,u,e.message)},i)}var fe=class extends Error{constructor(e){super(e),this.name="Eta Error"}},Fn=class extends fe{constructor(e){super(e),this.name="EtaParser Error"}},zi=class extends fe{constructor(e){super(e),this.name="EtaRuntime Error"}};var Wi=class extends fe{constructor(e){super(e),this.name="EtaNameResolution Error"}};function V(e,t,n){let r=t.slice(0,n).split(/\n/),s=r.length,o=r[s-1].length+1;throw e+=" at line "+s+" col "+o+`:
20
+
21
+ `+t.split(/\n/)[s-1]+`
22
+ `+Array(o).join(" ")+"^",new Fn(e)}function Ui(e,t,n,r){let s=t.split(`
23
+ `),o=Math.max(n-3,0),i=Math.min(s.length,n+3),a=r,c=s.slice(o,i).map((u,f)=>{let d=f+o+1;return(d===n?" >> ":" ")+d+"| "+u}).join(`
24
+ `),l=new zi((a?a+":"+n+`
25
+ `:"line "+n+`
26
+ `)+c+`
27
+
28
+ `+e.message);throw l.name=e.name,l.cause=e,l}var Vi=(async()=>{}).constructor;function qi(e,t){let n=this.config,r=t?.async?Vi:Function;try{return new r(n.varName,"options",this.compileToString.call(this,e,t))}catch(s){throw s instanceof SyntaxError?new Fn(`Bad template syntax
29
+
30
+ `+s.message+`
31
+ `+Array(s.message.length+1).join("=")+`
32
+ `+this.compileToString.call(this,e,t)+`
33
+ `):s}}function Gi(e,t){let n=this.config,r=t?.async,s=this.compileBody,o=this.parse.call(this,e),i=`${n.functionHeader}
34
+ let include = (__eta_t, __eta_d) => this.render(__eta_t, {...${n.varName}, ...(__eta_d ?? {})}, options);
35
+ let includeAsync = (__eta_t, __eta_d) => this.renderAsync(__eta_t, {...${n.varName}, ...(__eta_d ?? {})}, options);
36
+
37
+ let __eta = {res: "", e: this.config.escapeFunction, f: this.config.filterFunction, blocks: {}${n.debug?', line: 1, templateStr: "'+e.replace(/\\|"/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n")+'"':""}};
38
+
39
+ function layout(path, data) {
40
+ __eta.layout = path;
41
+ __eta.layoutData = data;
42
+ }${n.debug?"try {":""}${n.useWith?"with("+n.varName+"||{}){":""}
43
+
44
+ function ${n.outputFunctionName}(s){__eta.res+=s;}
45
+ function capture(fn){const s=__eta.res;__eta.res='';try{fn();return __eta.res}finally{__eta.res=s;}}
46
+ async function captureAsync(fn){const s=__eta.res;__eta.res='';try{await fn();return __eta.res}finally{__eta.res=s;}}
47
+ function block(name,fn){if(__eta.layout){if(fn){__eta.blocks[name]=capture(fn);}return '';}const b=${n.varName}.__blocks||{};if(name in b){return b[name];}return fn?capture(fn):'';}
48
+ async function blockAsync(name,fn){if(__eta.layout){if(fn){__eta.blocks[name]=await captureAsync(fn);}return '';}const b=${n.varName}.__blocks||{};if(name in b){return b[name];}return fn?await captureAsync(fn):'';}
49
+
50
+ ${s.call(this,o)}
51
+ if (__eta.layout) {
52
+ __eta.res = ${r?"await includeAsync":"include"} (__eta.layout, {...${n.varName}, body: __eta.res, ...__eta.layoutData, __blocks: __eta.blocks});
53
+ }
54
+ ${n.useWith?"}":""}${n.debug?"} catch (e) { this.RuntimeErr(e, __eta.templateStr, __eta.line, options.filepath) }":""}
55
+ return __eta.res;
56
+ `;if(n.plugins)for(let a=0;a<n.plugins.length;a++){let c=n.plugins[a];c.processFnString&&(i=c.processFnString(i,n))}return i}function Hi(e){let t=this.config,n=0,r=e.length,s="";for(;n<r;n++){let o=e[n];if(typeof o=="string")s+="__eta.res+='"+o+`';
57
+ `;else{let i=o.t,a=o.val||"";t.debug&&(s+="__eta.line="+o.lineNo+`
58
+ `),i==="r"?(t.autoFilter&&(a="__eta.f("+a+")"),s+="__eta.res+="+a+`;
59
+ `):i==="i"?(t.autoFilter&&(a="__eta.f("+a+")"),t.autoEscape&&(a="__eta.e("+a+")"),s+="__eta.res+="+a+`;
60
+ `):i==="e"?s+=a+`
61
+ `:Object.hasOwn(t.customTags,i)&&(s+=`__eta.res+=this.config.customTags[${JSON.stringify(i)}](${JSON.stringify(a)},${t.varName});
62
+ `)}}return s}function Ki(e,t,n,r){let s,o;return Array.isArray(t.autoTrim)?(s=t.autoTrim[1],o=t.autoTrim[0]):s=o=t.autoTrim,(n||n===!1)&&(s=n),(r||r===!1)&&(o=r),!o&&!s?e:s==="slurp"&&o==="slurp"?e.trim():(s==="_"||s==="slurp"?e=e.trimStart():(s==="-"||s==="nl")&&(e=e.replace(/^(?:\r\n|\n|\r)/,"")),o==="_"||o==="slurp"?e=e.trimEnd():(o==="-"||o==="nl")&&(e=e.replace(/(?:\r\n|\n|\r)$/,"")),e)}var Yi={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function Ji(e){return Yi[e]}function Xi(e){let t=String(e);return/[&<>"']/.test(t)?t.replace(/[&<>"']/g,Ji):t}var An={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,customTags:{},debug:!1,escapeFunction:Xi,filterFunction:(e)=>String(e),outputFunctionName:"output",functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},ae=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,ce=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,le=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;function ue(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function Zi(e,t){return e.slice(0,t).split(`
63
+ `).length}function Qi(e){let t=this.config,n=[],r=!1,s=0,o=t.parse,i=Object.keys(t.customTags);if(t.plugins)for(let d=0;d<t.plugins.length;d++){let m=t.plugins[d];m.processTemplate&&(e=m.processTemplate(e,t))}t.rmWhitespace&&(e=e.replace(/[\r\n]+/g,`
64
+ `).replace(/^\s+|\s+$/gm,"")),ae.lastIndex=0,ce.lastIndex=0,le.lastIndex=0;function a(d,m){d&&(d=Ki(d,t,r,m),d&&(d=d.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),n.push(d)))}let c=[o.exec,o.interpolate,o.raw,...i].reduce((d,m)=>d&&m?d+"|"+ue(m):m?ue(m):d,""),l=RegExp(ue(t.tags[0])+"(-|_)?\\s*("+c+")?\\s*","g"),u=RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+ue(t.tags[1])+")","g"),f;for(;f=l.exec(e);){let d=e.slice(s,f.index);s=f[0].length+f.index;let m=f[1],b=f[2]||"";a(d,m),u.lastIndex=s;let g,p=!1;for(;g=u.exec(e);)if(g[1]){let w=e.slice(s,g.index);l.lastIndex=s=u.lastIndex,r=g[2],p={t:b===o.exec?"e":b===o.raw?"r":b===o.interpolate?"i":i.includes(b)?b:"",val:w};break}else{let w=g[0];if(w==="/*"){let S=e.indexOf("*/",u.lastIndex);S===-1&&V("unclosed comment",e,g.index),u.lastIndex=S}else w==="'"?(ce.lastIndex=g.index,ce.exec(e)?u.lastIndex=ce.lastIndex:V("unclosed string",e,g.index)):w==='"'?(le.lastIndex=g.index,le.exec(e)?u.lastIndex=le.lastIndex:V("unclosed string",e,g.index)):w==="`"&&(ae.lastIndex=g.index,ae.exec(e)?u.lastIndex=ae.lastIndex:V("unclosed string",e,g.index))}p?(t.debug&&(p.lineNo=Zi(e,f.index)),n.push(p)):V("unclosed tag",e,f.index)}if(a(e.slice(s,e.length),!1),t.plugins)for(let d=0;d<t.plugins.length;d++){let m=t.plugins[d];m.processAST&&(n=m.processAST(n,t))}return n}function Pn(e,t){let n=t?.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!e.startsWith("@")){let r=t.filepath,s=n.get(r);if(this.config.cache&&s)return s;{let o=this.readFile(r),i=this.compile(o,t);return this.config.cache&&n.define(r,i),i}}else{let r=n.get(e);if(r)return r;throw new Wi(`Failed to get template '${e}'`)}}function Rn(e,t,n){let r,s={...n,async:!1};return typeof e=="string"?(this.resolvePath&&this.readFile&&!e.startsWith("@")&&(s.filepath=this.resolvePath(e,s)),r=Pn.call(this,e,s)):r=e,r.call(this,t,s)}function Dn(e,t,n){let r,s={...n,async:!0};typeof e=="string"?(this.resolvePath&&this.readFile&&!e.startsWith("@")&&(s.filepath=this.resolvePath(e,s)),r=Pn.call(this,e,s)):r=e;let o=r.call(this,t,s);return Promise.resolve(o)}function ea(e,t){let n=this.compile(e,{async:!1});return Rn.call(this,n,t)}function ta(e,t){let n=this.compile(e,{async:!0});return Dn.call(this,n,t)}var Tn=class{constructor(e){this.cache=e}define(e,t){this.cache[e]=t}get(e){return this.cache[e]}remove(e){delete this.cache[e]}reset(){this.cache={}}load(e){this.cache={...this.cache,...e}}},na=class{constructor(e){e?this.config={...An,...e}:this.config={...An};let t=[this.config.parse.exec,this.config.parse.interpolate,this.config.parse.raw,"-","_"];for(let n of Object.keys(this.config.customTags))if(t.includes(n))throw new fe(`Custom tag prefix "${n}" conflicts with a built-in prefix`)}config;RuntimeErr=Ui;compile=qi;compileToString=Gi;compileBody=Hi;parse=Qi;render=Rn;renderAsync=Dn;renderString=ea;renderStringAsync=ta;filepathCache={};templatesSync=new Tn({});templatesAsync=new Tn({});resolvePath=null;readFile=null;configure(e){this.config={...this.config,...e}}withConfig(e){return{...this,config:{...this.config,...e}}}loadTemplate(e,t,n){if(typeof t=="string")((n?.async)?this.templatesAsync:this.templatesSync).define(e,this.compile(t,n));else{let r=this.templatesSync;(t.constructor.name==="AsyncFunction"||n?.async)&&(r=this.templatesAsync),r.define(e,t)}}},Mn=class extends na{};var Bn={name:"@crustjs/core",version:"0.5.0",description:"Core library for the Crust CLI framework",type:"module",sideEffects:!1,license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/core"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","command","framework","parser","bun","typescript"],files:["dist"],types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./tooling":{types:"./dist/tooling.d.ts",import:"./dist/tooling.js"}},publishConfig:{access:"public"},scripts:{build:"vp run build:task",dev:"vp pack --watch","check:types":"vp run check:types:task",test:"vp run test:task",prepack:"cp ../../LICENSE LICENSE",postpack:"rm -f LICENSE"},dependencies:{"@crustjs/utils":"workspace:^"},devDependencies:{"@crustjs/config":"workspace:*","vite-plus":"catalog:"},peerDependencies:{typescript:"^7.0.0"},peerDependenciesMeta:{typescript:{optional:!0}},engines:{bun:">=1.4.0",node:">=22",deno:">=2.8"}};var Ln={name:"@crustjs/crust",version:"0.5.0",description:"CLI tooling for the Crust framework",type:"module",license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/crust"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","build","compile","standalone","bun","typescript"],publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},crust:{artifact:"binary",include:["schema","dist"]},bin:{crust:"src/cli.ts"},scripts:{build:"vp run build:task",release:"bun src/cli.ts publish",dev:"bun src/cli.ts",start:"bun .crust/root/bin/crust.js","check:types":"vp run check:types:task",test:"vp run test:task"},dependencies:{"@crustjs/core":"workspace:^","@crustjs/extensions":"workspace:^","@crustjs/style":"workspace:^"},optionalDependencies:{"@tsdown/exe":"0.23.0",tsdown:"0.23.0"},peerDependencies:{"@crustjs/core":"^0.5.0"},devDependencies:{"@arethetypeswrong/core":"^0.18.5","@crustjs/config":"workspace:*","@crustjs/testing":"workspace:*","@crustjs/utils":"workspace:*","@types/semver":"^7.8.0",publint:"^0.3.24",semver:"^7.8.5","vite-plus":"catalog:"},engines:{bun:">=1.4.0"}};var zn={name:"@crustjs/extensions",version:"0.5.0",description:"Official Extensions for the Crust CLI framework",type:"module",sideEffects:!1,license:"MIT",author:"chenxin-yan",repository:{type:"git",url:"git+https://github.com/chenxin-yan/crust.git",directory:"packages/extensions"},homepage:"https://crustjs.com",bugs:{url:"https://github.com/chenxin-yan/crust/issues"},keywords:["cli","extension","help","version","completion","did-you-mean","bun","typescript"],files:["dist"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},publishConfig:{access:"public"},scripts:{build:"vp run build:task",dev:"vp pack --watch","check:types":"vp run check:types:task",test:"vp run test:task",prepack:"cp ../../LICENSE LICENSE",postpack:"rm -f LICENSE"},dependencies:{"@crustjs/store":"workspace:^","@crustjs/style":"workspace:^","@crustjs/utils":"workspace:^"},devDependencies:{"@crustjs/config":"workspace:*","@crustjs/core":"workspace:*","vite-plus":"catalog:"},peerDependencies:{"@crustjs/core":"workspace:^",typescript:"^7.0.0"},peerDependenciesMeta:{typescript:{optional:!0}},engines:{bun:">=1.4.0",node:">=22",deno:">=2.8"}};var ca={bun:{shebang:"#!/usr/bin/env bun",tsLib:'"ESNext"',tsTypes:'"bun"'},node:{shebang:"#!/usr/bin/env node",tsLib:'"ESNext"',tsTypes:'"node"'},deno:{shebang:"#!/usr/bin/env -S deno run -A",tsLib:'"ESNext", "deno.window"',tsTypes:""}},la=new Mn({autoEscape:!1,autoTrim:!1}),ua=/^[A-Za-z0-9_~][A-Za-z0-9._~-]*$/;function Gn(e){if(e==="__proto__"||!ua.test(e))throw Error(`Project name ${JSON.stringify(e)} is not safe for the generated project.
65
+ The directory basename becomes the package and command name: use letters, digits, ".", "_", "~", and "-", not starting with "." or "-"; "__proto__" is reserved.`)}var fa=/[<>:"|?*\\]/;function da(e){if(!e)throw Error("Project directory cannot be empty");if(fa.test(e))throw Error(`Project directory contains invalid characters: ${e}`);Gn(Vn(qn(e)))}var ma=new Z("create-crust",{description:"Scaffold a new Crust CLI project"}).flags({name:"runtime",type:"string",choices:["bun","node","deno"],description:'Runtime to develop and build for ("bun", "node", or "deno")'},{name:"artifact",type:"string",choices:["package","binary"],description:"Build output: runtime package or standalone binary"},{name:"install",type:"boolean",description:"Install dependencies after scaffolding"},{name:"git",type:"boolean",description:"Initialize a git repository after scaffolding"},{name:"overwrite",type:"boolean",description:"Overwrite the destination directory if it already exists"}).args({name:"directory",type:"string",description:"Project directory to scaffold into"}).action(async({args:e,flags:t})=>{let n=e.directory??await Nn({message:"Project directory",default:"my-cli",validate:da}),r=qn(process.cwd(),n),s=Vn(r);Gn(s);let o=t.runtime,i=n==="."?ia(r).length>0:Wn(r),a=!1;if(i){if(a=await ie({message:n==="."?"Current directory is not empty. Overwrite conflicting files?":`Directory "${s}" already exists. Overwrite?`,default:!1,...t.overwrite!==void 0?{initial:t.overwrite}:{}}),!a){console.log("Aborted.");return}}let c=await Ze({message:"Runtime",choices:[{label:"Bun (recommended)",value:"bun",hint:"Bun APIs and TypeScript execution"},{label:"Node.js",value:"node",hint:"Node.js APIs and ecosystem"},{label:"Deno",value:"deno",hint:"Deno APIs and permission model"}],default:"bun",...o!==void 0?{initial:o}:{}}),l=await Ze({message:"Build output",choices:[{label:"Standalone binary",value:"binary",hint:"Embeds the runtime; users need no separate JavaScript runtime"},{label:"Runtime package",value:"package",hint:c==="deno"?"Requires Deno installed; experimental bundling":"JavaScript bundle; requires the selected runtime installed"}],default:c==="node"?"package":"binary",...t.artifact!==void 0?{initial:t.artifact}:{}}),u=await ie({message:"Install dependencies?",default:!0,...t.install!==void 0?{initial:t.install}:{}}),f=r;while(!Wn(f)&&Un(f)!==f)f=Un(f);let m=Kt(f)?!1:await ie({message:"Initialize a git repository?",default:!0,...t.git!==void 0?{initial:t.git}:{}}),b=s,g=c==="deno"?"deno":Re(r),p={name:b,runtime:c,artifact:l,run:g==="deno"?"deno task":`${g} run`,install:`${g} install`,...ca[c],coreVersion:Bn.version,extensionsVersion:zn.version,crustVersion:Ln.version};if(await qe({message:"Scaffolding project...",task:()=>Ht({template:aa(ge("templates"),"base"),dest:r,context:p,render:(w,S)=>la.renderString(w,S),...a?{conflict:"overwrite"}:{}})}),u)await De([c==="deno"?{type:"command",cmd:"deno install"}:{type:"install"}],r);if(m)await qe({message:"Initializing git repository...",task:()=>De([{type:"git-init",commit:"chore: initial commit"}],r)});if(console.log(`
21
66
  Created ${b}!
22
- `),console.log("Next steps:"),n!=="."){let p=n.startsWith("/")?n:`./${n}`;console.log(` cd ${p}`)}console.log(` ${m.run} dev`),console.log(` ${m.run} build`)});await Ei.execute();
67
+ `),console.log("Next steps:"),n!=="."){let w=n.startsWith("/")?n:`./${n}`;console.log(` cd ${w}`)}if(!u)console.log(` ${p.install}`);console.log(` ${p.run} dev`),console.log(` ${p.run} build`)});await ma.execute();
package/package.json CHANGED
@@ -1,41 +1,41 @@
1
1
  {
2
- "name": "create-crust",
3
- "version": "0.4.1",
4
- "description": "Scaffold a new Crust CLI project.",
5
- "license": "MIT",
6
- "author": "chenxin-yan",
7
- "homepage": "https://crustjs.com",
8
- "bugs": {
9
- "url": "https://github.com/chenxin-yan/crust/issues"
10
- },
11
- "repository": {
12
- "type": "git",
13
- "url": "git+https://github.com/chenxin-yan/crust.git",
14
- "directory": "packages/create-crust"
15
- },
16
- "keywords": [
17
- "cli",
18
- "scaffold",
19
- "create",
20
- "generator",
21
- "bun",
22
- "typescript",
23
- "crust"
24
- ],
25
- "publishConfig": {
26
- "access": "public"
27
- },
28
- "engines": {
29
- "bun": ">=1.4.0",
30
- "node": ">=22",
31
- "deno": ">=2.8"
32
- },
33
- "type": "module",
34
- "files": [
35
- "bin",
36
- "templates"
37
- ],
38
- "bin": {
39
- "create-crust": "bin/create-crust.js"
40
- }
41
- }
2
+ "name": "create-crust",
3
+ "version": "0.5.0",
4
+ "description": "Scaffold a new Crust CLI project.",
5
+ "license": "MIT",
6
+ "author": "chenxin-yan",
7
+ "homepage": "https://crustjs.com",
8
+ "bugs": {
9
+ "url": "https://github.com/chenxin-yan/crust/issues"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/chenxin-yan/crust.git",
14
+ "directory": "packages/create-crust"
15
+ },
16
+ "keywords": [
17
+ "cli",
18
+ "scaffold",
19
+ "create",
20
+ "generator",
21
+ "bun",
22
+ "typescript",
23
+ "crust"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "engines": {
29
+ "bun": ">=1.4.0",
30
+ "node": ">=22",
31
+ "deno": ">=2.8"
32
+ },
33
+ "type": "module",
34
+ "files": [
35
+ "bin",
36
+ "templates"
37
+ ],
38
+ "bin": {
39
+ "create-crust": "bin/create-crust.js"
40
+ }
41
+ }
@@ -1,31 +1,47 @@
1
- # {{name}}
1
+ # <%~ it.name %>
2
2
 
3
3
  A CLI built with [Crust](https://crustjs.com).
4
4
 
5
+ Runtime: **<%~ it.runtime %>**. Build output: **<%~ it.artifact %>**.
6
+ Change `crust.runtime` and `crust.artifact` in `package.json` to change these choices.
7
+
5
8
  ## Development
6
9
 
10
+ Install dependencies if you skipped installation or just cloned the project:
11
+
12
+ ```sh
13
+ <%~ it.install %>
14
+ ```
15
+
7
16
  ```sh
8
17
  # Run in dev mode
9
- {{run}} dev
18
+ <%~ it.run %> dev
10
19
 
11
20
  # Type-check
12
- {{run}} check:types
21
+ <%~ it.run %> check:types
13
22
 
14
23
  # Build into .crust/
15
- {{run}} build
24
+ <%~ it.run %> build
16
25
 
17
26
  # Run the built CLI
18
- {{run}} start
27
+ <%~ it.run %> start
19
28
  ```
20
29
 
21
- ## Publishing
30
+ ## Build and distribution
31
+
32
+ `<%~ it.run %> build` stages the selected output and npm metadata in `.crust/`:
33
+
34
+ - `package`: a JavaScript bundle in `.crust/root/` that requires the selected runtime installed.
35
+ - `binary`: a standalone executable per platform, with its runtime embedded. Pass `--target host` to `crust build` to build only this machine's target.
36
+
37
+ Bun is used for build preparation and Bun/Node bundling. Node binaries additionally need Node 26+ and Crust's optional compiler backend; Deno builds need Deno on PATH, with Deno 2.5+ required for experimental runtime-package bundling. Crust does not install or upgrade compilers. See [compiler requirements](https://crustjs.com/docs/guide/build-and-distribution#binary-runtime-version).
22
38
 
23
- `{{run}} build` stages the publishable npm package(s) in `.crust/`; `{{run}} release` publishes them. See [Build and distribution](https://crustjs.com/docs/guide/build-and-distribution).
39
+ `<%~ it.run %> release` publishes the staged packages to npm, but npm is optional. For direct downloads, Homebrew or Scoop, distribute the executable and adjacent assets from `.crust/<platform>/bin/`. Direct binaries need no separately installed JavaScript runtime; the generated npm binary launcher needs Node.js. Crust does not generate installer definitions or publish release archives. See [custom distribution](https://crustjs.com/docs/guide/build-and-distribution#custom-distribution).
24
40
 
25
41
  ## Usage
26
42
 
27
43
  ```sh
28
44
  # Run the CLI
29
- {{name}} world
30
- {{name}} --greet Hey world
45
+ <%~ it.name %> world
46
+ <%~ it.name %> --greet Hey world
31
47
  ```
@@ -0,0 +1,51 @@
1
+ <%
2
+ /* `dev` runs the source and `start` runs the built bin with the selected runtime.
3
+ Deno type-checks natively, so it needs no TypeScript packages. */
4
+ const dev = { bun: "bun run src/cli.ts", node: "node src/cli.ts", deno: "deno run -A src/cli.ts" }[it.runtime];
5
+ const startRunner = { bun: "bun", node: "node", deno: "deno run -A" }[it.runtime];
6
+ const checkTypes = it.runtime === "deno" ? "deno check src/cli.ts" : "tsc --noEmit";
7
+ -%>
8
+ {
9
+ "$schema": "./node_modules/@crustjs/crust/schema/package.json",
10
+ "name": <%~ JSON.stringify(it.name) %>,
11
+ "version": "0.0.0",
12
+ "private": true,
13
+ "type": "module",
14
+ "description": "A CLI built with Crust",
15
+ "crust": {
16
+ "runtime": <%~ JSON.stringify(it.runtime) %>,
17
+ "artifact": <%~ JSON.stringify(it.artifact) %>
18
+ },
19
+ "bin": {
20
+ <%~ JSON.stringify(it.name) %>: "src/cli.ts"
21
+ },
22
+ "scripts": {
23
+ "dev": <%~ JSON.stringify(dev) %>,
24
+ "build": "crust build",
25
+ "release": "crust publish",
26
+ "start": <%~ JSON.stringify(`${startRunner} .crust/root/bin/${it.name}.js`) %>,
27
+ "check:types": <%~ JSON.stringify(checkTypes) %>
28
+ },
29
+ <% if (it.runtime === "node") { -%>
30
+ "engines": {
31
+ "node": ">=22.18"
32
+ },
33
+ <% } -%>
34
+ "dependencies": {
35
+ "@crustjs/core": <%~ JSON.stringify(`^${it.coreVersion}`) %>,
36
+ "@crustjs/extensions": <%~ JSON.stringify(`^${it.extensionsVersion}`) %>
37
+ },
38
+ "devDependencies": {
39
+ <% if (it.runtime === "bun") { -%>
40
+ "@crustjs/crust": <%~ JSON.stringify(`^${it.crustVersion}`) %>,
41
+ "@types/bun": "latest",
42
+ "typescript": "^7.0.2"
43
+ <% } else if (it.runtime === "node") { -%>
44
+ "@crustjs/crust": <%~ JSON.stringify(`^${it.crustVersion}`) %>,
45
+ "@types/node": "^22",
46
+ "typescript": "^7.0.2"
47
+ <% } else { -%>
48
+ "@crustjs/crust": <%~ JSON.stringify(`^${it.crustVersion}`) %>
49
+ <% } -%>
50
+ }
51
+ }
@@ -1,10 +1,10 @@
1
- {{shebang}}
1
+ <%~ it.shebang %>
2
2
  import { Crust } from "@crustjs/core";
3
3
  import { help, version } from "@crustjs/extensions";
4
4
 
5
5
  import pkg from "../package.json" with { type: "json" };
6
6
 
7
- const app = new Crust("{{name}}", { description: "A CLI built with Crust", version: pkg.version })
7
+ const app = new Crust(<%~ JSON.stringify(it.name) %>, { description: "A CLI built with Crust", version: pkg.version })
8
8
  .extend(version(), help())
9
9
  .args({
10
10
  name: "name",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "lib": [{{tsLib}}],
4
- "types": [{{tsTypes}}],
3
+ "lib": [<%~ it.tsLib %>],
4
+ "types": [<%~ it.tsTypes %>],
5
5
  "target": "ESNext",
6
6
  "module": "Preserve",
7
7
  "moduleDetection": "force",
@@ -1,30 +0,0 @@
1
- {
2
- "$schema": "./node_modules/@crustjs/crust/schema/package.json",
3
- "name": "{{name}}",
4
- "version": "0.0.0",
5
- "private": true,
6
- "type": "module",
7
- "description": "A CLI built with Crust",
8
- "crust": {
9
- "runtime": "bun"
10
- },
11
- "bin": {
12
- "{{name}}": "src/cli.ts"
13
- },
14
- "scripts": {
15
- "dev": "bun run src/cli.ts",
16
- "build": "crust build",
17
- "release": "crust publish",
18
- "start": "bun .crust/root/bin/{{name}}.js",
19
- "check:types": "tsc --noEmit"
20
- },
21
- "dependencies": {
22
- "@crustjs/core": "^{{crustCoreVersion}}",
23
- "@crustjs/extensions": "^{{crustExtensionsVersion}}"
24
- },
25
- "devDependencies": {
26
- "@crustjs/crust": "^{{crustCliVersion}}",
27
- "@types/bun": "latest",
28
- "typescript": "^7.0.2"
29
- }
30
- }
@@ -1,28 +0,0 @@
1
- {
2
- "$schema": "./node_modules/@crustjs/crust/schema/package.json",
3
- "name": "{{name}}",
4
- "version": "0.0.0",
5
- "private": true,
6
- "type": "module",
7
- "description": "A CLI built with Crust",
8
- "crust": {
9
- "runtime": "deno"
10
- },
11
- "bin": {
12
- "{{name}}": "src/cli.ts"
13
- },
14
- "scripts": {
15
- "dev": "deno run -A src/cli.ts",
16
- "build": "crust build",
17
- "release": "crust publish",
18
- "start": "deno run -A .crust/root/bin/{{name}}.js",
19
- "check:types": "deno check src/cli.ts"
20
- },
21
- "dependencies": {
22
- "@crustjs/core": "^{{crustCoreVersion}}",
23
- "@crustjs/extensions": "^{{crustExtensionsVersion}}"
24
- },
25
- "devDependencies": {
26
- "@crustjs/crust": "^{{crustCliVersion}}"
27
- }
28
- }
@@ -1,33 +0,0 @@
1
- {
2
- "$schema": "./node_modules/@crustjs/crust/schema/package.json",
3
- "name": "{{name}}",
4
- "version": "0.0.0",
5
- "private": true,
6
- "type": "module",
7
- "description": "A CLI built with Crust",
8
- "crust": {
9
- "runtime": "node"
10
- },
11
- "bin": {
12
- "{{name}}": "src/cli.ts"
13
- },
14
- "scripts": {
15
- "dev": "node src/cli.ts",
16
- "build": "crust build",
17
- "release": "crust publish",
18
- "start": "node .crust/root/bin/{{name}}.js",
19
- "check:types": "tsc --noEmit"
20
- },
21
- "engines": {
22
- "node": ">=22.18"
23
- },
24
- "dependencies": {
25
- "@crustjs/core": "^{{crustCoreVersion}}",
26
- "@crustjs/extensions": "^{{crustExtensionsVersion}}"
27
- },
28
- "devDependencies": {
29
- "@crustjs/crust": "^{{crustCliVersion}}",
30
- "@types/node": "^22",
31
- "typescript": "^7.0.2"
32
- }
33
- }