arkenv 1.0.0-alpha.16 → 1.0.0-alpha.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.cjs CHANGED
@@ -1,92 +1,72 @@
1
1
  #!/usr/bin/env node
2
- const e=require(`./chunk-i8uDWG73.cjs`),t=require(`./dist-CSf6owGv.cjs`);let n=require(`radashi`),r=require(`node:util`),i=require(`node:process`);i=e.r(i,1);let a=require(`node:readline`);a=e.r(a,1);let o=require(`node:tty`);require(`node:fs`);let s=require(`node:path`);s=e.r(s,1);let c=require(`node:fs/promises`);c=e.r(c,1);let l=require(`dedent`);l=e.r(l,1);let u=require(`jiti`),d=require(`node:child_process`),f=require(`node:module`),p=require(`jsonc-parser`),m=require(`magicast`),h=require(`yaml`);var g=e.t(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),_=e.r(g(),1);const v={REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,INTERNAL:`CLI.INTERNAL_ERROR`,SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CANCELLED:`CLI.CANCELLED`,UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,INVALID_VALUE:`ENV.INVALID_VALUE`,MISSING_VARIABLE:`ENV.MISSING_VARIABLE`},y={CLI_INTERNAL_ERROR:`CLI.INTERNAL_ERROR`,CLI_SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CLI_REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,CLI_GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,CLI_NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,CLI_CANCELLED:`CLI.CANCELLED`,CLI_UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,CLI_INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,ENV_VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,ENV_INVALID_VALUE:`ENV.INVALID_VALUE`,ENV_MISSING_VARIABLE:`ENV.MISSING_VARIABLE`};function b(){let e=process.env.npm_config_user_agent||``;if(e.includes(`pnpm`))return process.env.npm_command===`dlx`?`pnpm dlx arkenv`:`pnpm arkenv`;if(e.includes(`bun`))return(process.env._||process.argv[1]||``).includes(`bunx`)||process.env.npm_command===`x`?`bunx arkenv`:`bun arkenv`;if(e.includes(`yarn`))return process.env.npm_command===`dlx`?`yarn dlx arkenv`:`yarn arkenv`;if(e.includes(`npm`))return`npx arkenv`;let t=process.env._||process.argv[1]||``;return t.includes(`npx`)?`npx arkenv`:t.includes(`bunx`)?`bunx arkenv`:t.includes(`pnpm`)?`pnpm arkenv`:t.includes(`yarn`)?`yarn arkenv`:t.includes(`bun`)?`bun arkenv`:`arkenv`}function x(e,t=b()){return e.replace(/\{bin\}/g,t)}function S(e,t=b()){let n={...e};return n.command&&=x(n.command,t),n.commands&&=n.commands.map(e=>x(e,t)),n}function C(e){return e.replace(/\x1B\[\d+m/g,``).replace(/\x1B\[[0-9;]*[a-zA-Z]/g,``)}function w(e,n,r){let i=C(e);return r?.debugSecrets||t.s(r?.debugSecrets)?i:n&&t.l(n)?i.replace(/\(was .*\)/g,`(was [REDACTED])`):i}var ee=class{info(e){process.stderr.write(`${_.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${_.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${_.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${_.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${_.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${_.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${_.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}reportCompleted(e){let t=e.diagnostics.map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>S(e))})),n=(e.nextActions??[]).map(e=>S(e));this.json({ok:!0,commandId:e.commandId,result:e.result,exitCode:e.exitCode,diagnostics:t,nextActions:n})}reportErrored(e){let t=(e.error.nextActions??[]).map(e=>S(e)),n=(e.nextActions??t).map(e=>S(e)),r=(e.diagnostics??[]).map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>S(e))}));this.json({ok:!1,commandId:e.commandId,error:{...e.error,nextActions:t},diagnostics:r,nextActions:n})}cancel(e,t=`cli`){this.reportErrored({ok:!1,commandId:t,error:{code:v.CANCELLED,severity:`info`,summary:w(e),nextActions:[]},diagnostics:[],nextActions:[]})}fatal(e,t,n=`cli`){let r=t instanceof Error?t.message:t?String(t):void 0;throw this.reportErrored({ok:!1,commandId:n,error:{code:v.INTERNAL,severity:`error`,summary:w(e),...r===void 0?{}:{why:w(r)},...r===void 0?{}:{meta:{error:r}},nextActions:[]},diagnostics:[],nextActions:[]}),t instanceof Error?t:Error(e)}refuse(e,t=`init`){let n=e.nextActions??(e.retryWith?.includes(`--force`)?[{kind:`run-command`,label:`Re-run with --force to bypass this check`,command:`{bin} ${t} --force`}]:[]);this.reportErrored({ok:!1,commandId:t,error:{code:e.code,severity:`error`,summary:w(e.message),...e.why?{why:w(e.why)}:{},...e.details===void 0?{}:{meta:e.details},nextActions:n},diagnostics:[],nextActions:n})}finish(e,t,n=`init`){this.reportCompleted({ok:!0,commandId:n,result:{message:e,...t??{}},exitCode:0,diagnostics:[],nextActions:[]})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},T=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t,n){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){}reportCompleted(e){}reportErrored(e){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const E=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),D=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,O=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,k=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,te=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ne=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,re=/\t{1,1000}/y,ie=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,ae=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,oe=/\p{M}+/gu,se={limit:1/0,ellipsis:``},ce=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ce(i,se,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[ae,l],[k,0],[te,o],[re,s],[ie,c],[ne,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(oe,``)){let t=e.codePointAt(0)||0;if(S=D(t)?2:O(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===ne?E(e.slice(p,n.lastIndex)):n===ie?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},le={limit:1/0,ellipsis:``,ellipsisWidth:0},A=(e,t={})=>ce(e,le,t).width,ue=`]8;;`,de=RegExp(`(?:\\[(?<code>\\d+)m|\\${ue}(?<uri>.*))`,`y`),fe=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},pe=e=>`[${e}m`,me=e=>`${ue}${e}`,he=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:A(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=A(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(ue,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},ge=e=>{let t=e.split(` `),n=t.length;for(;n&&!A(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},_e=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=A(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=A(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),he(s,r,t),c=A(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){he(s,r,t),c=A(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){he(s,r,t),c=A(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>ge(e)));let l=s.join(`
3
- `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){de.lastIndex=e+1;let t=de.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
4
- `){a&&(r+=me(``));let e=i?fe(i):void 0;i&&e&&(r+=pe(e))}else t===`
5
- `&&(i&&fe(i)&&(r+=pe(i)),a&&(r+=me(a)))}return r},ve=/\r?\n/;function j(e,t,n){return String(e).normalize().split(ve).map(e=>_e(e,t,n)).join(`
6
- `)}var M=e.t(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}}))();function ye(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a].disabled?ye(a,t<0?-1:1,n):a}const N={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,date:{monthNames:[...[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function be(e,t){if(typeof e==`string`)return N.aliases.get(e)===t;for(let n of e)if(n!==void 0&&be(n,t))return!0;return!1}function xe(e,t){if(e===t)return;let n=e.split(`
2
+ const e=require(`./chunk-i8uDWG73.cjs`),t=require(`./dist-CSf6owGv.cjs`);let n=require(`radashi`),r=require(`node:util`),i=require(`node:process`);i=e.r(i,1);let a=require(`node:readline`);a=e.r(a,1);let o=require(`node:tty`);require(`node:fs`);let s=require(`node:path`);s=e.r(s,1);let c=require(`jiti`),l=require(`node:child_process`),u=require(`node:fs/promises`);u=e.r(u,1);let d=require(`node:module`),f=require(`jsonc-parser`),p=require(`dedent`);p=e.r(p,1);let m=require(`magicast`),h=require(`yaml`);var g=e.t(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),_=e.r(g(),1);const v={REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,INTERNAL:`CLI.INTERNAL_ERROR`,SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CANCELLED:`CLI.CANCELLED`,UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,INVALID_VALUE:`ENV.INVALID_VALUE`,MISSING_VARIABLE:`ENV.MISSING_VARIABLE`},y={CLI_INTERNAL_ERROR:`CLI.INTERNAL_ERROR`,CLI_SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CLI_REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,CLI_GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,CLI_NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,CLI_CANCELLED:`CLI.CANCELLED`,CLI_UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,CLI_INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,ENV_VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,ENV_INVALID_VALUE:`ENV.INVALID_VALUE`,ENV_MISSING_VARIABLE:`ENV.MISSING_VARIABLE`};function b(){let e=process.env.npm_config_user_agent||``;if(e.includes(`pnpm`))return process.env.npm_command===`dlx`?`pnpm dlx arkenv`:`pnpm arkenv`;if(e.includes(`bun`))return(process.env._||process.argv[1]||``).includes(`bunx`)||process.env.npm_command===`x`?`bunx arkenv`:`bun arkenv`;if(e.includes(`yarn`))return process.env.npm_command===`dlx`?`yarn dlx arkenv`:`yarn arkenv`;if(e.includes(`npm`))return`npx arkenv`;let t=process.env._||process.argv[1]||``;return t.includes(`npx`)?`npx arkenv`:t.includes(`bunx`)?`bunx arkenv`:t.includes(`pnpm`)?`pnpm arkenv`:t.includes(`yarn`)?`yarn arkenv`:t.includes(`bun`)?`bun arkenv`:`arkenv`}function x(e,t=b()){return e.replace(/\{bin\}/g,t)}function S(e,t=b()){let n={...e};return n.command&&=x(n.command,t),n.commands&&=n.commands.map(e=>x(e,t)),n}function ee(e){return e.replace(/\x1B\[\d+m/g,``).replace(/\x1B\[[0-9;]*[a-zA-Z]/g,``)}function C(e,n,r){let i=ee(e);return r?.debugSecrets||t.s(r?.debugSecrets)?i:n&&t.l(n)?i.replace(/\(was .*\)/g,`(was [REDACTED])`):i}var te=class{info(e){process.stderr.write(`${_.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${_.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${_.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${_.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${_.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${_.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${_.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}reportCompleted(e){let t=e.diagnostics.map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>S(e))})),n=(e.nextActions??[]).map(e=>S(e));this.json({ok:!0,commandId:e.commandId,result:e.result,exitCode:e.exitCode,diagnostics:t,nextActions:n})}reportErrored(e){let t=(e.error.nextActions??[]).map(e=>S(e)),n=(e.nextActions??t).map(e=>S(e)),r=(e.diagnostics??[]).map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>S(e))}));this.json({ok:!1,commandId:e.commandId,error:{...e.error,nextActions:t},diagnostics:r,nextActions:n})}cancel(e,t=`cli`){this.reportErrored({ok:!1,commandId:t,error:{code:v.CANCELLED,severity:`info`,summary:C(e),nextActions:[]},diagnostics:[],nextActions:[]})}fatal(e,t,n=`cli`){let r=t instanceof Error?t.message:t?String(t):void 0;throw this.reportErrored({ok:!1,commandId:n,error:{code:v.INTERNAL,severity:`error`,summary:C(e),...r===void 0?{}:{why:C(r)},...r===void 0?{}:{meta:{error:r}},nextActions:[]},diagnostics:[],nextActions:[]}),t instanceof Error?t:Error(e)}refuse(e,t=`init`){let n=e.nextActions??(e.retryWith?.includes(`--force`)?[{kind:`run-command`,label:`Re-run with --force to bypass this check`,command:`{bin} ${t} --force`}]:[]);this.reportErrored({ok:!1,commandId:t,error:{code:e.code,severity:`error`,summary:C(e.message),...e.why?{why:C(e.why)}:{},...e.details===void 0?{}:{meta:e.details},nextActions:n},diagnostics:[],nextActions:n})}finish(e,t,n=`init`){this.reportCompleted({ok:!0,commandId:n,result:{message:e,...t??{}},exitCode:0,diagnostics:[],nextActions:[]})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},w=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t,n){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){}reportCompleted(e){}reportErrored(e){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const T=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),E=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,D=e=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,O=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,ne=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,re=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ie=/\t{1,1000}/y,ae=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/uy,oe=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,se=/\p{M}+/gu,ce={limit:1/0,ellipsis:``},le=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?le(i,ce,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[oe,l],[O,0],[ne,o],[ie,s],[ae,c],[re,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(se,``)){let t=e.codePointAt(0)||0;if(S=E(t)?2:D(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===re?T(e.slice(p,n.lastIndex)):n===ae?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},ue={limit:1/0,ellipsis:``,ellipsisWidth:0},k=(e,t={})=>le(e,ue,t).width,de=`]8;;`,fe=RegExp(`(?:\\[(?<code>\\d+)m|\\${de}(?<uri>.*))`,`y`),pe=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},me=e=>`[${e}m`,he=e=>`${de}${e}`,ge=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:k(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=k(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(de,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},_e=e=>{let t=e.split(` `),n=t.length;for(;n&&!k(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},ve=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=k(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=k(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),ge(s,r,t),c=k(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){ge(s,r,t),c=k(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){ge(s,r,t),c=k(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>_e(e)));let l=s.join(`
3
+ `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){fe.lastIndex=e+1;let t=fe.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
4
+ `){a&&(r+=he(``));let e=i?pe(i):void 0;i&&e&&(r+=me(e))}else t===`
5
+ `&&(i&&pe(i)&&(r+=me(i)),a&&(r+=he(a)))}return r},ye=/\r?\n/;function A(e,t,n){return String(e).normalize().split(ye).map(e=>ve(e,t,n)).join(`
6
+ `)}var j=e.t(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}}))();function be(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a].disabled?be(a,t<0?-1:1,n):a}const M={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,date:{monthNames:[...[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function xe(e,t){if(typeof e==`string`)return M.aliases.get(e)===t;for(let n of e)if(n!==void 0&&xe(n,t))return!0;return!1}function Se(e,t){if(e===t)return;let n=e.split(`
7
7
  `),r=t.split(`
8
- `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const Se=globalThis.process.platform.startsWith(`win`),Ce=Symbol(`clack:cancel`);function P(e){return e===Ce}function we(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Te({input:e=i.stdin,output:t=i.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let s=a.createInterface({input:e,output:t,prompt:``,tabSize:1});a.emitKeypressEvents(e,s),e instanceof o.ReadStream&&e.isTTY&&e.setRawMode(!0);let c=(i,{name:o,sequence:s})=>{if(be([String(i),o,s],`cancel`)){r&&t.write(M.cursor.show),process.exit(0);return}if(!n)return;let l=o===`return`?0:-1,u=o===`return`?-1:0;a.moveCursor(t,l,u,()=>{a.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return r&&t.write(M.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),r&&t.write(M.cursor.show),e instanceof o.ReadStream&&e.isTTY&&!Se&&e.setRawMode(!1),s.terminal=!1,s.close()}}const Ee=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,De=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function Oe(e,t,n,r=n,a){return j(t,Ee(e??i.stdout)-n.length,{hard:!0,trim:!1}).split(`
8
+ `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const Ce=globalThis.process.platform.startsWith(`win`),we=Symbol(`clack:cancel`);function N(e){return e===we}function Te(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Ee({input:e=i.stdin,output:t=i.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let s=a.createInterface({input:e,output:t,prompt:``,tabSize:1});a.emitKeypressEvents(e,s),e instanceof o.ReadStream&&e.isTTY&&e.setRawMode(!0);let c=(i,{name:o,sequence:s})=>{if(xe([String(i),o,s],`cancel`)){r&&t.write(j.cursor.show),process.exit(0);return}if(!n)return;let l=o===`return`?0:-1,u=o===`return`?-1:0;a.moveCursor(t,l,u,()=>{a.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return r&&t.write(j.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),r&&t.write(j.cursor.show),e instanceof o.ReadStream&&e.isTTY&&!Ce&&e.setRawMode(!1),s.terminal=!1,s.close()}}const De=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,Oe=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function ke(e,t,n,r=n,a){return A(t,De(e??i.stdout)-n.length,{hard:!0,trim:!1}).split(`
9
9
  `).map((e,t)=>{let i=a?a(e,t):e;return`${t===0?r:n}${i}`}).join(`
10
- `)}let ke=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;constructor(e,t=!0){let{input:n=i.stdin,output:r=i.stdout,render:a,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=a.bind(this),this._track=t,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(Ce);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=a.default.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),we(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),we(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),we(this.input,!1),e(Ce)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}onKeypress(e,t){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&N.aliases.has(t.name)&&this.emit(`cursor`,N.aliases.get(t.name)),N.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e?.toLowerCase(),t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}be([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
11
- `),we(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=j(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
- `).length-1;this.output.write(M.cursor.move(-999,e*-1))}render(){let e=j(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(M.cursor.hide);else{let t=xe(this._prevFrame,e),n=De(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(M.cursor.move(0,a-i)),this.output.write(M.erase.lines(1));let t=e.split(`
13
- `);this.output.write(t[a]),this._prevFrame=e,this.output.write(M.cursor.move(0,t.length-a-1));return}else if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(M.cursor.move(0,e))}this.output.write(M.erase.down());let t=e.split(`
10
+ `)}let Ae=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;constructor(e,t=!0){let{input:n=i.stdin,output:r=i.stdout,render:a,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=a.bind(this),this._track=t,this._abortSignal=o,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(we);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=a.default.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),Te(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(j.cursor.show),this.output.off(`resize`,this.render),Te(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(j.cursor.show),this.output.off(`resize`,this.render),Te(this.input,!1),e(we)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}onKeypress(e,t){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&M.aliases.has(t.name)&&this.emit(`cursor`,M.aliases.get(t.name)),M.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e?.toLowerCase(),t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}xe([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
11
+ `),Te(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=A(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
+ `).length-1;this.output.write(j.cursor.move(-999,e*-1))}render(){let e=A(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(j.cursor.hide);else{let t=Se(this._prevFrame,e),n=Oe(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(j.cursor.move(0,a-i)),this.output.write(j.erase.lines(1));let t=e.split(`
13
+ `);this.output.write(t[a]),this._prevFrame=e,this.output.write(j.cursor.move(0,t.length-a-1));return}else if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(j.cursor.move(0,e))}this.output.write(j.erase.down());let t=e.split(`
14
14
  `).slice(a);this.output.write(t.join(`
15
- `)),this._prevFrame=e;return}}this.output.write(M.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var Ae=class extends ke{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(M.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},je=class extends ke{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n].disabled?ye(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=ye(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=ye(this.cursor,1,this.options);break}this.changeValue()})}},Me=class extends ke{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),[n,...i]=e.slice(this.cursor);return`${t}${(0,r.styleText)(`inverse`,n)}${i.join(``)}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function Ne(){return i.default.platform===`win32`?!!i.default.env.CI||!!i.default.env.WT_SESSION||!!i.default.env.TERMINUS_SUBLIME||i.default.env.ConEmuTask===`{cmd::Cmder}`||i.default.env.TERM_PROGRAM===`Terminus-Sublime`||i.default.env.TERM_PROGRAM===`vscode`||i.default.env.TERM===`xterm-256color`||i.default.env.TERM===`alacritty`||i.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:i.default.env.TERM!==`linux`}const Pe=Ne(),Fe=()=>process.env.CI===`true`,F=(e,t)=>Pe?e:t,Ie=F(`◆`,`*`),Le=F(`■`,`x`),Re=F(`▲`,`x`),I=F(`◇`,`o`),L=F(`│`,`|`),R=F(`└`,`—`),ze=F(`●`,`>`),Be=F(`○`,` `),Ve=F(`─`,`-`),He=F(`╮`,`+`),Ue=F(`├`,`+`),We=F(`╯`,`+`),Ge=F(`╰`,`+`),Ke=F(`●`,`•`),qe=F(`◆`,`*`),Je=F(`▲`,`!`),Ye=F(`■`,`x`),Xe=e=>{switch(e){case`initial`:case`active`:return(0,r.styleText)(`cyan`,Ie);case`cancel`:return(0,r.styleText)(`red`,Le);case`error`:return(0,r.styleText)(`yellow`,Re);case`submit`:return(0,r.styleText)(`green`,I)}},Ze=e=>{switch(e){case`initial`:case`active`:return(0,r.styleText)(`cyan`,L);case`cancel`:return(0,r.styleText)(`red`,L);case`error`:return(0,r.styleText)(`yellow`,L);case`submit`:return(0,r.styleText)(`green`,L)}},Qe=(e,t,n,r,i)=>{let a=t,o=0;for(let t=n;t<r;t++){let n=e[t];if(a-=n.length,o++,a<=i)break}return{lineCount:a,removals:o}},$e=({cursor:e,options:t,style:n,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=Ee(i)-o,l=De(i),u=(0,r.styleText)(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let r=y;r<b;r++){let i=j(n(t[r],r===e),c,{hard:!0,trim:!1}).split(`
16
- `);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>Qe(_,r,e,t,d);m?({lineCount:r,removals:t}=a(0,i),r>d&&({lineCount:r,removals:n}=a(i+1,_.length))):({lineCount:r,removals:n}=a(i+1,_.length),r>d&&({lineCount:r,removals:t}=a(0,i))),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},z=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new Ae({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??N.withGuide,a=`${Xe(this.state)} `,o=i?`${(0,r.styleText)(`gray`,L)} `:``,s=Oe(e.output,e.message,o,a),c=`${i?`${(0,r.styleText)(`gray`,L)}
15
+ `)),this._prevFrame=e;return}}this.output.write(j.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var je=class extends Ae{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(j.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Me=class extends Ae{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n].disabled?be(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=be(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=be(this.cursor,1,this.options);break}this.changeValue()})}},Ne=class extends Ae{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),[n,...i]=e.slice(this.cursor);return`${t}${(0,r.styleText)(`inverse`,n)}${i.join(``)}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function Pe(){return i.default.platform===`win32`?!!i.default.env.CI||!!i.default.env.WT_SESSION||!!i.default.env.TERMINUS_SUBLIME||i.default.env.ConEmuTask===`{cmd::Cmder}`||i.default.env.TERM_PROGRAM===`Terminus-Sublime`||i.default.env.TERM_PROGRAM===`vscode`||i.default.env.TERM===`xterm-256color`||i.default.env.TERM===`alacritty`||i.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:i.default.env.TERM!==`linux`}const Fe=Pe(),Ie=()=>process.env.CI===`true`,P=(e,t)=>Fe?e:t,Le=P(`◆`,`*`),Re=P(`■`,`x`),ze=P(`▲`,`x`),F=P(`◇`,`o`),I=P(`│`,`|`),L=P(`└`,`—`),Be=P(`●`,`>`),Ve=P(`○`,` `),He=P(`─`,`-`),Ue=P(`╮`,`+`),We=P(`├`,`+`),Ge=P(`╯`,`+`),Ke=P(`╰`,`+`),qe=P(`●`,`•`),Je=P(`◆`,`*`),Ye=P(`▲`,`!`),Xe=P(`■`,`x`),Ze=e=>{switch(e){case`initial`:case`active`:return(0,r.styleText)(`cyan`,Le);case`cancel`:return(0,r.styleText)(`red`,Re);case`error`:return(0,r.styleText)(`yellow`,ze);case`submit`:return(0,r.styleText)(`green`,F)}},Qe=e=>{switch(e){case`initial`:case`active`:return(0,r.styleText)(`cyan`,I);case`cancel`:return(0,r.styleText)(`red`,I);case`error`:return(0,r.styleText)(`yellow`,I);case`submit`:return(0,r.styleText)(`green`,I)}},$e=(e,t,n,r,i)=>{let a=t,o=0;for(let t=n;t<r;t++){let n=e[t];if(a-=n.length,o++,a<=i)break}return{lineCount:a,removals:o}},et=({cursor:e,options:t,style:n,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=De(i)-o,l=Oe(i),u=(0,r.styleText)(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let r=y;r<b;r++){let i=A(n(t[r],r===e),c,{hard:!0,trim:!1}).split(`
16
+ `);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>$e(_,r,e,t,d);m?({lineCount:r,removals:t}=a(0,i),r>d&&({lineCount:r,removals:n}=a(i+1,_.length))):({lineCount:r,removals:n}=a(i+1,_.length),r>d&&({lineCount:r,removals:t}=a(0,i))),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},R=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new je({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??M.withGuide,a=`${Ze(this.state)} `,o=i?`${(0,r.styleText)(`gray`,I)} `:``,s=ke(e.output,e.message,o,a),c=`${i?`${(0,r.styleText)(`gray`,I)}
17
17
  `:``}${s}
18
- `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${i?`${(0,r.styleText)(`gray`,L)} `:``}${(0,r.styleText)(`dim`,l)}`;case`cancel`:return`${c}${i?`${(0,r.styleText)(`gray`,L)} `:``}${(0,r.styleText)([`strikethrough`,`dim`],l)}${i?`
19
- ${(0,r.styleText)(`gray`,L)}`:``}`;default:{let a=i?`${(0,r.styleText)(`cyan`,L)} `:``,o=i?(0,r.styleText)(`cyan`,R):``;return`${c}${a}${this.value?`${(0,r.styleText)(`green`,ze)} ${t}`:`${(0,r.styleText)(`dim`,Be)} ${(0,r.styleText)(`dim`,t)}`}${e.vertical?i?`
20
- ${(0,r.styleText)(`cyan`,L)} `:`
21
- `:` ${(0,r.styleText)(`dim`,`/`)} `}${this.value?`${(0,r.styleText)(`dim`,Be)} ${(0,r.styleText)(`dim`,n)}`:`${(0,r.styleText)(`green`,ze)} ${n}`}
18
+ `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${i?`${(0,r.styleText)(`gray`,I)} `:``}${(0,r.styleText)(`dim`,l)}`;case`cancel`:return`${c}${i?`${(0,r.styleText)(`gray`,I)} `:``}${(0,r.styleText)([`strikethrough`,`dim`],l)}${i?`
19
+ ${(0,r.styleText)(`gray`,I)}`:``}`;default:{let a=i?`${(0,r.styleText)(`cyan`,I)} `:``,o=i?(0,r.styleText)(`cyan`,L):``;return`${c}${a}${this.value?`${(0,r.styleText)(`green`,Be)} ${t}`:`${(0,r.styleText)(`dim`,Ve)} ${(0,r.styleText)(`dim`,t)}`}${e.vertical?i?`
20
+ ${(0,r.styleText)(`cyan`,I)} `:`
21
+ `:` ${(0,r.styleText)(`dim`,`/`)} `}${this.value?`${(0,r.styleText)(`dim`,Ve)} ${(0,r.styleText)(`dim`,n)}`:`${(0,r.styleText)(`green`,Be)} ${n}`}
22
22
  ${o}
23
- `}}}}).prompt()},B={message:(e=[],{symbol:t=(0,r.styleText)(`gray`,L),secondarySymbol:n=(0,r.styleText)(`gray`,L),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??N.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
23
+ `}}}}).prompt()},z={message:(e=[],{symbol:t=(0,r.styleText)(`gray`,I),secondarySymbol:n=(0,r.styleText)(`gray`,I),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??M.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
24
24
  `);if(f.length>0){let[e,...r]=f;e.length>0?s.push(`${u}${e}`):s.push(c?t:``);for(let e of r)e.length>0?s.push(`${d}${e}`):s.push(c?n:``)}i.write(`${s.join(`
25
25
  `)}
26
- `)},info:(e,t)=>{B.message(e,{...t,symbol:(0,r.styleText)(`blue`,Ke)})},success:(e,t)=>{B.message(e,{...t,symbol:(0,r.styleText)(`green`,qe)})},step:(e,t)=>{B.message(e,{...t,symbol:(0,r.styleText)(`green`,I)})},warn:(e,t)=>{B.message(e,{...t,symbol:(0,r.styleText)(`yellow`,Je)})},warning:(e,t)=>{B.warn(e,t)},error:(e,t)=>{B.message(e,{...t,symbol:(0,r.styleText)(`red`,Ye)})}},et=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${(0,r.styleText)(`gray`,R)} `:``;n.write(`${i}${(0,r.styleText)(`red`,e)}
26
+ `)},info:(e,t)=>{z.message(e,{...t,symbol:(0,r.styleText)(`blue`,qe)})},success:(e,t)=>{z.message(e,{...t,symbol:(0,r.styleText)(`green`,Je)})},step:(e,t)=>{z.message(e,{...t,symbol:(0,r.styleText)(`green`,F)})},warn:(e,t)=>{z.message(e,{...t,symbol:(0,r.styleText)(`yellow`,Ye)})},warning:(e,t)=>{z.warn(e,t)},error:(e,t)=>{z.message(e,{...t,symbol:(0,r.styleText)(`red`,Xe)})}},tt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${(0,r.styleText)(`gray`,L)} `:``;n.write(`${i}${(0,r.styleText)(`red`,e)}
27
27
 
28
- `)},tt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${(0,r.styleText)(`gray`,L)}
29
- ${(0,r.styleText)(`gray`,R)} `:``;n.write(`${i}${e}
28
+ `)},nt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??M.withGuide?`${(0,r.styleText)(`gray`,I)}
29
+ ${(0,r.styleText)(`gray`,L)} `:``;n.write(`${i}${e}
30
30
 
31
- `)},nt=e=>(0,r.styleText)(`dim`,e),rt=(e,t,n)=>{let r={hard:!0,trim:!1},i=j(e,t,r).split(`
32
- `),a=i.reduce((e,t)=>Math.max(A(t),e),0);return j(e,t-(i.map(n).reduce((e,t)=>Math.max(A(t),e),0)-a),r)},it=(e=``,t=``,n)=>{let a=n?.output??i.default.stdout,o=n?.withGuide??N.withGuide,s=n?.format??nt,c=[``,...rt(e,Ee(a)-6,s).split(`
33
- `).map(s),``],l=A(t),u=Math.max(c.reduce((e,t)=>{let n=A(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,r.styleText)(`gray`,L)} ${e}${` `.repeat(u-A(e))}${(0,r.styleText)(`gray`,L)}`).join(`
34
- `),f=o?`${(0,r.styleText)(`gray`,L)}
35
- `:``,p=o?Ue:Ge;a.write(`${f}${(0,r.styleText)(`green`,I)} ${(0,r.styleText)(`reset`,t)} ${(0,r.styleText)(`gray`,Ve.repeat(Math.max(u-l-1,1))+He)}
31
+ `)},rt=e=>(0,r.styleText)(`dim`,e),it=(e,t,n)=>{let r={hard:!0,trim:!1},i=A(e,t,r).split(`
32
+ `),a=i.reduce((e,t)=>Math.max(k(t),e),0);return A(e,t-(i.map(n).reduce((e,t)=>Math.max(k(t),e),0)-a),r)},at=(e=``,t=``,n)=>{let a=n?.output??i.default.stdout,o=n?.withGuide??M.withGuide,s=n?.format??rt,c=[``,...it(e,De(a)-6,s).split(`
33
+ `).map(s),``],l=k(t),u=Math.max(c.reduce((e,t)=>{let n=k(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,r.styleText)(`gray`,I)} ${e}${` `.repeat(u-k(e))}${(0,r.styleText)(`gray`,I)}`).join(`
34
+ `),f=o?`${(0,r.styleText)(`gray`,I)}
35
+ `:``,p=o?We:Ke;a.write(`${f}${(0,r.styleText)(`green`,F)} ${(0,r.styleText)(`reset`,t)} ${(0,r.styleText)(`gray`,He.repeat(Math.max(u-l-1,1))+Ue)}
36
36
  ${d}
37
- ${(0,r.styleText)(`gray`,p+Ve.repeat(u+2)+We)}
38
- `)},at=e=>(0,r.styleText)(`magenta`,e),ot=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:a,frames:o=Pe?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=Pe?80:120,signal:c,...l}={})=>{let u=Fe(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ee(n),y=l?.styleFrame??at,b=e=>{let n=e>1?a??N.messages.error:i??N.messages.cancel;m=e===1,p&&(k(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),C=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},w=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},ee=()=>{if(g===void 0)return;u&&n.write(`
39
- `);let e=j(g,v,{hard:!0,trim:!1}).split(`
40
- `);e.length>1&&n.write(M.cursor.up(e.length-1)),n.write(M.cursor.to(0)),n.write(M.erase.down())},T=e=>e.replace(/\.+$/,``),E=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},D=l.withGuide??N.withGuide,O=(t=``)=>{p=!0,d=Te({output:n}),h=T(t),_=performance.now(),D&&n.write(`${(0,r.styleText)(`gray`,L)}
41
- `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;ee(),g=h;let t=y(o[i]),r;if(u)r=`${t} ${h}...`;else if(e===`timer`)r=`${t} ${h} ${E(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);r=`${t} ${h}${e}`}let s=j(r,v,{hard:!0,trim:!1});n.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},k=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),ee();let o=i===0?(0,r.styleText)(`green`,I):i===1?(0,r.styleText)(`red`,Le):(0,r.styleText)(`red`,Re);h=t??h,a||(e===`timer`?n.write(`${o} ${h} ${E(_)}
37
+ ${(0,r.styleText)(`gray`,p+He.repeat(u+2)+Ge)}
38
+ `)},ot=e=>(0,r.styleText)(`magenta`,e),st=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:a,frames:o=Fe?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=Fe?80:120,signal:c,...l}={})=>{let u=Ie(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=De(n),y=l?.styleFrame??ot,b=e=>{let n=e>1?a??M.messages.error:i??M.messages.cancel;m=e===1,p&&(O(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),ee=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},C=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},te=()=>{if(g===void 0)return;u&&n.write(`
39
+ `);let e=A(g,v,{hard:!0,trim:!1}).split(`
40
+ `);e.length>1&&n.write(j.cursor.up(e.length-1)),n.write(j.cursor.to(0)),n.write(j.erase.down())},w=e=>e.replace(/\.+$/,``),T=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},E=l.withGuide??M.withGuide,D=(t=``)=>{p=!0,d=Ee({output:n}),h=w(t),_=performance.now(),E&&n.write(`${(0,r.styleText)(`gray`,I)}
41
+ `);let i=0,a=0;ee(),f=setInterval(()=>{if(u&&h===g)return;te(),g=h;let t=y(o[i]),r;if(u)r=`${t} ${h}...`;else if(e===`timer`)r=`${t} ${h} ${T(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);r=`${t} ${h}${e}`}let s=A(r,v,{hard:!0,trim:!1});n.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},O=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),te();let o=i===0?(0,r.styleText)(`green`,F):i===1?(0,r.styleText)(`red`,Re):(0,r.styleText)(`red`,ze);h=t??h,a||(e===`timer`?n.write(`${o} ${h} ${T(_)}
42
42
  `):n.write(`${o} ${h}
43
- `)),w(),d()};return{start:O,stop:(e=``)=>k(e,0),message:(e=``)=>{h=T(e??h)},cancel:(e=``)=>k(e,1),error:(e=``)=>k(e,2),clear:()=>k(``,0,!0),get isCancelled(){return m}}},st=(e,t)=>e.includes(`
43
+ `)),C(),d()};return{start:D,stop:(e=``)=>O(e,0),message:(e=``)=>{h=w(e??h)},cancel:(e=``)=>O(e,1),error:(e=``)=>O(e,2),clear:()=>O(``,0,!0),get isCancelled(){return m}}},ct=(e,t)=>e.includes(`
44
44
  `)?e.split(`
45
45
  `).map(e=>t(e)).join(`
46
- `):t(e),ct=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`disabled`:return`${(0,r.styleText)(`gray`,Be)} ${st(n,e=>(0,r.styleText)(`gray`,e))}${e.hint?` ${(0,r.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${st(n,e=>(0,r.styleText)(`dim`,e))}`;case`active`:return`${(0,r.styleText)(`green`,ze)} ${n}${e.hint?` ${(0,r.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${st(n,e=>(0,r.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,r.styleText)(`dim`,Be)} ${st(n,e=>(0,r.styleText)(`dim`,e))}`}};return new je({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??N.withGuide,i=`${Xe(this.state)} `,a=`${Ze(this.state)} `,o=Oe(e.output,e.message,a,i),s=`${n?`${(0,r.styleText)(`gray`,L)}
46
+ `):t(e),B=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`disabled`:return`${(0,r.styleText)(`gray`,Ve)} ${ct(n,e=>(0,r.styleText)(`gray`,e))}${e.hint?` ${(0,r.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${ct(n,e=>(0,r.styleText)(`dim`,e))}`;case`active`:return`${(0,r.styleText)(`green`,Be)} ${n}${e.hint?` ${(0,r.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${ct(n,e=>(0,r.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,r.styleText)(`dim`,Ve)} ${ct(n,e=>(0,r.styleText)(`dim`,e))}`}};return new Me({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??M.withGuide,i=`${Ze(this.state)} `,a=`${Qe(this.state)} `,o=ke(e.output,e.message,a,i),s=`${n?`${(0,r.styleText)(`gray`,I)}
47
47
  `:``}${o}
48
- `;switch(this.state){case`submit`:{let i=n?`${(0,r.styleText)(`gray`,L)} `:``;return`${s}${Oe(e.output,t(this.options[this.cursor],`selected`),i)}`}case`cancel`:{let i=n?`${(0,r.styleText)(`gray`,L)} `:``;return`${s}${Oe(e.output,t(this.options[this.cursor],`cancelled`),i)}${n?`
49
- ${(0,r.styleText)(`gray`,L)}`:``}`}default:{let i=n?`${(0,r.styleText)(`cyan`,L)} `:``,a=n?(0,r.styleText)(`cyan`,R):``,o=s.split(`
50
- `).length,c=n?2:1;return`${s}${i}${$e({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:o+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
48
+ `;switch(this.state){case`submit`:{let i=n?`${(0,r.styleText)(`gray`,I)} `:``;return`${s}${ke(e.output,t(this.options[this.cursor],`selected`),i)}`}case`cancel`:{let i=n?`${(0,r.styleText)(`gray`,I)} `:``;return`${s}${ke(e.output,t(this.options[this.cursor],`cancelled`),i)}${n?`
49
+ ${(0,r.styleText)(`gray`,I)}`:``}`}default:{let i=n?`${(0,r.styleText)(`cyan`,I)} `:``,a=n?(0,r.styleText)(`cyan`,L):``,o=s.split(`
50
+ `).length,c=n?2:1;return`${s}${i}${et({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:o+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
51
51
  ${i}`)}
52
52
  ${a}
53
- `}}}}).prompt()},lt=`${(0,r.styleText)(`gray`,L)} `,V={message:async(e,{symbol:t=(0,r.styleText)(`gray`,L)}={})=>{process.stdout.write(`${(0,r.styleText)(`gray`,L)}
53
+ `}}}}).prompt()},lt=`${(0,r.styleText)(`gray`,I)} `,V={message:async(e,{symbol:t=(0,r.styleText)(`gray`,I)}={})=>{process.stdout.write(`${(0,r.styleText)(`gray`,I)}
54
54
  ${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
55
55
  ${lt}`),t.includes(`
56
56
  `)&&(n=3+(0,r.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
57
57
  `))).length);let e=(0,r.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
58
58
  ${lt}${t.trimStart()}`),n=3+(0,r.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
59
- `)},info:e=>V.message(e,{symbol:(0,r.styleText)(`blue`,Ke)}),success:e=>V.message(e,{symbol:(0,r.styleText)(`green`,qe)}),step:e=>V.message(e,{symbol:(0,r.styleText)(`green`,I)}),warn:e=>V.message(e,{symbol:(0,r.styleText)(`yellow`,Je)}),warning:e=>V.warn(e),error:e=>V.message(e,{symbol:(0,r.styleText)(`red`,Ye)})},ut=e=>new Me({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??N.withGuide,n=`${`${t?`${(0,r.styleText)(`gray`,L)}
60
- `:``}${Xe(this.state)} `}${e.message}
61
- `,i=e.placeholder?(0,r.styleText)(`inverse`,e.placeholder[0])+(0,r.styleText)(`dim`,e.placeholder.slice(1)):(0,r.styleText)([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,r.styleText)(`yellow`,this.error)}`:``,i=t?`${(0,r.styleText)(`yellow`,L)} `:``,o=t?(0,r.styleText)(`yellow`,R):``;return`${n.trim()}
59
+ `)},info:e=>V.message(e,{symbol:(0,r.styleText)(`blue`,qe)}),success:e=>V.message(e,{symbol:(0,r.styleText)(`green`,Je)}),step:e=>V.message(e,{symbol:(0,r.styleText)(`green`,F)}),warn:e=>V.message(e,{symbol:(0,r.styleText)(`yellow`,Ye)}),warning:e=>V.warn(e),error:e=>V.message(e,{symbol:(0,r.styleText)(`red`,Xe)})},ut=e=>new Ne({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??M.withGuide,n=`${`${t?`${(0,r.styleText)(`gray`,I)}
60
+ `:``}${Ze(this.state)} `}${e.message}
61
+ `,i=e.placeholder?(0,r.styleText)(`inverse`,e.placeholder[0])+(0,r.styleText)(`dim`,e.placeholder.slice(1)):(0,r.styleText)([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,r.styleText)(`yellow`,this.error)}`:``,i=t?`${(0,r.styleText)(`yellow`,I)} `:``,o=t?(0,r.styleText)(`yellow`,L):``;return`${n.trim()}
62
62
  ${i}${a}
63
63
  ${o}${e}
64
- `}case`submit`:{let e=o?` ${(0,r.styleText)(`dim`,o)}`:``;return`${n}${t?(0,r.styleText)(`gray`,L):``}${e}`}case`cancel`:{let e=o?` ${(0,r.styleText)([`strikethrough`,`dim`],o)}`:``,i=t?(0,r.styleText)(`gray`,L):``;return`${n}${i}${e}${o.trim()?`
65
- ${i}`:``}`}default:return`${n}${t?`${(0,r.styleText)(`cyan`,L)} `:``}${a}
66
- ${t?(0,r.styleText)(`cyan`,R):``}
67
- `}}}).prompt();var dt=class{info(e){process.stdout.write(`${_.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${_.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${_.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){it(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return ot()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}fatal(e,t,n){if(process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`),t){let e=`${_.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){tt(e)}reportCompleted(e){e.exitCode===0&&this.success(`Environment variables are valid`)}reportErrored(e){this.error(e.error.summary),e.error.why&&this.warn(e.error.why)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},ft=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.reporter?this.reporter=e.reporter:e.isJson?this.reporter=new ee:e.isQuiet?this.reporter=new T:this.reporter=new dt}get isJson(){return this.options.isJson}debug(e){this.reporter.log(e)}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){!this.options.isJson||this.options.isYes||(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e,t=`cli`){this.reporter.cancel(e,t)}fatal(e,t,n=`cli`){this.reporter.fatal(e,t,n)}refuse(e,t=`init`){this.reporter.refuse(e,t)}finish(e,t,n=`init`){this.reporter.finish(e,t,n)}reportCompleted(e){this.reporter.reportCompleted(e)}reportErrored(e){this.reporter.reportErrored(e)}async flush(){await this.reporter.flush()}};function pt(e){return e instanceof Error?e.stack??e.message:String(e)}function mt(e,t,n){e(`${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&e(n.stack)}const ht={debug:0,info:1,warn:2,error:3},gt=new Set([`debug`,`info`,`warn`,`error`,`silent`]);function _t(e){if(!e)return;let t=e.trim().toLowerCase();if(gt.has(t))return t}function vt(){if(!(typeof process>`u`))return _t(process.env?.ARKENV_LOG_LEVEL)}function yt(e){return e?.level??vt()??`info`}function bt(e,t){return e===`silent`?!1:ht[t]>=ht[e]}function xt(e,t,n){return(r,...i)=>{bt(e,t)&&console[n](r,...i)}}function St(e){let t=yt(e);return{debug:xt(t,`debug`,`debug`),info:xt(t,`info`,`info`),warn:xt(t,`warn`,`warn`),error:xt(t,`error`,`error`)}}let Ct=St();const wt=`[ArkEnv]`,Tt=`[ArkEnv Watcher]`;function Et(e){return{logBuildWarning(t){e.warn(`⚠️ ${wt} ${t}`)},logBuildError(t){e.error(`❌ ${wt} ${t}`)},logBuildErrorDetail(t){e.error(t)},logBuildErrorBlankLine(){e.error(``)},logBuildErrorWithCause(t,n){e.error(`❌ ${wt} ${t}`),e.error(pt(n))},logWatcherError(t){e.error(`${Tt} ${t}`)},logWatcherErrorWithCause(t,n){e.error(`${Tt} ${t}`),e.error(pt(n))}}}let Dt=Et(Ct);function Ot(e,t){Dt.logBuildErrorWithCause(e,t)}var kt=e.n({safeAppend:()=>jt});const At=`// @arkenv-types`;async function jt(e,t,n,r){try{let r=await c.default.readFile(e,`utf-8`),i=n===`vite`?`ImportMetaEnvAugmented`:`ProcessEnvAugmented`;if(r.includes(At)||r.includes(i))return!1;let a=s.default.dirname(e),o=s.default.relative(a,t).replace(/\.(ts|js|tsx|jsx)$/,``).split(s.default.sep).join(`/`),l=o.startsWith(`.`)?o:`./${o}`,u=n===`vite`?Mt(l):Nt(l),d=r.endsWith(`
68
- `)?``:`
69
- `;return await c.default.appendFile(e,`${d}\n${At}\n${u}\n`,`utf-8`),!0}catch(t){let n=`Failed to append to ${e}`;return r?mt(r.error.bind(r),n,t):Ot(n,t),!1}}function Mt(e){return l.default`
70
- type ImportMetaEnvAugmented = import("@arkenv/vite-plugin").ImportMetaEnvAugmented<
71
- typeof import("${e}").Env
72
- >;
73
-
74
- interface ImportMetaEnv extends ImportMetaEnvAugmented {}
75
-
76
- interface ImportMeta {
77
- readonly env: ImportMetaEnv;
78
- }
79
- `}function Nt(e){return l.default`
80
- type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
81
- typeof import("${e}").Env
82
- >;
83
-
84
- declare namespace NodeJS {
85
- interface ProcessEnv extends ProcessEnvAugmented {}
86
- }
87
- `}function Pt(e,t){return Object.keys(e).includes(t)}function Ft(e){if(typeof e==`string`)return/=\s*\S/.test(e);if(!e||typeof e!=`object`)return!1;let t=e;if(Pt(t,`default`)||Pt(t,`fallback`))return!0;let n=t._def;if(n&&typeof n==`object`){let e=n;if(`defaultValue`in e||e.typeName===`ZodDefault`||e.type===`default`)return!0;if(`innerType`in e)return Ft(e.innerType)}return!1}function It(e){return e.endsWith(`?`)?e.slice(0,-1):e}function Lt(e,t,n){if(e){if(Array.isArray(e)){for(let r of e){if(Array.isArray(r)&&typeof r[0]==`string`){t.push({name:r[0],schema:r[1],hasDefault:!1}),n[r[0]]=r[1];continue}if(r&&typeof r==`object`){let e=r,i=e.key;if(typeof i!=`string`)continue;let a=`value`in e?e.value:void 0;t.push({name:i,schema:a,hasDefault:Pt(e,`default`)}),n[i]=a}}return}if(typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=i&&typeof i==`object`?i:void 0,a=e&&`value`in e?e.value:i;t.push({name:r,schema:a,hasDefault:!!(e&&Pt(e,`default`))}),n[r]=a}}}function Rt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0}function zt(e){let n=[],r={};for(let i of e){if(!i||typeof i!=`object`&&typeof i!=`function`)return{extractable:!1};let e=i,a=e.json,o=typeof a==`function`?a():a,s=n.length;if(o&&typeof o==`object`){let e=o;if((e.domain===`object`||e.required!==void 0||e.optional!==void 0)&&(Lt(e.required,n,r),Lt(e.optional,n,r),n.length>s))continue}let c=o?t.a(i):[];if(n.length===s&&c.length>0){for(let e of c)n.push({name:e,schema:void 0,hasDefault:!1}),r[e]=void 0;continue}if(!(n.length>s)){if(typeof i==`function`)return{extractable:!1};if(!Rt(i)){if(Object.keys(e).length===0)return{extractable:!1};for(let[t,i]of Object.entries(e)){let e=It(t);n.push({name:e,schema:i,hasDefault:Ft(i)}),r[e]=i}}}}return{extractable:!0,keys:n,schema:r}}async function Bt(e,t,n,r){if(r){let n=s.default.resolve(e,r);return await t.exists(n)?n:void 0}if(typeof n.readArkenvConfig==`function`){let r=await n.readArkenvConfig(e);if(r){let n=s.default.resolve(e,r.schema);if(await t.exists(n))return n}}let i=[s.default.resolve(e,`env.ts`),s.default.resolve(e,`src/env.ts`),s.default.resolve(e,`env.js`),s.default.resolve(e,`src/env.js`),s.default.resolve(e,`env.mjs`),s.default.resolve(e,`src/env.mjs`),s.default.resolve(e,`env/server.ts`),s.default.resolve(e,`src/env/server.ts`)],a=await n.suggestDefaultEnvPath(e);a&&i.unshift(s.default.resolve(e,a));for(let e of i)if(await t.exists(e))return e}const H={ERR_INSPECT_NO_CALL:`ERR_INSPECT_NO_CALL`,ERR_INSPECT_UNSUPPORTED:`ERR_INSPECT_UNSUPPORTED`,ERR_INSPECT_UNEXTRACTABLE:`ERR_INSPECT_UNEXTRACTABLE`,ERR_INSPECT_EVAL_THROW:`ERR_INSPECT_EVAL_THROW`};function Vt(e){if(e&&typeof e==`object`&&`name`in e&&e.name===`ArkEnvError`)return!0;let t=e instanceof Error?e.message:String(e);return/validating environment variables/i.test(t)}function Ht(e){if(!(e instanceof Error)&&typeof e!=`object`)return/cannot read propert/i.test(String(e));let t=e instanceof Error?e.message:String(e);return/cannot read propert/i.test(t)||e instanceof TypeError||/is not a function/i.test(t)}function Ut(e){return`No arkenv() schema definition was found in "${e}". No arkenv() definition was found. Ensure arkenv() is called at the top level of the schema module.`}function Wt(e,t){return`Failed to inspect schema module at "${e}": ${t instanceof Error?t.message:String(t)} Upgrade @arkenv/core or @arkenv/standard so the CLI can inspect the schema without validating the environment.`}function Gt(e){return`Failed to inspect schema module at "${e}": Cannot extract keys from the captured definition. Ensure the schema is a supported static map.`}function Kt(e,t){let n=t instanceof Error?t.message:String(t),r=`Failed to load schema module at "${e}": ${n}`;return Ht(t)||/missing [A-Z_][A-Z0-9_]*/.test(n)?`${r} Capture mode does not populate env values. Keep the schema module declarative (\`export const env = arkenv({...})\`) and do not read \`env\` at module scope.`:r}var qt=class{constructor(e={}){this.options=e}async load(e){t.t();try{this.evaluateModule(e.schemaPath);let n=t.n();if(n.length===0)return{ok:!1,code:H.ERR_INSPECT_NO_CALL,message:Ut(e.schemaPath)};let r=zt(n);return r.extractable?{ok:!0,keys:r.keys,schema:r.schema}:{ok:!1,code:H.ERR_INSPECT_UNEXTRACTABLE,message:Gt(e.schemaPath)}}catch(n){return t.n(),Vt(n)?{ok:!1,code:H.ERR_INSPECT_UNSUPPORTED,message:Wt(e.schemaPath,n),cause:n}:{ok:!1,code:H.ERR_INSPECT_EVAL_THROW,message:Kt(e.schemaPath,n),cause:n}}}async validate(e,t){let n={...process.env};for(let e of Object.keys(process.env))(!(e in t)||t[e]===void 0)&&delete process.env[e];for(let[e,n]of Object.entries(t))n!==void 0&&(process.env[e]=n);try{return this.evaluateModule(e.schemaPath),{ok:!0}}catch(t){if(Vt(t)){let e=t&&typeof t==`object`&&`issues`in t?t.issues??[]:[];return{ok:!1,kind:`validation`,message:t instanceof Error?t.message:String(t),issues:e}}return{ok:!1,kind:`load`,code:H.ERR_INSPECT_EVAL_THROW,message:Kt(e.schemaPath,t),cause:t}}finally{for(let e of Object.keys(process.env))e in n||delete process.env[e];for(let[e,t]of Object.entries(n))t!==void 0&&(process.env[e]=t)}}evaluateModule(e){let t={moduleCache:!1,fsCache:!1,tsconfigPaths:!0,...this.options.jitiAliases?{alias:this.options.jitiAliases}:{}};try{(0,u.createJiti)(e,t)(e)}catch(n){let r=n instanceof Error?n.message:String(n);if(!(n instanceof Error&&/tsconfig/i.test(r)&&(/not found/i.test(r)||n.code===`ENOENT`)))throw n;(0,u.createJiti)(e,{...t,tsconfigPaths:!1})(e)}}};async function Jt(e,t){for(let n of t)try{return await c.default.access(s.default.join(e,n)),!0}catch{}return!1}async function Yt(e=process.cwd(),t){if(t?.compilerOptions?.types){let e=t.compilerOptions.types;if(e.includes(`vite`)||e.includes(`vite/client`))return`vite`}try{let t=s.default.join(e,`package.json`),n=await c.default.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`}catch{}return await Jt(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await Jt(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await Jt(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await Xt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function Xt(e=process.cwd(),t){let n=[];try{let t=s.default.join(e,`bunfig.toml`),r=await c.default.readFile(t,`utf-8`);(r.includes(`[serve]`)||r.includes(`[serve.static]`))&&n.push(`serve`),r.includes(`[build]`)&&n.push(`build`)}catch{}if(n.includes(`serve`)&&n.includes(`build`))return n;let{walk:r}=await Promise.resolve().then(()=>$t),i=await r(e),a=n.includes(`serve`),o=n.includes(`build`);for(let e of i)try{let t=await c.default.readFile(e,`utf-8`);if(!a&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(a=!0,n.push(`serve`)),!o&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(o=!0,n.push(`build`)),a&&o)break}catch{}return n}async function Zt(e=process.cwd(),t){let n=process.env.npm_config_user_agent?.toString()||``;if(n.includes(`pnpm`))return`pnpm`;if(n.includes(`yarn`))return`yarn`;if(n.includes(`bun`))return`bun`;if(n.includes(`npm`))return`npm`;let r=t?.path?s.default.dirname(t.path):e;for(;r!==s.default.parse(r).root;){try{let e=s.default.join(r,`package.json`),t=await c.default.readFile(e,`utf-8`),n=JSON.parse(t);if(n.packageManager){if(n.packageManager.startsWith(`pnpm`))return`pnpm`;if(n.packageManager.startsWith(`yarn`))return`yarn`;if(n.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await c.default.readdir(r)}catch{}if(e.includes(`pnpm-lock.yaml`))return`pnpm`;if(e.includes(`yarn.lock`))return`yarn`;if(e.includes(`bun.lockb`))return`bun`;if(e.includes(`package-lock.json`))return`npm`;r=s.default.dirname(r)}return`npm`}async function Qt(e=process.cwd(),t){let n=t;if(!n){let{findTsConfig:t,loadTsConfig:r}=await Promise.resolve().then(()=>on),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=s.default.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!s.default.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await c.default.access(s.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var $t=e.n({getEnvExampleKeys:()=>an,parseEnvExample:()=>tn,resolveImportPaths:()=>nn,scanProjectEnvKeys:()=>rn,walk:()=>en});async function en(e,t=[]){try{let n=await c.default.readdir(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=r.name;if(n===`node_modules`||n===`dist`||n===`build`||n===`.git`||n===`.turbo`||n===`scratch`)continue;await en(s.default.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(s.default.join(e,r.name))}catch{}return t}function tn(e){let t=[],n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.match(/^([A-Z_][A-Z0-9_]*)\s*=/i);r?.[1]&&t.push(r[1])}return Array.from(new Set(t))}function nn(e,t,n){if(e.startsWith(`.`))return[s.default.resolve(s.default.dirname(n),e)];if(s.default.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||s.default.dirname(t.path),a=r.paths||{},o=[];for(let[e,t]of Object.entries(a)){let n=e.endsWith(`*`),r=e.replace(/\*$/,``);o.push({cleanPattern:r,targets:Array.isArray(t)?t:[t],hadStar:n})}o.sort((e,t)=>t.cleanPattern.length-e.cleanPattern.length);for(let{cleanPattern:t,targets:n,hadStar:r}of o)if(r&&e.startsWith(t)||!r&&e===t){let r=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${r}`;return s.default.resolve(i,t)})}return r.baseUrl?[s.default.resolve(i,e)]:[]}async function rn(e,t,n){let r=[],i=await en(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await c.default.readFile(e,`utf-8`),i=n.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of i)e[1]&&r.push(e[1]);let o=n.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of o)e[1]&&r.push(e[1]);if(a){let i=n.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let o of i){let i=o[1],c=[];if(t?c=nn(i,t,e):i.startsWith(`.`)&&(c=[s.default.resolve(s.default.dirname(e),i)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===a)){let e=n.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&r.push(t[1])}}}}catch{}return Array.from(new Set(r))}async function an(e=process.cwd(),t,n){let r=s.default.join(e,`.env.example`);try{let e=tn(await c.default.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await rn(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var on=e.n({checkTsConfig:()=>ln,findTsConfig:()=>U,loadTsConfig:()=>cn});const sn=(0,f.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function U(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==s.default.parse(n).root;){for(let e of t){let t=s.default.join(n,e);try{return await c.default.access(t),t}catch{}}n=s.default.dirname(n)}return null}async function cn(e,t=new Set){let n=s.default.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await c.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=(0,p.parse)(r)||{},a=i.compilerOptions||{},o={};if(i.extends){let n=Array.isArray(i.extends)?i.extends:[i.extends];for(let r of n){let n;if(r.startsWith(`.`)||s.default.isAbsolute(r))n=s.default.resolve(s.default.dirname(e),r);else try{n=sn(r,{paths:[s.default.dirname(e)]})}catch{n=s.default.resolve(s.default.dirname(e),`node_modules`,r)}let i={...(await cn(n,t)).compilerOptions};i.baseUrl&&=s.default.resolve(s.default.dirname(n),i.baseUrl),i.rootDir&&=s.default.resolve(s.default.dirname(n),i.rootDir),o={...o,...i}}}let l={...a};return l.baseUrl&&=s.default.resolve(s.default.dirname(e),l.baseUrl),l.rootDir&&=s.default.resolve(s.default.dirname(e),l.rootDir),o={...o,...l},{...i,path:e,compilerOptions:o}}async function ln(e=process.cwd()){let t=await U(e);if(!t)return{status:`not_found`};let n=s.default.basename(t);try{let e=await cn(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}function un(e,t){let n=e.replace(/^v/,``).split(`.`).map(Number),r=t.replace(/^v/,``).split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function dn(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function fn(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=dn(r[1]);return e!==null&&un(e,t)>=0}let i=n.match(/(?:>=|>|<=|<|=)\s*v?\d+(?:\.\d+){0,2}/g);return!i||i.join(` `)!==n.replace(/\s+/g,` `)?!1:i.some(e=>{let n=e.match(/^(>=|>|<=|<|=)\s*(v?\d+(?:\.\d+){0,2})$/);if(!n)return!1;let[,r,i]=n,a=dn(i);return a&&(r===`>=`||r===`>`||r===`=`)?un(a,t)>=0:!1})}async function pn(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;un(n,r)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${r}.`,current:n,expected:`>= ${r}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let i=null;try{let n=s.default.join(e,`package.json`),r=await c.default.readFile(n,`utf-8`);i=JSON.parse(r),t.push({status:`pass`,requirement:`package.json`,message:`package.json found.`})}catch{t.push({status:`warn`,requirement:`package.json`,message:`package.json not found in the current directory.`})}if(i){let e={...i.dependencies,...i.devDependencies}.typescript,n=`5.1.0`;e?fn(e,n)?t.push({status:`pass`,requirement:`TypeScript Version`,message:`TypeScript version is compatible.`}):t.push({status:`fail`,requirement:`TypeScript Version`,message:`TypeScript version should be >= ${n}.`,current:e,expected:`>= ${n}`}):t.push({status:`warn`,requirement:`TypeScript Version`,message:`TypeScript not found in package.json dependencies.`})}let a=await ln(e);if(a.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=a.parsed.compilerOptions||{};e.strict===!0?t.push({status:`pass`,requirement:`TypeScript Strict Mode`,message:`Strict mode is enabled.`}):t.push({status:`fail`,requirement:`TypeScript Strict Mode`,message:`Strict mode must be enabled.`,current:`false`,expected:`true`});let n=e.moduleResolution?.toLowerCase(),r=e.module?.toLowerCase();[`bundler`,`node16`,`nodenext`].includes(n||``)||!n&&(r===`node16`||r===`nodenext`)?t.push({status:`pass`,requirement:`TypeScript moduleResolution`,message:`moduleResolution is set to ${n||`implicit`}.`}):t.push({status:`fail`,requirement:`TypeScript moduleResolution`,message:`moduleResolution must be set to 'bundler', 'node16', or 'nodenext'.`,current:n||`default`,expected:`bundler, node16, or nodenext`})}return t}var mn=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await c.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await c.default.access(s.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return U(e)}async loadTsConfig(e,t=new Set){return cn(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return an(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return Qt(e,t)}async checkTsConfig(e=process.cwd()){return ln(e)}async checkRequirements(e=process.cwd()){return pn(e)}async detectFramework(e=process.cwd(),t){return Yt(e,t)}async detectBunFeatures(e=process.cwd(),t){return Xt(e,t)}async detectPackageManager(e=process.cwd(),t){return Zt(e,t)}async hasSkill(e=process.cwd()){try{let t=s.default.join(e,`skills-lock.json`),n=await c.default.readFile(t,`utf-8`),r=JSON.parse(n);if(r&&typeof r==`object`&&r.skills&&typeof r.skills==`object`&&`arkenv`in r.skills)return!0}catch{}for(let t of[`skills/arkenv/SKILL.md`,`.agent/skills/arkenv/SKILL.md`,`.agents/skills/arkenv/SKILL.md`])try{return await c.default.access(s.default.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return(0,d.execSync)(`git status --porcelain`,{cwd:e,encoding:`utf-8`}).trim().length===0?{status:`clean`}:{status:`dirty`}}catch(e){let t=e;return t.code===`ENOENT`?(this.logger?.log(`Git is not installed on this system. Skipping git status check.`),{status:`not_a_repo`}):typeof t.stderr==`string`&&t.stderr.includes(`not a git repository`)?{status:`not_a_repo`}:{status:`unknown`}}}async findPackageJson(e=process.cwd()){let t=s.default.resolve(e);for(;;){let e=s.default.join(t,`package.json`);try{return await c.default.access(e),e}catch{let e=s.default.dirname(t);if(e===t)return null;t=e}}}async readArkenvConfig(e=process.cwd()){let t=await this.findPackageJson(e);if(!t)return null;try{let e=await c.default.readFile(t,`utf-8`),n=JSON.parse(e);return n.arkenv?typeof n.arkenv==`string`?{schema:n.arkenv}:typeof n.arkenv==`object`&&typeof n.arkenv.schema==`string`?{schema:n.arkenv.schema}:null:null}catch{return null}}};const W=e=>_.default.cyan(e),hn=_.default.blue(`⛯`),G={nextjs:{id:`nextjs`,packageName:`@arkenv/nextjs`,clientPrefix:`NEXT_PUBLIC_`,displayName:`Next.js`,supportsWrapNextjsConfig:!0},nuxt:{id:`nuxt`,packageName:`@arkenv/nuxt`,clientPrefix:`NUXT_PUBLIC_`,displayName:`Nuxt`,supportsWrapNextjsConfig:!1}};function gn(e){if(e===`nextjs`||e===`nuxt`)return G[e]}function _n(e){return e===`nextjs`||e===`nuxt`}const K={nextjs:G.nextjs.clientPrefix,nuxt:G.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``};function vn(e,t){let n=gn(e.framework);return{framework:e.framework,clientPrefix:K[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const yn={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`};function bn(e){let t={};for(let n of e)t[n]=yn[n]??``;return t}function xn(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?s.default.dirname(n.path):e,a=s.default.relative(i,t).replace(/\\/g,`/`);for(let e of r){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||a.startsWith(t)){let e=a;return t!==``&&a.startsWith(t)&&(e=a.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),`@/${e}/env.gen`.replace(/\/+/g,`/`)}}}function Sn(e,t){if(!(!_n(t.framework)||t.disableCodegen)){if(t.framework===`nextjs`)return`@/.arkenv`;if(e.tsConfig?.parsed)return xn(e.cwd,s.default.join(e.targetDir,`generated`),e.tsConfig.parsed)}}function Cn(e,t,n,r){let i=vn(t,r),a=e.getSimpleTemplate(t.envKeys??[],i),o=n.existingFiles.includes(n.targetPath);return!o||t.overwriteEnvSchemaFile!==!1?[{path:n.targetPath,content:a,action:o?`overwrite`:`create`,label:`environment schema`}]:[]}const wn={clientPrefix:K[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?bn(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,BUN_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(e){return e.bunFeatures?.length?[`@arkenv/bun-plugin`]:[]},requiresArktypePeer(e){return!!e.bunFeatures?.length},bootstrap(e){return(0,n.shake)({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return Cn(e,t,n)},getTypeDefinitionFiles(){return[]}};function Tn(e){let{id:t,packageName:r,clientPrefix:i,supportsWrapNextjsConfig:a}=e,o=`${i}API_URL`;return{clientPrefix:i,getEnvDefaults(e){return e&&e.length>0?bn(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[o]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[r]},requiresArktypePeer(){return!0},bootstrap(e){return(0,n.shake)({framework:t,...a&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){return Cn(e,t,n,Sn(n,t))},getTypeDefinitionFiles(){return[]}}}const En=Tn(G.nextjs),Dn=Tn(G.nuxt),On={clientPrefix:K.vanilla,getEnvDefaults(e){return e&&e.length>0?bn(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return Cn(e,t,n)},getTypeDefinitionFiles(){return[]}},kn={vite:{clientPrefix:K.vite,getEnvDefaults(e){return e&&e.length>0?bn(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,VITE_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[`@arkenv/vite-plugin`]},requiresArktypePeer(){return!0},bootstrap(){return(0,n.shake)({framework:`vite`})},getSchemaFiles(e,t,n){return Cn(e,t,n)},getTypeDefinitionFiles(){return[]}},"bun-fullstack":wn,nextjs:En,nuxt:Dn,vanilla:On},q={vercel:{label:`Vercel`,hint:`Add VERCEL, VERCEL_ENV, VERCEL_URL, etc.`,serverOnlyKeys:[`VERCEL`],clientExposedKeys:[`VERCEL_ENV`,`VERCEL_URL`],fields:{VERCEL:{type:`string`},VERCEL_ENV:{type:`enum`,values:[`production`,`preview`,`development`]},VERCEL_URL:{type:`string`}}},netlify:{label:`Netlify`,hint:`Add NETLIFY, CONTEXT, URL, DEPLOY_URL, etc.`,serverOnlyKeys:[`NETLIFY`,`DEPLOY_URL`],clientExposedKeys:[`CONTEXT`,`URL`],fields:{NETLIFY:{type:`string`},DEPLOY_URL:{type:`string`},CONTEXT:{type:`enum`,values:[`production`,`deploy-preview`,`branch-deploy`]},URL:{type:`string`}}},cloudflare:{label:`Cloudflare Pages/Workers`,hint:`Add CF_PAGES, CF_PAGES_COMMIT_SHA, CF_PAGES_BRANCH, CF_PAGES_URL, etc.`,serverOnlyKeys:[`CF_PAGES`,`CF_PAGES_COMMIT_SHA`],clientExposedKeys:[`CF_PAGES_BRANCH`,`CF_PAGES_URL`],fields:{CF_PAGES:{type:`string`},CF_PAGES_COMMIT_SHA:{type:`string`},CF_PAGES_BRANCH:{type:`string`},CF_PAGES_URL:{type:`string`}}},railway:{label:`Railway`,hint:`Add RAILWAY_ENVIRONMENT_NAME, RAILWAY_PUBLIC_DOMAIN, RAILWAY_GIT_COMMIT_SHA, etc.`,serverOnlyKeys:[`RAILWAY_ENVIRONMENT_NAME`,`RAILWAY_PUBLIC_DOMAIN`,`RAILWAY_SERVICE_NAME`,`RAILWAY_GIT_COMMIT_SHA`],clientExposedKeys:[],fields:{RAILWAY_ENVIRONMENT_NAME:{type:`string`},RAILWAY_PUBLIC_DOMAIN:{type:`string`},RAILWAY_SERVICE_NAME:{type:`string`},RAILWAY_GIT_COMMIT_SHA:{type:`string`}}},render:{label:`Render`,hint:`Add RENDER, RENDER_SERVICE_ID, RENDER_SERVICE_TYPE, RENDER_EXTERNAL_URL, etc.`,serverOnlyKeys:[`RENDER`,`RENDER_SERVICE_ID`,`RENDER_SERVICE_TYPE`,`RENDER_EXTERNAL_URL`],clientExposedKeys:[],fields:{RENDER:{type:`string`},RENDER_SERVICE_ID:{type:`string`},RENDER_SERVICE_TYPE:{type:`string`},RENDER_EXTERNAL_URL:{type:`string`}}},fly:{label:`Fly.io`,hint:`Add FLY_APP_NAME, FLY_REGION, FLY_ALLOC_ID, etc.`,serverOnlyKeys:[`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`],clientExposedKeys:[],fields:{FLY_APP_NAME:{type:`string`},FLY_REGION:{type:`string`},FLY_ALLOC_ID:{type:`string`}}}};function An(e){return e===`none`||Object.keys(q).includes(e)}function jn(e){return Object.keys(q).includes(e)}function J(e,t){if(e===`none`)return[];let n=q[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function Mn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=q[n].fields;return r in i?i[r]:void 0}function Nn(e,t,n){let r=J(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}function Pn(e){return`// @arkenv-preset-start ${e}`}function Fn(e){return`// @arkenv-preset-end ${e}`}function In(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function Y(e,t,n,r){let i=Mn(t,n,r);if(i)return In(e,i)}const Ln={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=Y(Ln,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},defaultSimpleSchemaFields:` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
88
- PORT: "number.port = 3000",`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(Ln,e,t,n)??`"string?"`},`).join(`
89
- `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`\t\t${e}API_URL: "string = 'https://api.example.com'",`],sharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]}},assembleVanilla(e){return l.default`
64
+ `}case`submit`:{let e=o?` ${(0,r.styleText)(`dim`,o)}`:``;return`${n}${t?(0,r.styleText)(`gray`,I):``}${e}`}case`cancel`:{let e=o?` ${(0,r.styleText)([`strikethrough`,`dim`],o)}`:``,i=t?(0,r.styleText)(`gray`,I):``;return`${n}${i}${e}${o.trim()?`
65
+ ${i}`:``}`}default:return`${n}${t?`${(0,r.styleText)(`cyan`,I)} `:``}${a}
66
+ ${t?(0,r.styleText)(`cyan`,L):``}
67
+ `}}}).prompt();var dt=class{info(e){process.stdout.write(`${_.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${_.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${_.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){at(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return st()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`)}fatal(e,t,n){if(process.stderr.write(`${_.default.red(`✘ ${e}`)}\n`),t){let e=`${_.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){nt(e)}reportCompleted(e){e.exitCode===0&&this.success(`Environment variables are valid`)}reportErrored(e){this.error(e.error.summary),e.error.why&&this.warn(e.error.why)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},ft=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.reporter?this.reporter=e.reporter:e.isJson?this.reporter=new te:e.isQuiet?this.reporter=new w:this.reporter=new dt}get isJson(){return this.options.isJson}debug(e){this.reporter.log(e)}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){!this.options.isJson||this.options.isYes||(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e,t=`cli`){this.reporter.cancel(e,t)}fatal(e,t,n=`cli`){this.reporter.fatal(e,t,n)}refuse(e,t=`init`){this.reporter.refuse(e,t)}finish(e,t,n=`init`){this.reporter.finish(e,t,n)}reportCompleted(e){this.reporter.reportCompleted(e)}reportErrored(e){this.reporter.reportErrored(e)}async flush(){await this.reporter.flush()}};function pt(e,t){return Object.keys(e).includes(t)}function mt(e){if(typeof e==`string`)return/=\s*\S/.test(e);if(!e||typeof e!=`object`)return!1;let t=e;if(pt(t,`default`)||pt(t,`fallback`))return!0;let n=t._def;if(n&&typeof n==`object`){let e=n;if(`defaultValue`in e||e.typeName===`ZodDefault`||e.type===`default`)return!0;if(`innerType`in e)return mt(e.innerType)}return!1}function ht(e){return e.endsWith(`?`)?e.slice(0,-1):e}function gt(e,t,n){if(e){if(Array.isArray(e)){for(let r of e){if(Array.isArray(r)&&typeof r[0]==`string`){t.push({name:r[0],schema:r[1],hasDefault:!1}),n[r[0]]=r[1];continue}if(r&&typeof r==`object`){let e=r,i=e.key;if(typeof i!=`string`)continue;let a=`value`in e?e.value:void 0;t.push({name:i,schema:a,hasDefault:pt(e,`default`)}),n[i]=a}}return}if(typeof e==`object`)for(let[r,i]of Object.entries(e)){let e=i&&typeof i==`object`?i:void 0,a=e&&`value`in e?e.value:i;t.push({name:r,schema:a,hasDefault:!!(e&&pt(e,`default`))}),n[r]=a}}}function _t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0}function vt(e){let n=[],r={};for(let i of e){if(!i||typeof i!=`object`&&typeof i!=`function`)return{extractable:!1};let e=i,a=e.json,o=typeof a==`function`?a():a,s=n.length;if(o&&typeof o==`object`){let e=o;if((e.domain===`object`||e.required!==void 0||e.optional!==void 0)&&(gt(e.required,n,r),gt(e.optional,n,r),n.length>s))continue}let c=o?t.a(i):[];if(n.length===s&&c.length>0){for(let e of c)n.push({name:e,schema:void 0,hasDefault:!1}),r[e]=void 0;continue}if(!(n.length>s)){if(typeof i==`function`)return{extractable:!1};if(!_t(i)){if(Object.keys(e).length===0)return{extractable:!1};for(let[t,i]of Object.entries(e)){let e=ht(t);n.push({name:e,schema:i,hasDefault:mt(i)}),r[e]=i}}}}return{extractable:!0,keys:n,schema:r}}async function yt(e,t,n,r){if(r){let n=s.default.resolve(e,r);return await t.exists(n)?n:void 0}if(typeof n.readArkenvConfig==`function`){let r=await n.readArkenvConfig(e);if(r){let n=s.default.resolve(e,r.schema);if(await t.exists(n))return n}}let i=[s.default.resolve(e,`env.ts`),s.default.resolve(e,`src/env.ts`),s.default.resolve(e,`env.js`),s.default.resolve(e,`src/env.js`),s.default.resolve(e,`env.mjs`),s.default.resolve(e,`src/env.mjs`),s.default.resolve(e,`env/server.ts`),s.default.resolve(e,`src/env/server.ts`)],a=await n.suggestDefaultEnvPath(e);a&&i.unshift(s.default.resolve(e,a));for(let e of i)if(await t.exists(e))return e}const H={ERR_INSPECT_NO_CALL:`ERR_INSPECT_NO_CALL`,ERR_INSPECT_UNSUPPORTED:`ERR_INSPECT_UNSUPPORTED`,ERR_INSPECT_UNEXTRACTABLE:`ERR_INSPECT_UNEXTRACTABLE`,ERR_INSPECT_EVAL_THROW:`ERR_INSPECT_EVAL_THROW`};function bt(e){if(e&&typeof e==`object`&&`name`in e&&e.name===`ArkEnvError`)return!0;let t=e instanceof Error?e.message:String(e);return/validating environment variables/i.test(t)}function xt(e){if(!(e instanceof Error)&&typeof e!=`object`)return/cannot read propert/i.test(String(e));let t=e instanceof Error?e.message:String(e);return/cannot read propert/i.test(t)||e instanceof TypeError||/is not a function/i.test(t)}function St(e){return`No arkenv() schema definition was found in "${e}". No arkenv() definition was found. Ensure arkenv() is called at the top level of the schema module.`}function Ct(e,t){return`Failed to inspect schema module at "${e}": ${t instanceof Error?t.message:String(t)} Upgrade @arkenv/core or @arkenv/standard so the CLI can inspect the schema without validating the environment.`}function wt(e){return`Failed to inspect schema module at "${e}": Cannot extract keys from the captured definition. Ensure the schema is a supported static map.`}function Tt(e,t){let n=t instanceof Error?t.message:String(t),r=`Failed to load schema module at "${e}": ${n}`;return xt(t)||/missing [A-Z_][A-Z0-9_]*/.test(n)?`${r} Capture mode does not populate env values. Keep the schema module declarative (\`export const env = arkenv({...})\`) and do not read \`env\` at module scope.`:r}var Et=class{constructor(e={}){this.options=e}async load(e){t.t();try{this.evaluateModule(e.schemaPath);let n=t.n();if(n.length===0)return{ok:!1,code:H.ERR_INSPECT_NO_CALL,message:St(e.schemaPath)};let r=vt(n);return r.extractable?{ok:!0,keys:r.keys,schema:r.schema}:{ok:!1,code:H.ERR_INSPECT_UNEXTRACTABLE,message:wt(e.schemaPath)}}catch(n){return t.n(),bt(n)?{ok:!1,code:H.ERR_INSPECT_UNSUPPORTED,message:Ct(e.schemaPath,n),cause:n}:{ok:!1,code:H.ERR_INSPECT_EVAL_THROW,message:Tt(e.schemaPath,n),cause:n}}}async validate(e,t){let n={...process.env};for(let e of Object.keys(process.env))(!(e in t)||t[e]===void 0)&&delete process.env[e];for(let[e,n]of Object.entries(t))n!==void 0&&(process.env[e]=n);try{return this.evaluateModule(e.schemaPath),{ok:!0}}catch(t){if(bt(t)){let e=t&&typeof t==`object`&&`issues`in t?t.issues??[]:[];return{ok:!1,kind:`validation`,message:t instanceof Error?t.message:String(t),issues:e}}return{ok:!1,kind:`load`,code:H.ERR_INSPECT_EVAL_THROW,message:Tt(e.schemaPath,t),cause:t}}finally{for(let e of Object.keys(process.env))e in n||delete process.env[e];for(let[e,t]of Object.entries(n))t!==void 0&&(process.env[e]=t)}}evaluateModule(e){let t={moduleCache:!1,fsCache:!1,tsconfigPaths:!0,...this.options.jitiAliases?{alias:this.options.jitiAliases}:{}};try{(0,c.createJiti)(e,t)(e)}catch(n){let r=n instanceof Error?n.message:String(n);if(!(n instanceof Error&&/tsconfig/i.test(r)&&(/not found/i.test(r)||n.code===`ENOENT`)))throw n;(0,c.createJiti)(e,{...t,tsconfigPaths:!1})(e)}}};async function Dt(e,t){for(let n of t)try{return await u.default.access(s.default.join(e,n)),!0}catch{}return!1}async function Ot(e=process.cwd(),t){if(t?.compilerOptions?.types){let e=t.compilerOptions.types;if(e.includes(`vite`)||e.includes(`vite/client`))return`vite`}try{let t=s.default.join(e,`package.json`),n=await u.default.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`}catch{}return await Dt(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await Dt(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await Dt(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await kt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function kt(e=process.cwd(),t){let n=[];try{let t=s.default.join(e,`bunfig.toml`),r=await u.default.readFile(t,`utf-8`);(r.includes(`[serve]`)||r.includes(`[serve.static]`))&&n.push(`serve`),r.includes(`[build]`)&&n.push(`build`)}catch{}if(n.includes(`serve`)&&n.includes(`build`))return n;let{walk:r}=await Promise.resolve().then(()=>Mt),i=await r(e),a=n.includes(`serve`),o=n.includes(`build`);for(let e of i)try{let t=await u.default.readFile(e,`utf-8`);if(!a&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(a=!0,n.push(`serve`)),!o&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(o=!0,n.push(`build`)),a&&o)break}catch{}return n}async function At(e=process.cwd(),t){let n=process.env.npm_config_user_agent?.toString()||``;if(n.includes(`pnpm`))return`pnpm`;if(n.includes(`yarn`))return`yarn`;if(n.includes(`bun`))return`bun`;if(n.includes(`npm`))return`npm`;let r=t?.path?s.default.dirname(t.path):e;for(;r!==s.default.parse(r).root;){try{let e=s.default.join(r,`package.json`),t=await u.default.readFile(e,`utf-8`),n=JSON.parse(t);if(n.packageManager){if(n.packageManager.startsWith(`pnpm`))return`pnpm`;if(n.packageManager.startsWith(`yarn`))return`yarn`;if(n.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await u.default.readdir(r)}catch{}if(e.includes(`pnpm-lock.yaml`))return`pnpm`;if(e.includes(`yarn.lock`))return`yarn`;if(e.includes(`bun.lockb`))return`bun`;if(e.includes(`package-lock.json`))return`npm`;r=s.default.dirname(r)}return`npm`}async function jt(e=process.cwd(),t){let n=t;if(!n){let{findTsConfig:t,loadTsConfig:r}=await Promise.resolve().then(()=>Rt),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=s.default.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!s.default.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await u.default.access(s.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var Mt=e.n({getEnvExampleKeys:()=>Lt,parseEnvExample:()=>Pt,resolveImportPaths:()=>Ft,scanProjectEnvKeys:()=>It,walk:()=>Nt});async function Nt(e,t=[]){try{let n=await u.default.readdir(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=r.name;if(n===`node_modules`||n===`dist`||n===`build`||n===`.git`||n===`.turbo`||n===`scratch`)continue;await Nt(s.default.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(s.default.join(e,r.name))}catch{}return t}function Pt(e){let t=[],n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.match(/^([A-Z_][A-Z0-9_]*)\s*=/i);r?.[1]&&t.push(r[1])}return Array.from(new Set(t))}function Ft(e,t,n){if(e.startsWith(`.`))return[s.default.resolve(s.default.dirname(n),e)];if(s.default.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||s.default.dirname(t.path),a=r.paths||{},o=[];for(let[e,t]of Object.entries(a)){let n=e.endsWith(`*`),r=e.replace(/\*$/,``);o.push({cleanPattern:r,targets:Array.isArray(t)?t:[t],hadStar:n})}o.sort((e,t)=>t.cleanPattern.length-e.cleanPattern.length);for(let{cleanPattern:t,targets:n,hadStar:r}of o)if(r&&e.startsWith(t)||!r&&e===t){let r=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${r}`;return s.default.resolve(i,t)})}return r.baseUrl?[s.default.resolve(i,e)]:[]}async function It(e,t,n){let r=[],i=await Nt(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await u.default.readFile(e,`utf-8`),i=n.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of i)e[1]&&r.push(e[1]);let o=n.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of o)e[1]&&r.push(e[1]);if(a){let i=n.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let o of i){let i=o[1],c=[];if(t?c=Ft(i,t,e):i.startsWith(`.`)&&(c=[s.default.resolve(s.default.dirname(e),i)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===a)){let e=n.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&r.push(t[1])}}}}catch{}return Array.from(new Set(r))}async function Lt(e=process.cwd(),t,n){let r=s.default.join(e,`.env.example`);try{let e=Pt(await u.default.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await It(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var Rt=e.n({checkTsConfig:()=>Vt,findTsConfig:()=>U,loadTsConfig:()=>Bt});const zt=(0,d.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function U(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==s.default.parse(n).root;){for(let e of t){let t=s.default.join(n,e);try{return await u.default.access(t),t}catch{}}n=s.default.dirname(n)}return null}async function Bt(e,t=new Set){let n=s.default.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await u.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=(0,f.parse)(r)||{},a=i.compilerOptions||{},o={};if(i.extends){let n=Array.isArray(i.extends)?i.extends:[i.extends];for(let r of n){let n;if(r.startsWith(`.`)||s.default.isAbsolute(r))n=s.default.resolve(s.default.dirname(e),r);else try{n=zt(r,{paths:[s.default.dirname(e)]})}catch{n=s.default.resolve(s.default.dirname(e),`node_modules`,r)}let i={...(await Bt(n,t)).compilerOptions};i.baseUrl&&=s.default.resolve(s.default.dirname(n),i.baseUrl),i.rootDir&&=s.default.resolve(s.default.dirname(n),i.rootDir),o={...o,...i}}}let c={...a};return c.baseUrl&&=s.default.resolve(s.default.dirname(e),c.baseUrl),c.rootDir&&=s.default.resolve(s.default.dirname(e),c.rootDir),o={...o,...c},{...i,path:e,compilerOptions:o}}async function Vt(e=process.cwd()){let t=await U(e);if(!t)return{status:`not_found`};let n=s.default.basename(t);try{let e=await Bt(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}function Ht(e,t){let n=e.replace(/^v/,``).split(`.`).map(Number),r=t.replace(/^v/,``).split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function Ut(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function Wt(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=Ut(r[1]);return e!==null&&Ht(e,t)>=0}let i=n.match(/(?:>=|>|<=|<|=)\s*v?\d+(?:\.\d+){0,2}/g);return!i||i.join(` `)!==n.replace(/\s+/g,` `)?!1:i.some(e=>{let n=e.match(/^(>=|>|<=|<|=)\s*(v?\d+(?:\.\d+){0,2})$/);if(!n)return!1;let[,r,i]=n,a=Ut(i);return a&&(r===`>=`||r===`>`||r===`=`)?Ht(a,t)>=0:!1})}async function Gt(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;Ht(n,r)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${r}.`,current:n,expected:`>= ${r}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let i=null;try{let n=s.default.join(e,`package.json`),r=await u.default.readFile(n,`utf-8`);i=JSON.parse(r),t.push({status:`pass`,requirement:`package.json`,message:`package.json found.`})}catch{t.push({status:`warn`,requirement:`package.json`,message:`package.json not found in the current directory.`})}if(i){let e={...i.dependencies,...i.devDependencies}.typescript,n=`5.1.0`;e?Wt(e,n)?t.push({status:`pass`,requirement:`TypeScript Version`,message:`TypeScript version is compatible.`}):t.push({status:`fail`,requirement:`TypeScript Version`,message:`TypeScript version should be >= ${n}.`,current:e,expected:`>= ${n}`}):t.push({status:`warn`,requirement:`TypeScript Version`,message:`TypeScript not found in package.json dependencies.`})}let a=await Vt(e);if(a.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=a.parsed.compilerOptions||{};e.strict===!0?t.push({status:`pass`,requirement:`TypeScript Strict Mode`,message:`Strict mode is enabled.`}):t.push({status:`fail`,requirement:`TypeScript Strict Mode`,message:`Strict mode must be enabled.`,current:`false`,expected:`true`});let n=e.moduleResolution?.toLowerCase(),r=e.module?.toLowerCase();[`bundler`,`node16`,`nodenext`].includes(n||``)||!n&&(r===`node16`||r===`nodenext`)?t.push({status:`pass`,requirement:`TypeScript moduleResolution`,message:`moduleResolution is set to ${n||`implicit`}.`}):t.push({status:`fail`,requirement:`TypeScript moduleResolution`,message:`moduleResolution must be set to 'bundler', 'node16', or 'nodenext'.`,current:n||`default`,expected:`bundler, node16, or nodenext`})}return t}var Kt=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await u.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await u.default.access(s.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return U(e)}async loadTsConfig(e,t=new Set){return Bt(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return Lt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return jt(e,t)}async checkTsConfig(e=process.cwd()){return Vt(e)}async checkRequirements(e=process.cwd()){return Gt(e)}async detectFramework(e=process.cwd(),t){return Ot(e,t)}async detectBunFeatures(e=process.cwd(),t){return kt(e,t)}async detectPackageManager(e=process.cwd(),t){return At(e,t)}async hasSkill(e=process.cwd()){try{let t=s.default.join(e,`skills-lock.json`),n=await u.default.readFile(t,`utf-8`),r=JSON.parse(n);if(r&&typeof r==`object`&&r.skills&&typeof r.skills==`object`&&`arkenv`in r.skills)return!0}catch{}for(let t of[`skills/arkenv/SKILL.md`,`.agent/skills/arkenv/SKILL.md`,`.agents/skills/arkenv/SKILL.md`])try{return await u.default.access(s.default.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return(0,l.execSync)(`git status --porcelain`,{cwd:e,encoding:`utf-8`}).trim().length===0?{status:`clean`}:{status:`dirty`}}catch(e){let t=e;return t.code===`ENOENT`?(this.logger?.log(`Git is not installed on this system. Skipping git status check.`),{status:`not_a_repo`}):typeof t.stderr==`string`&&t.stderr.includes(`not a git repository`)?{status:`not_a_repo`}:{status:`unknown`}}}async findPackageJson(e=process.cwd()){let t=s.default.resolve(e);for(;;){let e=s.default.join(t,`package.json`);try{return await u.default.access(e),e}catch{let e=s.default.dirname(t);if(e===t)return null;t=e}}}async readArkenvConfig(e=process.cwd()){let t=await this.findPackageJson(e);if(!t)return null;try{let e=await u.default.readFile(t,`utf-8`),n=JSON.parse(e);return n.arkenv?typeof n.arkenv==`string`?{schema:n.arkenv}:typeof n.arkenv==`object`&&typeof n.arkenv.schema==`string`?{schema:n.arkenv.schema}:null:null}catch{return null}}};const W=e=>_.default.cyan(e),qt=_.default.blue(`⛯`),G={nextjs:{id:`nextjs`,packageName:`@arkenv/nextjs`,clientPrefix:`NEXT_PUBLIC_`,displayName:`Next.js`,supportsWrapNextjsConfig:!0},nuxt:{id:`nuxt`,packageName:`@arkenv/nuxt`,clientPrefix:`NUXT_PUBLIC_`,displayName:`Nuxt`,supportsWrapNextjsConfig:!1}};function Jt(e){if(e===`nextjs`||e===`nuxt`)return G[e]}function Yt(e){return e===`nextjs`||e===`nuxt`}const K={nextjs:G.nextjs.clientPrefix,nuxt:G.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``};function Xt(e,t){let n=Jt(e.framework);return{framework:e.framework,clientPrefix:K[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const Zt={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`};function Qt(e){let t={};for(let n of e)t[n]=Zt[n]??``;return t}function $t(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?s.default.dirname(n.path):e,a=s.default.relative(i,t).replace(/\\/g,`/`);for(let e of r){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||a.startsWith(t)){let e=a;return t!==``&&a.startsWith(t)&&(e=a.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),`@/${e}/env.gen`.replace(/\/+/g,`/`)}}}function en(e,t){if(!(!Yt(t.framework)||t.disableCodegen)){if(t.framework===`nextjs`)return`@/.arkenv`;if(e.tsConfig?.parsed)return $t(e.cwd,s.default.join(e.targetDir,`generated`),e.tsConfig.parsed)}}function tn(e,t,n,r){let i=Xt(t,r),a=e.getSimpleTemplate(t.envKeys??[],i),o=n.existingFiles.includes(n.targetPath);return!o||t.overwriteEnvSchemaFile!==!1?[{path:n.targetPath,content:a,action:o?`overwrite`:`create`,label:`environment schema`}]:[]}const nn={clientPrefix:K[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?Qt(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,BUN_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(e){return e.bunFeatures?.length?[`@arkenv/bun-plugin`]:[]},requiresArktypePeer(e){return!!e.bunFeatures?.length},bootstrap(e){return(0,n.shake)({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return tn(e,t,n)}};function rn(e){let{id:t,packageName:r,clientPrefix:i,supportsWrapNextjsConfig:a}=e,o=`${i}API_URL`;return{clientPrefix:i,getEnvDefaults(e){return e&&e.length>0?Qt(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[o]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[r]},requiresArktypePeer(){return!0},bootstrap(e){return(0,n.shake)({framework:t,...a&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){return tn(e,t,n,en(n,t))}}}const an=rn(G.nextjs),on=rn(G.nuxt),sn={clientPrefix:K.vanilla,getEnvDefaults(e){return e&&e.length>0?Qt(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return tn(e,t,n)}},cn={vite:{clientPrefix:K.vite,getEnvDefaults(e){return e&&e.length>0?Qt(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,VITE_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[`@arkenv/vite-plugin`]},requiresArktypePeer(){return!0},bootstrap(){return(0,n.shake)({framework:`vite`})},getSchemaFiles(e,t,n){return tn(e,t,n)}},"bun-fullstack":nn,nextjs:an,nuxt:on,vanilla:sn},q={vercel:{label:`Vercel`,hint:`Add VERCEL, VERCEL_ENV, VERCEL_URL, etc.`,serverOnlyKeys:[`VERCEL`],clientExposedKeys:[`VERCEL_ENV`,`VERCEL_URL`],fields:{VERCEL:{type:`string`},VERCEL_ENV:{type:`enum`,values:[`production`,`preview`,`development`]},VERCEL_URL:{type:`string`}}},netlify:{label:`Netlify`,hint:`Add NETLIFY, CONTEXT, URL, DEPLOY_URL, etc.`,serverOnlyKeys:[`NETLIFY`,`DEPLOY_URL`],clientExposedKeys:[`CONTEXT`,`URL`],fields:{NETLIFY:{type:`string`},DEPLOY_URL:{type:`string`},CONTEXT:{type:`enum`,values:[`production`,`deploy-preview`,`branch-deploy`]},URL:{type:`string`}}},cloudflare:{label:`Cloudflare Pages/Workers`,hint:`Add CF_PAGES, CF_PAGES_COMMIT_SHA, CF_PAGES_BRANCH, CF_PAGES_URL, etc.`,serverOnlyKeys:[`CF_PAGES`,`CF_PAGES_COMMIT_SHA`],clientExposedKeys:[`CF_PAGES_BRANCH`,`CF_PAGES_URL`],fields:{CF_PAGES:{type:`string`},CF_PAGES_COMMIT_SHA:{type:`string`},CF_PAGES_BRANCH:{type:`string`},CF_PAGES_URL:{type:`string`}}},railway:{label:`Railway`,hint:`Add RAILWAY_ENVIRONMENT_NAME, RAILWAY_PUBLIC_DOMAIN, RAILWAY_GIT_COMMIT_SHA, etc.`,serverOnlyKeys:[`RAILWAY_ENVIRONMENT_NAME`,`RAILWAY_PUBLIC_DOMAIN`,`RAILWAY_SERVICE_NAME`,`RAILWAY_GIT_COMMIT_SHA`],clientExposedKeys:[],fields:{RAILWAY_ENVIRONMENT_NAME:{type:`string`},RAILWAY_PUBLIC_DOMAIN:{type:`string`},RAILWAY_SERVICE_NAME:{type:`string`},RAILWAY_GIT_COMMIT_SHA:{type:`string`}}},render:{label:`Render`,hint:`Add RENDER, RENDER_SERVICE_ID, RENDER_SERVICE_TYPE, RENDER_EXTERNAL_URL, etc.`,serverOnlyKeys:[`RENDER`,`RENDER_SERVICE_ID`,`RENDER_SERVICE_TYPE`,`RENDER_EXTERNAL_URL`],clientExposedKeys:[],fields:{RENDER:{type:`string`},RENDER_SERVICE_ID:{type:`string`},RENDER_SERVICE_TYPE:{type:`string`},RENDER_EXTERNAL_URL:{type:`string`}}},fly:{label:`Fly.io`,hint:`Add FLY_APP_NAME, FLY_REGION, FLY_ALLOC_ID, etc.`,serverOnlyKeys:[`FLY_APP_NAME`,`FLY_REGION`,`FLY_ALLOC_ID`],clientExposedKeys:[],fields:{FLY_APP_NAME:{type:`string`},FLY_REGION:{type:`string`},FLY_ALLOC_ID:{type:`string`}}}};function ln(e){return e===`none`||Object.keys(q).includes(e)}function un(e){return Object.keys(q).includes(e)}function J(e,t){if(e===`none`)return[];let n=q[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function dn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=q[n].fields;return r in i?i[r]:void 0}function fn(e,t,n){let r=J(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}function pn(e){return`// @arkenv-preset-start ${e}`}function mn(e){return`// @arkenv-preset-end ${e}`}function hn(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function Y(e,t,n,r){let i=dn(t,n,r);if(i)return hn(e,i)}const gn={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=Y(gn,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},defaultSimpleSchemaFields:` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
68
+ PORT: "number.port = 3000",`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(gn,e,t,n)??`"string?"`},`).join(`
69
+ `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`\t\t${e}API_URL: "string = 'https://api.example.com'",`],sharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]}},assembleVanilla(e){return p.default`
90
70
  import arkenv, { type } from "@arkenv/core";
91
71
 
92
72
  /**
@@ -95,9 +75,9 @@ ${t?(0,r.styleText)(`cyan`,R):``}
95
75
  export const env = arkenv({
96
76
  ${e}
97
77
  });
98
- `}},Rn={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=Y(Rn,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},defaultSimpleSchemaFields:` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
99
- PORT: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(Rn,e,t,n)??`v.optional(v.string())`},`).join(`
100
- `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]}},assembleVanilla(e){return l.default`
78
+ `}},_n={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=Y(_n,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},defaultSimpleSchemaFields:` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
79
+ PORT: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(_n,e,t,n)??`v.optional(v.string())`},`).join(`
80
+ `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]}},assembleVanilla(e){return p.default`
101
81
  import { arkenv } from "@arkenv/standard/valibot";
102
82
  import * as v from "valibot";
103
83
 
@@ -107,9 +87,9 @@ ${e}
107
87
  export const env = arkenv({
108
88
  ${e}
109
89
  });
110
- `}},zn={extraImport:`import * as z from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=Y(zn,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
111
- PORT: z.int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(zn,e,t,n)??`z.string().optional()`},`).join(`
112
- `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},assembleVanilla(e){return l.default`
90
+ `}},vn={extraImport:`import * as z from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=Y(vn,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
91
+ PORT: z.int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(vn,e,t,n)??`z.string().optional()`},`).join(`
92
+ `)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},assembleVanilla(e){return p.default`
113
93
  import arkenv from "@arkenv/standard";
114
94
  import * as z from "zod";
115
95
 
@@ -119,22 +99,22 @@ ${e}
119
99
  export const env = arkenv({
120
100
  ${e}
121
101
  });
122
- `}},Bn={arktype:Ln,zod:zn,valibot:Rn};function Vn(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function Hn(e,t){return t.endsWith(`
102
+ `}},yn={arktype:gn,zod:vn,valibot:_n};function bn(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function xn(e,t){return t.endsWith(`
123
103
  `)&&!e.endsWith(`
124
- `)?`${e}\n`:e}function Un(e){try{let t=(0,m.parseModule)(e.code),n=e.code,r=t.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;if((e.$callee||JSON.stringify(r))===`defineConfig`&&e.$args){let t=e.$args[0];if(t&&typeof t==`object`&&`$type`in t&&(t.$type===`arrow-function-expression`||t.$type===`function-expression`))return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};r=t}}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Vite config`};if(r.plugins||=[],Array.isArray(r.plugins))if(!/\barkenv(?:Vite)?Plugin\b/.test(n))t.imports.$add({from:`@arkenv/vite-plugin`,local:`arkenvVitePlugin`,imported:`default`}),r.plugins.push(`__ARK_PLUGIN_PLACEHOLDER__`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'plugins' property in your Vite config is not an array.`};let i=(0,m.generateCode)(t,{format:(0,m.detectCodeFormat)(n)}).code;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,`arkenvVitePlugin()`),i=Vn(i),i=Hn(i,n),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Vite config: ${e instanceof Error?e.message:String(e)}`}}}function Wn(e){try{let t=e.code;if(/module\.exports\b/.test(t))return{success:!1,updated:!1,error:"CommonJS is not supported for automatic mutation. Please wrap your config with `withArkEnv` manually."};let n=(0,m.parseModule)(t);if(!n.exports.default)return{success:!1,updated:!1,error:`Could not find default export in Next.js config`};if(typeof n.exports.default==`object`&&`$type`in n.exports.default&&n.exports.default.$type===`function-call`&&n.exports.default.$callee===`withArkEnv`||/\bwithArkEnv\b/.test(t))return{success:!0,updated:!1};n.imports.$add({from:`@arkenv/nextjs/config`,imported:`withArkEnv`}),e.disableCodegen?n.exports.default=m.builders.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=m.builders.functionCall(`withArkEnv`,n.exports.default);let r=(0,m.generateCode)(n,{format:(0,m.detectCodeFormat)(t)}).code;return r=Vn(r),r=Hn(r,t),{success:!0,updated:!0,code:r}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Next.js config: ${e instanceof Error?e.message:String(e)}`}}}function Gn(e){try{let t=e.code,n=(0,m.parseModule)(t),r=n.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;(e.$callee||JSON.stringify(r))===`defineNuxtConfig`&&e.$args&&(r=e.$args[0])}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Nuxt config`};if(r.modules||=[],Array.isArray(r.modules))if(!r.modules.includes(`@arkenv/nuxt/module`))r.modules.push(`@arkenv/nuxt/module`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'modules' property in your Nuxt config is not an array.`};let i=(0,m.generateCode)(n,{format:(0,m.detectCodeFormat)(t)}).code;return i=Vn(i),i=Hn(i,t),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Nuxt config: ${e instanceof Error?e.message:String(e)}`}}}function Kn(e,t,n,r){let i=Bn[t];return Y(i,e,n,r)??i.formatOptionalString()}function qn(e){let t=e.split(/\r?\n/),n=[],r=null,i=/^\s*\/\/\s*@arkenv-preset-start(?:\s+(.*))?$/,a=/^\s*\/\/\s*@arkenv-preset-end(?:\s+(.*))?$/,o=/^[a-zA-Z0-9_:-]+$/,s=/(?:^|[,{\s])([A-Za-z_][A-Za-z0-9_]*|'[^']+'|"[^"]+")\s*:/g;for(let e=0;e<t.length;e++){let c=t[e],l=c.match(i);if(l){let t=l[1]?.trim();if(!t||!o.test(t))return{success:!1,error:`Malformed preset markers: missing or invalid preset id in "@arkenv-preset-start" at line ${e+1}.`};if(r)return{success:!1,error:`Malformed preset markers: nested or unclosed "@arkenv-preset-start ${r.markerId}" before line ${e+1}.`};r={markerId:t,startLineIndex:e};continue}let u=c.match(a);if(u){let i=u[1]?.trim();if(!i||!o.test(i))return{success:!1,error:`Malformed preset markers: missing or invalid preset id in "@arkenv-preset-end" at line ${e+1}.`};if(!r)return{success:!1,error:`Malformed preset markers: unexpected "@arkenv-preset-end ${i}" without matching start marker at line ${e+1}.`};if(r.markerId!==i)return{success:!1,error:`Malformed preset markers: mismatched start "${r.markerId}" (line ${r.startLineIndex+1}) and end "${i}" (line ${e+1}).`};let a=t.slice(r.startLineIndex,e+1),c=t.slice(r.startLineIndex+1,e),l=[];for(let e of c)for(let t of e.matchAll(s)){let e=t[1],n=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1,-1):e;l.push(n)}let d=Jn(r.markerId);n.push({markerId:r.markerId,baseId:d.baseId,...d.role===void 0?{}:{role:d.role},startLineIndex:r.startLineIndex,endLineIndex:e,rawContent:a.join(`
104
+ `)?`${e}\n`:e}function Sn(e){try{let t=(0,m.parseModule)(e.code),n=e.code,r=t.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;if((e.$callee||JSON.stringify(r))===`defineConfig`&&e.$args){let t=e.$args[0];if(t&&typeof t==`object`&&`$type`in t&&(t.$type===`arrow-function-expression`||t.$type===`function-expression`))return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};r=t}}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Vite config`};if(r.plugins||=[],Array.isArray(r.plugins))if(!/\barkenv(?:Vite)?Plugin\b/.test(n))t.imports.$add({from:`@arkenv/vite-plugin`,local:`arkenvVitePlugin`,imported:`default`}),r.plugins.push(`__ARK_PLUGIN_PLACEHOLDER__`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'plugins' property in your Vite config is not an array.`};let i=(0,m.generateCode)(t,{format:(0,m.detectCodeFormat)(n)}).code;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,`arkenvVitePlugin()`),i=bn(i),i=xn(i,n),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Vite config: ${e instanceof Error?e.message:String(e)}`}}}function Cn(e){try{let t=e.code;if(/module\.exports\b/.test(t))return{success:!1,updated:!1,error:"CommonJS is not supported for automatic mutation. Please wrap your config with `withArkEnv` manually."};let n=(0,m.parseModule)(t);if(!n.exports.default)return{success:!1,updated:!1,error:`Could not find default export in Next.js config`};if(typeof n.exports.default==`object`&&`$type`in n.exports.default&&n.exports.default.$type===`function-call`&&n.exports.default.$callee===`withArkEnv`||/\bwithArkEnv\b/.test(t))return{success:!0,updated:!1};n.imports.$add({from:`@arkenv/nextjs/config`,imported:`withArkEnv`}),e.disableCodegen?n.exports.default=m.builders.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=m.builders.functionCall(`withArkEnv`,n.exports.default);let r=(0,m.generateCode)(n,{format:(0,m.detectCodeFormat)(t)}).code;return r=bn(r),r=xn(r,t),{success:!0,updated:!0,code:r}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Next.js config: ${e instanceof Error?e.message:String(e)}`}}}function wn(e){try{let t=e.code,n=(0,m.parseModule)(t),r=n.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;(e.$callee||JSON.stringify(r))===`defineNuxtConfig`&&e.$args&&(r=e.$args[0])}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Nuxt config`};if(r.modules||=[],Array.isArray(r.modules))if(!r.modules.includes(`@arkenv/nuxt/module`))r.modules.push(`@arkenv/nuxt/module`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'modules' property in your Nuxt config is not an array.`};let i=(0,m.generateCode)(n,{format:(0,m.detectCodeFormat)(t)}).code;return i=bn(i),i=xn(i,t),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Nuxt config: ${e instanceof Error?e.message:String(e)}`}}}function Tn(e,t,n,r){let i=yn[t];return Y(i,e,n,r)??i.formatOptionalString()}function En(e){let t=e.split(/\r?\n/),n=[],r=null,i=/^\s*\/\/\s*@arkenv-preset-start(?:\s+(.*))?$/,a=/^\s*\/\/\s*@arkenv-preset-end(?:\s+(.*))?$/,o=/^[a-zA-Z0-9_:-]+$/,s=/(?:^|[,{\s])([A-Za-z_][A-Za-z0-9_]*|'[^']+'|"[^"]+")\s*:/g;for(let e=0;e<t.length;e++){let c=t[e],l=c.match(i);if(l){let t=l[1]?.trim();if(!t||!o.test(t))return{success:!1,error:`Malformed preset markers: missing or invalid preset id in "@arkenv-preset-start" at line ${e+1}.`};if(r)return{success:!1,error:`Malformed preset markers: nested or unclosed "@arkenv-preset-start ${r.markerId}" before line ${e+1}.`};r={markerId:t,startLineIndex:e};continue}let u=c.match(a);if(u){let i=u[1]?.trim();if(!i||!o.test(i))return{success:!1,error:`Malformed preset markers: missing or invalid preset id in "@arkenv-preset-end" at line ${e+1}.`};if(!r)return{success:!1,error:`Malformed preset markers: unexpected "@arkenv-preset-end ${i}" without matching start marker at line ${e+1}.`};if(r.markerId!==i)return{success:!1,error:`Malformed preset markers: mismatched start "${r.markerId}" (line ${r.startLineIndex+1}) and end "${i}" (line ${e+1}).`};let a=t.slice(r.startLineIndex,e+1),c=t.slice(r.startLineIndex+1,e),l=[];for(let e of c)for(let t of e.matchAll(s)){let e=t[1],n=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1,-1):e;l.push(n)}let d=Dn(r.markerId);n.push({markerId:r.markerId,baseId:d.baseId,...d.role===void 0?{}:{role:d.role},startLineIndex:r.startLineIndex,endLineIndex:e,rawContent:a.join(`
125
105
  `),innerContent:c.join(`
126
- `),keys:l}),r=null}}return r?{success:!1,error:`Malformed preset markers: unclosed "@arkenv-preset-start ${r.markerId}" starting at line ${r.startLineIndex+1}.`}:{success:!0,blocks:n}}function Jn(e){let t=e.indexOf(`:`);return t===-1?{baseId:e}:{baseId:e.slice(0,t),role:e.slice(t+1)}}function Yn(e,t,n){let r=0,i=!1,a=!1,o=!1,s=[],c=!1;for(let l=t;l<e.length;l++){let u=e[l],d=l===t?n:0,f=!1;for(let e=d;e<u.length;e++){let t=u[e],n=e+1<u.length?u[e+1]:``,d=e>0?u[e-1]:``;if(f)break;if(c){t===`*`&&n===`/`&&(c=!1,e++);continue}if(i){t===`'`&&d!==`\\`&&(i=!1);continue}if(a){t===`"`&&d!==`\\`&&(a=!1);continue}if(o){t==="`"&&d!==`\\`?o=!1:t===`$`&&n===`{`&&d!==`\\`&&(s.push(r),o=!1,r++,e++);continue}if(t===`/`&&n===`/`){f=!0,e++;continue}if(t===`/`&&n===`*`){c=!0,e++;continue}if(t===`'`){i=!0;continue}if(t===`"`){a=!0;continue}if(t==="`"){o=!0;continue}if(t===`{`)r++;else if(t===`}`){if(r--,r===0)return{endLine:l,endChar:e};s.length>0&&r===s[s.length-1]&&(s.pop(),o=!0)}}}return null}function Xn(e){let t=/\b(?:arkenv|type|z\.object|v\.object)\s*\(/;for(let n=0;n<e.length;n++){let r=e[n].match(t);if(r&&r.index!==void 0){let t=!1,i=!1,a=!1,o=!1;for(let s=n;s<e.length;s++){let c=e[s],l=s===n?r.index+r[0].length:0,u=!1;for(let e=l;e<c.length;e++){let r=c[e],l=e+1<c.length?c[e+1]:``,d=e>0?c[e-1]:``;if(u)break;if(o){r===`*`&&l===`/`&&(o=!1,e++);continue}if(t){r===`'`&&d!==`\\`&&(t=!1);continue}if(i){r===`"`&&d!==`\\`&&(i=!1);continue}if(a){r==="`"&&d!==`\\`&&(a=!1);continue}if(r===`/`&&l===`/`){u=!0,e++;continue}if(r===`/`&&l===`*`){o=!0,e++;continue}if(r===`'`){t=!0;continue}if(r===`"`){i=!0;continue}if(r==="`"){a=!0;continue}if(r===`{`)return{line:s,char:e};if(r===`;`&&s>n)break}}}}let n=/\bexport\s+const\s+[\w$]+\s*=\s*/;for(let t=0;t<e.length;t++){let r=e[t].match(n);if(r&&r.index!==void 0){let n=!1,i=!1,a=!1,o=!1;for(let s=t;s<e.length;s++){let c=e[s],l=s===t?r.index+r[0].length:0,u=!1;for(let e=l;e<c.length;e++){let r=c[e],l=e+1<c.length?c[e+1]:``,d=e>0?c[e-1]:``;if(u)break;if(o){r===`*`&&l===`/`&&(o=!1,e++);continue}if(n){r===`'`&&d!==`\\`&&(n=!1);continue}if(i){r===`"`&&d!==`\\`&&(i=!1);continue}if(a){r==="`"&&d!==`\\`&&(a=!1);continue}if(r===`/`&&l===`/`){u=!0,e++;continue}if(r===`/`&&l===`*`){o=!0,e++;continue}if(r===`'`){n=!0;continue}if(r===`"`){i=!0;continue}if(r==="`"){a=!0;continue}if(r===`{`)return{line:s,char:e};if(r===`;`&&s>t)break}}}}return null}function Zn(e){let t=Xn(e);if(!t)return null;let n=Yn(e,t.line,t.char);if(!n)return null;let r=t.line,i=n.endLine,a=t.char,o=n.endChar,s=r===i,c=` `;if(s){let t=e[r].match(/^(\s*)/)?.[1]||``;c=t.includes(` `)?`${t} `:`${t}\t`,!c.trim().length&&!t&&(c=` `)}else{for(let t=r+1;t<i;t++){let n=e[t].match(/^(\s+)\S/);if(n){c=n[1];break}}if(c===` `&&e[r].match(/^\s+/)){let t=e[r].match(/^(\s+)/)?.[1]||``;c=t.includes(` `)?`${t} `:`${t}\t`}}return{startLineIndex:r,endLineIndex:i,startCharIndex:a,endCharIndex:o,isSingleLine:s,indent:c}}function Qn(e,t){let{preset:n,framework:r,validator:i,targetKeys:a}=t,o=K[r]||``,s=a??J(n,o),c={};for(let e of s)c[e]=Kn(e,i,o,n);let l=qn(e);if(!l.success)return{success:!1,updated:!1,error:l.error,proposedFields:c};let u=l.blocks,d=e.split(/\r?\n/),f=Zn(d);if(!f)return{success:!1,updated:!1,error:`Could not find schema object literal in schema file.`,proposedFields:c};let p=t.markerId||n,m=new Set,h=new Map,g=/(?:^|[,{\s])([A-Za-z_][A-Za-z0-9_]*|'[^']+'|"[^"]+")\s*:/g;if(f.isSingleLine){let e=d[f.startLineIndex].slice(f.startCharIndex+1,f.endCharIndex);for(let t of e.matchAll(g)){let e=t[1],n=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1,-1):e;m.add(n)}}else for(let e=f.startLineIndex;e<=f.endLineIndex;e++){let t=u.find(t=>e>=t.startLineIndex&&e<=t.endLineIndex),r=d[e];if(e===f.startLineIndex?r=r.slice(f.startCharIndex+1):e===f.endLineIndex&&(r=r.slice(0,f.endCharIndex)),r.trim()){if(!t)for(let e of r.matchAll(g)){let t=e[1],n=t.startsWith(`'`)||t.startsWith(`"`)?t.slice(1,-1):t;m.add(n)}else if(t.baseId!==n)for(let e of r.matchAll(g)){let n=e[1],r=n.startsWith(`'`)||n.startsWith(`"`)?n.slice(1,-1):n;h.set(r,t.baseId)}}}for(let e of s){if(m.has(e))return{success:!1,updated:!1,error:`Collision detected: Key "${e}" already exists outside managed preset blocks (user-owned or legacy unmarked). Remove or migrate it before applying preset "${n}".`,proposedFields:c};if(h.has(e))return{success:!1,updated:!1,error:`Collision detected: Key "${e}" conflicts with existing managed preset "${h.get(e)}".`,proposedFields:c}}let _=f.indent,v=[`${_}// @arkenv-preset-start ${p}`,...s.map(e=>`${_}${e}: ${c[e]},`),`${_}// @arkenv-preset-end ${p}`],y=u.find(e=>e.markerId===p);if(y)return d.slice(y.startLineIndex,y.endLineIndex+1).join(`
106
+ `),keys:l}),r=null}}return r?{success:!1,error:`Malformed preset markers: unclosed "@arkenv-preset-start ${r.markerId}" starting at line ${r.startLineIndex+1}.`}:{success:!0,blocks:n}}function Dn(e){let t=e.indexOf(`:`);return t===-1?{baseId:e}:{baseId:e.slice(0,t),role:e.slice(t+1)}}function On(e,t,n){let r=0,i=!1,a=!1,o=!1,s=[],c=!1;for(let l=t;l<e.length;l++){let u=e[l],d=l===t?n:0,f=!1;for(let e=d;e<u.length;e++){let t=u[e],n=e+1<u.length?u[e+1]:``,d=e>0?u[e-1]:``;if(f)break;if(c){t===`*`&&n===`/`&&(c=!1,e++);continue}if(i){t===`'`&&d!==`\\`&&(i=!1);continue}if(a){t===`"`&&d!==`\\`&&(a=!1);continue}if(o){t==="`"&&d!==`\\`?o=!1:t===`$`&&n===`{`&&d!==`\\`&&(s.push(r),o=!1,r++,e++);continue}if(t===`/`&&n===`/`){f=!0,e++;continue}if(t===`/`&&n===`*`){c=!0,e++;continue}if(t===`'`){i=!0;continue}if(t===`"`){a=!0;continue}if(t==="`"){o=!0;continue}if(t===`{`)r++;else if(t===`}`){if(r--,r===0)return{endLine:l,endChar:e};s.length>0&&r===s[s.length-1]&&(s.pop(),o=!0)}}}return null}function kn(e){let t=/\b(?:arkenv|type|z\.object|v\.object)\s*\(/;for(let n=0;n<e.length;n++){let r=e[n].match(t);if(r&&r.index!==void 0){let t=!1,i=!1,a=!1,o=!1;for(let s=n;s<e.length;s++){let c=e[s],l=s===n?r.index+r[0].length:0,u=!1;for(let e=l;e<c.length;e++){let r=c[e],l=e+1<c.length?c[e+1]:``,d=e>0?c[e-1]:``;if(u)break;if(o){r===`*`&&l===`/`&&(o=!1,e++);continue}if(t){r===`'`&&d!==`\\`&&(t=!1);continue}if(i){r===`"`&&d!==`\\`&&(i=!1);continue}if(a){r==="`"&&d!==`\\`&&(a=!1);continue}if(r===`/`&&l===`/`){u=!0,e++;continue}if(r===`/`&&l===`*`){o=!0,e++;continue}if(r===`'`){t=!0;continue}if(r===`"`){i=!0;continue}if(r==="`"){a=!0;continue}if(r===`{`)return{line:s,char:e};if(r===`;`&&s>n)break}}}}let n=/\bexport\s+const\s+[\w$]+\s*=\s*/;for(let t=0;t<e.length;t++){let r=e[t].match(n);if(r&&r.index!==void 0){let n=!1,i=!1,a=!1,o=!1;for(let s=t;s<e.length;s++){let c=e[s],l=s===t?r.index+r[0].length:0,u=!1;for(let e=l;e<c.length;e++){let r=c[e],l=e+1<c.length?c[e+1]:``,d=e>0?c[e-1]:``;if(u)break;if(o){r===`*`&&l===`/`&&(o=!1,e++);continue}if(n){r===`'`&&d!==`\\`&&(n=!1);continue}if(i){r===`"`&&d!==`\\`&&(i=!1);continue}if(a){r==="`"&&d!==`\\`&&(a=!1);continue}if(r===`/`&&l===`/`){u=!0,e++;continue}if(r===`/`&&l===`*`){o=!0,e++;continue}if(r===`'`){n=!0;continue}if(r===`"`){i=!0;continue}if(r==="`"){a=!0;continue}if(r===`{`)return{line:s,char:e};if(r===`;`&&s>t)break}}}}return null}function An(e){let t=kn(e);if(!t)return null;let n=On(e,t.line,t.char);if(!n)return null;let r=t.line,i=n.endLine,a=t.char,o=n.endChar,s=r===i,c=` `;if(s){let t=e[r].match(/^(\s*)/)?.[1]||``;c=t.includes(` `)?`${t} `:`${t}\t`,!c.trim().length&&!t&&(c=` `)}else{for(let t=r+1;t<i;t++){let n=e[t].match(/^(\s+)\S/);if(n){c=n[1];break}}if(c===` `&&e[r].match(/^\s+/)){let t=e[r].match(/^(\s+)/)?.[1]||``;c=t.includes(` `)?`${t} `:`${t}\t`}}return{startLineIndex:r,endLineIndex:i,startCharIndex:a,endCharIndex:o,isSingleLine:s,indent:c}}function jn(e,t){let{preset:n,framework:r,validator:i,targetKeys:a}=t,o=K[r]||``,s=a??J(n,o),c={};for(let e of s)c[e]=Tn(e,i,o,n);let l=En(e);if(!l.success)return{success:!1,updated:!1,error:l.error,proposedFields:c};let u=l.blocks,d=e.split(/\r?\n/),f=An(d);if(!f)return{success:!1,updated:!1,error:`Could not find schema object literal in schema file.`,proposedFields:c};let p=t.markerId||n,m=new Set,h=new Map,g=/(?:^|[,{\s])([A-Za-z_][A-Za-z0-9_]*|'[^']+'|"[^"]+")\s*:/g;if(f.isSingleLine){let e=d[f.startLineIndex].slice(f.startCharIndex+1,f.endCharIndex);for(let t of e.matchAll(g)){let e=t[1],n=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1,-1):e;m.add(n)}}else for(let e=f.startLineIndex;e<=f.endLineIndex;e++){let t=u.find(t=>e>=t.startLineIndex&&e<=t.endLineIndex),r=d[e];if(e===f.startLineIndex?r=r.slice(f.startCharIndex+1):e===f.endLineIndex&&(r=r.slice(0,f.endCharIndex)),r.trim()){if(!t)for(let e of r.matchAll(g)){let t=e[1],n=t.startsWith(`'`)||t.startsWith(`"`)?t.slice(1,-1):t;m.add(n)}else if(t.baseId!==n)for(let e of r.matchAll(g)){let n=e[1],r=n.startsWith(`'`)||n.startsWith(`"`)?n.slice(1,-1):n;h.set(r,t.baseId)}}}for(let e of s){if(m.has(e))return{success:!1,updated:!1,error:`Collision detected: Key "${e}" already exists outside managed preset blocks (user-owned or legacy unmarked). Remove or migrate it before applying preset "${n}".`,proposedFields:c};if(h.has(e))return{success:!1,updated:!1,error:`Collision detected: Key "${e}" conflicts with existing managed preset "${h.get(e)}".`,proposedFields:c}}let _=f.indent,v=[`${_}// @arkenv-preset-start ${p}`,...s.map(e=>`${_}${e}: ${c[e]},`),`${_}// @arkenv-preset-end ${p}`],y=u.find(e=>e.markerId===p);if(y)return d.slice(y.startLineIndex,y.endLineIndex+1).join(`
127
107
  `)===v.join(`
128
108
  `)?{success:!0,updated:!1,code:e,proposedFields:c}:(d.splice(y.startLineIndex,y.endLineIndex-y.startLineIndex+1,...v),{success:!0,updated:!0,code:d.join(`
129
- `),proposedFields:c});if(f.isSingleLine){let e=d[f.startLineIndex],t=e.slice(0,f.startCharIndex+1),n=e.slice(f.startCharIndex+1,f.endCharIndex).trim(),r=e.slice(f.endCharIndex),i=e.match(/^(\s*)/)?.[1]||``;if(n){let e=$n(n),a=n;if(e!==-1){let t=n.slice(0,e),r=n.slice(e);if(t.trim()&&!t.trimEnd().endsWith(`,`)){let e=t.trimEnd();a=`${e},${t.slice(e.length)}${r}`}}else n.endsWith(`,`)||(a=`${n},`);d.splice(f.startLineIndex,1,t,`${_}${a}`,...v,`${i}${r.trimStart()}`)}else d.splice(f.startLineIndex,1,t,...v,`${i}${r.trimStart()}`);return{success:!0,updated:!0,code:d.join(`
130
- `),proposedFields:c}}return er(d,f.startLineIndex,f.endLineIndex,f.startCharIndex),d.splice(f.endLineIndex,0,...v),{success:!0,updated:!0,code:d.join(`
131
- `),proposedFields:c}}function $n(e){let t=!1,n=!1,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`){i=!0;continue}if(o===`'`&&!n&&!r){t=!t;continue}if(o===`"`&&!t&&!r){n=!n;continue}if(o==="`"&&!t&&!n){r=!r;continue}if(!t&&!n&&!r&&o===`/`&&a+1<e.length&&(e[a+1]===`/`||e[a+1]===`*`))return a}return-1}function er(e,t,n,r){for(let i=n-1;i>=t;i--){let n=e[i],a=n;i===t&&(a=a.slice(r+1));let o=a.trim();if(!o||o.startsWith(`//`)||o.startsWith(`/*`)||o.startsWith(`*`))continue;let s=$n(n),c=s===-1?n:n.slice(0,s),l=s===-1?``:n.slice(s);if(c.trim().length>0){if(!c.trimEnd().endsWith(`,`)){let t=c.trimEnd();e[i]=`${t},${c.slice(t.length)}${l}`}return}}}function tr(e,t){let{preset:n}=t,r=qn(e);if(!r.success)return{success:!1,updated:!1,error:r.error};let i=r.blocks.filter(e=>e.baseId===n);if(i.length===0)return{success:!0,updated:!1,code:e,removedKeys:[]};let a=i.flatMap(e=>e.keys),o=e.split(/\r?\n/),s=[...i].sort((e,t)=>t.startLineIndex-e.startLineIndex);for(let e of s)o.splice(e.startLineIndex,e.endLineIndex-e.startLineIndex+1);return{success:!0,updated:!0,code:o.join(`
132
- `),removedKeys:a}}async function nr(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=s.default.resolve(e,t);try{return await c.default.access(n),n}catch{}}return null}async function rr(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=s.default.resolve(e,t);try{return await c.default.access(n),n}catch{}}return null}async function ir(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=s.default.resolve(e,t);try{return await c.default.access(n),n}catch{}}return null}async function ar(e,t,n){try{let r=Wn({code:await e.readFile(t),disableCodegen:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function or(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=s.default.resolve(e,t);try{return await c.default.access(n),n}catch{}}return null}async function sr(e,t){try{let n=Gn({code:await e.readFile(t)});return n.success&&n.updated&&n.code&&await e.writeFile(t,n.code),n.success?n.updated===void 0?{success:!0}:{success:!0,updated:n.updated}:{success:!1,error:n.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function cr(e,t,n){try{let r=Un({code:await e.readFile(t),envImportPath:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function lr(e,t){if(!t||t.length===0)return{success:!0,instructions:l.default`
109
+ `),proposedFields:c});if(f.isSingleLine){let e=d[f.startLineIndex],t=e.slice(0,f.startCharIndex+1),n=e.slice(f.startCharIndex+1,f.endCharIndex).trim(),r=e.slice(f.endCharIndex),i=e.match(/^(\s*)/)?.[1]||``;if(n){let e=Mn(n),a=n;if(e!==-1){let t=n.slice(0,e),r=n.slice(e);if(t.trim()&&!t.trimEnd().endsWith(`,`)){let e=t.trimEnd();a=`${e},${t.slice(e.length)}${r}`}}else n.endsWith(`,`)||(a=`${n},`);d.splice(f.startLineIndex,1,t,`${_}${a}`,...v,`${i}${r.trimStart()}`)}else d.splice(f.startLineIndex,1,t,...v,`${i}${r.trimStart()}`);return{success:!0,updated:!0,code:d.join(`
110
+ `),proposedFields:c}}return Nn(d,f.startLineIndex,f.endLineIndex,f.startCharIndex),d.splice(f.endLineIndex,0,...v),{success:!0,updated:!0,code:d.join(`
111
+ `),proposedFields:c}}function Mn(e){let t=!1,n=!1,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(i){i=!1;continue}if(o===`\\`){i=!0;continue}if(o===`'`&&!n&&!r){t=!t;continue}if(o===`"`&&!t&&!r){n=!n;continue}if(o==="`"&&!t&&!n){r=!r;continue}if(!t&&!n&&!r&&o===`/`&&a+1<e.length&&(e[a+1]===`/`||e[a+1]===`*`))return a}return-1}function Nn(e,t,n,r){for(let i=n-1;i>=t;i--){let n=e[i],a=n;i===t&&(a=a.slice(r+1));let o=a.trim();if(!o||o.startsWith(`//`)||o.startsWith(`/*`)||o.startsWith(`*`))continue;let s=Mn(n),c=s===-1?n:n.slice(0,s),l=s===-1?``:n.slice(s);if(c.trim().length>0){if(!c.trimEnd().endsWith(`,`)){let t=c.trimEnd();e[i]=`${t},${c.slice(t.length)}${l}`}return}}}function Pn(e,t){let{preset:n}=t,r=En(e);if(!r.success)return{success:!1,updated:!1,error:r.error};let i=r.blocks.filter(e=>e.baseId===n);if(i.length===0)return{success:!0,updated:!1,code:e,removedKeys:[]};let a=i.flatMap(e=>e.keys),o=e.split(/\r?\n/),s=[...i].sort((e,t)=>t.startLineIndex-e.startLineIndex);for(let e of s)o.splice(e.startLineIndex,e.endLineIndex-e.startLineIndex+1);return{success:!0,updated:!0,code:o.join(`
112
+ `),removedKeys:a}}async function Fn(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=s.default.resolve(e,t);try{return await u.default.access(n),n}catch{}}return null}async function In(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=s.default.resolve(e,t);try{return await u.default.access(n),n}catch{}}return null}async function Ln(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=s.default.resolve(e,t);try{return await u.default.access(n),n}catch{}}return null}async function Rn(e,t,n){try{let r=Cn({code:await e.readFile(t),disableCodegen:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function zn(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=s.default.resolve(e,t);try{return await u.default.access(n),n}catch{}}return null}async function Bn(e,t){try{let n=wn({code:await e.readFile(t)});return n.success&&n.updated&&n.code&&await e.writeFile(t,n.code),n.success?n.updated===void 0?{success:!0}:{success:!0,updated:n.updated}:{success:!1,error:n.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Vn(e,t,n){try{let r=Sn({code:await e.readFile(t),envImportPath:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Hn(e,t){if(!t||t.length===0)return{success:!0,instructions:p.default`
133
113
  ${_.default.green(`✔`)} Use ${_.default.bold(`Vanilla`)} Bun runtime integration.
134
114
  Access validated variables via your ${W(`env`)} object for typesafety.
135
115
  Primarily used for ${_.default.cyan(`server-side`)} or runtime-only validation.
136
116
  No plugins are required.
137
- `};let n=t.includes(`serve`),r=t.includes(`build`),i=``;return n&&(i+=l.default`
117
+ `};let n=t.includes(`serve`),r=t.includes(`build`),i=``;return n&&(i+=p.default`
138
118
  ${_.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
139
119
  To inline environment variables (e.g. ${W(`PUBLIC_*`)}) in your ${_.default.cyan(`client-side`)} code, add the plugin to ${W(`bunfig.toml`)}:
140
120
 
@@ -142,7 +122,7 @@ ${e}
142
122
  plugins = ["@arkenv/bun-plugin"]
143
123
 
144
124
  `),r&&(i&&(i+=`
145
- `),i+=l.default`
125
+ `),i+=p.default`
146
126
  ${_.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
147
127
  To inline environment variables (e.g. ${W(`PUBLIC_*`)}) in your custom ${_.default.cyan(`client-side`)} build script, add the plugin to your ${W(`Bun.build`)} call:
148
128
 
@@ -153,31 +133,31 @@ ${e}
153
133
  outdir: "./dist",
154
134
  ${_.default.green(`plugins: [arkenvPlugin]`)}
155
135
  });
156
- `),{success:!0,instructions:i.trim()}}async function ur(e,t){let n=t||await U();if(!n)return{status:`not_found`};let r=s.default.basename(n);try{let t=await e.readFile(n);if((0,p.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=(0,p.applyEdits)(t,(0,p.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,i),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}const dr=`@/.arkenv`,fr=[`./.arkenv/index.ts`],pr=`.arkenv/**/*.ts`,mr={insertSpaces:!0,tabSize:2};async function hr(e,t){let n=t||await U();if(!n)return{status:`not_found`};let r=s.default.basename(n);try{let t=await e.readFile(n),i=(0,p.parse)(t),a=!1,o=i?.compilerOptions?.paths?.[dr];if(!o||o[0]!==fr[0]){let e=(0,p.modify)(t,[`compilerOptions`,`paths`,dr],fr,{formattingOptions:mr});t=(0,p.applyEdits)(t,e),a=!0}let s=Array.isArray(i?.include)?i.include:[];if(!s.includes(pr)){let e=(0,p.modify)(t,[`include`],[...s,pr],{formattingOptions:mr});t=(0,p.applyEdits)(t,e),a=!0}return a?(await e.writeFile(n,t),{status:`updated`,file:r}):{status:`already_configured`,file:r}}catch{return{status:`error`,file:r}}}var gr=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await c.default.access(e),!0}catch{return!1}}async readFile(e){return c.default.readFile(e,`utf-8`)}async writeFile(e,t){await c.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await c.default.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=(0,d.spawn)(e,t,{cwd:n,stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),o=``,s=``,c=1e4;this.isQuiet&&(a.stdout?.on(`data`,e=>{o=(o+e.toString()).slice(-c)}),a.stderr?.on(`data`,e=>{s=(s+e.toString()).slice(-c)})),a.on(`close`,(e,t)=>{if(e===0)r();else{let n=e===null?`Command terminated by signal ${t}`:`Command failed with code ${e}`;this.isQuiet&&(o&&(n+=`\n${_.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${_.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return ur(this,e)}async ensureNextjsArkEnvTsConfig(e){return hr(this,e)}async findViteConfig(e){return nr(e)}async findBunConfig(e){return rr(e)}async findNextjsConfig(e){return ir(e)}async findNuxtConfig(e){return or(e)}async bootstrapViteConfig(e,t){return cr(this,e,t)}async bootstrapBunConfig(e,t){return lr(e,t)}async bootstrapNextjsConfig(e,t){return ar(this,e,t)}async bootstrapNuxtConfig(e){return sr(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>kt);return r(e,t,n,this.logger)}async appendMissingEnvExampleKeys(e,t){let n=s.default.join(e,`.env.example`);if(!await this.exists(n))return!1;let r=await this.readFile(n),i=new Set;for(let e of r.split(/\r?\n/)){let t=e.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);t&&i.add(t[1])}let a=t.filter(e=>!i.has(e));if(a.length===0)return!1;let o=a.map(e=>`${e}=`).join(`
136
+ `),{success:!0,instructions:i.trim()}}async function Un(e,t){let n=t||await U();if(!n)return{status:`not_found`};let r=s.default.basename(n);try{let t=await e.readFile(n);if((0,f.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=(0,f.applyEdits)(t,(0,f.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,i),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}const Wn=`@/.arkenv`,Gn=[`./.arkenv/index.ts`],Kn=`.arkenv/**/*.ts`,qn={insertSpaces:!0,tabSize:2};async function Jn(e,t){let n=t||await U();if(!n)return{status:`not_found`};let r=s.default.basename(n);try{let t=await e.readFile(n),i=(0,f.parse)(t),a=!1,o=i?.compilerOptions?.paths?.[Wn];if(!o||o[0]!==Gn[0]){let e=(0,f.modify)(t,[`compilerOptions`,`paths`,Wn],Gn,{formattingOptions:qn});t=(0,f.applyEdits)(t,e),a=!0}let s=Array.isArray(i?.include)?i.include:[];if(!s.includes(Kn)){let e=(0,f.modify)(t,[`include`],[...s,Kn],{formattingOptions:qn});t=(0,f.applyEdits)(t,e),a=!0}return a?(await e.writeFile(n,t),{status:`updated`,file:r}):{status:`already_configured`,file:r}}catch{return{status:`error`,file:r}}}var Yn=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await u.default.access(e),!0}catch{return!1}}async readFile(e){return u.default.readFile(e,`utf-8`)}async writeFile(e,t){await u.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await u.default.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=(0,l.spawn)(e,t,{cwd:n,stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),o=``,s=``,c=1e4;this.isQuiet&&(a.stdout?.on(`data`,e=>{o=(o+e.toString()).slice(-c)}),a.stderr?.on(`data`,e=>{s=(s+e.toString()).slice(-c)})),a.on(`close`,(e,t)=>{if(e===0)r();else{let n=e===null?`Command terminated by signal ${t}`:`Command failed with code ${e}`;this.isQuiet&&(o&&(n+=`\n${_.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${_.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Un(this,e)}async ensureNextjsArkEnvTsConfig(e){return Jn(this,e)}async findViteConfig(e){return Fn(e)}async findBunConfig(e){return In(e)}async findNextjsConfig(e){return Ln(e)}async findNuxtConfig(e){return zn(e)}async bootstrapViteConfig(e,t){return Vn(this,e,t)}async bootstrapBunConfig(e,t){return Hn(e,t)}async bootstrapNextjsConfig(e,t){return Rn(this,e,t)}async bootstrapNuxtConfig(e){return Bn(this,e)}async appendMissingEnvExampleKeys(e,t){let n=s.default.join(e,`.env.example`);if(!await this.exists(n))return!1;let r=await this.readFile(n),i=new Set;for(let e of r.split(/\r?\n/)){let t=e.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);t&&i.add(t[1])}let a=t.filter(e=>!i.has(e));if(a.length===0)return!1;let o=a.map(e=>`${e}=`).join(`
157
137
  `)+`
158
138
  `,c=r.endsWith(`
159
139
  `)||r.length===0?`${r}${o}`:`${r}\n${o}`;return await this.writeFile(n,c),!0}async removeEnvExampleKeys(e,t,n=[]){let r=s.default.join(e,`.env.example`);if(!await this.exists(r))return!1;let i=new Set(t.filter(e=>!n.includes(e)));if(i.size===0)return!1;let a=await this.readFile(r),o=a.split(/\r?\n/).filter(e=>{let t=e.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);return!(t&&i.has(t[1]))}).join(`
160
140
  `);return a.endsWith(`
161
141
  `)&&!o.endsWith(`
162
142
  `)&&(o+=`
163
- `),o===a?!1:(await this.writeFile(r,o),!0)}};async function _r(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await z({message:_.default.yellow(`An existing ArkEnv configuration was found at ${W(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return P(e)||!e?null:e}return!0}async function vr(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await z({message:n===`.env.example`?`Detected ${W(`.env.example`)} with ${e} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${e} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return P(i)?null:i}return!1}async function yr(e){let t=await ct({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return P(t)?null:t}async function br(e){let t=await ct({message:`Select your framework or build tool:`,initialValue:e.framework,options:[{value:`vanilla`,label:`Vanilla${e.framework===`vanilla`?` (Detected)`:``}`,hint:`Node.js, Bun, server-side or runtime-only validation`},{value:`vite`,label:`Vite${e.framework===`vite`?` (Detected)`:``}`,hint:`Client-side and static inlining validation`},{value:`bun-fullstack`,label:`Bun fullstack dev server${e.framework===`bun-fullstack`?` (Detected)`:``}`,hint:`Client-side bundling and Bun.serve integration`},{value:`nextjs`,label:`Next.js${e.framework===`nextjs`?` (Detected)`:``}`,hint:`Next.js App or Pages Router with build and runtime validation`},{value:`nuxt`,label:`Nuxt${e.framework===`nuxt`?` (Detected)`:``}`,hint:`Nuxt with build and runtime validation`}]});return P(t)?null:t}async function xr(e){let t=await z({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return P(t)?null:t}async function Sr(){let e=await ct({message:`Select your preferred validator library:`,options:[{value:`arktype`,label:`ArkType (Recommended)`,hint:`TypeScript's 1:1 validator, optimized from editor to runtime`},{value:`zod`,label:`Zod`,hint:`TypeScript-first schema validation with static type inference`},{value:`valibot`,label:`Valibot`,hint:`The modular and type safe schema library`}]});return P(e)?null:e}async function Cr(e){let t=await z({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return P(t)?null:t}async function wr(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(q).map(([e,t])=>({value:e,label:t.label,hint:t.hint}))],n=await ct({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return P(n)?null:n}async function Tr(e){let t=await z({message:`Use default config path (${W(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return P(t)?null:t}async function Er(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await ut({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(P(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const X={example:yr,overwriteEnvSchemaFile:_r,framework:br,bunBuild:xr,nextjsCodegen:Cr,useDefaultPath:Tr,path:Er,validator:Sr,hostPreset:wr,useEnvExample:vr};async function Dr(e,t=!1){return(e?.mode||`existing`)===`new`?Or(e,t):kr(e,t)}async function Or(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||s.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Z(await ut({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||s.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Z(await X.example({examples:n})):!a&&t&&(a=`basic`);let o=n.find(e=>e.id===a);if(!o){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:o.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:o.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof Ar)return null;throw e}}async function kr(e,t=!1){let r=e?.defaultEnvPath||`./src/env.ts`,i=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(t){let t=e?.framework||`vanilla`;return(0,n.shake)({mode:`existing`,path:r,validator:`arktype`,framework:t,bunFeatures:t===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installSkill:!1,envKeys:i??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:t===`nextjs`?!0:void 0,hostPreset:e?.hostPreset||`none`})}try{let t=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Z(await X.framework({framework:e?.framework})),s;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);s=Z(await X.bunBuild({initialValue:t}))}let c=e?.disableCodegen;o===`nuxt`?c=!0:o===`nextjs`&&c===void 0&&(c=!Z(await X.nextjsCodegen({initialValue:!0,framework:o})));let l;if(o===`nextjs`&&!c){let e=await z({message:`Would you like to wrap your Next.js config with ${W(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(P(e))throw et(`Operation cancelled`),new Ar;l=e}let u=Z(await X.useDefaultPath({defaultEnvPath:r})),d=Z(await X.path({useDefaultPath:u,defaultEnvPath:r})),f=Z(await X.validator()),p=e?.hostPreset===void 0?Z(await X.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,m=Z(await X.useEnvExample({detectedKeys:i,keysSource:a}));return(0,n.shake)({mode:`existing`,overwriteEnvSchemaFile:t,framework:o,path:d,validator:f,hostPreset:p,bunFeatures:o===`bun-fullstack`?s?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:m?i??void 0:void 0,disableCodegen:c,wrapNextjsConfig:l})}catch(e){if(e instanceof Ar)return null;throw e}}var Ar=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||P(e))throw et(`Operation cancelled`),new Ar;return e}var jr=class{async confirm(e,t=!0,r,i){let a=await z((0,n.shake)({message:e,initialValue:t,active:r,inactive:i}));return P(a)?null:a}async runWizard(e,t=!1){return Dr(e,t)}async select(e,t,n){let r=await ct({message:e,options:t,initialValue:n});return P(r)?null:r}};const Q={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:``,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:``,kind:`value`},noCodegen:{long:`--no-codegen`,short:``,kind:`boolean`},preset:{long:`--preset`,short:`-P`,kind:`value`},hostPreset:{long:`--host-preset`,short:`-H`,kind:`value`},file:{long:`--file`,short:``,kind:`value`},schema:{long:`--schema`,short:`-s`,kind:`value`},envFile:{long:`--env-file`,short:``,kind:`value`}},Mr=new Set(Object.values(Q).flatMap(e=>[e.long,e.short].filter(Boolean))),Nr=new Set(Object.values(Q).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var Pr=class{constructor(e,t={}){let n=e.slice(2),r=[],i=!1;for(let e of n){if(i){r.push(e),i=!1;continue}if(Nr.has(e)){r.push(e),i=!0;continue}if(/^-[a-zA-Z]{2,}$/.test(e)){let t=e.slice(1).split(``);for(let e of t)r.push(`-${e}`);Nr.has(`-${t[t.length-1]}`)&&(i=!0)}else r.push(e)}this.args=r,this.command=this.args[0];let a=1,o=[];for(this.validationError=void 0;a<this.args.length;){let e=this.args[a];if(e.startsWith(`-`)){if(!Mr.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(Nr.has(e))if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}else a+=1}else o.push(e),a+=1}if(!this.validationError){let e=this.getFlagValue(Q.preset.long,Q.preset.short)??this.getFlagValue(Q.hostPreset.long,Q.hostPreset.short);e!==void 0&&!An(e)&&(this.validationError=`Invalid host preset: ${e}`)}if(this.positionalArgs=o,!this.validationError)if(this.command===`preset`)if(o.length===0)this.validationError=`Missing subcommand`;else{let e=o[0];if(e!==`apply`&&e!==`remove`&&e!==`rm`&&e!==`add`)this.validationError=`Unknown preset action: ${e}`;else if(o.length>2)this.validationError=`Unknown argument: ${o[2]}`;else{let e=o[1];e!==void 0&&!jn(e)&&(this.validationError=`Invalid host preset: ${e}`)}}else this.command===`check`||this.command===`example`?o.length>0&&(this.validationError=`Unknown argument: ${o[0]}`):o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0];this.logger=t.logger||new ft({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=Q.example;return this.getFlagValue(e.long,e.short)}get noCodegen(){return this.hasFlag(`noCodegen`)}get file(){let e=Q.file;return this.getFlagValue(e.long,e.short)}get schema(){let e=Q.schema;return this.getFlagValue(e.long,e.short)??this.file}get envFiles(){let e=Q.envFile;return this.getFlagValues(e.long,e.short)}get hostPreset(){let e=this.getFlagValue(Q.preset.long,Q.preset.short)??this.getFlagValue(Q.hostPreset.long,Q.hostPreset.short);if(e&&An(e))return e}hasFlag(e){let t=Q[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),this.hostPreset!==void 0&&(e.hostPreset=this.hostPreset),e}get presetInput(){let e=this.positionalArgs[0],t=e===`remove`||e===`rm`?`remove`:`apply`,n=this.positionalArgs[1],r=this.file;return{action:t,...n&&jn(n)?{provider:n}:{},...r===void 0?{}:{file:r},isForce:this.isForce,isYes:this.isYes}}get checkInput(){return{...this.schema===void 0?{}:{schema:this.schema,file:this.schema},...this.envFiles.length>0?{envFiles:this.envFiles}:{},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent,isYes:this.isYes,isForce:this.isForce}}get exampleInput(){return{...this.schema===void 0?{}:{schema:this.schema,file:this.schema},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent}}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}getFlagValues(e,t){let n=[];for(let r=0;r<this.args.length-1;r++){let i=this.args[r];(i===e||t&&i===t)&&!this.args[r+1].startsWith(`-`)&&n.push(this.args[r+1])}return n}};function Fr(e){return e.replace(/\\([nrtbfv0"\\])/g,(e,t)=>{switch(t){case`n`:return`
164
- `;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`0`:return`\0`;case`"`:return`"`;case`\\`:return`\\`;default:return`\\${t}`}})}function Ir(e,t){for(let n=0;n<e.length;n++){if(t===`"`&&e[n]===`\\`){n++;continue}if(e[n]===t)return n}return-1}function Lr(e){let t={},n=e.split(/\r?\n/),r=null,i=``,a=null;for(let e=0;e<n.length;e++){let o=n[e];if(a!==null){let e=Ir(o,a);if(e!==-1){i+=`
165
- `+o.slice(0,e);let n=a===`"`?Fr(i):i;r!==null&&(t[r]=n),r=null,i=``,a=null}else i+=`
166
- `+o;continue}let s=o.trimStart();if(!s||s.startsWith(`#`))continue;s.startsWith(`export `)&&(s=s.slice(7).trimStart());let c=s.indexOf(`=`);if(c===-1)continue;let l=s.slice(0,c).trim();if(!l||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))continue;let u=s.slice(c+1).trimStart(),d=u[0];if(d===`"`||d===`'`||d==="`"){let e=u.slice(1),n=Ir(e,d);if(n!==-1){let r=e.slice(0,n);t[l]=d===`"`?Fr(r):r}else r=l,i=e,a=d}else{let e=u.indexOf(` #`);e!==-1&&(u=u.slice(0,e)),t[l]=u.trimEnd()}}return t}var Rr=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let n=e.cwd??process.cwd(),r=e.schema??e.file,i=!!(this.logger.isJson||e.isJson||e.isAgent),a=`.env`;try{await this.scanner.detectFramework(n)===`nextjs`&&(a=`.env.local`)}catch{}let o=await Bt(n,this.workspace,this.scanner,r);if(!o){let e=r?`Schema file not found at "${s.default.resolve(n,r)}".`:`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --schema <path>.`,t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,why:`The schema file could not be found in package.json or convention paths.`,docsUrl:`https://arkenv.js.org/docs/reference/check`,nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let c=s.default.relative(n,o)||o,l={...process.env};if(e.envFiles&&e.envFiles.length>0)for(let t of e.envFiles){let e=s.default.resolve(n,t);if(!await this.workspace.exists(e)){let n=`Environment file not found at "${e}".`;return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_INVALID_ARGUMENT,severity:`error`,summary:n,where:{path:t},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(n),2}let r=Lr(await this.workspace.readFile(e));Object.assign(l,r)}let u=await this.schemaLoader.load({schemaPath:o});if(!u.ok){let e=w(u.message);if(u.code===H.ERR_INSPECT_NO_CALL){let t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,where:{path:c},nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let t=u.cause?w(u.cause instanceof Error?u.cause.stack??u.cause.message:String(u.cause)):void 0,n=[{kind:`edit-file`,label:`Fix errors in ${c}`,where:{path:c}}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,...t?{why:t}:{},where:{path:c},nextActions:n},diagnostics:[],nextActions:n}):(this.logger.error(e),t&&this.logger.warn(t)),2}let d=await this.schemaLoader.validate({schemaPath:o},l);if(d.ok)return i?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:c}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — your environment matches the schema`),0;if(d.kind===`validation`){let e=d.issues??[],n=e.map(e=>{let n=e.code===`MISSING_VARIABLE`||e.received===void 0,r=n?y.ENV_MISSING_VARIABLE:y.ENV_INVALID_VALUE,i=t.l(e.path)&&!t.s(),o;o=i?n?`missing`:`[REDACTED]`:n||e.received===void 0?`missing`:typeof e.received==`string`?e.received:t.c(e.received,e.path);let s=w(e.message.startsWith(e.path)?e.message:`${e.path} ${e.message.trimStart()}`,e.path),l=[{kind:`edit-file`,label:`Set ${e.path} in ${a}`,where:{path:a},meta:{targetFile:a,key:e.path,...e.expected===void 0?{}:{expected:e.expected}}}],u={key:e.path,...e.expected===void 0?{}:{expected:e.expected},received:o,issueCode:e.code,...e.meta?e.meta:{}};return{code:r,severity:`error`,summary:s,where:{path:c},meta:u,nextActions:l}}),r=n.flatMap(e=>e.nextActions);return i?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:c}},exitCode:4,diagnostics:n,nextActions:r}):this.logger.error(`Errors found while validating environment variables:\n${t.o(t.i(e))}`),4}let f=d.message,p=w(f);return d.cause&&!(d.cause instanceof SyntaxError)&&!/syntax|cannot find module/i.test(f)?(i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_INTERNAL_ERROR,severity:`error`,summary:p,where:{path:c},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to validate environment: ${p}`),1):(i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:p,where:{path:c},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to load schema file at ${c}: ${p}`),2)}};const zr=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;function Br(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function Vr(e){return zr.test(e)}function Hr(e){return zr.exec(e)?.[1]}function Ur(e,t,n){if(e.length===0)return n?t:``;let r=e.join(t);return n?`${r}${t}`:r}function Wr(e){let t=e.includes(`\r
143
+ `),o===a?!1:(await this.writeFile(r,o),!0)}};async function Xn(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await R({message:_.default.yellow(`An existing ArkEnv configuration was found at ${W(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return N(e)||!e?null:e}return!0}async function Zn(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await R({message:n===`.env.example`?`Detected ${W(`.env.example`)} with ${e} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${e} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return N(i)?null:i}return!1}async function Qn(e){let t=await B({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return N(t)?null:t}async function $n(e){let t=await B({message:`Select your framework or build tool:`,initialValue:e.framework,options:[{value:`vanilla`,label:`Vanilla${e.framework===`vanilla`?` (Detected)`:``}`,hint:`Node.js, Bun, server-side or runtime-only validation`},{value:`vite`,label:`Vite${e.framework===`vite`?` (Detected)`:``}`,hint:`Client-side and static inlining validation`},{value:`bun-fullstack`,label:`Bun fullstack dev server${e.framework===`bun-fullstack`?` (Detected)`:``}`,hint:`Client-side bundling and Bun.serve integration`},{value:`nextjs`,label:`Next.js${e.framework===`nextjs`?` (Detected)`:``}`,hint:`Next.js App or Pages Router with build and runtime validation`},{value:`nuxt`,label:`Nuxt${e.framework===`nuxt`?` (Detected)`:``}`,hint:`Nuxt with build and runtime validation`}]});return N(t)?null:t}async function er(e){let t=await R({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return N(t)?null:t}async function tr(){let e=await B({message:`Select your preferred validator library:`,options:[{value:`arktype`,label:`ArkType (Recommended)`,hint:`TypeScript's 1:1 validator, optimized from editor to runtime`},{value:`zod`,label:`Zod`,hint:`TypeScript-first schema validation with static type inference`},{value:`valibot`,label:`Valibot`,hint:`The modular and type safe schema library`}]});return N(e)?null:e}async function nr(e){let t=await R({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return N(t)?null:t}async function rr(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(q).map(([e,t])=>({value:e,label:t.label,hint:t.hint}))],n=await B({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return N(n)?null:n}async function ir(e){let t=await R({message:`Use default config path (${W(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return N(t)?null:t}async function ar(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await ut({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(N(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const X={example:Qn,overwriteEnvSchemaFile:Xn,framework:$n,bunBuild:er,nextjsCodegen:nr,useDefaultPath:ir,path:ar,validator:tr,hostPreset:rr,useEnvExample:Zn};async function or(e,t=!1){return(e?.mode||`existing`)===`new`?sr(e,t):cr(e,t)}async function sr(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||s.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Z(await ut({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||s.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Z(await X.example({examples:n})):!a&&t&&(a=`basic`);let o=n.find(e=>e.id===a);if(!o){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:o.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:o.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof lr)return null;throw e}}async function cr(e,t=!1){let r=e?.defaultEnvPath||`./src/env.ts`,i=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(t){let t=e?.framework||`vanilla`;return(0,n.shake)({mode:`existing`,path:r,validator:`arktype`,framework:t,bunFeatures:t===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installSkill:!1,envKeys:i??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:t===`nextjs`?!0:void 0,hostPreset:e?.hostPreset||`none`})}try{let t=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Z(await X.framework({framework:e?.framework})),s;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);s=Z(await X.bunBuild({initialValue:t}))}let c=e?.disableCodegen;o===`nuxt`?c=!0:o===`nextjs`&&c===void 0&&(c=!Z(await X.nextjsCodegen({initialValue:!0,framework:o})));let l;if(o===`nextjs`&&!c){let e=await R({message:`Would you like to wrap your Next.js config with ${W(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(N(e))throw tt(`Operation cancelled`),new lr;l=e}let u=Z(await X.useDefaultPath({defaultEnvPath:r})),d=Z(await X.path({useDefaultPath:u,defaultEnvPath:r})),f=Z(await X.validator()),p=e?.hostPreset===void 0?Z(await X.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,m=Z(await X.useEnvExample({detectedKeys:i,keysSource:a}));return(0,n.shake)({mode:`existing`,overwriteEnvSchemaFile:t,framework:o,path:d,validator:f,hostPreset:p,bunFeatures:o===`bun-fullstack`?s?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:m?i??void 0:void 0,disableCodegen:c,wrapNextjsConfig:l})}catch(e){if(e instanceof lr)return null;throw e}}var lr=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||N(e))throw tt(`Operation cancelled`),new lr;return e}var ur=class{async confirm(e,t=!0,r,i){let a=await R((0,n.shake)({message:e,initialValue:t,active:r,inactive:i}));return N(a)?null:a}async runWizard(e,t=!1){return or(e,t)}async select(e,t,n){let r=await B({message:e,options:t,initialValue:n});return N(r)?null:r}};const Q={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:``,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:``,kind:`value`},noCodegen:{long:`--no-codegen`,short:``,kind:`boolean`},preset:{long:`--preset`,short:`-P`,kind:`value`},hostPreset:{long:`--host-preset`,short:`-H`,kind:`value`},file:{long:`--file`,short:``,kind:`value`},schema:{long:`--schema`,short:`-s`,kind:`value`},envFile:{long:`--env-file`,short:``,kind:`value`}},dr=new Set(Object.values(Q).flatMap(e=>[e.long,e.short].filter(Boolean))),fr=new Set(Object.values(Q).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var pr=class{constructor(e,t={}){let n=e.slice(2),r=[],i=!1;for(let e of n){if(i){r.push(e),i=!1;continue}if(fr.has(e)){r.push(e),i=!0;continue}if(/^-[a-zA-Z]{2,}$/.test(e)){let t=e.slice(1).split(``);for(let e of t)r.push(`-${e}`);fr.has(`-${t[t.length-1]}`)&&(i=!0)}else r.push(e)}this.args=r,this.command=this.args[0];let a=1,o=[];for(this.validationError=void 0;a<this.args.length;){let e=this.args[a];if(e.startsWith(`-`)){if(!dr.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(fr.has(e))if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}else a+=1}else o.push(e),a+=1}if(!this.validationError){let e=this.getFlagValue(Q.preset.long,Q.preset.short)??this.getFlagValue(Q.hostPreset.long,Q.hostPreset.short);e!==void 0&&!ln(e)&&(this.validationError=`Invalid host preset: ${e}`)}if(this.positionalArgs=o,!this.validationError)if(this.command===`preset`)if(o.length===0)this.validationError=`Missing subcommand`;else{let e=o[0];if(e!==`apply`&&e!==`remove`&&e!==`rm`&&e!==`add`)this.validationError=`Unknown preset action: ${e}`;else if(o.length>2)this.validationError=`Unknown argument: ${o[2]}`;else{let e=o[1];e!==void 0&&!un(e)&&(this.validationError=`Invalid host preset: ${e}`)}}else this.command===`check`||this.command===`example`?o.length>0&&(this.validationError=`Unknown argument: ${o[0]}`):o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0];this.logger=t.logger||new ft({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=Q.example;return this.getFlagValue(e.long,e.short)}get noCodegen(){return this.hasFlag(`noCodegen`)}get file(){let e=Q.file;return this.getFlagValue(e.long,e.short)}get schema(){let e=Q.schema;return this.getFlagValue(e.long,e.short)??this.file}get envFiles(){let e=Q.envFile;return this.getFlagValues(e.long,e.short)}get hostPreset(){let e=this.getFlagValue(Q.preset.long,Q.preset.short)??this.getFlagValue(Q.hostPreset.long,Q.hostPreset.short);if(e&&ln(e))return e}hasFlag(e){let t=Q[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),this.hostPreset!==void 0&&(e.hostPreset=this.hostPreset),e}get presetInput(){let e=this.positionalArgs[0],t=e===`remove`||e===`rm`?`remove`:`apply`,n=this.positionalArgs[1],r=this.file;return{action:t,...n&&un(n)?{provider:n}:{},...r===void 0?{}:{file:r},isForce:this.isForce,isYes:this.isYes}}get checkInput(){return{...this.schema===void 0?{}:{schema:this.schema,file:this.schema},...this.envFiles.length>0?{envFiles:this.envFiles}:{},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent,isYes:this.isYes,isForce:this.isForce}}get exampleInput(){return{...this.schema===void 0?{}:{schema:this.schema,file:this.schema},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent}}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}getFlagValues(e,t){let n=[];for(let r=0;r<this.args.length-1;r++){let i=this.args[r];(i===e||t&&i===t)&&!this.args[r+1].startsWith(`-`)&&n.push(this.args[r+1])}return n}};function mr(e){return e.replace(/\\([nrtbfv0"\\])/g,(e,t)=>{switch(t){case`n`:return`
144
+ `;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`0`:return`\0`;case`"`:return`"`;case`\\`:return`\\`;default:return`\\${t}`}})}function hr(e,t){for(let n=0;n<e.length;n++){if(t===`"`&&e[n]===`\\`){n++;continue}if(e[n]===t)return n}return-1}function gr(e){let t={},n=e.split(/\r?\n/),r=null,i=``,a=null;for(let e=0;e<n.length;e++){let o=n[e];if(a!==null){let e=hr(o,a);if(e!==-1){i+=`
145
+ `+o.slice(0,e);let n=a===`"`?mr(i):i;r!==null&&(t[r]=n),r=null,i=``,a=null}else i+=`
146
+ `+o;continue}let s=o.trimStart();if(!s||s.startsWith(`#`))continue;s.startsWith(`export `)&&(s=s.slice(7).trimStart());let c=s.indexOf(`=`);if(c===-1)continue;let l=s.slice(0,c).trim();if(!l||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))continue;let u=s.slice(c+1).trimStart(),d=u[0];if(d===`"`||d===`'`||d==="`"){let e=u.slice(1),n=hr(e,d);if(n!==-1){let r=e.slice(0,n);t[l]=d===`"`?mr(r):r}else r=l,i=e,a=d}else{let e=u.indexOf(` #`);e!==-1&&(u=u.slice(0,e)),t[l]=u.trimEnd()}}return t}var _r=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let n=e.cwd??process.cwd(),r=e.schema??e.file,i=!!(this.logger.isJson||e.isJson||e.isAgent),a=`.env`;try{await this.scanner.detectFramework(n)===`nextjs`&&(a=`.env.local`)}catch{}let o=await yt(n,this.workspace,this.scanner,r);if(!o){let e=r?`Schema file not found at "${s.default.resolve(n,r)}".`:`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --schema <path>.`,t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,why:`The schema file could not be found in package.json or convention paths.`,docsUrl:`https://arkenv.js.org/docs/reference/check`,nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let c=s.default.relative(n,o)||o,l={...process.env};if(e.envFiles&&e.envFiles.length>0)for(let t of e.envFiles){let e=s.default.resolve(n,t);if(!await this.workspace.exists(e)){let n=`Environment file not found at "${e}".`;return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_INVALID_ARGUMENT,severity:`error`,summary:n,where:{path:t},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(n),2}let r=gr(await this.workspace.readFile(e));Object.assign(l,r)}let u=await this.schemaLoader.load({schemaPath:o});if(!u.ok){let e=C(u.message);if(u.code===H.ERR_INSPECT_NO_CALL){let t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,where:{path:c},nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let t=u.cause?C(u.cause instanceof Error?u.cause.stack??u.cause.message:String(u.cause)):void 0,n=[{kind:`edit-file`,label:`Fix errors in ${c}`,where:{path:c}}];return i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,...t?{why:t}:{},where:{path:c},nextActions:n},diagnostics:[],nextActions:n}):(this.logger.error(e),t&&this.logger.warn(t)),2}let d=await this.schemaLoader.validate({schemaPath:o},l);if(d.ok)return i?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:c}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — your environment matches the schema`),0;if(d.kind===`validation`){let e=d.issues??[],n=e.map(e=>{let n=e.code===`MISSING_VARIABLE`||e.received===void 0,r=n?y.ENV_MISSING_VARIABLE:y.ENV_INVALID_VALUE,i=t.l(e.path)&&!t.s(),o;o=i?n?`missing`:`[REDACTED]`:n||e.received===void 0?`missing`:typeof e.received==`string`?e.received:t.c(e.received,e.path);let s=C(e.message.startsWith(e.path)?e.message:`${e.path} ${e.message.trimStart()}`,e.path),l=[{kind:`edit-file`,label:`Set ${e.path} in ${a}`,where:{path:a},meta:{targetFile:a,key:e.path,...e.expected===void 0?{}:{expected:e.expected}}}],u={key:e.path,...e.expected===void 0?{}:{expected:e.expected},received:o,issueCode:e.code,...e.meta?e.meta:{}};return{code:r,severity:`error`,summary:s,where:{path:c},meta:u,nextActions:l}}),r=n.flatMap(e=>e.nextActions);return i?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:c}},exitCode:4,diagnostics:n,nextActions:r}):this.logger.error(`Errors found while validating environment variables:\n${t.o(t.i(e))}`),4}let f=d.message,p=C(f);return d.cause&&!(d.cause instanceof SyntaxError)&&!/syntax|cannot find module/i.test(f)?(i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_INTERNAL_ERROR,severity:`error`,summary:p,where:{path:c},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to validate environment: ${p}`),1):(i?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:p,where:{path:c},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to load schema file at ${c}: ${p}`),2)}};const vr=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/;function yr(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}function br(e){return vr.test(e)}function xr(e){return vr.exec(e)?.[1]}function Sr(e,t,n){if(e.length===0)return n?t:``;let r=e.join(t);return n?`${r}${t}`:r}function Cr(e){let t=e.includes(`\r
167
147
  `)?`\r
168
148
  `:`
169
149
  `,n=e.endsWith(`
170
- `),r=e.split(/\r?\n/);n&&r[r.length-1]===``&&r.pop();let i=[],a=[],o=[],s=0;for(;s<r.length&&!Vr(r[s]);)i.push(r[s]),s+=1;for(;s<r.length;){let e=[];for(;s<r.length&&!Vr(r[s]);)e.push(r[s]),s+=1;if(s>=r.length){o.push(...e);break}let t=Hr(r[s]);if(!t){e.push(r[s]),s+=1;continue}a.push({key:t,lines:[...e,r[s]]}),s+=1}return{header:i,blocks:a,footer:o,newline:t,trailingNewline:n}}function Gr(e,t){let n=Br(t),r=new Set(n);if(e===null)return{content:n.length===0?``:`${n.map(e=>`${e}=`).join(`
171
- `)}\n`,status:`created`};let i=Wr(e),a=new Set,o=[...i.header];for(let e of i.blocks)!r.has(e.key)||a.has(e.key)||(o.push(...e.lines),a.add(e.key));for(let e of n)a.has(e)||(o.push(`${e}=`),a.add(e));for(o.push(...i.footer);o.length>0&&o[0]===``;)o.shift();for(;o.length>0&&o[o.length-1]===``;)o.pop();let s=Ur(o,i.newline,i.trailingNewline);return s===e?{content:s,status:`unchanged`}:{content:s,status:`updated`}}const Kr=`.env.example`;var qr=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let t=e.cwd??process.cwd(),n=e.schema??e.file,r=!!(!e.embedded&&(this.logger.isJson||e.isJson||e.isAgent)),i=await Bt(t,this.workspace,this.scanner,n);if(!i){let i=n?`Schema file not found at "${s.default.resolve(t,n)}".`:`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --schema <path>.`;return this.reportLoadFailure(r,e.embedded,i,[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}]),2}let a=s.default.relative(t,i)||i,o=await this.schemaLoader.load({schemaPath:i});if(!o.ok){let t=w(o.message),n=o.cause?w(o.cause instanceof Error?o.cause.stack??o.cause.message:String(o.cause)):void 0,i=o.code===H.ERR_INSPECT_NO_CALL?[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}]:[{kind:`edit-file`,label:`Fix errors in ${a}`,where:{path:a}}];return this.reportLoadFailure(r,e.embedded,t,i,a,n),2}let c=s.default.join(t,Kr),l=await this.workspace.exists(c),u=l?await this.workspace.readFile(c):null,d=o.keys.map(e=>e.name),f=Gr(u,d);if(f.status!==`unchanged`&&await this.workspace.writeFile(c,f.content),e.embedded)return 0;let p=l?f.status:`created`;return r?(this.logger.reportCompleted({ok:!0,commandId:`example`,result:{status:p,schema:{path:a},file:{path:Kr},keys:{declared:d.length}},exitCode:0,diagnostics:[],nextActions:[]}),0):(p===`created`?this.logger.success(`Created ${Kr} from ${a}`):p===`updated`?this.logger.success(`Updated ${Kr} from ${a}`):this.logger.success(`${Kr} already matches the schema`),0)}reportLoadFailure(e,t,n,r,i,a){if(t){this.logger.warn(n),a&&this.logger.warn(a);return}if(e){this.logger.reportErrored({ok:!1,commandId:`example`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:n,docsUrl:`https://arkenv.js.org/docs/reference/example`,...a?{why:a}:{},...i?{where:{path:i}}:{},nextActions:r},diagnostics:[],nextActions:r});return}this.logger.error(n),a&&this.logger.warn(a)}},Jr=`1.0.0-alpha.16`;function $(e,t=2,n=4){let r=Math.max(...e.map(e=>e.left.length),0),i=` `.repeat(t);return e.map(e=>{let t=` `.repeat(r-e.left.length+n);return`${i}${e.left}${t}${e.right}`})}var Yr=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{left:`arkenv check`,right:`Validate the environment against the schema`},{left:`arkenv example`,right:`Update .env.example from the schema`},{left:`arkenv preset apply [provider]`,right:`Apply or refresh hosting provider preset (vercel, netlify, cloudflare, railway, render, fly)`},{left:`arkenv preset remove [provider]`,right:`Remove hosting provider preset from schema`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--agent`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--help, -h`,right:`Show this help message`}],n=[{left:`--example`,right:`Specify an example name when creating a new project`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--no-codegen`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--preset, -P <preset>`,right:`Specify a hosting provider preset (none, vercel, netlify, cloudflare, railway, render, fly)`}],r=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides package.json or convention discovery)`},{left:`--env-file <file>`,right:`Path to .env file to load (repeatable; merged in order over process.env)`}],i=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides package.json or convention discovery)`}],a=[{left:`--file <path>`,right:`Path to schema file (overrides package.json arkenv pointer)`},{left:`--force, -f`,right:`Bypass dirty git working tree check`}];this.logger.log(`ArkEnv CLI v${Jr}`),this.logger.log(`\n${_.default.bold(`Usage:`)}`);for(let t of $(e))this.logger.log(t);this.logger.log(`\n${_.default.bold(`Global options:`)}`);for(let e of $(t))this.logger.log(e);this.logger.log(`\n${_.default.bold(`init options:`)}`);for(let e of $(n))this.logger.log(e);this.logger.log(`\n${_.default.bold(`check options:`)}`);for(let e of $(r))this.logger.log(e);this.logger.log(`\n${_.default.bold(`example options:`)}`);for(let e of $(i))this.logger.log(e);this.logger.log(`\n${_.default.bold(`preset options:`)}`);for(let e of $(a))this.logger.log(e)}};async function Xr(e,t){let n=t.targetDir??process.cwd(),r=s.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(r,!0),t.targetDir&&await e.mkdir(n,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,r]);let i=`examples/${t.example}`;await e.execute(`git`,[`-C`,r,`sparse-checkout`,`set`,i]);let a=s.default.join(r,i),o=await c.default.readdir(a),l=[];for(let t of o){let r=s.default.join(n,t);await e.exists(r)&&l.push(t)}if(l.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${l.join(`, `)}`);await Zr(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await c.default.rm(s.default.join(n,e),{force:!0});let u=s.default.join(n,`package.json`);if(await e.exists(u)){let n=await e.readFile(u),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(u,JSON.stringify(r,null,2))}}finally{await c.default.rm(r,{recursive:!0,force:!0})}}async function Zr(e,t){let n=await c.default.readdir(e);await Promise.all(n.map(n=>c.default.cp(s.default.join(e,n),s.default.join(t,n),{recursive:!0,force:!1})))}function Qr(e,t){let n=t.length>0;switch(e){case`pnpm`:return[`pnpm`,[n?`add`:`install`,...t]];case`yarn`:return[`yarn`,[n?`add`:`install`,...t]];case`bun`:return[`bun`,[n?`add`:`install`,...t]];default:return[`npm`,[`install`,...t]]}}function $r(e,t,n){if(t||e.metadata.skillDetected){let t=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen,r=e.metadata.framework===`nuxt`&&!e.metadata.disableCodegen,i=t&&!n,a=l.default`
150
+ `),r=e.split(/\r?\n/);n&&r[r.length-1]===``&&r.pop();let i=[],a=[],o=[],s=0;for(;s<r.length&&!br(r[s]);)i.push(r[s]),s+=1;for(;s<r.length;){let e=[];for(;s<r.length&&!br(r[s]);)e.push(r[s]),s+=1;if(s>=r.length){o.push(...e);break}let t=xr(r[s]);if(!t){e.push(r[s]),s+=1;continue}a.push({key:t,lines:[...e,r[s]]}),s+=1}return{header:i,blocks:a,footer:o,newline:t,trailingNewline:n}}function wr(e,t){let n=yr(t),r=new Set(n);if(e===null)return{content:n.length===0?``:`${n.map(e=>`${e}=`).join(`
151
+ `)}\n`,status:`created`};let i=Cr(e),a=new Set,o=[...i.header];for(let e of i.blocks)!r.has(e.key)||a.has(e.key)||(o.push(...e.lines),a.add(e.key));for(let e of n)a.has(e)||(o.push(`${e}=`),a.add(e));for(o.push(...i.footer);o.length>0&&o[0]===``;)o.shift();for(;o.length>0&&o[o.length-1]===``;)o.pop();let s=Sr(o,i.newline,i.trailingNewline);return s===e?{content:s,status:`unchanged`}:{content:s,status:`updated`}}const Tr=`.env.example`;var Er=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let t=e.cwd??process.cwd(),n=e.schema??e.file,r=!!(!e.embedded&&(this.logger.isJson||e.isJson||e.isAgent)),i=await yt(t,this.workspace,this.scanner,n);if(!i){let i=n?`Schema file not found at "${s.default.resolve(t,n)}".`:`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --schema <path>.`;return this.reportLoadFailure(r,e.embedded,i,[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}]),2}let a=s.default.relative(t,i)||i,o=await this.schemaLoader.load({schemaPath:i});if(!o.ok){let t=C(o.message),n=o.cause?C(o.cause instanceof Error?o.cause.stack??o.cause.message:String(o.cause)):void 0,i=o.code===H.ERR_INSPECT_NO_CALL?[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}]:[{kind:`edit-file`,label:`Fix errors in ${a}`,where:{path:a}}];return this.reportLoadFailure(r,e.embedded,t,i,a,n),2}let c=s.default.join(t,Tr),l=await this.workspace.exists(c),u=l?await this.workspace.readFile(c):null,d=o.keys.map(e=>e.name),f=wr(u,d);if(f.status!==`unchanged`&&await this.workspace.writeFile(c,f.content),e.embedded)return 0;let p=l?f.status:`created`;return r?(this.logger.reportCompleted({ok:!0,commandId:`example`,result:{status:p,schema:{path:a},file:{path:Tr},keys:{declared:d.length}},exitCode:0,diagnostics:[],nextActions:[]}),0):(p===`created`?this.logger.success(`Created ${Tr} from ${a}`):p===`updated`?this.logger.success(`Updated ${Tr} from ${a}`):this.logger.success(`${Tr} already matches the schema`),0)}reportLoadFailure(e,t,n,r,i,a){if(t){this.logger.warn(n),a&&this.logger.warn(a);return}if(e){this.logger.reportErrored({ok:!1,commandId:`example`,error:{code:y.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:n,docsUrl:`https://arkenv.js.org/docs/reference/example`,...a?{why:a}:{},...i?{where:{path:i}}:{},nextActions:r},diagnostics:[],nextActions:r});return}this.logger.error(n),a&&this.logger.warn(a)}},Dr=`1.0.0-alpha.17`;function $(e,t=2,n=4){let r=Math.max(...e.map(e=>e.left.length),0),i=` `.repeat(t);return e.map(e=>{let t=` `.repeat(r-e.left.length+n);return`${i}${e.left}${t}${e.right}`})}var Or=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{left:`arkenv check`,right:`Validate the environment against the schema`},{left:`arkenv example`,right:`Update .env.example from the schema`},{left:`arkenv preset apply [provider]`,right:`Apply or refresh hosting provider preset (vercel, netlify, cloudflare, railway, render, fly)`},{left:`arkenv preset remove [provider]`,right:`Remove hosting provider preset from schema`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--agent`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--help, -h`,right:`Show this help message`}],n=[{left:`--example`,right:`Specify an example name when creating a new project`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--no-codegen`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--preset, -P <preset>`,right:`Specify a hosting provider preset (none, vercel, netlify, cloudflare, railway, render, fly)`}],r=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides package.json or convention discovery)`},{left:`--env-file <file>`,right:`Path to .env file to load (repeatable; merged in order over process.env)`}],i=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides package.json or convention discovery)`}],a=[{left:`--file <path>`,right:`Path to schema file (overrides package.json arkenv pointer)`},{left:`--force, -f`,right:`Bypass dirty git working tree check`}];this.logger.log(`ArkEnv CLI v${Dr}`),this.logger.log(`\n${_.default.bold(`Usage:`)}`);for(let t of $(e))this.logger.log(t);this.logger.log(`\n${_.default.bold(`Global options:`)}`);for(let e of $(t))this.logger.log(e);this.logger.log(`\n${_.default.bold(`init options:`)}`);for(let e of $(n))this.logger.log(e);this.logger.log(`\n${_.default.bold(`check options:`)}`);for(let e of $(r))this.logger.log(e);this.logger.log(`\n${_.default.bold(`example options:`)}`);for(let e of $(i))this.logger.log(e);this.logger.log(`\n${_.default.bold(`preset options:`)}`);for(let e of $(a))this.logger.log(e)}};async function kr(e,t){let n=t.targetDir??process.cwd(),r=s.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(r,!0),t.targetDir&&await e.mkdir(n,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,r]);let i=`examples/${t.example}`;await e.execute(`git`,[`-C`,r,`sparse-checkout`,`set`,i]);let a=s.default.join(r,i),o=await u.default.readdir(a),c=[];for(let t of o){let r=s.default.join(n,t);await e.exists(r)&&c.push(t)}if(c.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${c.join(`, `)}`);await Ar(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await u.default.rm(s.default.join(n,e),{force:!0});let l=s.default.join(n,`package.json`);if(await e.exists(l)){let n=await e.readFile(l),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(l,JSON.stringify(r,null,2))}}finally{await u.default.rm(r,{recursive:!0,force:!0})}}async function Ar(e,t){let n=await u.default.readdir(e);await Promise.all(n.map(n=>u.default.cp(s.default.join(e,n),s.default.join(t,n),{recursive:!0,force:!1})))}function jr(e,t){let n=t.length>0;switch(e){case`pnpm`:return[`pnpm`,[n?`add`:`install`,...t]];case`yarn`:return[`yarn`,[n?`add`:`install`,...t]];case`bun`:return[`bun`,[n?`add`:`install`,...t]];default:return[`npm`,[`install`,...t]]}}function Mr(e,t,n){if(t||e.metadata.skillDetected){let t=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen,r=e.metadata.framework===`nuxt`&&!e.metadata.disableCodegen,i=t&&!n,a=p.default`
172
152
  Inside your AI assistant (e.g. Claude Code), use:
173
153
  ${W(`/arkenv`)} - automatically refine your schema and configure integrations.
174
154
  `;return i?(a+=`
175
155
 
176
156
  `,a+=`Also, wrap your Next.js config with ${W(`withArkEnv`)}:\n`,a+=` ${W(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${W(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${W(`import { env } from "${e.metadata.importPath}"`)}\n`):r&&(a+=`
177
157
 
178
- `,a+=`Import and use: ${W(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:a,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,i=e.skill?.packageName||`yamcodes/arkenv`,a=``,o=1,s=e.metadata.displayPath;a+=`${o++}. Check ${W(s)} and refine your environment schema.\n`;let c=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`nextjs`&&(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${W(`withArkEnv`)} inside ${W(`next.config.ts`)}:\n`,a+=` ${W(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${W(`export default withArkEnv(nextConfig);`)}\n`)),a+=`${o++}. Import and use: ${W(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${W(`${r} skills add ${i}`)}\n`,a+=` Then run ${W(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const ei=[`esbuild`];var ti=class{constructor(e,t){this.workspace=e,this.reporter=t}async execute(e){let t=this.reporter.spinner();t.start(`Scaffolding ArkEnv configuration...`);try{e.clone&&(t.stop(`Starting new project scaffolding...`),this.reporter.step(`Cloning example ${W(e.clone.example)}...`),await Xr(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files){if(t.action===`append`){if(!e.bootstrap||e.bootstrap.framework!==`vite`&&e.bootstrap.framework!==`bun-fullstack`){this.reporter.warn(`Skipping safe-append for ${W(s.default.basename(t.path))}: unsupported framework.`);continue}await this.workspace.safeAppend(t.path,t.content,e.bootstrap.framework)?this.reporter.info(`Appended ArkEnv types to ${W(s.default.basename(t.path))}.`):this.reporter.info(`${W(s.default.basename(t.path))} already contains ArkEnv types.`);continue}if(!(t.action===`create`&&await this.workspace.exists(t.path))&&(await this.workspace.mkdir(s.default.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content),t.label!==`environment schema`&&t.label?.includes(`types`))){let e=t.action===`overwrite`?`Updated`:`Created`;this.reporter.info(`${e} ${W(s.default.basename(t.path))} for typesafe environment variables.`)}}if(t.stop(`Configuration scaffolded!`),await this.configurePackageJsonArkenv(e.install?.cwd??e.cwd,e.metadata),e.install&&process.env.SKIP_INSTALL!==`true`){e.install.packageManager===`pnpm`&&await this.configurePnpmBuilds(e.install.cwd??e.cwd),this.reporter.step(`Installing dependencies with ${W(e.install.packageManager)}...`);let[t,n]=Qr(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n,e.install.cwd??e.cwd)}let n=!1;if(e.tsConfig){let t=await this.workspace.updateTsConfigToStrict(e.tsConfig.path);t.status===`updated`?(this.reporter.info(`Enforced strict: true in your ${W(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${W(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let r=!1;if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig(e.cwd);if(t){this.reporter.step(`Bootstrapping Vite plugin...`);let n=await this.workspace.bootstrapViteConfig(t,e.bootstrap.importPath||`./src/env`);n.success?n.updated&&this.reporter.info(`Updated ${W(s.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${W(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${W(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let t=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(process.cwd(), '.arkenv', 'env.gen.ts'); runCodegen(schemaPath, outputPath); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,t],e.cwd),this.reporter.info(`Generated ${W(`.arkenv/env.gen.ts`)} for Next.js`);let n=await this.workspace.ensureNextjsArkEnvTsConfig(e.tsConfig?.path);n.status===`updated`&&this.reporter.info(`Mapped ${W(`@/.arkenv`)} in ${W(n.file||`tsconfig.json`)}`)}catch{this.reporter.warn(`Failed to automatically generate ${W(`.arkenv/env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let n=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen);n.success?n.updated?(this.reporter.info(`Updated ${W(s.default.basename(t))}`),r=!0):(this.reporter.info(`${W(s.default.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${W(`withArkEnv`)} manually.`)}}else if(e.bootstrap.framework===`nuxt`){this.reporter.step(`Bootstrapping Nuxt config...`);let t=await this.workspace.findNuxtConfig(e.cwd);if(t){let e=await this.workspace.bootstrapNuxtConfig(t);e.success?(e.updated?this.reporter.info(`Updated ${W(s.default.basename(t))}`):this.reporter.info(`${W(s.default.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${W(`@arkenv/nuxt/module`)} manually.`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r,e.cwd),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=$r(e,i,r);this.reporter.note(a.message,a.title),this.reporter.finish(`${hn} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i},`init`)}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=s.default.join(e,`package.json`);if(await this.workspace.exists(t))try{let e=await this.workspace.readFile(t),n=JSON.parse(e);n.pnpm=n.pnpm||{},n.pnpm.onlyBuiltDependencies=n.pnpm.onlyBuiltDependencies||[];for(let e of ei)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
179
- `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=s.default.join(e,`pnpm-workspace.yaml`),r=``;if(await this.workspace.exists(n))try{r=await this.workspace.readFile(n)}catch{}let i=this.updatePnpmWorkspaceYaml(r);try{await this.workspace.writeFile(n,i)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=(0,h.parseDocument)(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if((0,h.isMap)(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),(0,h.isMap)(n))for(let e of ei)n.get(e)!==!0&&n.set(e,!0);return String(t)}async configurePackageJsonArkenv(e,t){let n=s.default.join(e,`package.json`);if(await this.workspace.exists(n))try{let e=await this.workspace.readFile(n),r=JSON.parse(e);r.arkenv={schema:t.displayPath},await this.workspace.writeFile(n,JSON.stringify(r,null,2)+`
180
- `)}catch(e){this.reporter.warn(`Could not update package.json with arkenv schema entry: ${e}`)}}};const ni={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-zod":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-vite-react-zod":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-zod":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-valibot":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"mix-and-match":{DATABASE_URL:`https://postgres.example.com/db`,API_KEY:`12345678901234567890123456789012`,NODE_ENV:`development`,PORT:`3000`,DEBUG:`false`}};function ri(e,t){return ni[e]??t()}function ii(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function ai(e,t,n,r){if(!r||r===`none`)return;let i=J(r,n);for(let a of i)n&&a.startsWith(n)?e.clientFields.push(`\t\t${t.formatCodegenField(a,`client`,n,r)}`):e.serverFields.push(`\t\t${t.formatCodegenField(a,`server`,n,r)}`)}function oi(e){let t=[];for(let n of e){let e=n.trim().match(/^([a-zA-Z0-9_]+)\s*:/);e&&t.push(e[1])}return t}function si(e,t,n,r=[]){let i=[],a=new Set,o=e=>{a.has(e)||(a.add(e),i.push(`\t\t${e}: process.env.${e},`))};if(e&&e.length>0){for(let n of e)(n.startsWith(t)||n===`NODE_ENV`||r.includes(n))&&o(n);return i}o(`${t}API_URL`),o(`NODE_ENV`);for(let e of oi(n))o(e);for(let e of r)o(e);return i}function ci(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,hostPreset:o}=e,{clientPrefix:s}=r,c=[],l=[],u=[];if(t&&t.length>0)for(let e of t)e.startsWith(s)?l.push(`\t\t${n.formatCodegenField(e,`client`,s,o)}`):e===`NODE_ENV`?u.push(`\t\t${n.formatCodegenField(e,`shared`,s,o)}`):c.push(`\t\t${n.formatCodegenField(e,`server`,s,o)}`);else{let e=n.getDefaultCodegenFields(s);c.push(...e.serverFields),l.push(...e.clientFields),u.push(...e.sharedFields),ai({serverFields:c,clientFields:l},n,s,o)}return li({serverFields:c,clientFields:l,sharedFields:u,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,hostPreset:o})}function li(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c,hostPreset:l}=e,{clientPrefix:u,packageName:d,displayName:f}=o,p=o.id,m=a.extraImport,h=J(l??`none`,u),g;if(l&&l!==`none`&&h.length>0){let e=[...t,...n,...r].filter(e=>{let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/)?.[1];return t&&!h.includes(t)}).map(e=>e.replace(/^\t\t/,` `)),i=[];for(let e of h){let t=u&&e.startsWith(u)?`client`:e===`NODE_ENV`?`shared`:`server`;i.push(`\t${a.formatCodegenField(e,t,u,l)}`)}g=[...e,...e.length>0?[``]:[],`\t${Pn(l)}`,...i,`\t${Fn(l)}`]}else g=[...t,...n,...r].map(e=>e.replace(/^\t\t/,` `));let _=[];for(let e of r){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&_.push(e)}}let v=[];if(_.length>0&&v.push(`\texposeToClient: [${_.map(e=>`"${e}"`).join(`, `)}]`),c&&p===`nextjs`){let e=si(i,u,n,_);v.push(`\truntimeEnv: {\n${e.join(`
158
+ `,a+=`Import and use: ${W(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:a,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,i=e.skill?.packageName||`yamcodes/arkenv`,a=``,o=1,s=e.metadata.displayPath;a+=`${o++}. Check ${W(s)} and refine your environment schema.\n`;let c=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`nextjs`&&(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${W(`withArkEnv`)} inside ${W(`next.config.ts`)}:\n`,a+=` ${W(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${W(`export default withArkEnv(nextConfig);`)}\n`)),a+=`${o++}. Import and use: ${W(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${W(`${r} skills add ${i}`)}\n`,a+=` Then run ${W(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const Nr=[`esbuild`];var Pr=class{constructor(e,t){this.workspace=e,this.reporter=t}async execute(e){let t=this.reporter.spinner();t.start(`Scaffolding ArkEnv configuration...`);try{e.clone&&(t.stop(`Starting new project scaffolding...`),this.reporter.step(`Cloning example ${W(e.clone.example)}...`),await kr(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files)t.action===`create`&&await this.workspace.exists(t.path)||(await this.workspace.mkdir(s.default.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content));if(t.stop(`Configuration scaffolded!`),await this.configurePackageJsonArkenv(e.install?.cwd??e.cwd,e.metadata),e.install&&process.env.SKIP_INSTALL!==`true`){e.install.packageManager===`pnpm`&&await this.configurePnpmBuilds(e.install.cwd??e.cwd),this.reporter.step(`Installing dependencies with ${W(e.install.packageManager)}...`);let[t,n]=jr(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n,e.install.cwd??e.cwd)}let n=!1;if(e.tsConfig){let t=await this.workspace.updateTsConfigToStrict(e.tsConfig.path);t.status===`updated`?(this.reporter.info(`Enforced strict: true in your ${W(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${W(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let r=!1;if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig(e.cwd);if(t){this.reporter.step(`Bootstrapping Vite plugin...`);let n=await this.workspace.bootstrapViteConfig(t,e.bootstrap.importPath||`./src/env`);n.success?n.updated&&this.reporter.info(`Updated ${W(s.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${W(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${W(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let t=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(process.cwd(), '.arkenv', 'env.gen.ts'); runCodegen(schemaPath, outputPath); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,t],e.cwd),this.reporter.info(`Generated ${W(`.arkenv/env.gen.ts`)} for Next.js`);let n=await this.workspace.ensureNextjsArkEnvTsConfig(e.tsConfig?.path);n.status===`updated`&&this.reporter.info(`Mapped ${W(`@/.arkenv`)} in ${W(n.file||`tsconfig.json`)}`)}catch{this.reporter.warn(`Failed to automatically generate ${W(`.arkenv/env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let n=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen);n.success?n.updated?(this.reporter.info(`Updated ${W(s.default.basename(t))}`),r=!0):(this.reporter.info(`${W(s.default.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${W(`withArkEnv`)} manually.`)}}else if(e.bootstrap.framework===`nuxt`){this.reporter.step(`Bootstrapping Nuxt config...`);let t=await this.workspace.findNuxtConfig(e.cwd);if(t){let e=await this.workspace.bootstrapNuxtConfig(t);e.success?(e.updated?this.reporter.info(`Updated ${W(s.default.basename(t))}`):this.reporter.info(`${W(s.default.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${W(s.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${W(`@arkenv/nuxt/module`)} manually.`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r,e.cwd),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=Mr(e,i,r);this.reporter.note(a.message,a.title),this.reporter.finish(`${qt} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i},`init`)}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=s.default.join(e,`package.json`);if(await this.workspace.exists(t))try{let e=await this.workspace.readFile(t),n=JSON.parse(e);n.pnpm=n.pnpm||{},n.pnpm.onlyBuiltDependencies=n.pnpm.onlyBuiltDependencies||[];for(let e of Nr)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
159
+ `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=s.default.join(e,`pnpm-workspace.yaml`),r=``;if(await this.workspace.exists(n))try{r=await this.workspace.readFile(n)}catch{}let i=this.updatePnpmWorkspaceYaml(r);try{await this.workspace.writeFile(n,i)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=(0,h.parseDocument)(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if((0,h.isMap)(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),(0,h.isMap)(n))for(let e of Nr)n.get(e)!==!0&&n.set(e,!0);return String(t)}async configurePackageJsonArkenv(e,t){let n=s.default.join(e,`package.json`);if(await this.workspace.exists(n))try{let e=await this.workspace.readFile(n),r=JSON.parse(e);r.arkenv={schema:t.displayPath},await this.workspace.writeFile(n,JSON.stringify(r,null,2)+`
160
+ `)}catch(e){this.reporter.warn(`Could not update package.json with arkenv schema entry: ${e}`)}}};const Fr={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-zod":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-vite-react-zod":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-zod":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-valibot":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"mix-and-match":{DATABASE_URL:`https://postgres.example.com/db`,API_KEY:`12345678901234567890123456789012`,NODE_ENV:`development`,PORT:`3000`,DEBUG:`false`}};function Ir(e,t){return Fr[e]??t()}function Lr(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function Rr(e,t,n,r){if(!r||r===`none`)return;let i=J(r,n);for(let a of i)n&&a.startsWith(n)?e.clientFields.push(`\t\t${t.formatCodegenField(a,`client`,n,r)}`):e.serverFields.push(`\t\t${t.formatCodegenField(a,`server`,n,r)}`)}function zr(e){let t=[];for(let n of e){let e=n.trim().match(/^([a-zA-Z0-9_]+)\s*:/);e&&t.push(e[1])}return t}function Br(e,t,n,r=[]){let i=[],a=new Set,o=e=>{a.has(e)||(a.add(e),i.push(`\t\t${e}: process.env.${e},`))};if(e&&e.length>0){for(let n of e)(n.startsWith(t)||n===`NODE_ENV`||r.includes(n))&&o(n);return i}o(`${t}API_URL`),o(`NODE_ENV`);for(let e of zr(n))o(e);for(let e of r)o(e);return i}function Vr(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,hostPreset:o}=e,{clientPrefix:s}=r,c=[],l=[],u=[];if(t&&t.length>0)for(let e of t)e.startsWith(s)?l.push(`\t\t${n.formatCodegenField(e,`client`,s,o)}`):e===`NODE_ENV`?u.push(`\t\t${n.formatCodegenField(e,`shared`,s,o)}`):c.push(`\t\t${n.formatCodegenField(e,`server`,s,o)}`);else{let e=n.getDefaultCodegenFields(s);c.push(...e.serverFields),l.push(...e.clientFields),u.push(...e.sharedFields),Rr({serverFields:c,clientFields:l},n,s,o)}return Hr({serverFields:c,clientFields:l,sharedFields:u,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,hostPreset:o})}function Hr(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c,hostPreset:l}=e,{clientPrefix:u,packageName:d,displayName:f}=o,p=o.id,m=a.extraImport,h=J(l??`none`,u),g;if(l&&l!==`none`&&h.length>0){let e=[...t,...n,...r].filter(e=>{let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/)?.[1];return t&&!h.includes(t)}).map(e=>e.replace(/^\t\t/,` `)),i=[];for(let e of h){let t=u&&e.startsWith(u)?`client`:e===`NODE_ENV`?`shared`:`server`;i.push(`\t${a.formatCodegenField(e,t,u,l)}`)}g=[...e,...e.length>0?[``]:[],`\t${pn(l)}`,...i,`\t${mn(l)}`]}else g=[...t,...n,...r].map(e=>e.replace(/^\t\t/,` `));let _=[];for(let e of r){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&_.push(e)}}let v=[];if(_.length>0&&v.push(`\texposeToClient: [${_.map(e=>`"${e}"`).join(`, `)}]`),c&&p===`nextjs`){let e=Br(i,u,n,_);v.push(`\truntimeEnv: {\n${e.join(`
181
161
  `)}\n\t}`)}let y=v.length>0?`, {\n${v.join(`,
182
162
  `)}\n}`:``;return`${[`import arkenv from "${p===`nuxt`||c?d:s||`@/.arkenv`}";`,...m?[m]:[]].join(`
183
163
  `)}
@@ -191,9 +171,9 @@ export const env = arkenv({
191
171
  ${g.join(`
192
172
  `)}
193
173
  }${y});
194
- `}function ui(e,t,n){let r=J(n.hostPreset??`none`,n.clientPrefix),i=gn(n.framework);if(i){let a=t.length>0?Array.from(new Set([...t,...r])):void 0;return`${ci({...a===void 0?{}:{envKeys:a},dialect:e,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(n.hostPreset&&n.hostPreset!==`none`&&r.length>0){let i=`\t\t${Pn(n.hostPreset)}`,o=`\t\t${Fn(n.hostPreset)}`,s=e.formatSimpleSchemaFields(r,n.clientPrefix,n.hostPreset),c=t.filter(e=>!r.includes(e));a=c.length>0?`${e.formatSimpleSchemaFields(c,n.clientPrefix,void 0)}\n\n${i}\n${s}\n${o}`:`${e.defaultSimpleSchemaFields}\n\n${i}\n${s}\n${o}`}else a=t.length>0?e.formatSimpleSchemaFields(t,n.clientPrefix,n.hostPreset):e.defaultSimpleSchemaFields;return`${e.assembleVanilla(a)}\n`}function di(e){return{getSimpleTemplate(t,n){return ui(e,t,n)}}}const fi={arktype:di(Bn.arktype),zod:di(Bn.zod),valibot:di(Bn.valibot)};function pi(e){return e.mode===`new`?bi(e):xi(e)}function mi(e,t){return e.some(e=>{let n=e.indexOf(`#`),r=(n===-1?e:e.slice(0,n)).trim();if(!r)return!1;if(r===t||r===`/${t}`)return!0;if(r.includes(`*`)){let e=`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`).replace(/^\//,`/?`)}$`;try{let n=new RegExp(e);return n.test(t)||n.test(`/${t}`)}catch{return!1}}return!1})}function hi(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
174
+ `}function Ur(e,t,n){let r=J(n.hostPreset??`none`,n.clientPrefix),i=Jt(n.framework);if(i){let a=t.length>0?Array.from(new Set([...t,...r])):void 0;return`${Vr({...a===void 0?{}:{envKeys:a},dialect:e,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(n.hostPreset&&n.hostPreset!==`none`&&r.length>0){let i=`\t\t${pn(n.hostPreset)}`,o=`\t\t${mn(n.hostPreset)}`,s=e.formatSimpleSchemaFields(r,n.clientPrefix,n.hostPreset),c=t.filter(e=>!r.includes(e));a=c.length>0?`${e.formatSimpleSchemaFields(c,n.clientPrefix,void 0)}\n\n${i}\n${s}\n${o}`:`${e.defaultSimpleSchemaFields}\n\n${i}\n${s}\n${o}`}else a=t.length>0?e.formatSimpleSchemaFields(t,n.clientPrefix,n.hostPreset):e.defaultSimpleSchemaFields;return`${e.assembleVanilla(a)}\n`}function Wr(e){return{getSimpleTemplate(t,n){return Ur(e,t,n)}}}const Gr={arktype:Wr(yn.arktype),zod:Wr(yn.zod),valibot:Wr(yn.valibot)};function Kr(e){return e.mode===`new`?$r(e):ei(e)}function qr(e,t){return e.some(e=>{let n=e.indexOf(`#`),r=(n===-1?e:e.slice(0,n)).trim();if(!r)return!1;if(r===t||r===`/${t}`)return!0;if(r.includes(`*`)){let e=`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`).replace(/^\//,`/?`)}$`;try{let n=new RegExp(e);return n.test(t)||n.test(`/${t}`)}catch{return!1}}return!1})}function Jr(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
195
175
  `)+`
196
- `}function gi(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=kn[r.framework],o=s.default.join(n,`.env`),c=s.default.join(n,`.env.example`),l=i.includes(o),u=i.includes(c),d=Nn(r.envKeys,r.hostPreset,a.clientPrefix);if(!l){let e=r.envExampleContent===void 0?hi(a.getEnvDefaults(d)):r.envExampleContent;t.files.push({path:o,content:e,action:`create`,label:`local environment variables`})}u||t.files.push({path:c,content:hi(a.getEnvDefaults(d)),action:`create`,label:`environment variables template`})}function _i(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=s.default.join(n,`.gitignore`),o=i.includes(a),c=r.framework===`nextjs`;if(o&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=mi(e,`.env`),i=mi(e,`.env.local`),o=mi(e,`.arkenv`)||mi(e,`.arkenv/`);if(!n||!i||c&&!o){let e=``;(!n||!i)&&(e+=`
176
+ `}function Yr(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=cn[r.framework],o=s.default.join(n,`.env`),c=s.default.join(n,`.env.example`),l=i.includes(o),u=i.includes(c),d=fn(r.envKeys,r.hostPreset,a.clientPrefix);if(!l){let e=r.envExampleContent===void 0?Jr(a.getEnvDefaults(d)):r.envExampleContent;t.files.push({path:o,content:e,action:`create`,label:`local environment variables`})}u||t.files.push({path:c,content:Jr(a.getEnvDefaults(d)),action:`create`,label:`environment variables template`})}function Xr(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=s.default.join(n,`.gitignore`),o=i.includes(a),c=r.framework===`nextjs`;if(o&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=qr(e,`.env`),i=qr(e,`.env.local`),o=qr(e,`.arkenv`)||qr(e,`.arkenv/`);if(!n||!i||c&&!o){let e=``;(!n||!i)&&(e+=`
197
177
  # Environment variables
198
178
  `,n||(e+=`.env
199
179
  `),i||(e+=`.env.local
@@ -207,4 +187,4 @@ ${g.join(`
207
187
  `;c&&(e+=`
208
188
  # ArkEnv generated factory
209
189
  .arkenv/
210
- `),t.files.push({path:a,content:e,action:`create`,label:`.gitignore file`})}}function vi(e){let{mode:t,options:r,packageManager:i}=e,a=r.name&&r.name!==`.`?s.default.basename(r.name):void 0;return(0,n.shake)({displayPath:``,framework:r.framework,validator:r.validator,packageManager:i,importPath:``,mode:t,example:r.example,name:a,skillDetected:r.skillDetected,disableCodegen:r.disableCodegen})}function yi(e,t){e.options.installSkill&&(t.skill={dlxCommand:ii(e.packageManager),packageName:`yamcodes/arkenv`,isYes:e.isYes})}function bi(e){let{options:t,packageManager:n,cwd:r}=e;if(!t.example)throw Error(`New project scaffolding requires an example.`);let i=t.name&&t.name!==`.`?s.default.join(r,t.name):void 0,a=t.name&&t.name!==`.`?s.default.basename(t.name):s.default.basename(r),o={files:[],cwd:r,metadata:vi(e),clone:{repository:`https://github.com/yamcodes/arkenv.git`,example:t.example,targetName:a,...i!==void 0&&{targetDir:i}},install:{packageManager:n,dependencies:[],...i!==void 0&&{cwd:i}}};yi(e,o);let c=hi(ri(t.example,()=>kn[t.framework].getEnvDefaults())),l=i??r;return o.files.push({path:s.default.join(l,`.env`),content:c,action:`create`,label:`local environment variables`},{path:s.default.join(l,`.env.example`),content:c,action:`create`,label:`environment variables template`}),o.metadata.displayPath=`./src/env.ts`,o.metadata.importPath=`./src/env`,o}function xi(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,c=kn[t.framework],l=fi[t.validator],u=s.default.resolve(a,t.path),d=s.default.dirname(u),f={files:[],cwd:a,metadata:vi(e)},p={targetPath:u,targetDir:d,cwd:a,existingFiles:o,overwriteEnvSchemaFile:t.overwriteEnvSchemaFile,path:t.path,tsConfig:r};f.files.push(...c.getSchemaFiles(l,t,p)),gi(e,f),_i(e,f);let m=t.framework===`nextjs`||t.framework===`nuxt`?void 0:t.validator===`arktype`?`@arkenv/core`:`@arkenv/standard`,h=[...m?[m]:[],t.validator,...t.validator===`valibot`?[`@valibot/to-json-schema`]:[],...c.getDependencies(t)];c.requiresArktypePeer(t)&&!h.includes(`arktype`)&&h.push(`arktype`),f.install={packageManager:n,dependencies:Array.from(new Set(h))},i&&r.file&&(f.tsConfig={path:s.default.resolve(a,r.file),action:`strict`}),f.files.push(...c.getTypeDefinitionFiles(t,p));let g=c.bootstrap(t);g&&(f.bootstrap=g),yi(e,f);let _=s.default.relative(a,u).replace(/\\/g,`/`),v=_.startsWith(`.`)?_:`./${_}`,y=v.replace(/\.(ts|js|tsx|jsx)$/,``);return f.metadata.displayPath=v,f.metadata.importPath=y,f.bootstrap&&(f.bootstrap.importPath=y),f}var Si=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/main/examples/registry.json`);if(!e.ok)throw Error(`Failed to fetch registry: ${e.statusText}`);return await e.json()}catch{return{examples:[{id:`basic`,name:`Basic`,description:`A minimal ArkEnv setup in Node.js`,framework:`vanilla`},{id:`with-nextjs`,name:`Next.js`,description:`Minimal Next.js project with ArkType`,framework:`nextjs`},{id:`with-nextjs-zod`,name:`Next.js (Zod)`,description:`Next.js with @arkenv/nextjs/standard and Zod`,framework:`nextjs`},{id:`with-vite-react`,name:`React + Vite`,framework:`vite`},{id:`with-vite-react-zod`,name:`React + Vite (Zod)`,description:`React + Vite with @arkenv/vite-plugin/standard and Zod`,framework:`vite`},{id:`with-bun`,name:`Bun (Vanilla)`,description:`Minimal Bun project with ArkType`,framework:`vanilla`},{id:`with-bun-react`,name:`React + Bun fullstack dev server`,framework:`bun-fullstack`},{id:`with-zod`,name:`Zod`,description:`ArkEnv with Zod in Node.js`,framework:`vanilla`},{id:`with-valibot`,name:`Valibot`,description:`ArkEnv with Valibot in Node.js`,framework:`vanilla`},{id:`mix-and-match`,name:`Mix and Match`,description:`ArkEnv with mixed ArkType, Zod, and Valibot in Node.js`,framework:`vanilla`}]}}}},Ci=class{constructor(e,t,n,r,i=new Si,a){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i,this.exampleUseCase=a}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=pi(t),r=new ti(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return this.exampleUseCase&&t.mode===`existing`&&await this.exampleUseCase.execute({cwd:t.cwd,embedded:!0,isQuiet:e.isQuiet})!==0&&!e.isQuiet&&!e.isAgent&&this.logger.warn(`Could not update ${W(`.env.example`)} from the schema. Run ${W(`arkenv example`)} after fixing the schema file.`),!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&s.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?s.default.resolve(process.cwd(),t):process.cwd(),i=await this.workspace.exists(r),a=i?await this.scanner.hasPackageJson(r):!1,o=i?await this.scanner.isEmptyDirectory(r):!0;return n.example===void 0?a?await this.collectExistingProject(n,r):o||n.isForce?await this.collectNewProject(n,o):(this.logger.error(`Directory is not empty and no ${W(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${W(`arkenv init`)} in an empty directory or use ${W(`--force`)} to proceed anyway.`),this.logger.refuse({code:v.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,why:`To scaffold a new project, run arkenv init in an empty directory or use --force to proceed anyway.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,t){let{isYes:r,isForce:i,isQuiet:a,isAgent:o}=e,c=await this.scanner.checkRequirements(t),l=c.filter(e=>e.status===`fail`),u=c.filter(e=>e.status===`warn`);for(let e of u)this.logger.warn(`${e.requirement}: ${e.message}`);if(l.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of l)this.logger.error(`- ${e.requirement}: ${e.message}${e.current?` (Current: ${e.current}, Expected: ${e.expected})`:``}`);return this.logger.info(`Use --force to bypass these checks.`),this.logger.refuse({code:v.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,why:`Technical requirements (e.g. Node.js version) were not met.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass technical requirements`,command:`{bin} init --force`}],details:{requirements:l.map(e=>(0,n.shake)({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}},`init`),null}let d=await this.scanner.checkGitStatus(t);if(d.status===`dirty`)if(i)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes (use 'git stash -u' for untracked files) before running arkenv init.`),this.logger.info(`Use --force to bypass this check.`),this.logger.refuse({code:v.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv init.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} init --force`}]},`init`),null;d.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let f=!1,p=await this.scanner.checkTsConfig(t);if(p.status===`not_strict`)if(r)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${W(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${W(`strict`)} mode in your ${W(p.file)}. Would you like to enable it now?`,!0,`Yes (Recommended)`);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;f=!0}let m=await this.scanner.detectFramework(t,p.parsed),h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(t,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(t,p.parsed),_=s.default.resolve(t,g),y=await this.scanner.getEnvExampleKeys(t,p.parsed,_),b=await this.workspace.exists(_),x=await this.prompt.runWizard((0,n.shake)({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:p.parsed??null,envKeys:y?.keys,envKeysSource:y?.source,hasEnvSchemaFile:b,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),r);if(x===null)return null;let S=await this.scanner.hasSkill(t);if(S&&(x.skillDetected=!0,!a&&!o&&this.logger.info(`ArkEnv agent skill detected.`)),S)x.installSkill=!1;else if(o)x.installSkill=!1;else if(r)x.installSkill=!0;else{let e=await this.prompt.confirm(`Would you like to install the ArkEnv agent skill?`,!0,`Yes (Recommended)`);if(e===null)return null;x.installSkill=e}let C=s.default.resolve(t,x.path);if(x.overwriteEnvSchemaFile===void 0&&await this.workspace.exists(C)){let e=s.default.basename(C),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;x.overwriteEnvSchemaFile=t}let w=await this.scanner.detectPackageManager(t,p.parsed),ee=[C],T=[];for(let e of ee)await this.workspace.exists(e)&&T.push(e);let E=s.default.join(t,`.env`),D=s.default.join(t,`.env.example`);await this.workspace.exists(E)&&T.push(E),await this.workspace.exists(D)&&(T.push(D),x.envExampleContent=await this.workspace.readFile(D));let O=s.default.join(t,`.gitignore`);return await this.workspace.exists(O)&&(T.push(O),x.gitignoreContent=await this.workspace.readFile(O)),(0,n.shake)({mode:`existing`,cwd:t,options:x,detectedFramework:m,detectedBunFeatures:h,packageManager:w,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:T,isYes:r})}async collectNewProject(e,t=!0){let{isYes:r,example:i,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard((0,n.shake)({mode:`new`,examples:s.examples,example:i,name:a}),r);if(c===null)return null;if(c.name===`.`&&!t&&!o)return this.logger.error(`Cannot scaffold into ${W(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${W(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:v.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,why:`Run arkenv init in an empty directory or choose a sub-directory name instead, or use --force.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null;let l=this.detectPackageManager();return(0,n.shake)({mode:`new`,cwd:process.cwd(),options:c,detectedFramework:c.framework,packageManager:l,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:r})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function wi(e){let t=e.replace(/\/\/.*/g,``).replace(/\/\*[\s\S]*?\*\//g,``);return/(?:^|\n)\s*import\s+[\s\S]*?from\s+['"]zod['"]/.test(t)?`zod`:/(?:^|\n)\s*import\s+[\s\S]*?from\s+['"]valibot['"]/.test(t)?`valibot`:`arktype`}var Ti=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r}async execute(e){this.logger.interactiveStdout(!0);try{let t=process.cwd(),n=await this.scanner.checkGitStatus(t);if(n.status===`dirty`)if(e.isForce)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes before running arkenv preset.`),this.logger.info(`Use --force to bypass this check.`),this.logger.refuse({code:v.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv preset.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} preset ${e.action} --force`}]},`preset`),!1;else n.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let r=e.provider;if(!r)if(e.isYes)r=`vercel`;else{let t=e.action===`remove`?`remove`:`apply`,n=await this.prompt.select(`Select a hosting provider preset to ${t}:`,Object.entries(q).map(([e,t])=>({value:e,label:t.label,hint:t.hint})),`vercel`);if(n&&n!==`none`)r=n;else return!1}let i=q[r]?.label||r,a=await this.discoverSchema(t,e.file);if(!a)return!1;let o=(await this.scanner.checkTsConfig(t)).parsed||null,c=await this.scanner.detectFramework(t,o),l=K[c]||``,u=J(r,l);if(e.action===`apply`){let e=a.filePath,n=s.default.relative(t,e);if(!await this.workspace.exists(e))return this.logger.error(`Schema file not found at ${n}.`),!1;let o=await this.workspace.readFile(e),l=wi(o),d=Qn(o,{preset:r,framework:c,validator:l});return!d.success||!d.code?(this.logger.error(d.error||`Failed to apply preset to ${n}.`),!1):(d.updated?(await this.workspace.writeFile(e,d.code),this.logger.success(`Applied ${i} preset to ${n}`)):this.logger.info(`${i} preset is already up-to-date in ${n}`),typeof this.workspace.appendMissingEnvExampleKeys==`function`&&await this.workspace.appendMissingEnvExampleKeys(t,u),!0)}let d=a.filePath,f=s.default.relative(t,d);if(!await this.workspace.exists(d))return this.logger.error(`Schema file not found at ${f}.`),!1;let p=tr(await this.workspace.readFile(d),{preset:r});if(!p.success||!p.code)return this.logger.error(p.error||`Failed to remove preset from ${f}.`),!1;if(p.updated){await this.workspace.writeFile(d,p.code);let e=qn(p.code),n=(e.success?e.blocks:[]).flatMap(e=>e.keys);typeof this.workspace.removeEnvExampleKeys==`function`&&await this.workspace.removeEnvExampleKeys(t,p.removedKeys||[],n),this.logger.success(`Removed ${i} preset from ${f}`)}else this.logger.info(`${i} preset was not present in ${f}`);return!0}finally{this.logger.interactiveStdout(!1)}}async discoverSchema(e,t){if(t)return{filePath:s.default.resolve(e,t)};if(typeof this.scanner.readArkenvConfig==`function`){let t=await this.scanner.readArkenvConfig(e);if(t)return{filePath:s.default.resolve(e,t.schema)}}let n=[s.default.resolve(e,`env.ts`),s.default.resolve(e,`src/env.ts`)];for(let e of n)if(await this.workspace.exists(e))return{filePath:e};return this.logger.error(`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --file <path>.`),null}};function Ei(e,t={}){let n=new Pr(e),r=n.logger,i=new gr(n.isQuiet,r.stdio,r),a=new jr,o=new mn(r),s=new qt(t.jitiAliases?{jitiAliases:t.jitiAliases}:{}),c=new qr(r,i,o,s);return{cli:n,logger:r,workspace:i,prompt:a,initUseCase:new Ci(r,i,a,o,void 0,c),presetUseCase:new Ti(r,i,a,o),checkUseCase:new Rr(r,i,o,s),exampleUseCase:c,helpUseCase:new Yr(r),schemaLoader:s}}const Di=new ft({isQuiet:!1,isJson:!1});let Oi,ki=!1;async function Ai(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:t,initUseCase:r,presetUseCase:i,helpUseCase:a,checkUseCase:o,exampleUseCase:s}=Ei(process.argv);Oi=t,ji(t,e.command),e.validationError&&(t.error(e.validationError),await a.execute(),await t.flush(),process.exit(2)),e.helpRequested&&(await a.execute(),await t.flush(),process.exit(0));let c=e.command?{init:()=>r.execute((0,n.shake)(e.initInput)),preset:()=>i.execute(e.presetInput),check:()=>o.execute(e.checkInput),example:()=>s.execute(e.exampleInput)}[e.command]:void 0;c||(e.command?t.error(`Unknown command: ${e.command}`):t.error(`Missing command.`),await a.execute(),await t.flush(),process.exit(2));try{let e=await c();typeof e==`number`&&(await t.flush(),process.exit(e)),e||(await t.flush(),process.exit(2)),await t.flush(),process.exit(0)}catch(n){try{t.fatal(`An unexpected error occurred`,n,e.command||`cli`)}catch{}await t.flush(),process.exit(1)}}function ji(e,t){let n=async n=>{ki&&process.exit(n),ki=!0,setTimeout(()=>{process.exit(n)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`,t),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(n===130?3:n)}};process.on(`SIGINT`,()=>n(130)),process.on(`SIGTERM`,()=>n(143))}Ai(),process.on(`unhandledRejection`,async e=>{let t=Oi??Di;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=Oi??Di;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});
190
+ `),t.files.push({path:a,content:e,action:`create`,label:`.gitignore file`})}}function Zr(e){let{mode:t,options:r,packageManager:i}=e,a=r.name&&r.name!==`.`?s.default.basename(r.name):void 0;return(0,n.shake)({displayPath:``,framework:r.framework,validator:r.validator,packageManager:i,importPath:``,mode:t,example:r.example,name:a,skillDetected:r.skillDetected,disableCodegen:r.disableCodegen})}function Qr(e,t){e.options.installSkill&&(t.skill={dlxCommand:Lr(e.packageManager),packageName:`yamcodes/arkenv`,isYes:e.isYes})}function $r(e){let{options:t,packageManager:n,cwd:r}=e;if(!t.example)throw Error(`New project scaffolding requires an example.`);let i=t.name&&t.name!==`.`?s.default.join(r,t.name):void 0,a=t.name&&t.name!==`.`?s.default.basename(t.name):s.default.basename(r),o={files:[],cwd:r,metadata:Zr(e),clone:{repository:`https://github.com/yamcodes/arkenv.git`,example:t.example,targetName:a,...i!==void 0&&{targetDir:i}},install:{packageManager:n,dependencies:[],...i!==void 0&&{cwd:i}}};Qr(e,o);let c=Jr(Ir(t.example,()=>cn[t.framework].getEnvDefaults())),l=i??r;return o.files.push({path:s.default.join(l,`.env`),content:c,action:`create`,label:`local environment variables`},{path:s.default.join(l,`.env.example`),content:c,action:`create`,label:`environment variables template`}),o.metadata.displayPath=`./src/env.ts`,o.metadata.importPath=`./src/env`,o}function ei(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,c=cn[t.framework],l=Gr[t.validator],u=s.default.resolve(a,t.path),d=s.default.dirname(u),f={files:[],cwd:a,metadata:Zr(e)},p={targetPath:u,targetDir:d,cwd:a,existingFiles:o,overwriteEnvSchemaFile:t.overwriteEnvSchemaFile,path:t.path,tsConfig:r};f.files.push(...c.getSchemaFiles(l,t,p)),Yr(e,f),Xr(e,f);let m=t.framework===`nextjs`||t.framework===`nuxt`?void 0:t.validator===`arktype`?`@arkenv/core`:`@arkenv/standard`,h=[...m?[m]:[],t.validator,...t.validator===`valibot`?[`@valibot/to-json-schema`]:[],...c.getDependencies(t)];c.requiresArktypePeer(t)&&!h.includes(`arktype`)&&h.push(`arktype`),f.install={packageManager:n,dependencies:Array.from(new Set(h))},i&&r.file&&(f.tsConfig={path:s.default.resolve(a,r.file),action:`strict`});let g=c.bootstrap(t);g&&(f.bootstrap=g),Qr(e,f);let _=s.default.relative(a,u).replace(/\\/g,`/`),v=_.startsWith(`.`)?_:`./${_}`,y=v.replace(/\.(ts|js|tsx|jsx)$/,``);return f.metadata.displayPath=v,f.metadata.importPath=y,f.bootstrap&&(f.bootstrap.importPath=y),f}var ti=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/main/examples/registry.json`);if(!e.ok)throw Error(`Failed to fetch registry: ${e.statusText}`);return await e.json()}catch{return{examples:[{id:`basic`,name:`Basic`,description:`A minimal ArkEnv setup in Node.js`,framework:`vanilla`},{id:`with-nextjs`,name:`Next.js`,description:`Minimal Next.js project with ArkType`,framework:`nextjs`},{id:`with-nextjs-zod`,name:`Next.js (Zod)`,description:`Next.js with @arkenv/nextjs/standard and Zod`,framework:`nextjs`},{id:`with-vite-react`,name:`React + Vite`,framework:`vite`},{id:`with-vite-react-zod`,name:`React + Vite (Zod)`,description:`React + Vite with @arkenv/vite-plugin/standard and Zod`,framework:`vite`},{id:`with-bun`,name:`Bun (Vanilla)`,description:`Minimal Bun project with ArkType`,framework:`vanilla`},{id:`with-bun-react`,name:`React + Bun fullstack dev server`,framework:`bun-fullstack`},{id:`with-zod`,name:`Zod`,description:`ArkEnv with Zod in Node.js`,framework:`vanilla`},{id:`with-valibot`,name:`Valibot`,description:`ArkEnv with Valibot in Node.js`,framework:`vanilla`},{id:`mix-and-match`,name:`Mix and Match`,description:`ArkEnv with mixed ArkType, Zod, and Valibot in Node.js`,framework:`vanilla`}]}}}},ni=class{constructor(e,t,n,r,i=new ti,a){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i,this.exampleUseCase=a}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=Kr(t),r=new Pr(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return this.exampleUseCase&&t.mode===`existing`&&await this.exampleUseCase.execute({cwd:t.cwd,embedded:!0,isQuiet:e.isQuiet})!==0&&!e.isQuiet&&!e.isAgent&&this.logger.warn(`Could not update ${W(`.env.example`)} from the schema. Run ${W(`arkenv example`)} after fixing the schema file.`),!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&s.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?s.default.resolve(process.cwd(),t):process.cwd(),i=await this.workspace.exists(r),a=i?await this.scanner.hasPackageJson(r):!1,o=i?await this.scanner.isEmptyDirectory(r):!0;return n.example===void 0?a?await this.collectExistingProject(n,r):o||n.isForce?await this.collectNewProject(n,o):(this.logger.error(`Directory is not empty and no ${W(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${W(`arkenv init`)} in an empty directory or use ${W(`--force`)} to proceed anyway.`),this.logger.refuse({code:v.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,why:`To scaffold a new project, run arkenv init in an empty directory or use --force to proceed anyway.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,t){let{isYes:r,isForce:i,isQuiet:a,isAgent:o}=e,c=await this.scanner.checkRequirements(t),l=c.filter(e=>e.status===`fail`),u=c.filter(e=>e.status===`warn`);for(let e of u)this.logger.warn(`${e.requirement}: ${e.message}`);if(l.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of l)this.logger.error(`- ${e.requirement}: ${e.message}${e.current?` (Current: ${e.current}, Expected: ${e.expected})`:``}`);return this.logger.info(`Use --force to bypass these checks.`),this.logger.refuse({code:v.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,why:`Technical requirements (e.g. Node.js version) were not met.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass technical requirements`,command:`{bin} init --force`}],details:{requirements:l.map(e=>(0,n.shake)({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}},`init`),null}let d=await this.scanner.checkGitStatus(t);if(d.status===`dirty`)if(i)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes (use 'git stash -u' for untracked files) before running arkenv init.`),this.logger.info(`Use --force to bypass this check.`),this.logger.refuse({code:v.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv init.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} init --force`}]},`init`),null;d.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let f=!1,p=await this.scanner.checkTsConfig(t);if(p.status===`not_strict`)if(r)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${W(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${W(`strict`)} mode in your ${W(p.file)}. Would you like to enable it now?`,!0,`Yes (Recommended)`);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;f=!0}let m=await this.scanner.detectFramework(t,p.parsed),h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(t,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(t,p.parsed),_=s.default.resolve(t,g),y=await this.scanner.getEnvExampleKeys(t,p.parsed,_),b=await this.workspace.exists(_),x=await this.prompt.runWizard((0,n.shake)({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:p.parsed??null,envKeys:y?.keys,envKeysSource:y?.source,hasEnvSchemaFile:b,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),r);if(x===null)return null;let S=await this.scanner.hasSkill(t);if(S&&(x.skillDetected=!0,!a&&!o&&this.logger.info(`ArkEnv agent skill detected.`)),S)x.installSkill=!1;else if(o)x.installSkill=!1;else if(r)x.installSkill=!0;else{let e=await this.prompt.confirm(`Would you like to install the ArkEnv agent skill?`,!0,`Yes (Recommended)`);if(e===null)return null;x.installSkill=e}let ee=s.default.resolve(t,x.path);if(x.overwriteEnvSchemaFile===void 0&&await this.workspace.exists(ee)){let e=s.default.basename(ee),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;x.overwriteEnvSchemaFile=t}let C=await this.scanner.detectPackageManager(t,p.parsed),te=[ee],w=[];for(let e of te)await this.workspace.exists(e)&&w.push(e);let T=s.default.join(t,`.env`),E=s.default.join(t,`.env.example`);await this.workspace.exists(T)&&w.push(T),await this.workspace.exists(E)&&(w.push(E),x.envExampleContent=await this.workspace.readFile(E));let D=s.default.join(t,`.gitignore`);return await this.workspace.exists(D)&&(w.push(D),x.gitignoreContent=await this.workspace.readFile(D)),(0,n.shake)({mode:`existing`,cwd:t,options:x,detectedFramework:m,detectedBunFeatures:h,packageManager:C,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:w,isYes:r})}async collectNewProject(e,t=!0){let{isYes:r,example:i,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard((0,n.shake)({mode:`new`,examples:s.examples,example:i,name:a}),r);if(c===null)return null;if(c.name===`.`&&!t&&!o)return this.logger.error(`Cannot scaffold into ${W(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${W(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:v.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,why:`Run arkenv init in an empty directory or choose a sub-directory name instead, or use --force.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null;let l=this.detectPackageManager();return(0,n.shake)({mode:`new`,cwd:process.cwd(),options:c,detectedFramework:c.framework,packageManager:l,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:r})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function ri(e){let t=e.replace(/\/\/.*/g,``).replace(/\/\*[\s\S]*?\*\//g,``);return/(?:^|\n)\s*import\s+[\s\S]*?from\s+['"]zod['"]/.test(t)?`zod`:/(?:^|\n)\s*import\s+[\s\S]*?from\s+['"]valibot['"]/.test(t)?`valibot`:`arktype`}var ii=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r}async execute(e){this.logger.interactiveStdout(!0);try{let t=process.cwd(),n=await this.scanner.checkGitStatus(t);if(n.status===`dirty`)if(e.isForce)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes before running arkenv preset.`),this.logger.info(`Use --force to bypass this check.`),this.logger.refuse({code:v.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv preset.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} preset ${e.action} --force`}]},`preset`),!1;else n.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let r=e.provider;if(!r)if(e.isYes)r=`vercel`;else{let t=e.action===`remove`?`remove`:`apply`,n=await this.prompt.select(`Select a hosting provider preset to ${t}:`,Object.entries(q).map(([e,t])=>({value:e,label:t.label,hint:t.hint})),`vercel`);if(n&&n!==`none`)r=n;else return!1}let i=q[r]?.label||r,a=await this.discoverSchema(t,e.file);if(!a)return!1;let o=(await this.scanner.checkTsConfig(t)).parsed||null,c=await this.scanner.detectFramework(t,o),l=K[c]||``,u=J(r,l);if(e.action===`apply`){let e=a.filePath,n=s.default.relative(t,e);if(!await this.workspace.exists(e))return this.logger.error(`Schema file not found at ${n}.`),!1;let o=await this.workspace.readFile(e),l=ri(o),d=jn(o,{preset:r,framework:c,validator:l});return!d.success||!d.code?(this.logger.error(d.error||`Failed to apply preset to ${n}.`),!1):(d.updated?(await this.workspace.writeFile(e,d.code),this.logger.success(`Applied ${i} preset to ${n}`)):this.logger.info(`${i} preset is already up-to-date in ${n}`),typeof this.workspace.appendMissingEnvExampleKeys==`function`&&await this.workspace.appendMissingEnvExampleKeys(t,u),!0)}let d=a.filePath,f=s.default.relative(t,d);if(!await this.workspace.exists(d))return this.logger.error(`Schema file not found at ${f}.`),!1;let p=Pn(await this.workspace.readFile(d),{preset:r});if(!p.success||!p.code)return this.logger.error(p.error||`Failed to remove preset from ${f}.`),!1;if(p.updated){await this.workspace.writeFile(d,p.code);let e=En(p.code),n=(e.success?e.blocks:[]).flatMap(e=>e.keys);typeof this.workspace.removeEnvExampleKeys==`function`&&await this.workspace.removeEnvExampleKeys(t,p.removedKeys||[],n),this.logger.success(`Removed ${i} preset from ${f}`)}else this.logger.info(`${i} preset was not present in ${f}`);return!0}finally{this.logger.interactiveStdout(!1)}}async discoverSchema(e,t){if(t)return{filePath:s.default.resolve(e,t)};if(typeof this.scanner.readArkenvConfig==`function`){let t=await this.scanner.readArkenvConfig(e);if(t)return{filePath:s.default.resolve(e,t.schema)}}let n=[s.default.resolve(e,`env.ts`),s.default.resolve(e,`src/env.ts`)];for(let e of n)if(await this.workspace.exists(e))return{filePath:e};return this.logger.error(`Could not locate your schema file. Add an 'arkenv' entry to package.json or specify --file <path>.`),null}};function ai(e,t={}){let n=new pr(e),r=n.logger,i=new Yn(n.isQuiet,r.stdio,r),a=new ur,o=new Kt(r),s=new Et(t.jitiAliases?{jitiAliases:t.jitiAliases}:{}),c=new Er(r,i,o,s);return{cli:n,logger:r,workspace:i,prompt:a,initUseCase:new ni(r,i,a,o,void 0,c),presetUseCase:new ii(r,i,a,o),checkUseCase:new _r(r,i,o,s),exampleUseCase:c,helpUseCase:new Or(r),schemaLoader:s}}const oi=new ft({isQuiet:!1,isJson:!1});let si,ci=!1;async function li(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:t,initUseCase:r,presetUseCase:i,helpUseCase:a,checkUseCase:o,exampleUseCase:s}=ai(process.argv);si=t,ui(t,e.command),e.validationError&&(t.error(e.validationError),await a.execute(),await t.flush(),process.exit(2)),e.helpRequested&&(await a.execute(),await t.flush(),process.exit(0));let c=e.command?{init:()=>r.execute((0,n.shake)(e.initInput)),preset:()=>i.execute(e.presetInput),check:()=>o.execute(e.checkInput),example:()=>s.execute(e.exampleInput)}[e.command]:void 0;c||(e.command?t.error(`Unknown command: ${e.command}`):t.error(`Missing command.`),await a.execute(),await t.flush(),process.exit(2));try{let e=await c();typeof e==`number`&&(await t.flush(),process.exit(e)),e||(await t.flush(),process.exit(2)),await t.flush(),process.exit(0)}catch(n){try{t.fatal(`An unexpected error occurred`,n,e.command||`cli`)}catch{}await t.flush(),process.exit(1)}}function ui(e,t){let n=async n=>{ci&&process.exit(n),ci=!0,setTimeout(()=>{process.exit(n)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`,t),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(n===130?3:n)}};process.on(`SIGINT`,()=>n(130)),process.on(`SIGTERM`,()=>n(143))}li(),process.on(`unhandledRejection`,async e=>{let t=si??oi;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=si??oi;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});