arkenv 1.0.0-alpha.13 → 1.0.0-alpha.14

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.js CHANGED
@@ -1,72 +1,72 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import{shake as t}from"radashi";import{stripVTControlCharacters as n,styleText as r}from"node:util";import i,{stdin as a,stdout as o}from"node:process";import*as s from"node:readline";import c from"node:readline";import{ReadStream as l}from"node:tty";import"node:fs";import u from"node:path";import d from"node:fs/promises";import f from"dedent";import{execSync as p,spawn as m}from"node:child_process";import{applyEdits as h,modify as g,parse as _}from"jsonc-parser";import{builders as v,detectCodeFormat as y,generateCode as b,parseModule as x}from"magicast";import{isMap as S,parseDocument as ee}from"yaml";var C=Object.create,w=Object.defineProperty,te=Object.getOwnPropertyDescriptor,T=Object.getOwnPropertyNames,ne=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),re=(e,t)=>{let n={};for(var r in e)w(n,r,{get:e[r],enumerable:!0});return t||w(n,Symbol.toStringTag,{value:`Module`}),n},ie=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=T(t),a=0,o=i.length,s;a<o;a++)s=i[a],!E.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=te(t,s))||r.enumerable});return e},O=((e,t,n)=>(n=e==null?{}:C(ne(e)),ie(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e)))(D(((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}))(),1);const k={REQUIREMENTS_NOT_MET:`REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`GIT_TREE_DIRTY`,NON_EMPTY_DIR:`NON_EMPTY_DIR`,INTERNAL:`INTERNAL`};var ae=class{info(e){process.stderr.write(`${O.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${O.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${O.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${O.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${O.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${O.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${O.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${O.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){this.json({status:`cancelled`,message:e})}fatal(e,t){let n=t instanceof Error?t.message:t?String(t):void 0;throw this.json({status:`error`,code:k.INTERNAL,message:e,retryWith:[],...n===void 0?{}:{details:{error:n}}}),t instanceof Error?t:Error(e)}refuse(e){this.json({status:`error`,code:e.code,message:e.message,retryWith:e.retryWith,...e.details===void 0?{}:{details:e.details}})}finish(e,t){this.json({status:`success`,message:e,details:t})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},oe=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){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t){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){}finish(e,t){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const se=(()=>{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}})(),ce=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,le=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,ue=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,de=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,fe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,pe=/\t{1,1000}/y,me=/[\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,he=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ge=/\p{M}+/gu,_e={limit:1/0,ellipsis:``},ve=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ve(i,_e,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[he,l],[ue,0],[de,o],[pe,s],[me,c],[fe,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(ge,``)){let t=e.codePointAt(0)||0;if(S=ce(t)?2:le(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===fe?se(e.slice(p,n.lastIndex)):n===me?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}},ye={limit:1/0,ellipsis:``,ellipsisWidth:0},A=(e,t={})=>ve(e,ye,t).width,be=`]8;;`,xe=RegExp(`(?:\\[(?<code>\\d+)m|\\${be}(?<uri>.*))`,`y`),Se=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},Ce=e=>`[${e}m`,we=e=>`${be}${e}`,Te=(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(be,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())},Ee=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(``)},De=(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(``),Te(s,r,t),c=A(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Te(s,r,t),c=A(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Te(s,r,t),c=A(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Ee(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===`›`){xe.lastIndex=e+1;let t=xe.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+=we(``));let e=i?Se(i):void 0;i&&e&&(r+=Ce(e))}else t===`
5
- `&&(i&&Se(i)&&(r+=Ce(i)),a&&(r+=we(a)))}return r},Oe=/\r?\n/;function j(e,t,n){return String(e).normalize().split(Oe).map(e=>De(e,t,n)).join(`
6
- `)}var M=D(((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 ke(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?ke(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 Ae(e,t){if(typeof e==`string`)return N.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Ae(n,t))return!0;return!1}function je(e,t){if(e===t)return;let n=e.split(`
2
+ import{i as e,n as t,t as n}from"./dist-CWLy9Ohj.js";import{createRequire as r}from"node:module";import{shake as i}from"radashi";import{stripVTControlCharacters as a,styleText as o}from"node:util";import s,{stdin as c,stdout as l}from"node:process";import*as u from"node:readline";import d from"node:readline";import{ReadStream as f}from"node:tty";import"node:fs";import p from"node:path";import m from"node:fs/promises";import h from"dedent";import{createJiti as g}from"jiti";import{execSync as _,spawn as v}from"node:child_process";import{applyEdits as y,modify as b,parse as x}from"jsonc-parser";import{builders as S,detectCodeFormat as C,generateCode as w,parseModule as T}from"magicast";import{isMap as E,parseDocument as D}from"yaml";var ee=Object.create,O=Object.defineProperty,k=Object.getOwnPropertyDescriptor,te=Object.getOwnPropertyNames,ne=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,ie=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ae=(e,t)=>{let n={};for(var r in e)O(n,r,{get:e[r],enumerable:!0});return t||O(n,Symbol.toStringTag,{value:`Module`}),n},oe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=te(t),a=0,o=i.length,s;a<o;a++)s=i[a],!re.call(e,s)&&s!==n&&O(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=k(t,s))||r.enumerable});return e},A=((e,t,n)=>(n=e==null?{}:ee(ne(e)),oe(t||!e||!e.__esModule?O(n,`default`,{value:e,enumerable:!0}):n,e)))(ie(((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}))(),1);const j={REQUIREMENTS_NOT_MET:`REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`GIT_TREE_DIRTY`,NON_EMPTY_DIR:`NON_EMPTY_DIR`,INTERNAL:`INTERNAL`};var se=class{info(e){process.stderr.write(`${A.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${A.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${A.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${A.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${A.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${A.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${A.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${A.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){this.json({status:`cancelled`,message:e})}fatal(e,t){let n=t instanceof Error?t.message:t?String(t):void 0;throw this.json({status:`error`,code:j.INTERNAL,message:e,retryWith:[],...n===void 0?{}:{details:{error:n}}}),t instanceof Error?t:Error(e)}refuse(e){this.json({status:`error`,code:e.code,message:e.message,retryWith:e.retryWith,...e.details===void 0?{}:{details:e.details}})}finish(e,t){this.json({status:`success`,message:e,details:t})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},ce=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){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t){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){}finish(e,t){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const le=(()=>{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}})(),ue=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,de=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,fe=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,pe=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,me=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,he=/\t{1,1000}/y,ge=/[\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,_e=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ve=/\p{M}+/gu,ye={limit:1/0,ellipsis:``},be=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?be(i,ye,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[_e,l],[fe,0],[pe,o],[he,s],[ge,c],[me,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(ve,``)){let t=e.codePointAt(0)||0;if(S=ue(t)?2:de(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===me?le(e.slice(p,n.lastIndex)):n===ge?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}},xe={limit:1/0,ellipsis:``,ellipsisWidth:0},M=(e,t={})=>be(e,xe,t).width,Se=`]8;;`,Ce=RegExp(`(?:\\[(?<code>\\d+)m|\\${Se}(?<uri>.*))`,`y`),we=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},Te=e=>`[${e}m`,Ee=e=>`${Se}${e}`,De=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:M(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=M(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(Se,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())},Oe=e=>{let t=e.split(` `),n=t.length;for(;n&&!M(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},ke=(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=M(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=M(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(``),De(s,r,t),c=M(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){De(s,r,t),c=M(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){De(s,r,t),c=M(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Oe(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===`›`){Ce.lastIndex=e+1;let t=Ce.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+=Ee(``));let e=i?we(i):void 0;i&&e&&(r+=Te(e))}else t===`
5
+ `&&(i&&we(i)&&(r+=Te(i)),a&&(r+=Ee(a)))}return r},Ae=/\r?\n/;function N(e,t,n){return String(e).normalize().split(Ae).map(e=>ke(e,t,n)).join(`
6
+ `)}var P=ie(((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 je(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?je(a,t<0?-1:1,n):a}const F={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 Me(e,t){if(typeof e==`string`)return F.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Me(n,t))return!0;return!1}function Ne(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 Me=globalThis.process.platform.startsWith(`win`),Ne=Symbol(`clack:cancel`);function P(e){return e===Ne}function Pe(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Fe({input:e=a,output:t=o,overwrite:n=!0,hideCursor:r=!0}={}){let i=s.createInterface({input:e,output:t,prompt:``,tabSize:1});s.emitKeypressEvents(e,i),e instanceof l&&e.isTTY&&e.setRawMode(!0);let c=(i,{name:a,sequence:o})=>{if(Ae([String(i),a,o],`cancel`)){r&&t.write(M.cursor.show),process.exit(0);return}if(!n)return;let l=a===`return`?0:-1,u=a===`return`?-1:0;s.moveCursor(t,l,u,()=>{s.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 l&&e.isTTY&&!Me&&e.setRawMode(!1),i.terminal=!1,i.close()}}const Ie=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,Le=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function Re(e,t,n,r=n,i){return j(t,Ie(e??o)-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 Pe=globalThis.process.platform.startsWith(`win`),Fe=Symbol(`clack:cancel`);function I(e){return e===Fe}function Ie(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Le({input:e=c,output:t=l,overwrite:n=!0,hideCursor:r=!0}={}){let i=u.createInterface({input:e,output:t,prompt:``,tabSize:1});u.emitKeypressEvents(e,i),e instanceof f&&e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(Me([String(i),o,s],`cancel`)){r&&t.write(P.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;u.moveCursor(t,c,l,()=>{u.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(P.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(P.cursor.show),e instanceof f&&e.isTTY&&!Pe&&e.setRawMode(!1),i.terminal=!1,i.close()}}const Re=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,ze=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function Be(e,t,n,r=n,i){return N(t,Re(e??l)-n.length,{hard:!0,trim:!1}).split(`
9
9
  `).map((e,t)=>{let a=i?i(e,t):e;return`${t===0?r:n}${a}`}).join(`
10
- `)}let ze=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=a,output:r=o,render:i,signal:s,...c}=e;this.opts=c,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=s,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(Ne);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=c.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),Pe(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),Pe(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),Pe(this.input,!1),e(Ne)})})}_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`)}Ae([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
- `),Pe(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=je(this._prevFrame,e),n=Le(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 Ve=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=c,output:r=l,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,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(Fe);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=d.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),Ie(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),Ie(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),Ie(this.input,!1),e(Fe)})})}_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&&F.aliases.has(t.name)&&this.emit(`cursor`,F.aliases.get(t.name)),F.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`)}Me([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
+ `),Ie(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=N(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
12
+ `).length-1;this.output.write(P.cursor.move(-999,e*-1))}render(){let e=N(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(P.cursor.hide);else{let t=Ne(this._prevFrame,e),n=ze(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(P.cursor.move(0,a-i)),this.output.write(P.erase.lines(1));let t=e.split(`
13
+ `);this.output.write(t[a]),this._prevFrame=e,this.output.write(P.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(P.cursor.move(0,e))}this.output.write(P.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 Be=class extends ze{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})}},Ve=class extends ze{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?ke(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=ke(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=ke(this.cursor,1,this.options);break}this.changeValue()})}},He=class extends ze{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}${r(`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 Ue(){return i.platform===`win32`?!!i.env.CI||!!i.env.WT_SESSION||!!i.env.TERMINUS_SUBLIME||i.env.ConEmuTask===`{cmd::Cmder}`||i.env.TERM_PROGRAM===`Terminus-Sublime`||i.env.TERM_PROGRAM===`vscode`||i.env.TERM===`xterm-256color`||i.env.TERM===`alacritty`||i.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:i.env.TERM!==`linux`}const We=Ue(),Ge=()=>process.env.CI===`true`,F=(e,t)=>We?e:t,Ke=F(`◆`,`*`),qe=F(`■`,`x`),Je=F(`▲`,`x`),I=F(`◇`,`o`),L=F(`│`,`|`),R=F(`└`,`—`),Ye=F(`●`,`>`),Xe=F(`○`,` `),Ze=F(`─`,`-`),Qe=F(`╮`,`+`),$e=F(`├`,`+`),et=F(`╯`,`+`),tt=F(`╰`,`+`),nt=F(`●`,`•`),rt=F(`◆`,`*`),it=F(`▲`,`!`),at=F(`■`,`x`),ot=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,Ke);case`cancel`:return r(`red`,qe);case`error`:return r(`yellow`,Je);case`submit`:return r(`green`,I)}},st=e=>{switch(e){case`initial`:case`active`:return r(`cyan`,L);case`cancel`:return r(`red`,L);case`error`:return r(`yellow`,L);case`submit`:return r(`green`,L)}},ct=(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}},lt=({cursor:e,options:t,style:n,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=Ie(i)-o,l=Le(i),u=r(`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)=>ct(_,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 Be({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=`${ot(this.state)} `,o=i?`${r(`gray`,L)} `:``,s=Re(e.output,e.message,o,a),c=`${i?`${r(`gray`,L)}
15
+ `)),this._prevFrame=e;return}}this.output.write(P.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var He=class extends Ve{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(P.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Ue=class extends Ve{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?je(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=je(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=je(this.cursor,1,this.options);break}this.changeValue()})}},We=class extends Ve{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,...r]=e.slice(this.cursor);return`${t}${o(`inverse`,n)}${r.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 Ge(){return s.platform===`win32`?!!s.env.CI||!!s.env.WT_SESSION||!!s.env.TERMINUS_SUBLIME||s.env.ConEmuTask===`{cmd::Cmder}`||s.env.TERM_PROGRAM===`Terminus-Sublime`||s.env.TERM_PROGRAM===`vscode`||s.env.TERM===`xterm-256color`||s.env.TERM===`alacritty`||s.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:s.env.TERM!==`linux`}const Ke=Ge(),qe=()=>process.env.CI===`true`,L=(e,t)=>Ke?e:t,Je=L(`◆`,`*`),Ye=L(`■`,`x`),Xe=L(`▲`,`x`),R=L(`◇`,`o`),z=L(`│`,`|`),B=L(`└`,`—`),Ze=L(`●`,`>`),Qe=L(`○`,` `),$e=L(`─`,`-`),et=L(`╮`,`+`),tt=L(`├`,`+`),nt=L(`╯`,`+`),rt=L(`╰`,`+`),it=L(`●`,`•`),at=L(`◆`,`*`),ot=L(`▲`,`!`),st=L(`■`,`x`),ct=e=>{switch(e){case`initial`:case`active`:return o(`cyan`,Je);case`cancel`:return o(`red`,Ye);case`error`:return o(`yellow`,Xe);case`submit`:return o(`green`,R)}},lt=e=>{switch(e){case`initial`:case`active`:return o(`cyan`,z);case`cancel`:return o(`red`,z);case`error`:return o(`yellow`,z);case`submit`:return o(`green`,z)}},ut=(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}},dt=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:a=0,rowPadding:s=4})=>{let c=Re(r)-a,l=ze(r),u=o(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(i,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=N(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)=>ut(_,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},V=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new He({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??F.withGuide,i=`${ct(this.state)} `,a=r?`${o(`gray`,z)} `:``,s=Be(e.output,e.message,a,i),c=`${r?`${o(`gray`,z)}
17
17
  `:``}${s}
18
- `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${i?`${r(`gray`,L)} `:``}${r(`dim`,l)}`;case`cancel`:return`${c}${i?`${r(`gray`,L)} `:``}${r([`strikethrough`,`dim`],l)}${i?`
19
- ${r(`gray`,L)}`:``}`;default:{let a=i?`${r(`cyan`,L)} `:``,o=i?r(`cyan`,R):``;return`${c}${a}${this.value?`${r(`green`,Ye)} ${t}`:`${r(`dim`,Xe)} ${r(`dim`,t)}`}${e.vertical?i?`
20
- ${r(`cyan`,L)} `:`
21
- `:` ${r(`dim`,`/`)} `}${this.value?`${r(`dim`,Xe)} ${r(`dim`,n)}`:`${r(`green`,Ye)} ${n}`}
22
- ${o}
23
- `}}}}).prompt()},B={message:(e=[],{symbol:t=r(`gray`,L),secondarySymbol:n=r(`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(`
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(`
18
+ `,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${r?`${o(`gray`,z)} `:``}${o(`dim`,l)}`;case`cancel`:return`${c}${r?`${o(`gray`,z)} `:``}${o([`strikethrough`,`dim`],l)}${r?`
19
+ ${o(`gray`,z)}`:``}`;default:{let i=r?`${o(`cyan`,z)} `:``,a=r?o(`cyan`,B):``;return`${c}${i}${this.value?`${o(`green`,Ze)} ${t}`:`${o(`dim`,Qe)} ${o(`dim`,t)}`}${e.vertical?r?`
20
+ ${o(`cyan`,z)} `:`
21
+ `:` ${o(`dim`,`/`)} `}${this.value?`${o(`dim`,Qe)} ${o(`dim`,n)}`:`${o(`green`,Ze)} ${n}`}
22
+ ${a}
23
+ `}}}}).prompt()},H={message:(e=[],{symbol:t=o(`gray`,z),secondarySymbol:n=o(`gray`,z),output:r=process.stdout,spacing:i=1,withGuide:a}={})=>{let s=[],c=a??F.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<i;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
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:``)}r.write(`${s.join(`
25
25
  `)}
26
- `)},info:(e,t)=>{B.message(e,{...t,symbol:r(`blue`,nt)})},success:(e,t)=>{B.message(e,{...t,symbol:r(`green`,rt)})},step:(e,t)=>{B.message(e,{...t,symbol:r(`green`,I)})},warn:(e,t)=>{B.message(e,{...t,symbol:r(`yellow`,it)})},warning:(e,t)=>{B.warn(e,t)},error:(e,t)=>{B.message(e,{...t,symbol:r(`red`,at)})}},ut=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${r(`gray`,R)} `:``;n.write(`${i}${r(`red`,e)}
26
+ `)},info:(e,t)=>{H.message(e,{...t,symbol:o(`blue`,it)})},success:(e,t)=>{H.message(e,{...t,symbol:o(`green`,at)})},step:(e,t)=>{H.message(e,{...t,symbol:o(`green`,R)})},warn:(e,t)=>{H.message(e,{...t,symbol:o(`yellow`,ot)})},warning:(e,t)=>{H.warn(e,t)},error:(e,t)=>{H.message(e,{...t,symbol:o(`red`,st)})}},ft=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??F.withGuide?`${o(`gray`,B)} `:``;n.write(`${r}${o(`red`,e)}
27
27
 
28
- `)},dt=(e=``,t)=>{let n=t?.output??process.stdout,i=t?.withGuide??N.withGuide?`${r(`gray`,L)}
29
- ${r(`gray`,R)} `:``;n.write(`${i}${e}
28
+ `)},pt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??F.withGuide?`${o(`gray`,z)}
29
+ ${o(`gray`,B)} `:``;n.write(`${r}${e}
30
30
 
31
- `)},ft=e=>r(`dim`,e),pt=(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)},mt=(e=``,t=``,n)=>{let a=n?.output??i.stdout,o=n?.withGuide??N.withGuide,s=n?.format??ft,c=[``,...pt(e,Ie(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=>`${r(`gray`,L)} ${e}${` `.repeat(u-A(e))}${r(`gray`,L)}`).join(`
34
- `),f=o?`${r(`gray`,L)}
35
- `:``,p=o?$e:tt;a.write(`${f}${r(`green`,I)} ${r(`reset`,t)} ${r(`gray`,Ze.repeat(Math.max(u-l-1,1))+Qe)}
31
+ `)},mt=e=>o(`dim`,e),ht=(e,t,n)=>{let r={hard:!0,trim:!1},i=N(e,t,r).split(`
32
+ `),a=i.reduce((e,t)=>Math.max(M(t),e),0);return N(e,t-(i.map(n).reduce((e,t)=>Math.max(M(t),e),0)-a),r)},gt=(e=``,t=``,n)=>{let r=n?.output??s.stdout,i=n?.withGuide??F.withGuide,a=n?.format??mt,c=[``,...ht(e,Re(r)-6,a).split(`
33
+ `).map(a),``],l=M(t),u=Math.max(c.reduce((e,t)=>{let n=M(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${o(`gray`,z)} ${e}${` `.repeat(u-M(e))}${o(`gray`,z)}`).join(`
34
+ `),f=i?`${o(`gray`,z)}
35
+ `:``,p=i?tt:rt;r.write(`${f}${o(`green`,R)} ${o(`reset`,t)} ${o(`gray`,$e.repeat(Math.max(u-l-1,1))+et)}
36
36
  ${d}
37
- ${r(`gray`,p+Ze.repeat(u+2)+et)}
38
- `)},ht=e=>r(`magenta`,e),gt=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:i,errorMessage:a,frames:o=We?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=We?80:120,signal:c,...l}={})=>{let u=Ge(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ie(n),y=l?.styleFrame??ht,b=e=>{let n=e>1?a??N.messages.error:i??N.messages.cancel;m=e===1,p&&(D(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)},w=()=>{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())},te=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]`},ne=l.withGuide??N.withGuide,E=(t=``)=>{p=!0,d=Fe({output:n}),h=te(t),_=performance.now(),ne&&n.write(`${r(`gray`,L)}
41
- `);let i=0,a=0;ee(),f=setInterval(()=>{if(u&&h===g)return;w(),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=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)},D=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),w();let o=i===0?r(`green`,I):i===1?r(`red`,qe):r(`red`,Je);h=t??h,a||(e===`timer`?n.write(`${o} ${h} ${T(_)}
42
- `):n.write(`${o} ${h}
43
- `)),C(),d()};return{start:E,stop:(e=``)=>D(e,0),message:(e=``)=>{h=te(e??h)},cancel:(e=``)=>D(e,1),error:(e=``)=>D(e,2),clear:()=>D(``,0,!0),get isCancelled(){return m}}},_t=(e,t)=>e.includes(`
37
+ ${o(`gray`,p+$e.repeat(u+2)+nt)}
38
+ `)},_t=e=>o(`magenta`,e),vt=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:a=Ke?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=Ke?80:120,signal:c,...l}={})=>{let u=qe(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Re(n),y=l?.styleFrame??_t,b=e=>{let n=e>1?i??F.messages.error:r??F.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)},T=()=>{if(g===void 0)return;u&&n.write(`
39
+ `);let e=N(g,v,{hard:!0,trim:!1}).split(`
40
+ `);e.length>1&&n.write(P.cursor.up(e.length-1)),n.write(P.cursor.to(0)),n.write(P.erase.down())},E=e=>e.replace(/\.+$/,``),D=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]`},ee=l.withGuide??F.withGuide,O=(t=``)=>{p=!0,d=Le({output:n}),h=E(t),_=performance.now(),ee&&n.write(`${o(`gray`,z)}
41
+ `);let r=0,i=0;C(),f=setInterval(()=>{if(u&&h===g)return;T(),g=h;let t=y(a[r]),o;if(u)o=`${t} ${h}...`;else if(e===`timer`)o=`${t} ${h} ${D(_)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);o=`${t} ${h}${e}`}let s=N(o,v,{hard:!0,trim:!1});n.write(s),r=r+1<a.length?r+1:0,i=i<4?i+.125:0},s)},k=(t=``,r=0,i=!1)=>{if(!p)return;p=!1,clearInterval(f),T();let a=r===0?o(`green`,R):r===1?o(`red`,Ye):o(`red`,Xe);h=t??h,i||(e===`timer`?n.write(`${a} ${h} ${D(_)}
42
+ `):n.write(`${a} ${h}
43
+ `)),w(),d()};return{start:O,stop:(e=``)=>k(e,0),message:(e=``)=>{h=E(e??h)},cancel:(e=``)=>k(e,1),error:(e=``)=>k(e,2),clear:()=>k(``,0,!0),get isCancelled(){return m}}},yt=(e,t)=>e.includes(`
44
44
  `)?e.split(`
45
45
  `).map(e=>t(e)).join(`
46
- `):t(e),V=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`disabled`:return`${r(`gray`,Xe)} ${_t(n,e=>r(`gray`,e))}${e.hint?` ${r(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${_t(n,e=>r(`dim`,e))}`;case`active`:return`${r(`green`,Ye)} ${n}${e.hint?` ${r(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${_t(n,e=>r([`strikethrough`,`dim`],e))}`;default:return`${r(`dim`,Xe)} ${_t(n,e=>r(`dim`,e))}`}};return new Ve({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??N.withGuide,i=`${ot(this.state)} `,a=`${st(this.state)} `,o=Re(e.output,e.message,a,i),s=`${n?`${r(`gray`,L)}
47
- `:``}${o}
48
- `;switch(this.state){case`submit`:{let i=n?`${r(`gray`,L)} `:``;return`${s}${Re(e.output,t(this.options[this.cursor],`selected`),i)}`}case`cancel`:{let i=n?`${r(`gray`,L)} `:``;return`${s}${Re(e.output,t(this.options[this.cursor],`cancelled`),i)}${n?`
49
- ${r(`gray`,L)}`:``}`}default:{let i=n?`${r(`cyan`,L)} `:``,a=n?r(`cyan`,R):``,o=s.split(`
50
- `).length,c=n?2:1;return`${s}${i}${lt({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
- ${i}`)}
52
- ${a}
53
- `}}}}).prompt()},vt=`${r(`gray`,L)} `,H={message:async(e,{symbol:t=r(`gray`,L)}={})=>{process.stdout.write(`${r(`gray`,L)}
54
- ${t} `);let i=3;for await(let t of e){t=t.replace(/\n/g,`
55
- ${vt}`),t.includes(`
56
- `)&&(i=3+n(t.slice(t.lastIndexOf(`
57
- `))).length);let e=n(t).length;i+e<process.stdout.columns?(i+=e,process.stdout.write(t)):(process.stdout.write(`
58
- ${vt}${t.trimStart()}`),i=3+n(t.trimStart()).length)}process.stdout.write(`
59
- `)},info:e=>H.message(e,{symbol:r(`blue`,nt)}),success:e=>H.message(e,{symbol:r(`green`,rt)}),step:e=>H.message(e,{symbol:r(`green`,I)}),warn:e=>H.message(e,{symbol:r(`yellow`,it)}),warning:e=>H.warn(e),error:e=>H.message(e,{symbol:r(`red`,at)})},yt=e=>new He({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?`${r(`gray`,L)}
60
- `:``}${ot(this.state)} `}${e.message}
61
- `,i=e.placeholder?r(`inverse`,e.placeholder[0])+r(`dim`,e.placeholder.slice(1)):r([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${r(`yellow`,this.error)}`:``,i=t?`${r(`yellow`,L)} `:``,o=t?r(`yellow`,R):``;return`${n.trim()}
62
- ${i}${a}
63
- ${o}${e}
64
- `}case`submit`:{let e=o?` ${r(`dim`,o)}`:``;return`${n}${t?r(`gray`,L):``}${e}`}case`cancel`:{let e=o?` ${r([`strikethrough`,`dim`],o)}`:``,i=t?r(`gray`,L):``;return`${n}${i}${e}${o.trim()?`
65
- ${i}`:``}`}default:return`${n}${t?`${r(`cyan`,L)} `:``}${a}
66
- ${t?r(`cyan`,R):``}
67
- `}}}).prompt();var bt=class{info(e){process.stdout.write(`${O.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${O.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${O.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${O.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){mt(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return gt()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${O.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${O.default.red(`✘ ${e}`)}\n`),t){let e=`${O.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){}finish(e,t){dt(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},xt=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new ae:e.isQuiet?this.reporter=new oe:this.reporter=new bt}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){this.reporter.cancel(e)}fatal(e,t){this.reporter.fatal(e,t)}refuse(e){this.reporter.refuse(e)}finish(e,t){this.reporter.finish(e,t)}async flush(){await this.reporter.flush()}};function St(e){return e instanceof Error?e.stack??e.message:String(e)}function Ct(e,t,n){e(`${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&e(n.stack)}const wt={debug:0,info:1,warn:2,error:3},Tt=new Set([`debug`,`info`,`warn`,`error`,`silent`]);function Et(e){if(!e)return;let t=e.trim().toLowerCase();if(Tt.has(t))return t}function Dt(){if(!(typeof process>`u`))return Et(process.env?.ARKENV_LOG_LEVEL)}function Ot(e){return e?.level??Dt()??`info`}function kt(e,t){return e===`silent`?!1:wt[t]>=wt[e]}function At(e,t,n){return(r,...i)=>{kt(e,t)&&console[n](r,...i)}}function jt(e){let t=Ot(e);return{debug:At(t,`debug`,`debug`),info:At(t,`info`,`info`),warn:At(t,`warn`,`warn`),error:At(t,`error`,`error`)}}let Mt=jt();const Nt=`[ArkEnv]`,Pt=`[ArkEnv Watcher]`;function Ft(e){return{logBuildWarning(t){e.warn(`⚠️ ${Nt} ${t}`)},logBuildError(t){e.error(`❌ ${Nt} ${t}`)},logBuildErrorDetail(t){e.error(t)},logBuildErrorBlankLine(){e.error(``)},logBuildErrorWithCause(t,n){e.error(`❌ ${Nt} ${t}`),e.error(St(n))},logWatcherError(t){e.error(`${Pt} ${t}`)},logWatcherErrorWithCause(t,n){e.error(`${Pt} ${t}`),e.error(St(n))}}}let It=Ft(Mt);function Lt(e,t){It.logBuildErrorWithCause(e,t)}var Rt=re({safeAppend:()=>Bt});const zt=`// @arkenv-types`;async function Bt(e,t,n,r){try{let r=await d.readFile(e,`utf-8`),i=n===`vite`?`ImportMetaEnvAugmented`:`ProcessEnvAugmented`;if(r.includes(zt)||r.includes(i))return!1;let a=u.dirname(e),o=u.relative(a,t).replace(/\.(ts|js|tsx|jsx)$/,``).split(u.sep).join(`/`),s=o.startsWith(`.`)?o:`./${o}`,c=n===`vite`?Vt(s):Ht(s),l=r.endsWith(`
46
+ `):t(e),U=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`disabled`:return`${o(`gray`,Qe)} ${yt(n,e=>o(`gray`,e))}${e.hint?` ${o(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${yt(n,e=>o(`dim`,e))}`;case`active`:return`${o(`green`,Ze)} ${n}${e.hint?` ${o(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${yt(n,e=>o([`strikethrough`,`dim`],e))}`;default:return`${o(`dim`,Qe)} ${yt(n,e=>o(`dim`,e))}`}};return new Ue({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??F.withGuide,r=`${ct(this.state)} `,i=`${lt(this.state)} `,a=Be(e.output,e.message,i,r),s=`${n?`${o(`gray`,z)}
47
+ `:``}${a}
48
+ `;switch(this.state){case`submit`:{let r=n?`${o(`gray`,z)} `:``;return`${s}${Be(e.output,t(this.options[this.cursor],`selected`),r)}`}case`cancel`:{let r=n?`${o(`gray`,z)} `:``;return`${s}${Be(e.output,t(this.options[this.cursor],`cancelled`),r)}${n?`
49
+ ${o(`gray`,z)}`:``}`}default:{let r=n?`${o(`cyan`,z)} `:``,i=n?o(`cyan`,B):``,a=s.split(`
50
+ `).length,c=n?2:1;return`${s}${r}${dt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:r.length,rowPadding:a+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
51
+ ${r}`)}
52
+ ${i}
53
+ `}}}}).prompt()},bt=`${o(`gray`,z)} `,W={message:async(e,{symbol:t=o(`gray`,z)}={})=>{process.stdout.write(`${o(`gray`,z)}
54
+ ${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
55
+ ${bt}`),t.includes(`
56
+ `)&&(n=3+a(t.slice(t.lastIndexOf(`
57
+ `))).length);let e=a(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
58
+ ${bt}${t.trimStart()}`),n=3+a(t.trimStart()).length)}process.stdout.write(`
59
+ `)},info:e=>W.message(e,{symbol:o(`blue`,it)}),success:e=>W.message(e,{symbol:o(`green`,at)}),step:e=>W.message(e,{symbol:o(`green`,R)}),warn:e=>W.message(e,{symbol:o(`yellow`,ot)}),warning:e=>W.warn(e),error:e=>W.message(e,{symbol:o(`red`,st)})},xt=e=>new We({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??F.withGuide,n=`${`${t?`${o(`gray`,z)}
60
+ `:``}${ct(this.state)} `}${e.message}
61
+ `,r=e.placeholder?o(`inverse`,e.placeholder[0])+o(`dim`,e.placeholder.slice(1)):o([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,a=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${o(`yellow`,this.error)}`:``,r=t?`${o(`yellow`,z)} `:``,a=t?o(`yellow`,B):``;return`${n.trim()}
62
+ ${r}${i}
63
+ ${a}${e}
64
+ `}case`submit`:{let e=a?` ${o(`dim`,a)}`:``;return`${n}${t?o(`gray`,z):``}${e}`}case`cancel`:{let e=a?` ${o([`strikethrough`,`dim`],a)}`:``,r=t?o(`gray`,z):``;return`${n}${r}${e}${a.trim()?`
65
+ ${r}`:``}`}default:return`${n}${t?`${o(`cyan`,z)} `:``}${i}
66
+ ${t?o(`cyan`,B):``}
67
+ `}}}).prompt();var St=class{info(e){process.stdout.write(`${A.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${A.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${A.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${A.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){gt(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return vt()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${A.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${A.default.red(`✘ ${e}`)}\n`),t){let e=`${A.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){}finish(e,t){pt(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},Ct=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new se:e.isQuiet?this.reporter=new ce:this.reporter=new St}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){this.reporter.cancel(e)}fatal(e,t){this.reporter.fatal(e,t)}refuse(e){this.reporter.refuse(e)}finish(e,t){this.reporter.finish(e,t)}async flush(){await this.reporter.flush()}};function wt(e){return e instanceof Error?e.stack??e.message:String(e)}function Tt(e,t,n){e(`${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&e(n.stack)}const Et={debug:0,info:1,warn:2,error:3},Dt=new Set([`debug`,`info`,`warn`,`error`,`silent`]);function Ot(e){if(!e)return;let t=e.trim().toLowerCase();if(Dt.has(t))return t}function kt(){if(!(typeof process>`u`))return Ot(process.env?.ARKENV_LOG_LEVEL)}function At(e){return e?.level??kt()??`info`}function jt(e,t){return e===`silent`?!1:Et[t]>=Et[e]}function Mt(e,t,n){return(r,...i)=>{jt(e,t)&&console[n](r,...i)}}function Nt(e){let t=At(e);return{debug:Mt(t,`debug`,`debug`),info:Mt(t,`info`,`info`),warn:Mt(t,`warn`,`warn`),error:Mt(t,`error`,`error`)}}let Pt=Nt();const Ft=`[ArkEnv]`,It=`[ArkEnv Watcher]`;function Lt(e){return{logBuildWarning(t){e.warn(`⚠️ ${Ft} ${t}`)},logBuildError(t){e.error(`❌ ${Ft} ${t}`)},logBuildErrorDetail(t){e.error(t)},logBuildErrorBlankLine(){e.error(``)},logBuildErrorWithCause(t,n){e.error(`❌ ${Ft} ${t}`),e.error(wt(n))},logWatcherError(t){e.error(`${It} ${t}`)},logWatcherErrorWithCause(t,n){e.error(`${It} ${t}`),e.error(wt(n))}}}let Rt=Lt(Pt);function zt(e,t){Rt.logBuildErrorWithCause(e,t)}var Bt=ae({safeAppend:()=>Ht});const Vt=`// @arkenv-types`;async function Ht(e,t,n,r){try{let r=await m.readFile(e,`utf-8`),i=n===`vite`?`ImportMetaEnvAugmented`:`ProcessEnvAugmented`;if(r.includes(Vt)||r.includes(i))return!1;let a=p.dirname(e),o=p.relative(a,t).replace(/\.(ts|js|tsx|jsx)$/,``).split(p.sep).join(`/`),s=o.startsWith(`.`)?o:`./${o}`,c=n===`vite`?Ut(s):Wt(s),l=r.endsWith(`
68
68
  `)?``:`
69
- `;return await d.appendFile(e,`${l}\n${zt}\n${c}\n`,`utf-8`),!0}catch(t){let n=`Failed to append to ${e}`;return r?Ct(r.error.bind(r),n,t):Lt(n,t),!1}}function Vt(e){return f`
69
+ `;return await m.appendFile(e,`${l}\n${Vt}\n${c}\n`,`utf-8`),!0}catch(t){let n=`Failed to append to ${e}`;return r?Tt(r.error.bind(r),n,t):zt(n,t),!1}}function Ut(e){return h`
70
70
  type ImportMetaEnvAugmented = import("@arkenv/vite-plugin").ImportMetaEnvAugmented<
71
71
  typeof import("${e}").Env
72
72
  >;
@@ -76,7 +76,7 @@ ${t?r(`cyan`,R):``}
76
76
  interface ImportMeta {
77
77
  readonly env: ImportMetaEnv;
78
78
  }
79
- `}function Ht(e){return f`
79
+ `}function Wt(e){return h`
80
80
  type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
81
81
  typeof import("${e}").Env
82
82
  >;
@@ -84,9 +84,9 @@ ${t?r(`cyan`,R):``}
84
84
  declare namespace NodeJS {
85
85
  interface ProcessEnv extends ProcessEnvAugmented {}
86
86
  }
87
- `}async function Ut(e,t){for(let n of t)try{return await d.access(u.join(e,n)),!0}catch{}return!1}async function Wt(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=u.join(e,`package.json`),n=await d.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 Ut(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await Ut(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await Ut(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await Gt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function Gt(e=process.cwd(),t){let n=[];try{let t=u.join(e,`bunfig.toml`),r=await d.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(()=>Jt),i=await r(e),a=n.includes(`serve`),o=n.includes(`build`);for(let e of i)try{let t=await d.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 Kt(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?u.dirname(t.path):e;for(;r!==u.parse(r).root;){try{let e=u.join(r,`package.json`),t=await d.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 d.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=u.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(()=>en),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=u.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!u.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await d.access(u.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var Jt=re({getEnvExampleKeys:()=>$t,parseEnvExample:()=>Xt,resolveImportPaths:()=>Zt,scanProjectEnvKeys:()=>Qt,walk:()=>Yt});async function Yt(e,t=[]){try{let n=await d.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 Yt(u.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(u.join(e,r.name))}catch{}return t}function Xt(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 Zt(e,t,n){if(e.startsWith(`.`))return[u.resolve(u.dirname(n),e)];if(u.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||u.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 u.resolve(i,t)})}return r.baseUrl?[u.resolve(i,e)]:[]}async function Qt(e,t,n){let r=[],i=await Yt(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await d.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],s=[];if(t?s=Zt(i,t,e):i.startsWith(`.`)&&(s=[u.resolve(u.dirname(e),i)]),s.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 $t(e=process.cwd(),t,n){let r=u.join(e,`.env.example`);try{let e=Xt(await d.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await Qt(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var en=re({checkTsConfig:()=>an,findTsConfig:()=>nn,loadTsConfig:()=>rn});const tn=e(import.meta.url).resolve;async function nn(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==u.parse(n).root;){for(let e of t){let t=u.join(n,e);try{return await d.access(t),t}catch{}}n=u.dirname(n)}return null}async function rn(e,t=new Set){let n=u.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await d.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=_(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(`.`)||u.isAbsolute(r))n=u.resolve(u.dirname(e),r);else try{n=tn(r,{paths:[u.dirname(e)]})}catch{n=u.resolve(u.dirname(e),`node_modules`,r)}let i={...(await rn(n,t)).compilerOptions};i.baseUrl&&=u.resolve(u.dirname(n),i.baseUrl),i.rootDir&&=u.resolve(u.dirname(n),i.rootDir),o={...o,...i}}}let s={...a};return s.baseUrl&&=u.resolve(u.dirname(e),s.baseUrl),s.rootDir&&=u.resolve(u.dirname(e),s.rootDir),o={...o,...s},{...i,path:e,compilerOptions:o}}async function an(e=process.cwd()){let t=await nn(e);if(!t)return{status:`not_found`};let n=u.basename(t);try{let e=await rn(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 on(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 sn(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function cn(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=sn(r[1]);return e!==null&&on(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=sn(i);return a&&(r===`>=`||r===`>`||r===`=`)?on(a,t)>=0:!1})}async function ln(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;on(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=u.join(e,`package.json`),r=await d.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?cn(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 an(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 un=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await d.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await d.access(u.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return nn(e)}async loadTsConfig(e,t=new Set){return rn(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return $t(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return qt(e,t)}async checkTsConfig(e=process.cwd()){return an(e)}async checkRequirements(e=process.cwd()){return ln(e)}async detectFramework(e=process.cwd(),t){return Wt(e,t)}async detectBunFeatures(e=process.cwd(),t){return Gt(e,t)}async detectPackageManager(e=process.cwd(),t){return Kt(e,t)}async hasSkill(e=process.cwd()){try{let t=u.join(e,`skills-lock.json`),n=await d.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 d.access(u.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return p(`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=u.resolve(e);for(;;){let e=u.join(t,`package.json`);try{return await d.access(e),e}catch{let e=u.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 d.readFile(t,`utf-8`),n=JSON.parse(e);return n.arkenv?typeof n.arkenv==`string`?{schema:n.arkenv,layout:`flat`}:typeof n.arkenv==`object`&&typeof n.arkenv.schema==`string`?{schema:n.arkenv.schema,layout:n.arkenv.layout===`strict`?`strict`:`flat`}:null:null}catch{return null}}};const U=e=>O.default.cyan(e),dn=O.default.blue(`⛯`),W={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 fn(e){if(e===`nextjs`||e===`nuxt`)return W[e]}function pn(e){return e===`nextjs`||e===`nuxt`}const G={nextjs:W.nextjs.clientPrefix,nuxt:W.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``};function mn(e,t){let n=fn(e.framework);return{framework:e.framework,clientPrefix:G[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...e.layout!==void 0&&{layout:e.layout},...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const hn={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`},gn=`generated`;function _n(e){let t={};for(let n of e)t[n]=hn[n]??``;return t}function vn(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?u.dirname(n.path):e,a=u.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 yn(e,t,n){if(!(!pn(n.framework)||n.disableCodegen||!e.tsConfig?.parsed))return vn(e.cwd,t,e.tsConfig.parsed)}function bn(e,t){return yn(e,u.join(e.targetDir,gn),t)}function xn(e,t,n){return yn(e,u.join(t,gn),n)}function Sn(e,t,n,r){let i=mn(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`}]:[]}function Cn(e,t,n,r){let i=u.extname(n.targetPath),a=n.targetPath.slice(0,-i.length),o=u.join(a,`internal`,`shared${i}`),s=u.join(a,`client${i}`),c=u.join(a,`server${i}`),l=mn(t,r),d=e.getStrictTemplates(t.envKeys??[],l),f=n.existingFiles.includes(o),p=n.existingFiles.includes(s),m=n.existingFiles.includes(c),h=[];return(!f||t.overwriteEnvSchemaFile!==!1)&&h.push({path:o,content:d.shared,action:f?`overwrite`:`create`,label:`shared environment schema`}),(!p||t.overwriteEnvSchemaFile!==!1)&&h.push({path:s,content:d.client,action:p?`overwrite`:`create`,label:`client environment schema`}),(!m||t.overwriteEnvSchemaFile!==!1)&&h.push({path:c,content:d.server,action:m?`overwrite`:`create`,label:`server environment schema`}),h}const wn={clientPrefix:G[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?_n(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 t({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return t.layout===`strict`?Cn(e,t,n):Sn(e,t,n)},getTypeDefinitionFiles(){return[]}};function Tn(e){let{id:n,packageName:r,clientPrefix:i,supportsWrapNextjsConfig:a}=e,o=`${i}API_URL`;return{clientPrefix:i,getEnvDefaults(e){return e&&e.length>0?_n(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[o]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[r]},requiresArktypePeer(){return!0},bootstrap(e){return t({framework:n,...a&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){if(t.layout===`strict`){let r=u.extname(n.targetPath);return Cn(e,t,n,xn(n,n.targetPath.slice(0,-r.length),t))}return Sn(e,t,n,bn(n,t))},getTypeDefinitionFiles(){return[]}}}const En=Tn(W.nextjs),Dn=Tn(W.nuxt),On={clientPrefix:G.vanilla,getEnvDefaults(e){return e&&e.length>0?_n(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return t.layout===`strict`?Cn(e,t,n):Sn(e,t,n)},getTypeDefinitionFiles(){return[]}},kn={vite:{clientPrefix:G.vite,getEnvDefaults(e){return e&&e.length>0?_n(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 t({framework:`vite`})},getSchemaFiles(e,t,n){return t.layout===`strict`?Cn(e,t,n):Sn(e,t,n)},getTypeDefinitionFiles(){return[]}},"bun-fullstack":wn,nextjs:En,nuxt:Dn,vanilla:On},K={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(K).includes(e)}function jn(e){return Object.keys(K).includes(e)}function q(e,t){if(e===`none`)return[];let n=K[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function Mn(e,t){if(e===`none`)return{clientKeys:[],serverKeys:[]};let n=K[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys],i=[];if(t)for(let e of n.clientExposedKeys)i.push(`${t}${e}`);return{clientKeys:i,serverKeys:r}}function Nn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=K[n].fields;return r in i?i[r]:void 0}function Pn(e,t,n){let r=q(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}function Fn(e){return`// @arkenv-preset-start ${e}`}function In(e){return`// @arkenv-preset-end ${e}`}function Ln(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function J(e,t,n,r){let i=Nn(t,n,r);if(i)return Ln(e,i)}const Rn={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;if(t===`server`&&e===`PORT`)return`PORT: "number.port = 3000",`;let i=J(Rn,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=J(Rn,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}: ${J(Rn,e,t,n)??`"string?"`},`).join(`
89
- `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`${t}: "string = 'https://api.example.com'",`],sharedFields:[`NODE_ENV: "'development' | 'production' | 'test' = 'development'",`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},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'",`]}},sharedImports:`import { type } from "@arkenv/core";`,wrapSharedSchema(e){return`type(${e})`},strictExtraImports:``,assembleVanilla(e){return f`
87
+ `}function Gt(e,t){return Object.keys(e).includes(t)}function Kt(e){if(typeof e==`string`)return/=\s*\S/.test(e);if(!e||typeof e!=`object`)return!1;let t=e;if(Gt(t,`default`)||Gt(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 Kt(e.innerType)}return!1}function qt(e){return e.endsWith(`?`)?e.slice(0,-1):e}function Jt(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:Gt(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&&Gt(e,`default`))}),n[r]=a}}}function Yt(t){let n=[],r={};for(let i of t){if(!i||typeof i!=`object`&&typeof i!=`function`)continue;let t=i,a=t.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)&&(Jt(e.required,n,r),Jt(e.optional,n,r),n.length>s))continue}let c=o?e(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)&&typeof i!=`function`)for(let[e,i]of Object.entries(t)){let t=qt(e);n.push({name:t,schema:i,hasDefault:Kt(i)}),r[t]=i}}return{keys:n,schema:r}}const Xt={MODULE_LOAD_FAILED:`MODULE_LOAD_FAILED`,NO_SCHEMA:`NO_SCHEMA`},Zt=`If this file calls arkenv(), upgrade @arkenv/core or @arkenv/standard so the CLI can inspect the schema without validating the environment.`;function Qt(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 $t(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 en(e){return`No arkenv() schema definition was found in "${e}". ${Zt}`}function tn(e,t){let n=t instanceof Error?t.message:String(t),r=`Failed to load schema module at "${e}": ${n}`;return Qt(t)?`${r} ${Zt}`:$t(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 nn=class{constructor(e={}){this.options=e}async load(e){n();try{this.evaluateModule(e.schemaPath);let n=t();if(n.length===0)return{ok:!1,code:Xt.NO_SCHEMA,message:en(e.schemaPath)};let r=Yt(n);return{ok:!0,keys:r.keys,schema:r.schema}}catch(n){return t(),{ok:!1,code:Xt.MODULE_LOAD_FAILED,message:tn(e.schemaPath,n),cause:n}}}evaluateModule(e){let t={moduleCache:!1,fsCache:!1,tsconfigPaths:!0,...this.options.jitiAliases?{alias:this.options.jitiAliases}:{}};try{g(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;g(e,{...t,tsconfigPaths:!1})(e)}}};async function rn(e,t){for(let n of t)try{return await m.access(p.join(e,n)),!0}catch{}return!1}async function an(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=p.join(e,`package.json`),n=await m.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 rn(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await rn(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await rn(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await on(e,t)).length>0?`bun-fullstack`:`vanilla`}async function on(e=process.cwd(),t){let n=[];try{let t=p.join(e,`bunfig.toml`),r=await m.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(()=>ln),i=await r(e),a=n.includes(`serve`),o=n.includes(`build`);for(let e of i)try{let t=await m.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 sn(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?p.dirname(t.path):e;for(;r!==p.parse(r).root;){try{let e=p.join(r,`package.json`),t=await m.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 m.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=p.dirname(r)}return`npm`}async function cn(e=process.cwd(),t){let n=t;if(!n){let{findTsConfig:t,loadTsConfig:r}=await Promise.resolve().then(()=>hn),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=p.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!p.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await m.access(p.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var ln=ae({getEnvExampleKeys:()=>mn,parseEnvExample:()=>dn,resolveImportPaths:()=>fn,scanProjectEnvKeys:()=>pn,walk:()=>un});async function un(e,t=[]){try{let n=await m.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 un(p.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(p.join(e,r.name))}catch{}return t}function dn(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 fn(e,t,n){if(e.startsWith(`.`))return[p.resolve(p.dirname(n),e)];if(p.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||p.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 p.resolve(i,t)})}return r.baseUrl?[p.resolve(i,e)]:[]}async function pn(e,t,n){let r=[],i=await un(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await m.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],s=[];if(t?s=fn(i,t,e):i.startsWith(`.`)&&(s=[p.resolve(p.dirname(e),i)]),s.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 mn(e=process.cwd(),t,n){let r=p.join(e,`.env.example`);try{let e=dn(await m.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await pn(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var hn=ae({checkTsConfig:()=>yn,findTsConfig:()=>_n,loadTsConfig:()=>vn});const gn=r(import.meta.url).resolve;async function _n(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==p.parse(n).root;){for(let e of t){let t=p.join(n,e);try{return await m.access(t),t}catch{}}n=p.dirname(n)}return null}async function vn(e,t=new Set){let n=p.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await m.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=x(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(`.`)||p.isAbsolute(r))n=p.resolve(p.dirname(e),r);else try{n=gn(r,{paths:[p.dirname(e)]})}catch{n=p.resolve(p.dirname(e),`node_modules`,r)}let i={...(await vn(n,t)).compilerOptions};i.baseUrl&&=p.resolve(p.dirname(n),i.baseUrl),i.rootDir&&=p.resolve(p.dirname(n),i.rootDir),o={...o,...i}}}let s={...a};return s.baseUrl&&=p.resolve(p.dirname(e),s.baseUrl),s.rootDir&&=p.resolve(p.dirname(e),s.rootDir),o={...o,...s},{...i,path:e,compilerOptions:o}}async function yn(e=process.cwd()){let t=await _n(e);if(!t)return{status:`not_found`};let n=p.basename(t);try{let e=await vn(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 bn(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 xn(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function Sn(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=xn(r[1]);return e!==null&&bn(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=xn(i);return a&&(r===`>=`||r===`>`||r===`=`)?bn(a,t)>=0:!1})}async function Cn(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;bn(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=p.join(e,`package.json`),r=await m.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?Sn(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 yn(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 wn=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await m.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await m.access(p.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return _n(e)}async loadTsConfig(e,t=new Set){return vn(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return mn(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return cn(e,t)}async checkTsConfig(e=process.cwd()){return yn(e)}async checkRequirements(e=process.cwd()){return Cn(e)}async detectFramework(e=process.cwd(),t){return an(e,t)}async detectBunFeatures(e=process.cwd(),t){return on(e,t)}async detectPackageManager(e=process.cwd(),t){return sn(e,t)}async hasSkill(e=process.cwd()){try{let t=p.join(e,`skills-lock.json`),n=await m.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 m.access(p.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return _(`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=p.resolve(e);for(;;){let e=p.join(t,`package.json`);try{return await m.access(e),e}catch{let e=p.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 m.readFile(t,`utf-8`),n=JSON.parse(e);return n.arkenv?typeof n.arkenv==`string`?{schema:n.arkenv,layout:`flat`}:typeof n.arkenv==`object`&&typeof n.arkenv.schema==`string`?{schema:n.arkenv.schema,layout:n.arkenv.layout===`strict`?`strict`:`flat`}:null:null}catch{return null}}};const G=e=>A.default.cyan(e),Tn=A.default.blue(`⛯`),En={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 Dn(e){if(e===`nextjs`||e===`nuxt`)return En[e]}function On(e){return e===`nextjs`||e===`nuxt`}const K={nextjs:En.nextjs.clientPrefix,nuxt:En.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``};function kn(e,t){let n=Dn(e.framework);return{framework:e.framework,clientPrefix:K[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...e.layout!==void 0&&{layout:e.layout},...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const An={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`},jn=`generated`;function Mn(e){let t={};for(let n of e)t[n]=An[n]??``;return t}function Nn(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?p.dirname(n.path):e,a=p.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 Pn(e,t,n){if(!(!On(n.framework)||n.disableCodegen||!e.tsConfig?.parsed))return Nn(e.cwd,t,e.tsConfig.parsed)}function Fn(e,t){return Pn(e,p.join(e.targetDir,jn),t)}function In(e,t,n){return Pn(e,p.join(t,jn),n)}function Ln(e,t,n,r){let i=kn(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`}]:[]}function Rn(e,t,n,r){let i=p.extname(n.targetPath),a=n.targetPath.slice(0,-i.length),o=p.join(a,`internal`,`shared${i}`),s=p.join(a,`client${i}`),c=p.join(a,`server${i}`),l=kn(t,r),u=e.getStrictTemplates(t.envKeys??[],l),d=n.existingFiles.includes(o),f=n.existingFiles.includes(s),m=n.existingFiles.includes(c),h=[];return(!d||t.overwriteEnvSchemaFile!==!1)&&h.push({path:o,content:u.shared,action:d?`overwrite`:`create`,label:`shared environment schema`}),(!f||t.overwriteEnvSchemaFile!==!1)&&h.push({path:s,content:u.client,action:f?`overwrite`:`create`,label:`client environment schema`}),(!m||t.overwriteEnvSchemaFile!==!1)&&h.push({path:c,content:u.server,action:m?`overwrite`:`create`,label:`server environment schema`}),h}const zn={clientPrefix:K[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?Mn(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 i({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return t.layout===`strict`?Rn(e,t,n):Ln(e,t,n)},getTypeDefinitionFiles(){return[]}};function Bn(e){let{id:t,packageName:n,clientPrefix:r,supportsWrapNextjsConfig:a}=e,o=`${r}API_URL`;return{clientPrefix:r,getEnvDefaults(e){return e&&e.length>0?Mn(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[o]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[n]},requiresArktypePeer(){return!0},bootstrap(e){return i({framework:t,...a&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){if(t.layout===`strict`){let r=p.extname(n.targetPath);return Rn(e,t,n,In(n,n.targetPath.slice(0,-r.length),t))}return Ln(e,t,n,Fn(n,t))},getTypeDefinitionFiles(){return[]}}}const Vn=Bn(En.nextjs),Hn=Bn(En.nuxt),Un={clientPrefix:K.vanilla,getEnvDefaults(e){return e&&e.length>0?Mn(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return t.layout===`strict`?Rn(e,t,n):Ln(e,t,n)},getTypeDefinitionFiles(){return[]}},Wn={vite:{clientPrefix:K.vite,getEnvDefaults(e){return e&&e.length>0?Mn(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 i({framework:`vite`})},getSchemaFiles(e,t,n){return t.layout===`strict`?Rn(e,t,n):Ln(e,t,n)},getTypeDefinitionFiles(){return[]}},"bun-fullstack":zn,nextjs:Vn,nuxt:Hn,vanilla:Un},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 Gn(e){return e===`none`||Object.keys(q).includes(e)}function Kn(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 qn(e,t){if(e===`none`)return{clientKeys:[],serverKeys:[]};let n=q[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys],i=[];if(t)for(let e of n.clientExposedKeys)i.push(`${t}${e}`);return{clientKeys:i,serverKeys:r}}function Jn(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 Yn(e,t,n){let r=J(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}function Xn(e){return`// @arkenv-preset-start ${e}`}function Zn(e){return`// @arkenv-preset-end ${e}`}function Qn(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function Y(e,t,n,r){let i=Jn(t,n,r);if(i)return Qn(e,i)}const $n={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;if(t===`server`&&e===`PORT`)return`PORT: "number.port = 3000",`;let i=Y($n,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=Y($n,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($n,e,t,n)??`"string?"`},`).join(`
89
+ `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`${t}: "string = 'https://api.example.com'",`],sharedFields:[`NODE_ENV: "'development' | 'production' | 'test' = 'development'",`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},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'",`]}},sharedImports:`import { type } from "@arkenv/core";`,wrapSharedSchema(e){return`type(${e})`},strictExtraImports:``,assembleVanilla(e){return h`
90
90
  import arkenv, { type } from "@arkenv/core";
91
91
 
92
92
  /**
@@ -95,11 +95,11 @@ ${t?r(`cyan`,R):``}
95
95
  export const env = arkenv({
96
96
  ${e}
97
97
  });
98
- `}},zn={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;if(t===`server`&&e===`PORT`)return`PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`;let i=J(zn,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=J(zn,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.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${J(zn,e,t,n)??`v.optional(v.string())`},`).join(`
98
+ `}},er={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;if(t===`server`&&e===`PORT`)return`PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`;let i=Y(er,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=Y(er,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.string(), v.transform(Number), 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(er,e,t,n)??`v.optional(v.string())`},`).join(`
100
100
  `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`${t}: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[`NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},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"),`]}},sharedImports:`import * as v from "valibot";`,wrapSharedSchema(e){return`v.object(${e})`},strictExtraImports:`import * as v from "valibot";
101
- `,assembleVanilla(e){return f`
102
- import arkenv from "@arkenv/standard";
101
+ `,assembleVanilla(e){return h`
102
+ import { arkenv } from "@arkenv/standard/valibot";
103
103
  import * as v from "valibot";
104
104
 
105
105
  /**
@@ -108,10 +108,10 @@ ${e}
108
108
  export const env = arkenv({
109
109
  ${e}
110
110
  });
111
- `}},Bn={extraImport:`import { z } from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;if(t===`server`&&e===`PORT`)return`PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;let i=J(Bn,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=J(Bn,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
112
- PORT: z.coerce.number().int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${J(Bn,e,t,n)??`z.string().optional()`},`).join(`
111
+ `}},tr={extraImport:`import { z } from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;if(t===`server`&&e===`PORT`)return`PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;let i=Y(tr,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=Y(tr,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
112
+ PORT: z.coerce.number().int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${Y(tr,e,t,n)??`z.string().optional()`},`).join(`
113
113
  `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`],clientFields:[`${t}: z.string().url().default("https://api.example.com"),`],sharedFields:[`NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.string().url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},sharedImports:`import { z } from "zod";`,wrapSharedSchema(e){return`z.object(${e})`},strictExtraImports:`import { z } from "zod";
114
- `,assembleVanilla(e){return f`
114
+ `,assembleVanilla(e){return h`
115
115
  import arkenv from "@arkenv/standard";
116
116
  import { z } from "zod";
117
117
 
@@ -121,57 +121,57 @@ ${e}
121
121
  export const env = arkenv({
122
122
  ${e}
123
123
  });
124
- `}},Y={arktype:Rn,zod:Bn,valibot:zn};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(`
124
+ `}},nr={arktype:$n,zod:tr,valibot:er};function rr(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function ir(e,t){return t.endsWith(`
125
125
  `)&&!e.endsWith(`
126
- `)?`${e}\n`:e}function Un(e){try{let t=x(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=b(t,{format:y(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=x(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=v.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=v.functionCall(`withArkEnv`,n.exports.default);let r=b(n,{format:y(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=x(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=b(n,{format:y(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=Y[t];return J(i,e,n,r)??i.formatOptionalString()}function X(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=qn(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(`
126
+ `)?`${e}\n`:e}function ar(e){try{let t=T(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=w(t,{format:C(n)}).code;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,`arkenvVitePlugin()`),i=rr(i),i=ir(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 or(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=T(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=S.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=S.functionCall(`withArkEnv`,n.exports.default);let r=w(n,{format:C(t)}).code;return r=rr(r),r=ir(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 sr(e){try{let t=e.code,n=T(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=w(n,{format:C(t)}).code;return i=rr(i),i=ir(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 cr(e,t,n,r){let i=nr[t];return Y(i,e,n,r)??i.formatOptionalString()}function X(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=lr(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(`
127
127
  `),innerContent:c.join(`
128
- `),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 qn(e){let t=e.indexOf(`:`);return t===-1?{baseId:e}:{baseId:e.slice(0,t),role:e.slice(t+1)}}function Jn(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 Yn(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 Xn(e){let t=Yn(e);if(!t)return null;let n=Jn(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 Zn(e,t){let{preset:n,framework:r,validator:i,targetKeys:a}=t,o=G[r]||``,s=a??q(n,o),c={};for(let e of s)c[e]=Kn(e,i,o,n);let l=X(e);if(!l.success)return{success:!1,updated:!1,error:l.error,proposedFields:c};let u=l.blocks,d=e.split(/\r?\n/),f=Xn(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(`
128
+ `),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 lr(e){let t=e.indexOf(`:`);return t===-1?{baseId:e}:{baseId:e.slice(0,t),role:e.slice(t+1)}}function ur(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 dr(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 fr(e){let t=dr(e);if(!t)return null;let n=ur(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 pr(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]=cr(e,i,o,n);let l=X(e);if(!l.success)return{success:!1,updated:!1,error:l.error,proposedFields:c};let u=l.blocks,d=e.split(/\r?\n/),f=fr(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(`
129
129
  `)===v.join(`
130
130
  `)?{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(`
131
- `),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=Qn(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(`
132
- `),proposedFields:c}}return $n(d,f.startLineIndex,f.endLineIndex,f.startCharIndex),d.splice(f.endLineIndex,0,...v),{success:!0,updated:!0,code:d.join(`
133
- `),proposedFields:c}}function Qn(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 $n(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=Qn(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 er(e,t){let{preset:n}=t,r=X(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(`
134
- `),removedKeys:a}}async function tr(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=u.resolve(e,t);try{return await d.access(n),n}catch{}}return null}async function nr(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=u.resolve(e,t);try{return await d.access(n),n}catch{}}return null}async function rr(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=u.resolve(e,t);try{return await d.access(n),n}catch{}}return null}async function ir(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 ar(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=u.resolve(e,t);try{return await d.access(n),n}catch{}}return null}async function or(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 sr(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 cr(e,t){if(!t||t.length===0)return{success:!0,instructions:f`
135
- ${O.default.green(`✔`)} Use ${O.default.bold(`Vanilla`)} Bun runtime integration.
136
- Access validated variables via your ${U(`env`)} object for typesafety.
137
- Primarily used for ${O.default.cyan(`server-side`)} or runtime-only validation.
131
+ `),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=mr(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(`
132
+ `),proposedFields:c}}return hr(d,f.startLineIndex,f.endLineIndex,f.startCharIndex),d.splice(f.endLineIndex,0,...v),{success:!0,updated:!0,code:d.join(`
133
+ `),proposedFields:c}}function mr(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 hr(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=mr(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 gr(e,t){let{preset:n}=t,r=X(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(`
134
+ `),removedKeys:a}}async function _r(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=p.resolve(e,t);try{return await m.access(n),n}catch{}}return null}async function vr(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=p.resolve(e,t);try{return await m.access(n),n}catch{}}return null}async function yr(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=p.resolve(e,t);try{return await m.access(n),n}catch{}}return null}async function br(e,t,n){try{let r=or({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 xr(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=p.resolve(e,t);try{return await m.access(n),n}catch{}}return null}async function Sr(e,t){try{let n=sr({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=ar({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 wr(e,t){if(!t||t.length===0)return{success:!0,instructions:h`
135
+ ${A.default.green(`✔`)} Use ${A.default.bold(`Vanilla`)} Bun runtime integration.
136
+ Access validated variables via your ${G(`env`)} object for typesafety.
137
+ Primarily used for ${A.default.cyan(`server-side`)} or runtime-only validation.
138
138
  No plugins are required.
139
- `};let n=t.includes(`serve`),r=t.includes(`build`),i=``;return n&&(i+=f`
140
- ${O.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
141
- To inline environment variables (e.g. ${U(`PUBLIC_*`)}) in your ${O.default.cyan(`client-side`)} code, add the plugin to ${U(`bunfig.toml`)}:
139
+ `};let n=t.includes(`serve`),r=t.includes(`build`),i=``;return n&&(i+=h`
140
+ ${A.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
141
+ To inline environment variables (e.g. ${G(`PUBLIC_*`)}) in your ${A.default.cyan(`client-side`)} code, add the plugin to ${G(`bunfig.toml`)}:
142
142
 
143
143
  [serve.static]
144
144
  plugins = ["@arkenv/bun-plugin"]
145
145
 
146
146
  `),r&&(i&&(i+=`
147
- `),i+=f`
148
- ${O.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
149
- To inline environment variables (e.g. ${U(`PUBLIC_*`)}) in your custom ${O.default.cyan(`client-side`)} build script, add the plugin to your ${U(`Bun.build`)} call:
147
+ `),i+=h`
148
+ ${A.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
149
+ To inline environment variables (e.g. ${G(`PUBLIC_*`)}) in your custom ${A.default.cyan(`client-side`)} build script, add the plugin to your ${G(`Bun.build`)} call:
150
150
 
151
- ${U(`import arkenvPlugin from "@arkenv/bun-plugin";`)}
151
+ ${G(`import arkenvPlugin from "@arkenv/bun-plugin";`)}
152
152
 
153
153
  await Bun.build({
154
154
  entrypoints: ["./index.ts"],
155
155
  outdir: "./dist",
156
- ${O.default.green(`plugins: [arkenvPlugin]`)}
156
+ ${A.default.green(`plugins: [arkenvPlugin]`)}
157
157
  });
158
- `),{success:!0,instructions:i.trim()}}async function lr(e,t){let n=t||await nn();if(!n)return{status:`not_found`};let r=u.basename(n);try{let t=await e.readFile(n);if(_(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=h(t,g(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}}}var ur=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await d.access(e),!0}catch{return!1}}async readFile(e){return d.readFile(e,`utf-8`)}async writeFile(e,t){await d.writeFile(e,t,`utf-8`)}async mkdir(e,t){await d.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=m(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${O.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${O.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return lr(this,e)}async findViteConfig(e){return tr(e)}async findBunConfig(e){return nr(e)}async findNextjsConfig(e){return rr(e)}async findNuxtConfig(e){return ar(e)}async bootstrapViteConfig(e,t){return sr(this,e,t)}async bootstrapBunConfig(e,t){return cr(e,t)}async bootstrapNextjsConfig(e,t){return ir(this,e,t)}async bootstrapNuxtConfig(e){return or(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>Rt);return r(e,t,n,this.logger)}async appendMissingEnvExampleKeys(e,t){let n=u.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(`
158
+ `),{success:!0,instructions:i.trim()}}async function Tr(e,t){let n=t||await _n();if(!n)return{status:`not_found`};let r=p.basename(n);try{let t=await e.readFile(n);if(x(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=y(t,b(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}}}var Er=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await m.access(e),!0}catch{return!1}}async readFile(e){return m.readFile(e,`utf-8`)}async writeFile(e,t){await m.writeFile(e,t,`utf-8`)}async mkdir(e,t){await m.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=v(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${A.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${A.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Tr(this,e)}async findViteConfig(e){return _r(e)}async findBunConfig(e){return vr(e)}async findNextjsConfig(e){return yr(e)}async findNuxtConfig(e){return xr(e)}async bootstrapViteConfig(e,t){return Cr(this,e,t)}async bootstrapBunConfig(e,t){return wr(e,t)}async bootstrapNextjsConfig(e,t){return br(this,e,t)}async bootstrapNuxtConfig(e){return Sr(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>Bt);return r(e,t,n,this.logger)}async appendMissingEnvExampleKeys(e,t){let n=p.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(`
159
159
  `)+`
160
160
  `,s=r.endsWith(`
161
- `)||r.length===0?`${r}${o}`:`${r}\n${o}`;return await this.writeFile(n,s),!0}async removeEnvExampleKeys(e,t,n=[]){let r=u.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(`
161
+ `)||r.length===0?`${r}${o}`:`${r}\n${o}`;return await this.writeFile(n,s),!0}async removeEnvExampleKeys(e,t,n=[]){let r=p.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(`
162
162
  `);return a.endsWith(`
163
163
  `)&&!o.endsWith(`
164
164
  `)&&(o+=`
165
- `),o===a?!1:(await this.writeFile(r,o),!0)}};async function dr(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await z({message:O.default.yellow(`An existing ArkEnv configuration was found at ${U(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 fr(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 ${U(`.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 pr(e){let t=await V({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 mr(e){let t=await V({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 hr(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 gr(){let e=await V({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 _r(e){let t=await V({message:`How would you like to structure your environment variables?`,options:(e?.framework,[{value:`flat`,label:`Flat (Recommended)`,hint:`A single flat env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}])});return P(t)?null:t}async function vr(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 yr(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(K).map(([e,t])=>({value:e,label:t.label,hint:t.hint}))],n=await V({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return P(n)?null:n}async function br(e){let t=await z({message:`Use default config path (${U(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return P(t)?null:t}async function xr(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await yt({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 Z={example:pr,overwriteEnvSchemaFile:dr,framework:mr,bunBuild:hr,layout:_r,nextjsCodegen:vr,useDefaultPath:br,path:xr,validator:gr,hostPreset:yr,useEnvExample:fr};async function Sr(e,t=!1){return(e?.mode||`existing`)===`new`?Cr(e,t):wr(e,t)}async function Cr(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||u.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Q(await yt({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||u.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Q(await Z.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 Tr)return null;throw e}}async function wr(e,n=!1){let r=e?.defaultEnvPath||`./src/env.ts`,i=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(n){let n=e?.framework||`vanilla`,a;return(n===`nextjs`||n===`nuxt`)&&(a=e?.isStrict?`strict`:e?.isSimple?`simple`:(e?.isFlat,`flat`)),t({mode:`existing`,path:r,validator:`arktype`,framework:n,layout:a,bunFeatures:n===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installSkill:!1,envKeys:i??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:n===`nextjs`?!0:void 0,hostPreset:e?.hostPreset||`none`})}try{let n=Q(await Z.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Q(await Z.framework({framework:e?.framework})),s;(o===`nextjs`||o===`nuxt`)&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:e?.isFlat?`flat`:Q(await Z.layout({framework:o})));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Q(await Z.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nuxt`?l=!0:o===`nextjs`&&l===void 0&&(l=!Q(await Z.nextjsCodegen({initialValue:!0,framework:o})));let u;if(o===`nextjs`&&!l){let e=await z({message:`Would you like to wrap your Next.js config with ${U(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(P(e))throw ut(`Operation cancelled`),new Tr;u=e}let d=Q(await Z.useDefaultPath({defaultEnvPath:r})),f=Q(await Z.path({useDefaultPath:d,defaultEnvPath:r})),p=Q(await Z.validator()),m=e?.hostPreset===void 0?Q(await Z.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,h=Q(await Z.useEnvExample({detectedKeys:i,keysSource:a}));return t({mode:`existing`,overwriteEnvSchemaFile:n,framework:o,layout:s,path:f,validator:p,hostPreset:m,bunFeatures:o===`bun-fullstack`?c?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:h?i??void 0:void 0,disableCodegen:l,wrapNextjsConfig:u})}catch(e){if(e instanceof Tr)return null;throw e}}var Tr=class extends Error{constructor(){super(`Operation cancelled`)}};function Q(e){if(e===null||P(e))throw ut(`Operation cancelled`),new Tr;return e}var Er=class{async confirm(e,n=!0,r,i){let a=await z(t({message:e,initialValue:n,active:r,inactive:i}));return P(a)?null:a}async runWizard(e,t=!1){return Sr(e,t)}async select(e,t,n){let r=await V({message:e,options:t,initialValue:n});return P(r)?null:r}};const $={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`},isStrict:{long:`--strict`,short:``,kind:`boolean`},isSimple:{long:`--simple`,short:``,kind:`boolean`},isFlat:{long:`--flat`,short:``,kind:`boolean`},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`}},Dr=new Set(Object.values($).flatMap(e=>[e.long,e.short].filter(Boolean))),Or=new Set(Object.values($).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var kr=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(Or.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}`);Or.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(Or.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($.preset.long,$.preset.short)??this.getFlagValue($.hostPreset.long,$.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 o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0];this.logger=t.logger||new xt({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=$.example;return this.getFlagValue(e.long,e.short)}get isStrict(){return this.hasFlag(`isStrict`)}get isSimple(){return this.hasFlag(`isSimple`)}get isFlat(){return this.hasFlag(`isFlat`)}get noCodegen(){return this.hasFlag(`noCodegen`)}get file(){let e=$.file;return this.getFlagValue(e.long,e.short)}get hostPreset(){let e=this.getFlagValue($.preset.long,$.preset.short)??this.getFlagValue($.hostPreset.long,$.hostPreset.short);if(e&&An(e))return e}hasFlag(e){let t=$[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,isStrict:this.isStrict,isSimple:this.isSimple,isFlat:this.isFlat};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}}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]}},Ar=`1.0.0-alpha.13`;function jr(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 Mr=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{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:`--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${Ar}`),this.logger.log(`\n${O.default.bold(`Usage:`)}`);for(let t of jr(e))this.logger.log(t);this.logger.log(`\n${O.default.bold(`Global options:`)}`);for(let e of jr(t))this.logger.log(e);this.logger.log(`\n${O.default.bold(`init options:`)}`);for(let e of jr(n))this.logger.log(e);this.logger.log(`\n${O.default.bold(`preset options:`)}`);for(let e of jr(r))this.logger.log(e)}};async function Nr(e,t){let n=t.targetDir??process.cwd(),r=u.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=u.join(r,i),o=await d.readdir(a),s=[];for(let t of o){let r=u.join(n,t);await e.exists(r)&&s.push(t)}if(s.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${s.join(`, `)}`);await Pr(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await d.rm(u.join(n,e),{force:!0});let c=u.join(n,`package.json`);if(await e.exists(c)){let n=await e.readFile(c),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(c,JSON.stringify(r,null,2))}}finally{await d.rm(r,{recursive:!0,force:!0})}}async function Pr(e,t){let n=await d.readdir(e);await Promise.all(n.map(n=>d.cp(u.join(e,n),u.join(t,n),{recursive:!0,force:!1})))}function Fr(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 Ir(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=f`
165
+ `),o===a?!1:(await this.writeFile(r,o),!0)}};async function Dr(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await V({message:A.default.yellow(`An existing ArkEnv configuration was found at ${G(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return I(e)||!e?null:e}return!0}async function Or(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await V({message:n===`.env.example`?`Detected ${G(`.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 I(i)?null:i}return!1}async function kr(e){let t=await U({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return I(t)?null:t}async function Ar(e){let t=await U({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 I(t)?null:t}async function jr(e){let t=await V({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return I(t)?null:t}async function Mr(){let e=await U({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 I(e)?null:e}async function Nr(e){let t=await U({message:`How would you like to structure your environment variables?`,options:(e?.framework,[{value:`flat`,label:`Flat (Recommended)`,hint:`A single flat env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}])});return I(t)?null:t}async function Pr(e){let t=await V({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return I(t)?null:t}async function Fr(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 U({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return I(n)?null:n}async function Ir(e){let t=await V({message:`Use default config path (${G(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return I(t)?null:t}async function Lr(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await xt({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(I(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const Z={example:kr,overwriteEnvSchemaFile:Dr,framework:Ar,bunBuild:jr,layout:Nr,nextjsCodegen:Pr,useDefaultPath:Ir,path:Lr,validator:Mr,hostPreset:Fr,useEnvExample:Or};async function Rr(e,t=!1){return(e?.mode||`existing`)===`new`?zr(e,t):Br(e,t)}async function zr(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||p.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Q(await xt({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||p.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Q(await Z.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 Vr)return null;throw e}}async function Br(e,t=!1){let n=e?.defaultEnvPath||`./src/env.ts`,r=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(t){let t=e?.framework||`vanilla`,a;return(t===`nextjs`||t===`nuxt`)&&(a=e?.isStrict?`strict`:e?.isSimple?`simple`:(e?.isFlat,`flat`)),i({mode:`existing`,path:n,validator:`arktype`,framework:t,layout:a,bunFeatures:t===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installSkill:!1,envKeys:r??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:t===`nextjs`?!0:void 0,hostPreset:e?.hostPreset||`none`})}try{let t=Q(await Z.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:n})),o=Q(await Z.framework({framework:e?.framework})),s;(o===`nextjs`||o===`nuxt`)&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:e?.isFlat?`flat`:Q(await Z.layout({framework:o})));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Q(await Z.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nuxt`?l=!0:o===`nextjs`&&l===void 0&&(l=!Q(await Z.nextjsCodegen({initialValue:!0,framework:o})));let u;if(o===`nextjs`&&!l){let e=await V({message:`Would you like to wrap your Next.js config with ${G(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(I(e))throw ft(`Operation cancelled`),new Vr;u=e}let d=Q(await Z.useDefaultPath({defaultEnvPath:n})),f=Q(await Z.path({useDefaultPath:d,defaultEnvPath:n})),p=Q(await Z.validator()),m=e?.hostPreset===void 0?Q(await Z.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,h=Q(await Z.useEnvExample({detectedKeys:r,keysSource:a}));return i({mode:`existing`,overwriteEnvSchemaFile:t,framework:o,layout:s,path:f,validator:p,hostPreset:m,bunFeatures:o===`bun-fullstack`?c?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:h?r??void 0:void 0,disableCodegen:l,wrapNextjsConfig:u})}catch(e){if(e instanceof Vr)return null;throw e}}var Vr=class extends Error{constructor(){super(`Operation cancelled`)}};function Q(e){if(e===null||I(e))throw ft(`Operation cancelled`),new Vr;return e}var Hr=class{async confirm(e,t=!0,n,r){let a=await V(i({message:e,initialValue:t,active:n,inactive:r}));return I(a)?null:a}async runWizard(e,t=!1){return Rr(e,t)}async select(e,t,n){let r=await U({message:e,options:t,initialValue:n});return I(r)?null:r}};const $={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`},isStrict:{long:`--strict`,short:``,kind:`boolean`},isSimple:{long:`--simple`,short:``,kind:`boolean`},isFlat:{long:`--flat`,short:``,kind:`boolean`},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`}},Ur=new Set(Object.values($).flatMap(e=>[e.long,e.short].filter(Boolean))),Wr=new Set(Object.values($).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var Gr=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(Wr.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}`);Wr.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(!Ur.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(Wr.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($.preset.long,$.preset.short)??this.getFlagValue($.hostPreset.long,$.hostPreset.short);e!==void 0&&!Gn(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&&!Kn(e)&&(this.validationError=`Invalid host preset: ${e}`)}}else o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0];this.logger=t.logger||new Ct({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=$.example;return this.getFlagValue(e.long,e.short)}get isStrict(){return this.hasFlag(`isStrict`)}get isSimple(){return this.hasFlag(`isSimple`)}get isFlat(){return this.hasFlag(`isFlat`)}get noCodegen(){return this.hasFlag(`noCodegen`)}get file(){let e=$.file;return this.getFlagValue(e.long,e.short)}get hostPreset(){let e=this.getFlagValue($.preset.long,$.preset.short)??this.getFlagValue($.hostPreset.long,$.hostPreset.short);if(e&&Gn(e))return e}hasFlag(e){let t=$[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,isStrict:this.isStrict,isSimple:this.isSimple,isFlat:this.isFlat};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&&Kn(n)?{provider:n}:{},...r===void 0?{}:{file:r},isForce:this.isForce,isYes:this.isYes}}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]}},Kr=`1.0.0-alpha.14`;function qr(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 Jr=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{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:`--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${Kr}`),this.logger.log(`\n${A.default.bold(`Usage:`)}`);for(let t of qr(e))this.logger.log(t);this.logger.log(`\n${A.default.bold(`Global options:`)}`);for(let e of qr(t))this.logger.log(e);this.logger.log(`\n${A.default.bold(`init options:`)}`);for(let e of qr(n))this.logger.log(e);this.logger.log(`\n${A.default.bold(`preset options:`)}`);for(let e of qr(r))this.logger.log(e)}};async function Yr(e,t){let n=t.targetDir??process.cwd(),r=p.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=p.join(r,i),o=await m.readdir(a),s=[];for(let t of o){let r=p.join(n,t);await e.exists(r)&&s.push(t)}if(s.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${s.join(`, `)}`);await Xr(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await m.rm(p.join(n,e),{force:!0});let c=p.join(n,`package.json`);if(await e.exists(c)){let n=await e.readFile(c),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(c,JSON.stringify(r,null,2))}}finally{await m.rm(r,{recursive:!0,force:!0})}}async function Xr(e,t){let n=await m.readdir(e);await Promise.all(n.map(n=>m.cp(p.join(e,n),p.join(t,n),{recursive:!0,force:!1})))}function Zr(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 Qr(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=h`
166
166
  Inside your AI assistant (e.g. Claude Code), use:
167
- ${U(`/arkenv`)} - automatically refine your schema and configure integrations.
167
+ ${G(`/arkenv`)} - automatically refine your schema and configure integrations.
168
168
  `;return i?(a+=`
169
169
 
170
- `,a+=`Also, wrap your Next.js config with ${U(`withArkEnv`)}:\n`,a+=` ${U(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(a+=` ${U(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${U(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${U(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(a+=` ${U(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${U(`import { env } from "${e.metadata.importPath}"`)}\n`)):r&&(a+=`
170
+ `,a+=`Also, wrap your Next.js config with ${G(`withArkEnv`)}:\n`,a+=` ${G(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(a+=` ${G(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${G(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${G(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(a+=` ${G(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${G(`import { env } from "${e.metadata.importPath}"`)}\n`)):r&&(a+=`
171
171
 
172
- `,e.metadata.layout===`strict`?a+=`Import and use: ${U(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${U(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`Import and use: ${U(`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;if(e.metadata.layout===`strict`){let e=s.lastIndexOf(`.`),t=e===-1?s:s.slice(0,e);s=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}a+=`${o++}. Check ${U(s)} and refine your environment schema.\n`;let c=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${U(`withArkEnv`)} inside ${U(`next.config.ts`)}:\n`,a+=` ${U(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${U(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${U(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${U(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${U(`withArkEnv`)} inside ${U(`next.config.ts`)}:\n`,a+=` ${U(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${U(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${U(`import { env } from "${e.metadata.importPath}"`)}\n`):e.metadata.layout===`strict`?a+=`${o++}. Import and use: ${U(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${U(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`${o++}. Import and use: ${U(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${U(`${r} skills add ${i}`)}\n`,a+=` Then run ${U(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const Lr=[`esbuild`];var Rr=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 ${U(e.clone.example)}...`),await Nr(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 ${U(u.basename(t.path))}: unsupported framework.`);continue}await this.workspace.safeAppend(t.path,t.content,e.bootstrap.framework)?this.reporter.info(`Appended ArkEnv types to ${U(u.basename(t.path))}.`):this.reporter.info(`${U(u.basename(t.path))} already contains ArkEnv types.`);continue}if(!(t.action===`create`&&await this.workspace.exists(t.path))&&(await this.workspace.mkdir(u.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} ${U(u.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 ${U(e.install.packageManager)}...`);let[t,n]=Fr(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 ${U(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${U(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 ${U(u.basename(t))}`):(this.reporter.warn(`Could not automatically update ${U(u.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${U(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${U(`@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(path.dirname(schemaPath), 'generated', '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 ${U(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${U(`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 ${U(u.basename(t))}`),r=!0):(this.reporter.info(`${U(u.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${U(u.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${U(`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 ${U(u.basename(t))}`):this.reporter.info(`${U(u.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${U(u.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${U(`@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=Ir(e,i,r);if(this.reporter.note(a.message,a.title),e.metadata.layout===`strict`){let t=u.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=u.basename(t,u.extname(t));this.reporter.warn(`Found existing single-file schema at ${U(t)}. You can delete it after updating your imports to point to your new ${U(`${n}/client`)} and ${U(`${n}/server`)}.`)}}this.reporter.finish(`${dn} 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})}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=u.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 Lr)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
173
- `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=u.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=ee(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if(S(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),S(n))for(let e of Lr)n.get(e)!==!0&&n.set(e,!0);return String(t)}async configurePackageJsonArkenv(e,t){let n=u.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,layout:t.layout===`strict`?`strict`:`flat`},await this.workspace.writeFile(n,JSON.stringify(r,null,2)+`
174
- `)}catch(e){this.reporter.warn(`Could not update package.json with arkenv schema entry: ${e}`)}}};const zr={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-strict":{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 Br(e,t){return zr[e]??t()}function Vr(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function Hr(e,t,n,r){if(!r||r===`none`)return;let i=q(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 Ur(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 Wr(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 Ur(n))o(e);for(let e of r)o(e);return i}function Gr(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,layout:o,hostPreset:s}=e,{clientPrefix:c}=r,l=[],u=[],d=[];if(t&&t.length>0)for(let e of t)e.startsWith(c)?u.push(`\t\t${n.formatCodegenField(e,`client`,c,s)}`):e===`NODE_ENV`?d.push(`\t\t${n.formatCodegenField(e,`shared`,c,s)}`):l.push(`\t\t${n.formatCodegenField(e,`server`,c,s)}`);else{let e=n.getDefaultCodegenFields(c);l.push(...e.serverFields),u.push(...e.clientFields),d.push(...e.sharedFields),Hr({serverFields:l,clientFields:u},n,c,s)}return o!==`simple`&&o!==`strict`?Kr({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,hostPreset:s}):qr({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,layout:o,hostPreset:s})}function Kr(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=q(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${Fn(l)}`,...i,`\t${In(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=Wr(i,u,n,_);v.push(`\truntimeEnv: {\n${e.join(`
172
+ `,e.metadata.layout===`strict`?a+=`Import and use: ${G(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${G(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`Import and use: ${G(`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;if(e.metadata.layout===`strict`){let e=s.lastIndexOf(`.`),t=e===-1?s:s.slice(0,e);s=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}a+=`${o++}. Check ${G(s)} and refine your environment schema.\n`;let c=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${G(`withArkEnv`)} inside ${G(`next.config.ts`)}:\n`,a+=` ${G(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${G(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${G(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${G(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${G(`withArkEnv`)} inside ${G(`next.config.ts`)}:\n`,a+=` ${G(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${G(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${G(`import { env } from "${e.metadata.importPath}"`)}\n`):e.metadata.layout===`strict`?a+=`${o++}. Import and use: ${G(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${G(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`${o++}. Import and use: ${G(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${G(`${r} skills add ${i}`)}\n`,a+=` Then run ${G(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const $r=[`esbuild`];var ei=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 ${G(e.clone.example)}...`),await Yr(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 ${G(p.basename(t.path))}: unsupported framework.`);continue}await this.workspace.safeAppend(t.path,t.content,e.bootstrap.framework)?this.reporter.info(`Appended ArkEnv types to ${G(p.basename(t.path))}.`):this.reporter.info(`${G(p.basename(t.path))} already contains ArkEnv types.`);continue}if(!(t.action===`create`&&await this.workspace.exists(t.path))&&(await this.workspace.mkdir(p.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} ${G(p.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 ${G(e.install.packageManager)}...`);let[t,n]=Zr(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 ${G(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${G(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 ${G(p.basename(t))}`):(this.reporter.warn(`Could not automatically update ${G(p.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${G(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${G(`@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(path.dirname(schemaPath), 'generated', '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 ${G(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${G(`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 ${G(p.basename(t))}`),r=!0):(this.reporter.info(`${G(p.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${G(p.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${G(`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 ${G(p.basename(t))}`):this.reporter.info(`${G(p.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${G(p.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${G(`@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=Qr(e,i,r);if(this.reporter.note(a.message,a.title),e.metadata.layout===`strict`){let t=p.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=p.basename(t,p.extname(t));this.reporter.warn(`Found existing single-file schema at ${G(t)}. You can delete it after updating your imports to point to your new ${G(`${n}/client`)} and ${G(`${n}/server`)}.`)}}this.reporter.finish(`${Tn} 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})}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=p.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 $r)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
173
+ `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=p.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=D(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if(E(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),E(n))for(let e of $r)n.get(e)!==!0&&n.set(e,!0);return String(t)}async configurePackageJsonArkenv(e,t){let n=p.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,layout:t.layout===`strict`?`strict`:`flat`},await this.workspace.writeFile(n,JSON.stringify(r,null,2)+`
174
+ `)}catch(e){this.reporter.warn(`Could not update package.json with arkenv schema entry: ${e}`)}}};const ti={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-strict":{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 ni(e,t){return ti[e]??t()}function ri(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function ii(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 ai(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 oi(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 ai(n))o(e);for(let e of r)o(e);return i}function si(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,layout:o,hostPreset:s}=e,{clientPrefix:c}=r,l=[],u=[],d=[];if(t&&t.length>0)for(let e of t)e.startsWith(c)?u.push(`\t\t${n.formatCodegenField(e,`client`,c,s)}`):e===`NODE_ENV`?d.push(`\t\t${n.formatCodegenField(e,`shared`,c,s)}`):l.push(`\t\t${n.formatCodegenField(e,`server`,c,s)}`);else{let e=n.getDefaultCodegenFields(c);l.push(...e.serverFields),u.push(...e.clientFields),d.push(...e.sharedFields),ii({serverFields:l,clientFields:u},n,c,s)}return o!==`simple`&&o!==`strict`?ci({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,hostPreset:s}):li({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,layout:o,hostPreset:s})}function ci(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${Xn(l)}`,...i,`\t${Zn(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=oi(i,u,n,_);v.push(`\truntimeEnv: {\n${e.join(`
175
175
  `)}\n\t}`)}let y=v.length>0?`, {\n${v.join(`,
176
176
  `)}\n}`:``;return`${[`import arkenv from "${p===`nuxt`||c?d:s||`./generated/env.gen`}";`,...m?[m]:[]].join(`
177
177
  `)}
@@ -185,10 +185,10 @@ export const env = arkenv({
185
185
  ${g.join(`
186
186
  `)}
187
187
  }${y});
188
- `}function qr(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c,layout:l}=e,{clientPrefix:u,packageName:d,displayName:f}=o,p=o.id,m=a.extraImport,h=[];if(t.length>0&&h.push(`\tserver: {\n${t.join(`
188
+ `}function li(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c,layout:l}=e,{clientPrefix:u,packageName:d,displayName:f}=o,p=o.id,m=a.extraImport,h=[];if(t.length>0&&h.push(`\tserver: {\n${t.join(`
189
189
  `)}\n\t}`),n.length>0&&h.push(`\tclient: {\n${n.join(`
190
190
  `)}\n\t}`),r.length>0&&h.push(`\tshared: {\n${r.join(`
191
- `)}\n\t}`),c||p===`nuxt`&&l===`simple`){let e=Wr(i,u,n);return p!==`nuxt`&&h.push(`\truntimeEnv: {\n${e.join(`
191
+ `)}\n\t}`),c||p===`nuxt`&&l===`simple`){let e=oi(i,u,n);return p!==`nuxt`&&h.push(`\truntimeEnv: {\n${e.join(`
192
192
  `)}\n\t}`),`${[`import arkenv from "${d}";`,...m?[m]:[]].join(`
193
193
  `)}
194
194
 
@@ -213,8 +213,8 @@ export const env = arkenv({
213
213
  ${h.join(`,
214
214
  `)},
215
215
  });
216
- `}function Jr(e,t,n){let r=q(n.hostPreset??`none`,n.clientPrefix),i=fn(n.framework);if(i){let a=t.length>0?Array.from(new Set([...t,...r])):void 0;return`${Gr({...a===void 0?{}:{envKeys:a},dialect:e,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.layout!==void 0&&{layout:n.layout},...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(n.hostPreset&&n.hostPreset!==`none`&&r.length>0){let i=`\t\t${Fn(n.hostPreset)}`,o=`\t\t${In(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 Yr(e,t=` `){return e.length===0?`{}`:`{\n${t}${e.map(e=>e.trim()).join(`\n${t}`)}\n${t.slice(1)}}`}function Xr(e,t,n){let r=[],i=[],a=[],o=[];for(let s of e)s.startsWith(t.clientPrefix)?(i.push(n(s,`client`,t)),o.push(`${s}: process.env.${s},`)):s===`NODE_ENV`?(a.push(n(s,`shared`,t)),o.push(`${s}: process.env.${s},`)):r.push(n(s,`server`,t));return{serverFields:r,clientFields:i,sharedFields:a,runtimeEnvFields:o}}function Zr(e,t){return{shared:`${e.shared}\n`,client:`${ei(t)?e.clientNoCodegen:e.clientCodegen}\n`,server:`${e.server}\n`}}function Qr(e){return e.packageName??fn(e.framework)?.packageName??`@arkenv/nextjs`}function $r(e,t){return t.framework===`nuxt`?``:`,\n\t\truntimeEnv: {\n\t\t\t${e.map(e=>e.trim()).join(`
217
- `)}\n\t\t}`}function ei(e){return e.disableCodegen||e.framework===`nuxt`}function ti(e){return ei(e)?`${Qr(e)}/client`:e.nextjsImportPath||`./generated/env.gen`}function ni(e,t,n){if(!n.hostPreset||n.hostPreset===`none`)return;let r=q(n.hostPreset,n.clientPrefix),i=[],a=[];for(let o of r)n.clientPrefix&&o.startsWith(n.clientPrefix)?(i.push(t.formatStrictField(o,`client`,n.clientPrefix,n.hostPreset)),e.runtimeEnvFields.push(`${o}: process.env.${o},`)):a.push(t.formatStrictField(o,`server`,n.clientPrefix,n.hostPreset));i.length>0&&e.clientFields.push(Fn(`${n.hostPreset}:client`),...i,In(`${n.hostPreset}:client`)),a.length>0&&e.serverFields.push(Fn(`${n.hostPreset}:server`),...a,In(`${n.hostPreset}:server`))}function ri(e,t,n){let r=Qr(n),i=ti(n),a=q(n.hostPreset??`none`,n.clientPrefix),{serverFields:o,clientFields:s,sharedFields:c,runtimeEnvFields:l}=t.length>0?Xr(Array.from(new Set([...t,...a])),n,(t,r)=>e.formatStrictField(t,r,n.clientPrefix,n.hostPreset)):(()=>{let t=e.getDefaultStrictFields(n.clientPrefix);return ni(t,e,n),t})(),u=$r(l,n),d=Yr(c,` `),f=Yr(s,` `),p=Yr(o,` `),m=e.strictExtraImports,h=new Set([`nuxt`,`nextjs`]).has(n.framework),g=`import arkenv from "${i}";
216
+ `}function ui(e,t,n){let r=J(n.hostPreset??`none`,n.clientPrefix),i=Dn(n.framework);if(i){let a=t.length>0?Array.from(new Set([...t,...r])):void 0;return`${si({...a===void 0?{}:{envKeys:a},dialect:e,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.layout!==void 0&&{layout:n.layout},...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(n.hostPreset&&n.hostPreset!==`none`&&r.length>0){let i=`\t\t${Xn(n.hostPreset)}`,o=`\t\t${Zn(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,t=` `){return e.length===0?`{}`:`{\n${t}${e.map(e=>e.trim()).join(`\n${t}`)}\n${t.slice(1)}}`}function fi(e,t,n){let r=[],i=[],a=[],o=[];for(let s of e)s.startsWith(t.clientPrefix)?(i.push(n(s,`client`,t)),o.push(`${s}: process.env.${s},`)):s===`NODE_ENV`?(a.push(n(s,`shared`,t)),o.push(`${s}: process.env.${s},`)):r.push(n(s,`server`,t));return{serverFields:r,clientFields:i,sharedFields:a,runtimeEnvFields:o}}function pi(e,t){return{shared:`${e.shared}\n`,client:`${gi(t)?e.clientNoCodegen:e.clientCodegen}\n`,server:`${e.server}\n`}}function mi(e){return e.packageName??Dn(e.framework)?.packageName??`@arkenv/nextjs`}function hi(e,t){return t.framework===`nuxt`?``:`,\n\t\truntimeEnv: {\n\t\t\t${e.map(e=>e.trim()).join(`
217
+ `)}\n\t\t}`}function gi(e){return e.disableCodegen||e.framework===`nuxt`}function _i(e){return gi(e)?`${mi(e)}/client`:e.nextjsImportPath||`./generated/env.gen`}function vi(e,t,n){if(!n.hostPreset||n.hostPreset===`none`)return;let r=J(n.hostPreset,n.clientPrefix),i=[],a=[];for(let o of r)n.clientPrefix&&o.startsWith(n.clientPrefix)?(i.push(t.formatStrictField(o,`client`,n.clientPrefix,n.hostPreset)),e.runtimeEnvFields.push(`${o}: process.env.${o},`)):a.push(t.formatStrictField(o,`server`,n.clientPrefix,n.hostPreset));i.length>0&&e.clientFields.push(Xn(`${n.hostPreset}:client`),...i,Zn(`${n.hostPreset}:client`)),a.length>0&&e.serverFields.push(Xn(`${n.hostPreset}:server`),...a,Zn(`${n.hostPreset}:server`))}function yi(e,t,n){let r=mi(n),i=_i(n),a=J(n.hostPreset??`none`,n.clientPrefix),{serverFields:o,clientFields:s,sharedFields:c,runtimeEnvFields:l}=t.length>0?fi(Array.from(new Set([...t,...a])),n,(t,r)=>e.formatStrictField(t,r,n.clientPrefix,n.hostPreset)):(()=>{let t=e.getDefaultStrictFields(n.clientPrefix);return vi(t,e,n),t})(),u=hi(l,n),d=di(c,` `),f=di(s,` `),p=di(o,` `),m=e.strictExtraImports,h=new Set([`nuxt`,`nextjs`]).has(n.framework),g=`import arkenv from "${i}";
218
218
  ${m}
219
219
  export const env = arkenv(
220
220
  ${f},
@@ -234,7 +234,7 @@ export const env = arkenv(
234
234
  {
235
235
  extends: [SharedSchema]${u}
236
236
  },
237
- );`,y=n.framework===`nuxt`?"/**\n * @internal 🛑 INTERNAL SCHEMA ONLY.\n * Do not import this directly. Import `env` from `./client` or `./server` instead.\n * Automatically picked up by `@arkenv/nuxt/client` when `extends` is omitted;\n * `@arkenv/nuxt/server` includes it through the composed client env.\n */":"/**\n * @internal 🛑 INTERNAL SCHEMA ONLY.\n * Do not import this directly. Import `env` from `./client` or `./server` instead.\n */";return Zr({shared:`${e.sharedImports}
237
+ );`,y=n.framework===`nuxt`?"/**\n * @internal 🛑 INTERNAL SCHEMA ONLY.\n * Do not import this directly. Import `env` from `./client` or `./server` instead.\n * Automatically picked up by `@arkenv/nuxt/client` when `extends` is omitted;\n * `@arkenv/nuxt/server` includes it through the composed client env.\n */":"/**\n * @internal 🛑 INTERNAL SCHEMA ONLY.\n * Do not import this directly. Import `env` from `./client` or `./server` instead.\n */";return pi({shared:`${e.sharedImports}
238
238
 
239
239
  ${y}
240
240
  export const SharedSchema = ${e.wrapSharedSchema(d)};`,clientCodegen:n.framework===`nuxt`?g:_,clientNoCodegen:n.framework===`nuxt`?g:v,server:h?`import arkenv from "${r}/server";
@@ -249,9 +249,9 @@ export const env = arkenv(
249
249
  {
250
250
  extends: [clientEnv],
251
251
  },
252
- );`},n)}function ii(e){return{formatField(t,n,r){return e.formatStrictField(t,n,r.clientPrefix,r.hostPreset)},getSimpleTemplate(t,n){return Jr(e,t,n)},getStrictTemplates(t,n){return ri(e,t,n)}}}const ai={arktype:ii(Y.arktype),zod:ii(Y.zod),valibot:ii(Y.valibot)};function oi(e){return e.mode===`new`?pi(e):mi(e)}function si(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 ci(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
252
+ );`},n)}function bi(e){return{formatField(t,n,r){return e.formatStrictField(t,n,r.clientPrefix,r.hostPreset)},getSimpleTemplate(t,n){return ui(e,t,n)},getStrictTemplates(t,n){return yi(e,t,n)}}}const xi={arktype:bi(nr.arktype),zod:bi(nr.zod),valibot:bi(nr.valibot)};function Si(e){return e.mode===`new`?ki(e):Ai(e)}function Ci(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 wi(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
253
253
  `)+`
254
- `}function li(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=kn[r.framework],o=u.join(n,`.env`),s=u.join(n,`.env.example`),c=i.includes(o),l=i.includes(s),d=Pn(r.envKeys,r.hostPreset,a.clientPrefix);if(!c){let e=r.envExampleContent===void 0?ci(a.getEnvDefaults(d)):r.envExampleContent;t.files.push({path:o,content:e,action:`create`,label:`local environment variables`})}l||t.files.push({path:s,content:ci(a.getEnvDefaults(d)),action:`create`,label:`environment variables template`})}function ui(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=u.join(n,`.gitignore`),o=i.includes(a);if(o&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=si(e,`.env`),i=si(e,`.env.local`);if(!n||!i){let e=`
254
+ `}function Ti(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=Wn[r.framework],o=p.join(n,`.env`),s=p.join(n,`.env.example`),c=i.includes(o),l=i.includes(s),u=Yn(r.envKeys,r.hostPreset,a.clientPrefix);if(!c){let e=r.envExampleContent===void 0?wi(a.getEnvDefaults(u)):r.envExampleContent;t.files.push({path:o,content:e,action:`create`,label:`local environment variables`})}l||t.files.push({path:s,content:wi(a.getEnvDefaults(u)),action:`create`,label:`environment variables template`})}function Ei(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=p.join(n,`.gitignore`),o=i.includes(a);if(o&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=Ci(e,`.env`),i=Ci(e,`.env.local`);if(!n||!i){let e=`
255
255
  # Environment variables
256
256
  `;n||(e+=`.env
257
257
  `),i||(e+=`.env.local
@@ -259,5 +259,5 @@ export const env = arkenv(
259
259
  `)?`${r.gitignoreContent}${e.trim()}\n`:`${r.gitignoreContent}\n${e.trim()}\n`;t.files.push({path:a,content:o,action:`overwrite`,label:`.gitignore update`})}}else o||t.files.push({path:a,content:`# Environment variables
260
260
  .env
261
261
  .env.local
262
- `,action:`create`,label:`.gitignore file`})}function di(e){let{mode:n,options:r,packageManager:i}=e,a=r.name&&r.name!==`.`?u.basename(r.name):void 0;return t({displayPath:``,framework:r.framework,validator:r.validator,packageManager:i,importPath:``,mode:n,example:r.example,name:a,layout:r.layout,skillDetected:r.skillDetected,disableCodegen:r.disableCodegen})}function fi(e,t){e.options.installSkill&&(t.skill={dlxCommand:Vr(e.packageManager),packageName:`yamcodes/arkenv`,isYes:e.isYes})}function pi(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!==`.`?u.join(r,t.name):void 0,a=t.name&&t.name!==`.`?u.basename(t.name):u.basename(r),o={files:[],cwd:r,metadata:di(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}}};fi(e,o);let s=ci(Br(t.example,()=>kn[t.framework].getEnvDefaults())),c=i??r;return o.files.push({path:u.join(c,`.env`),content:s,action:`create`,label:`local environment variables`},{path:u.join(c,`.env.example`),content:s,action:`create`,label:`environment variables template`}),o.metadata.displayPath=`./src/env.ts`,o.metadata.importPath=`./src/env`,o}function mi(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,s=kn[t.framework],c=ai[t.validator],l=u.resolve(a,t.path),d=u.dirname(l),f={files:[],cwd:a,metadata:di(e)},p={targetPath:l,targetDir:d,cwd:a,existingFiles:o,overwriteEnvSchemaFile:t.overwriteEnvSchemaFile,path:t.path,tsConfig:r};f.files.push(...s.getSchemaFiles(c,t,p)),li(e,f),ui(e,f);let m=t.framework===`nextjs`||t.framework===`nuxt`?void 0:t.validator===`arktype`?`@arkenv/core`:`@arkenv/standard`,h=[...m?[m]:[],t.validator,...s.getDependencies(t)];s.requiresArktypePeer(t)&&!h.includes(`arktype`)&&h.push(`arktype`),f.install={packageManager:n,dependencies:Array.from(new Set(h))},i&&r.file&&(f.tsConfig={path:u.resolve(a,r.file),action:`strict`}),f.files.push(...s.getTypeDefinitionFiles(t,p));let g=s.bootstrap(t);g&&(f.bootstrap=g),fi(e,f);let _=u.relative(a,l).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 hi=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`}]}}}},gi=class{constructor(e,t,n,r,i=new hi){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=oi(t),r=new Rr(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&u.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?u.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 ${U(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${U(`arkenv init`)} in an empty directory or use ${U(`--force`)} to proceed anyway.`),this.logger.refuse({code:k.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,retryWith:[`--force`]}),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:r,isForce:i,isQuiet:a,isAgent:o}=e,s=await this.scanner.checkRequirements(n),c=s.filter(e=>e.status===`fail`),l=s.filter(e=>e.status===`warn`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`);if(c.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of c)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of c)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:k.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,retryWith:[`--force`],details:{requirements:c.map(e=>t({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}}),null}let d=await this.scanner.checkGitStatus(n);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:k.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,retryWith:[`--force`]}),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(n);if(p.status===`not_strict`)if(r)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${U(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${U(`strict`)} mode in your ${U(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(n,p.parsed);if(e.isSimple&&m===`nextjs`)return this.logger.error(`❌ Error: The --simple layout is deprecated and no longer supported by the CLI. Arkenv now exclusively uses the Flat Layout. Run npx arkenv init without this flag.`),null;let h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(n,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(n,p.parsed),_=u.resolve(n,g),v=await this.scanner.getEnvExampleKeys(n,p.parsed,_),y=await(async()=>{if(e.isStrict){let e=u.extname(_),t=_.slice(0,-e.length),n=[u.join(t,`internal`,`shared${e}`),u.join(t,`client${e}`),u.join(t,`server${e}`)];if((await Promise.all(n.map(e=>this.workspace.exists(e)))).some(Boolean))return!0}return this.workspace.exists(_)})(),b=await this.prompt.runWizard(t({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:p.parsed??null,envKeys:v?.keys,envKeysSource:v?.source,hasEnvSchemaFile:y,isStrict:e.isStrict,isSimple:e.isSimple,isFlat:e.isFlat,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),r);if(b===null)return null;let x=await this.scanner.hasSkill(n);if(x&&(b.skillDetected=!0,!a&&!o&&this.logger.info(`ArkEnv agent skill detected.`)),x)b.installSkill=!1;else if(o)b.installSkill=!1;else if(r)b.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;b.installSkill=e}let S=u.resolve(n,b.path);if(b.overwriteEnvSchemaFile===void 0&&(b.layout===`strict`?await(async()=>{let e=u.extname(S),t=S.slice(0,-e.length);return(await Promise.all([this.workspace.exists(u.join(t,`internal`,`shared${e}`)),this.workspace.exists(u.join(t,`client${e}`)),this.workspace.exists(u.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(S))){let e=b.layout===`strict`?`Strict layout files (client, server, internal/shared)`:u.basename(S),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;b.overwriteEnvSchemaFile=t}let ee=await this.scanner.detectPackageManager(n,p.parsed),C=u.extname(S),w=S.slice(0,-C.length),te=b.layout===`strict`?[u.join(w,`internal`,`shared${C}`),u.join(w,`client${C}`),u.join(w,`server${C}`)]:[S],T=[];for(let e of te)await this.workspace.exists(e)&&T.push(e);let ne=u.join(n,`.env`),E=u.join(n,`.env.example`);await this.workspace.exists(ne)&&T.push(ne),await this.workspace.exists(E)&&(T.push(E),b.envExampleContent=await this.workspace.readFile(E));let D=u.join(n,`.gitignore`);return await this.workspace.exists(D)&&(T.push(D),b.gitignoreContent=await this.workspace.readFile(D)),t({mode:`existing`,cwd:n,options:b,detectedFramework:m,detectedBunFeatures:h,packageManager:ee,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:T,isYes:r})}async collectNewProject(e,n=!0){let{isYes:r,example:i,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard(t({mode:`new`,examples:s.examples,example:i,name:a}),r);if(c===null)return null;if(c.name===`.`&&!n&&!o)return this.logger.error(`Cannot scaffold into ${U(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${U(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:k.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,retryWith:[`--force`]}),null;let l=this.detectPackageManager();return t({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 _i(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 vi=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:k.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,retryWith:[`--force`]}),!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(K).map(([e,t])=>({value:e,label:t.label,hint:t.hint})),`vercel`);if(n&&n!==`none`)r=n;else return!1}let i=K[r]?.label||r,a=await this.discoverSchema(t,e.file);if(!a)return!1;let o=(await this.scanner.checkTsConfig(t)).parsed||null,s=await this.scanner.detectFramework(t,o),c=G[s]||``,l=q(r,c);if(e.action===`apply`){if(a.layout===`strict`){let e=u.join(a.dir,`client.ts`),n=u.join(a.dir,`server.ts`),o=u.relative(t,e),d=u.relative(t,n);if(!await this.workspace.exists(e)||!await this.workspace.exists(n))return this.logger.error(`Strict layout files not found in ${u.relative(t,a.dir)}.`),!1;let f=await this.workspace.readFile(e),p=await this.workspace.readFile(n),m=_i(f),h=_i(p),{clientKeys:g,serverKeys:_}=Mn(r,c),v=Zn(f,{preset:r,framework:s,validator:m,markerId:`${r}:client`,targetKeys:g}),y=Zn(p,{preset:r,framework:s,validator:h,markerId:`${r}:server`,targetKeys:_});if(!v.success||!v.code)return this.logger.error(v.error||`Failed to apply preset to ${o}.`),!1;if(!y.success||!y.code)return this.logger.error(y.error||`Failed to apply preset to ${d}.`),!1;let b=!1;return v.updated&&(await this.workspace.writeFile(e,v.code),b=!0),y.updated&&(await this.workspace.writeFile(n,y.code),b=!0),typeof this.workspace.appendMissingEnvExampleKeys==`function`&&await this.workspace.appendMissingEnvExampleKeys(t,l),b?this.logger.success(`Applied ${i} preset to ${o} and ${d}`):this.logger.info(`${i} preset is already up-to-date in ${o} and ${d}`),!0}let e=a.filePath,n=u.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),d=_i(o),f=Zn(o,{preset:r,framework:s,validator:d});return!f.success||!f.code?(this.logger.error(f.error||`Failed to apply preset to ${n}.`),!1):(f.updated?(await this.workspace.writeFile(e,f.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,l),!0)}if(a.layout===`strict`){let e=u.join(a.dir,`client.ts`),n=u.join(a.dir,`server.ts`),o=u.relative(t,e),s=u.relative(t,n);if(!await this.workspace.exists(e)||!await this.workspace.exists(n))return this.logger.error(`Strict layout files not found in ${u.relative(t,a.dir)}.`),!1;let c=await this.workspace.readFile(e),l=await this.workspace.readFile(n),d=er(c,{preset:r}),f=er(l,{preset:r});if(!d.success||!d.code)return this.logger.error(d.error||`Failed to remove preset from ${o}.`),!1;if(!f.success||!f.code)return this.logger.error(f.error||`Failed to remove preset from ${s}.`),!1;let p=!1,m=[];if(d.updated&&(await this.workspace.writeFile(e,d.code),p=!0,d.removedKeys&&m.push(...d.removedKeys)),f.updated&&(await this.workspace.writeFile(n,f.code),p=!0,f.removedKeys&&m.push(...f.removedKeys)),p){let e=X(d.code||c),n=e.success?e.blocks:[],r=X(f.code||l),a=r.success?r.blocks:[],u=[...n.flatMap(e=>e.keys),...a.flatMap(e=>e.keys)];typeof this.workspace.removeEnvExampleKeys==`function`&&await this.workspace.removeEnvExampleKeys(t,m,u),this.logger.success(`Removed ${i} preset from ${o} and ${s}`)}else this.logger.info(`${i} preset was not present in ${o} and ${s}`);return!0}let d=a.filePath,f=u.relative(t,d);if(!await this.workspace.exists(d))return this.logger.error(`Schema file not found at ${f}.`),!1;let p=er(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=X(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){let n=u.resolve(e,t),r=u.join(n,`client.ts`),i=u.join(n,`server.ts`);return await this.workspace.exists(r)&&await this.workspace.exists(i)?{layout:`strict`,dir:n}:{layout:`flat`,filePath:n}}if(typeof this.scanner.readArkenvConfig==`function`){let t=await this.scanner.readArkenvConfig(e);if(t){let n=u.resolve(e,t.schema);return t.layout===`strict`?{layout:`strict`,dir:n}:{layout:`flat`,filePath:n}}}let n=[u.resolve(e,`env`),u.resolve(e,`src/env`)];for(let e of n)if(await this.workspace.exists(u.join(e,`client.ts`))&&await this.workspace.exists(u.join(e,`server.ts`)))return{layout:`strict`,dir:e};let r=[u.resolve(e,`env.ts`),u.resolve(e,`src/env.ts`)];for(let e of r)if(await this.workspace.exists(e))return{layout:`flat`,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 yi(e){let t=new kr(e),n=t.logger,r=new ur(t.isQuiet,n.stdio,n),i=new Er,a=new un(n);return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new gi(n,r,i,a),presetUseCase:new vi(n,r,i,a),helpUseCase:new Mr(n)}}const bi=new xt({isQuiet:!1,isJson:!1});let xi,Si=!1;async function Ci(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,presetUseCase:i,helpUseCase:a}=yi(process.argv);xi=n,wi(n),e.validationError&&(n.error(e.validationError),await a.execute(),await n.flush(),process.exit(1)),e.helpRequested&&(await a.execute(),await n.flush(),process.exit(0));let o=e.command?{init:()=>r.execute(t(e.initInput)),preset:()=>i.execute(e.presetInput)}[e.command]:void 0;o||(e.command?n.error(`Unknown command: ${e.command}`):n.error(`Missing command.`),await a.execute(),await n.flush(),process.exit(1));try{await o()||(await n.flush(),process.exit(1))}catch(e){try{n.fatal(`An unexpected error occurred`,e)}catch{}await n.flush(),process.exit(1)}}function wi(e){let t=async t=>{Si&&process.exit(t),Si=!0,setTimeout(()=>{process.exit(t)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(t)}};process.on(`SIGINT`,()=>t(130)),process.on(`SIGTERM`,()=>t(143))}Ci(),process.on(`unhandledRejection`,async e=>{let t=xi??bi;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=xi??bi;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});export{};
262
+ `,action:`create`,label:`.gitignore file`})}function Di(e){let{mode:t,options:n,packageManager:r}=e,a=n.name&&n.name!==`.`?p.basename(n.name):void 0;return i({displayPath:``,framework:n.framework,validator:n.validator,packageManager:r,importPath:``,mode:t,example:n.example,name:a,layout:n.layout,skillDetected:n.skillDetected,disableCodegen:n.disableCodegen})}function Oi(e,t){e.options.installSkill&&(t.skill={dlxCommand:ri(e.packageManager),packageName:`yamcodes/arkenv`,isYes:e.isYes})}function ki(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!==`.`?p.join(r,t.name):void 0,a=t.name&&t.name!==`.`?p.basename(t.name):p.basename(r),o={files:[],cwd:r,metadata:Di(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}}};Oi(e,o);let s=wi(ni(t.example,()=>Wn[t.framework].getEnvDefaults())),c=i??r;return o.files.push({path:p.join(c,`.env`),content:s,action:`create`,label:`local environment variables`},{path:p.join(c,`.env.example`),content:s,action:`create`,label:`environment variables template`}),o.metadata.displayPath=`./src/env.ts`,o.metadata.importPath=`./src/env`,o}function Ai(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,s=Wn[t.framework],c=xi[t.validator],l=p.resolve(a,t.path),u=p.dirname(l),d={files:[],cwd:a,metadata:Di(e)},f={targetPath:l,targetDir:u,cwd:a,existingFiles:o,overwriteEnvSchemaFile:t.overwriteEnvSchemaFile,path:t.path,tsConfig:r};d.files.push(...s.getSchemaFiles(c,t,f)),Ti(e,d),Ei(e,d);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`]:[],...s.getDependencies(t)];s.requiresArktypePeer(t)&&!h.includes(`arktype`)&&h.push(`arktype`),d.install={packageManager:n,dependencies:Array.from(new Set(h))},i&&r.file&&(d.tsConfig={path:p.resolve(a,r.file),action:`strict`}),d.files.push(...s.getTypeDefinitionFiles(t,f));let g=s.bootstrap(t);g&&(d.bootstrap=g),Oi(e,d);let _=p.relative(a,l).replace(/\\/g,`/`),v=_.startsWith(`.`)?_:`./${_}`,y=v.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=v,d.metadata.importPath=y,d.bootstrap&&(d.bootstrap.importPath=y),d}var ji=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`}]}}}},Mi=class{constructor(e,t,n,r,i=new ji){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=Si(t),r=new ei(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&p.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?p.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 ${G(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${G(`arkenv init`)} in an empty directory or use ${G(`--force`)} to proceed anyway.`),this.logger.refuse({code:j.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,retryWith:[`--force`]}),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,t){let{isYes:n,isForce:r,isQuiet:a,isAgent:o}=e,s=await this.scanner.checkRequirements(t),c=s.filter(e=>e.status===`fail`),l=s.filter(e=>e.status===`warn`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`);if(c.length>0)if(r){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of c)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of c)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:j.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,retryWith:[`--force`],details:{requirements:c.map(e=>i({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}}),null}let u=await this.scanner.checkGitStatus(t);if(u.status===`dirty`)if(r)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:j.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,retryWith:[`--force`]}),null;u.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let d=!1,f=await this.scanner.checkTsConfig(t);if(f.status===`not_strict`)if(n)d=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${G(f.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${G(`strict`)} mode in your ${G(f.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;d=!0}let m=await this.scanner.detectFramework(t,f.parsed);if(e.isSimple&&m===`nextjs`)return this.logger.error(`❌ Error: The --simple layout is deprecated and no longer supported by the CLI. Arkenv now exclusively uses the Flat Layout. Run npx arkenv init without this flag.`),null;let h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(t,f.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(t,f.parsed),_=p.resolve(t,g),v=await this.scanner.getEnvExampleKeys(t,f.parsed,_),y=await(async()=>{if(e.isStrict){let e=p.extname(_),t=_.slice(0,-e.length),n=[p.join(t,`internal`,`shared${e}`),p.join(t,`client${e}`),p.join(t,`server${e}`)];if((await Promise.all(n.map(e=>this.workspace.exists(e)))).some(Boolean))return!0}return this.workspace.exists(_)})(),b=await this.prompt.runWizard(i({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:f.parsed??null,envKeys:v?.keys,envKeysSource:v?.source,hasEnvSchemaFile:y,isStrict:e.isStrict,isSimple:e.isSimple,isFlat:e.isFlat,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),n);if(b===null)return null;let x=await this.scanner.hasSkill(t);if(x&&(b.skillDetected=!0,!a&&!o&&this.logger.info(`ArkEnv agent skill detected.`)),x)b.installSkill=!1;else if(o)b.installSkill=!1;else if(n)b.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;b.installSkill=e}let S=p.resolve(t,b.path);if(b.overwriteEnvSchemaFile===void 0&&(b.layout===`strict`?await(async()=>{let e=p.extname(S),t=S.slice(0,-e.length);return(await Promise.all([this.workspace.exists(p.join(t,`internal`,`shared${e}`)),this.workspace.exists(p.join(t,`client${e}`)),this.workspace.exists(p.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(S))){let e=b.layout===`strict`?`Strict layout files (client, server, internal/shared)`:p.basename(S),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;b.overwriteEnvSchemaFile=t}let C=await this.scanner.detectPackageManager(t,f.parsed),w=p.extname(S),T=S.slice(0,-w.length),E=b.layout===`strict`?[p.join(T,`internal`,`shared${w}`),p.join(T,`client${w}`),p.join(T,`server${w}`)]:[S],D=[];for(let e of E)await this.workspace.exists(e)&&D.push(e);let ee=p.join(t,`.env`),O=p.join(t,`.env.example`);await this.workspace.exists(ee)&&D.push(ee),await this.workspace.exists(O)&&(D.push(O),b.envExampleContent=await this.workspace.readFile(O));let k=p.join(t,`.gitignore`);return await this.workspace.exists(k)&&(D.push(k),b.gitignoreContent=await this.workspace.readFile(k)),i({mode:`existing`,cwd:t,options:b,detectedFramework:m,detectedBunFeatures:h,packageManager:C,tsConfig:f,shouldUpdateTsConfig:d,existingFiles:D,isYes:n})}async collectNewProject(e,t=!0){let{isYes:n,example:r,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard(i({mode:`new`,examples:s.examples,example:r,name:a}),n);if(c===null)return null;if(c.name===`.`&&!t&&!o)return this.logger.error(`Cannot scaffold into ${G(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${G(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:j.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,retryWith:[`--force`]}),null;let l=this.detectPackageManager();return i({mode:`new`,cwd:process.cwd(),options:c,detectedFramework:c.framework,packageManager:l,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:n})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function Ni(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 Pi=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:j.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,retryWith:[`--force`]}),!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,s=await this.scanner.detectFramework(t,o),c=K[s]||``,l=J(r,c);if(e.action===`apply`){if(a.layout===`strict`){let e=p.join(a.dir,`client.ts`),n=p.join(a.dir,`server.ts`),o=p.relative(t,e),u=p.relative(t,n);if(!await this.workspace.exists(e)||!await this.workspace.exists(n))return this.logger.error(`Strict layout files not found in ${p.relative(t,a.dir)}.`),!1;let d=await this.workspace.readFile(e),f=await this.workspace.readFile(n),m=Ni(d),h=Ni(f),{clientKeys:g,serverKeys:_}=qn(r,c),v=pr(d,{preset:r,framework:s,validator:m,markerId:`${r}:client`,targetKeys:g}),y=pr(f,{preset:r,framework:s,validator:h,markerId:`${r}:server`,targetKeys:_});if(!v.success||!v.code)return this.logger.error(v.error||`Failed to apply preset to ${o}.`),!1;if(!y.success||!y.code)return this.logger.error(y.error||`Failed to apply preset to ${u}.`),!1;let b=!1;return v.updated&&(await this.workspace.writeFile(e,v.code),b=!0),y.updated&&(await this.workspace.writeFile(n,y.code),b=!0),typeof this.workspace.appendMissingEnvExampleKeys==`function`&&await this.workspace.appendMissingEnvExampleKeys(t,l),b?this.logger.success(`Applied ${i} preset to ${o} and ${u}`):this.logger.info(`${i} preset is already up-to-date in ${o} and ${u}`),!0}let e=a.filePath,n=p.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),u=Ni(o),d=pr(o,{preset:r,framework:s,validator:u});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,l),!0)}if(a.layout===`strict`){let e=p.join(a.dir,`client.ts`),n=p.join(a.dir,`server.ts`),o=p.relative(t,e),s=p.relative(t,n);if(!await this.workspace.exists(e)||!await this.workspace.exists(n))return this.logger.error(`Strict layout files not found in ${p.relative(t,a.dir)}.`),!1;let c=await this.workspace.readFile(e),l=await this.workspace.readFile(n),u=gr(c,{preset:r}),d=gr(l,{preset:r});if(!u.success||!u.code)return this.logger.error(u.error||`Failed to remove preset from ${o}.`),!1;if(!d.success||!d.code)return this.logger.error(d.error||`Failed to remove preset from ${s}.`),!1;let f=!1,m=[];if(u.updated&&(await this.workspace.writeFile(e,u.code),f=!0,u.removedKeys&&m.push(...u.removedKeys)),d.updated&&(await this.workspace.writeFile(n,d.code),f=!0,d.removedKeys&&m.push(...d.removedKeys)),f){let e=X(u.code||c),n=e.success?e.blocks:[],r=X(d.code||l),a=r.success?r.blocks:[],f=[...n.flatMap(e=>e.keys),...a.flatMap(e=>e.keys)];typeof this.workspace.removeEnvExampleKeys==`function`&&await this.workspace.removeEnvExampleKeys(t,m,f),this.logger.success(`Removed ${i} preset from ${o} and ${s}`)}else this.logger.info(`${i} preset was not present in ${o} and ${s}`);return!0}let u=a.filePath,d=p.relative(t,u);if(!await this.workspace.exists(u))return this.logger.error(`Schema file not found at ${d}.`),!1;let f=gr(await this.workspace.readFile(u),{preset:r});if(!f.success||!f.code)return this.logger.error(f.error||`Failed to remove preset from ${d}.`),!1;if(f.updated){await this.workspace.writeFile(u,f.code);let e=X(f.code),n=(e.success?e.blocks:[]).flatMap(e=>e.keys);typeof this.workspace.removeEnvExampleKeys==`function`&&await this.workspace.removeEnvExampleKeys(t,f.removedKeys||[],n),this.logger.success(`Removed ${i} preset from ${d}`)}else this.logger.info(`${i} preset was not present in ${d}`);return!0}finally{this.logger.interactiveStdout(!1)}}async discoverSchema(e,t){if(t){let n=p.resolve(e,t),r=p.join(n,`client.ts`),i=p.join(n,`server.ts`);return await this.workspace.exists(r)&&await this.workspace.exists(i)?{layout:`strict`,dir:n}:{layout:`flat`,filePath:n}}if(typeof this.scanner.readArkenvConfig==`function`){let t=await this.scanner.readArkenvConfig(e);if(t){let n=p.resolve(e,t.schema);return t.layout===`strict`?{layout:`strict`,dir:n}:{layout:`flat`,filePath:n}}}let n=[p.resolve(e,`env`),p.resolve(e,`src/env`)];for(let e of n)if(await this.workspace.exists(p.join(e,`client.ts`))&&await this.workspace.exists(p.join(e,`server.ts`)))return{layout:`strict`,dir:e};let r=[p.resolve(e,`env.ts`),p.resolve(e,`src/env.ts`)];for(let e of r)if(await this.workspace.exists(e))return{layout:`flat`,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 Fi(e){let t=new Gr(e),n=t.logger,r=new Er(t.isQuiet,n.stdio,n),i=new Hr,a=new wn(n),o=new nn;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new Mi(n,r,i,a),presetUseCase:new Pi(n,r,i,a),helpUseCase:new Jr(n),schemaLoader:o}}const Ii=new Ct({isQuiet:!1,isJson:!1});let Li,Ri=!1;async function zi(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:t,initUseCase:n,presetUseCase:r,helpUseCase:a}=Fi(process.argv);Li=t,Bi(t),e.validationError&&(t.error(e.validationError),await a.execute(),await t.flush(),process.exit(1)),e.helpRequested&&(await a.execute(),await t.flush(),process.exit(0));let o=e.command?{init:()=>n.execute(i(e.initInput)),preset:()=>r.execute(e.presetInput)}[e.command]:void 0;o||(e.command?t.error(`Unknown command: ${e.command}`):t.error(`Missing command.`),await a.execute(),await t.flush(),process.exit(1));try{await o()||(await t.flush(),process.exit(1))}catch(e){try{t.fatal(`An unexpected error occurred`,e)}catch{}await t.flush(),process.exit(1)}}function Bi(e){let t=async t=>{Ri&&process.exit(t),Ri=!0,setTimeout(()=>{process.exit(t)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(t)}};process.on(`SIGINT`,()=>t(130)),process.on(`SIGTERM`,()=>t(143))}zi(),process.on(`unhandledRejection`,async e=>{let t=Li??Ii;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=Li??Ii;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});export{};
263
263
  //# sourceMappingURL=bin.js.map