arkenv 1.0.0-rc.2 → 1.0.0-rc.3
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.d.ts +1 -1
- package/dist/bin.js +82 -102
- package/dist/{dist-CsNQC_OA.js → dist-waSn9fHo.js} +2 -2
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/dist/bin.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
package/dist/bin.js
CHANGED
|
@@ -1,130 +1,110 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as e,c as t,i as n,l as r,n as i,o as a,s as o,t as s}from"./dist-CsNQC_OA.js";import{createRequire as c}from"node:module";import{shake as l}from"radashi";import{stripVTControlCharacters as u,styleText as d}from"node:util";import f,{stdin as p,stdout as m}from"node:process";import*as h from"node:readline";import g from"node:readline";import{ReadStream as _}from"node:tty";import"node:fs";import v from"node:path";import{createJiti as y}from"jiti";import{execSync as b,spawn as x}from"node:child_process";import S from"node:fs/promises";import{applyEdits as C,modify as w,parse as T}from"jsonc-parser";import E from"dedent";import{builders as D,detectCodeFormat as O,generateCode as k,parseModule as A}from"magicast";import{isMap as ee,parseDocument as te}from"yaml";var ne=Object.create,re=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,ae=Object.getOwnPropertyNames,oe=Object.getPrototypeOf,se=Object.prototype.hasOwnProperty,ce=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),le=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ae(t),a=0,o=i.length,s;a<o;a++)s=i[a],!se.call(e,s)&&s!==n&&re(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ie(t,s))||r.enumerable});return e},j=((e,t,n)=>(n=e==null?{}:ne(oe(e)),le(t||!e||!e.__esModule?re(n,`default`,{value:e,enumerable:!0}):n,e)))(ce(((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 M={REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,INTERNAL:`CLI.INTERNAL_ERROR`,SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CANCELLED:`CLI.CANCELLED`,UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,INVALID_VALUE:`ENV.INVALID_VALUE`,MISSING_VARIABLE:`ENV.MISSING_VARIABLE`},N={CLI_INTERNAL_ERROR:`CLI.INTERNAL_ERROR`,CLI_SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CLI_REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,CLI_GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,CLI_NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,CLI_CANCELLED:`CLI.CANCELLED`,CLI_UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,CLI_INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,ENV_VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,ENV_INVALID_VALUE:`ENV.INVALID_VALUE`,ENV_MISSING_VARIABLE:`ENV.MISSING_VARIABLE`};function ue(){let e=process.env.npm_config_user_agent||``;if(e.includes(`pnpm`))return process.env.npm_command===`dlx`?`pnpm dlx arkenv`:`pnpm arkenv`;if(e.includes(`bun`))return(process.env._||process.argv[1]||``).includes(`bunx`)||process.env.npm_command===`x`?`bunx arkenv`:`bun arkenv`;if(e.includes(`yarn`))return process.env.npm_command===`dlx`?`yarn dlx arkenv`:`yarn arkenv`;if(e.includes(`npm`))return`npx arkenv`;let t=process.env._||process.argv[1]||``;return t.includes(`npx`)?`npx arkenv`:t.includes(`bunx`)?`bunx arkenv`:t.includes(`pnpm`)?`pnpm arkenv`:t.includes(`yarn`)?`yarn arkenv`:t.includes(`bun`)?`bun arkenv`:`arkenv`}function de(e,t=ue()){return e.replace(/\{bin\}/g,t)}function fe(e,t=ue()){let n={...e};return n.command&&=de(n.command,t),n.commands&&=n.commands.map(e=>de(e,t)),n}function pe(e){return e.replace(/\x1B\[\d+m/g,``).replace(/\x1B\[[0-9;]*[a-zA-Z]/g,``)}function P(e,t,n){let i=pe(e);return n?.debugSecrets||o(n?.debugSecrets)?i:t&&r(t)?i.replace(/\(was .*\)/g,`(was [REDACTED])`):i}var me=class{info(e){process.stderr.write(`${j.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${j.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${j.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${j.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${j.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${j.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${j.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${j.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}reportCompleted(e){let t=e.diagnostics.map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>fe(e))})),n=(e.nextActions??[]).map(e=>fe(e));this.json({ok:!0,commandId:e.commandId,result:e.result,exitCode:e.exitCode,diagnostics:t,nextActions:n})}reportErrored(e){let t=(e.error.nextActions??[]).map(e=>fe(e)),n=(e.nextActions??t).map(e=>fe(e)),r=(e.diagnostics??[]).map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>fe(e))}));this.json({ok:!1,commandId:e.commandId,error:{...e.error,nextActions:t},diagnostics:r,nextActions:n})}cancel(e,t=`cli`){this.reportErrored({ok:!1,commandId:t,error:{code:M.CANCELLED,severity:`info`,summary:P(e),nextActions:[]},diagnostics:[],nextActions:[]})}fatal(e,t,n=`cli`){let r=t instanceof Error?t.message:t?String(t):void 0;throw this.reportErrored({ok:!1,commandId:n,error:{code:M.INTERNAL,severity:`error`,summary:P(e),...r===void 0?{}:{why:P(r)},...r===void 0?{}:{meta:{error:r}},nextActions:[]},diagnostics:[],nextActions:[]}),t instanceof Error?t:Error(e)}refuse(e,t=`init`){let n=e.nextActions??(e.retryWith?.includes(`--force`)?[{kind:`run-command`,label:`Re-run with --force to bypass this check`,command:`{bin} ${t} --force`}]:[]);this.reportErrored({ok:!1,commandId:t,error:{code:e.code,severity:`error`,summary:P(e.message),...e.why?{why:P(e.why)}:{},...e.details===void 0?{}:{meta:e.details},nextActions:n},diagnostics:[],nextActions:n})}finish(e,t,n=`init`){this.reportCompleted({ok:!0,commandId:n,result:{message:e,...t??{}},exitCode:0,diagnostics:[],nextActions:[]})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},he=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t,n){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){}reportCompleted(e){}reportErrored(e){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const ge=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),_e=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ve=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,ye=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,be=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,xe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Se=/\t{1,1000}/y,Ce=/[\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,we=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Te=/\p{M}+/gu,Ee={limit:1/0,ellipsis:``},De=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?De(i,Ee,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[we,l],[ye,0],[be,o],[Se,s],[Ce,c],[xe,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(Te,``)){let t=e.codePointAt(0)||0;if(S=_e(t)?2:ve(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===xe?ge(e.slice(p,n.lastIndex)):n===Ce?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}},Oe={limit:1/0,ellipsis:``,ellipsisWidth:0},F=(e,t={})=>De(e,Oe,t).width,ke=`]8;;`,Ae=RegExp(`(?:\\[(?<code>\\d+)m|\\${ke}(?<uri>.*))`,`y`),je=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Me=e=>`[${e}m`,Ne=e=>`${ke}${e}`,Pe=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:F(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=F(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(ke,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())},Fe=e=>{let t=e.split(` `),n=t.length;for(;n&&!F(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ie=(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=F(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=F(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(``),Pe(s,r,t),c=F(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Pe(s,r,t),c=F(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Pe(s,r,t),c=F(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Fe(e)));let l=s.join(`
|
|
2
|
+
import{a as e,c as t,i as n,l as r,n as i,o as a,s as o,t as s}from"./dist-waSn9fHo.js";import{createRequire as c}from"node:module";import{shake as l}from"radashi";import{styleText as u}from"node:util";import d,{stdin as f,stdout as p}from"node:process";import*as m from"node:readline";import h from"node:readline";import{ReadStream as g}from"node:tty";import _ from"node:path";import{createJiti as v}from"jiti";import{execSync as y,spawn as b}from"node:child_process";import x from"node:fs/promises";import{applyEdits as S,modify as C,parse as w}from"jsonc-parser";import T from"dedent";import{builders as ee,detectCodeFormat as E,generateCode as D,parseModule as te}from"magicast";import{isMap as O,parseDocument as ne}from"yaml";var re=Object.create,ie=Object.defineProperty,ae=Object.getOwnPropertyDescriptor,oe=Object.getOwnPropertyNames,se=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty,le=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ue=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=oe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ce.call(e,s)&&s!==n&&ie(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ae(t,s))||r.enumerable});return e},k=/* @__PURE__ */ ((e,t,n)=>(n=e==null?{}:re(se(e)),ue(t||!e||!e.__esModule||!ce.call(e,`default`)?ie(n,`default`,{value:e,enumerable:!0}):n,e)))((/* @__PURE__ */ le(((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 A={REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,INTERNAL:`CLI.INTERNAL_ERROR`,SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CANCELLED:`CLI.CANCELLED`,UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,INVALID_VALUE:`ENV.INVALID_VALUE`,MISSING_VARIABLE:`ENV.MISSING_VARIABLE`},j={CLI_INTERNAL_ERROR:`CLI.INTERNAL_ERROR`,CLI_SCHEMA_NOT_FOUND:`CLI.SCHEMA_NOT_FOUND`,CLI_REQUIREMENTS_NOT_MET:`CLI.REQUIREMENTS_NOT_MET`,CLI_GIT_TREE_DIRTY:`CLI.GIT_TREE_DIRTY`,CLI_NON_EMPTY_DIR:`CLI.NON_EMPTY_DIR`,CLI_CANCELLED:`CLI.CANCELLED`,CLI_UNKNOWN_COMMAND:`CLI.UNKNOWN_COMMAND`,CLI_INVALID_ARGUMENT:`CLI.INVALID_ARGUMENT`,ENV_VALIDATION_FAILED:`ENV.VALIDATION_FAILED`,ENV_INVALID_VALUE:`ENV.INVALID_VALUE`,ENV_MISSING_VARIABLE:`ENV.MISSING_VARIABLE`};function de(){let e=process.env.npm_config_user_agent||``;if(e.includes(`pnpm`))return process.env.npm_command===`dlx`?`pnpm dlx arkenv`:`pnpm arkenv`;if(e.includes(`bun`))return(process.env._||process.argv[1]||``).includes(`bunx`)||process.env.npm_command===`x`?`bunx arkenv`:`bun arkenv`;if(e.includes(`yarn`))return process.env.npm_command===`dlx`?`yarn dlx arkenv`:`yarn arkenv`;if(e.includes(`npm`))return`npx arkenv`;let t=process.env._||process.argv[1]||``;return t.includes(`npx`)?`npx arkenv`:t.includes(`bunx`)?`bunx arkenv`:t.includes(`pnpm`)?`pnpm arkenv`:t.includes(`yarn`)?`yarn arkenv`:t.includes(`bun`)?`bun arkenv`:`arkenv`}function fe(e,t=de()){return e.replace(/\{bin\}/g,t)}function M(e,t=de()){let n={...e};return n.command&&=fe(n.command,t),n.commands&&=n.commands.map(e=>fe(e,t)),n}function pe(e){return e.replace(/\x1B\[\d+m/g,``).replace(/\x1B\[[0-9;]*[a-zA-Z]/g,``)}function N(e,t,n){let i=pe(e);return n?.debugSecrets||o(n?.debugSecrets)?i:t&&r(t)?i.replace(/\(was .*\)/g,`(was [REDACTED])`):i}var me=class{info(e){process.stderr.write(`${k.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${k.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${k.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${k.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${k.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${k.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${k.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${k.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}reportCompleted(e){let t=e.diagnostics.map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>M(e))})),n=(e.nextActions??[]).map(e=>M(e));this.json({ok:!0,commandId:e.commandId,result:e.result,exitCode:e.exitCode,diagnostics:t,nextActions:n})}reportErrored(e){let t=(e.error.nextActions??[]).map(e=>M(e)),n=(e.nextActions??t).map(e=>M(e)),r=(e.diagnostics??[]).map(e=>({...e,nextActions:(e.nextActions??[]).map(e=>M(e))}));this.json({ok:!1,commandId:e.commandId,error:{...e.error,nextActions:t},diagnostics:r,nextActions:n})}cancel(e,t=`cli`){this.reportErrored({ok:!1,commandId:t,error:{code:A.CANCELLED,severity:`info`,summary:N(e),nextActions:[]},diagnostics:[],nextActions:[]})}fatal(e,t,n=`cli`){let r=t instanceof Error?t.message:t?String(t):void 0;throw this.reportErrored({ok:!1,commandId:n,error:{code:A.INTERNAL,severity:`error`,summary:N(e),...r===void 0?{}:{why:N(r)},...r===void 0?{}:{meta:{error:r}},nextActions:[]},diagnostics:[],nextActions:[]}),t instanceof Error?t:Error(e)}refuse(e,t=`init`){let n=e.nextActions??[];this.reportErrored({ok:!1,commandId:t,error:{code:e.code,severity:`error`,summary:N(e.message),...e.why?{why:N(e.why)}:{},...e.details===void 0?{}:{meta:e.details},nextActions:n},diagnostics:[],nextActions:n})}finish(e,t,n=`init`){this.reportCompleted({ok:!0,commandId:n,result:{message:e,...t??{}},exitCode:0,diagnostics:[],nextActions:[]})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},he=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t,n){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){}reportCompleted(e){}reportErrored(e){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const ge=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),_e=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ve=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,ye=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,be=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,xe=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,Se=/\t{1,1000}/y,Ce=/[\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,we=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Te=/\p{M}+/gu,Ee={limit:1/0,ellipsis:``},De=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?De(i,Ee,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[we,l],[ye,0],[be,o],[Se,s],[Ce,c],[xe,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(Te,``)){let t=e.codePointAt(0)||0;if(S=_e(t)?2:ve(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===xe?ge(e.slice(p,n.lastIndex)):n===Ce?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}},Oe={limit:1/0,ellipsis:``,ellipsisWidth:0},P=(e,t={})=>De(e,Oe,t).width,ke=`]8;;`,Ae=RegExp(`(?:\\[(?<code>\\d+)m|\\${ke}(?<uri>.*))`,`y`),je=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},Me=e=>`[${e}m`,Ne=e=>`${ke}${e}`,Pe=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:P(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=P(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(ke,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())},Fe=e=>{let t=e.split(` `),n=t.length;for(;n&&!P(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Ie=(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=P(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=P(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(``),Pe(s,r,t),c=P(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){Pe(s,r,t),c=P(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){Pe(s,r,t),c=P(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>Fe(e)));let l=s.join(`
|
|
3
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===``){Ae.lastIndex=e+1;let t=Ae.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
4
|
`){a&&(r+=Ne(``));let e=i?je(i):void 0;i&&e&&(r+=Me(e))}else t===`
|
|
5
|
-
`&&(i&&je(i)&&(r+=Me(i)),a&&(r+=Ne(a)))}return r},Le=/\r?\n/;function
|
|
6
|
-
`)}var
|
|
5
|
+
`&&(i&&je(i)&&(r+=Me(i)),a&&(r+=Ne(a)))}return r},Le=/\r?\n/;function F(e,t,n){return String(e).normalize().split(Le).map(e=>Ie(e,t,n)).join(`
|
|
6
|
+
`)}var I=(/* @__PURE__ */ le(((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 Re(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?Re(a,t<0?-1:1,n):a}const L={actions:/* @__PURE__ */ new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:/* @__PURE__ */ new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,accessible:void 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 ze(e){if(e!==void 0)return e;if(L.accessible!==void 0)return L.accessible;let t=process.env.ACCESSIBLE;return t!==void 0&&t!==``&&t!==`0`&&t!==`false`}function Be(e,t){if(typeof e==`string`)return L.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Be(n,t))return!0;return!1}function Ve(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
|
|
9
|
-
`).map((e,t)=>{let a
|
|
10
|
-
`)}let
|
|
11
|
-
`),
|
|
12
|
-
`).length-1;this.output.write(
|
|
13
|
-
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(
|
|
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 He=globalThis.process.platform.startsWith(`win`),Ue=Symbol(`clack:cancel`);function R(e){return e===Ue}function We(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Ge({input:e=f,output:t=p,overwrite:n=!0,hideCursor:r=!0}={}){let i=m.createInterface({input:e,output:t,prompt:``,tabSize:1});m.emitKeypressEvents(e,i),e instanceof g&&e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(Be([String(i),o,s],`cancel`)){r&&t.write(I.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;m.moveCursor(t,c,l,()=>{m.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(I.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(I.cursor.show),e instanceof g&&e.isTTY&&!He&&e.setRawMode(!1),i.terminal=!1,i.close()}}const Ke=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,qe=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function Je(e,t,n,r=n,i=n,a){return F(t,Ke(e??p)-n.length,{hard:!0,trim:!1}).split(`
|
|
9
|
+
`).map((e,t,o)=>{let s=a?a(e,t):e;return t===0?`${r}${s}`:t===o.length-1?`${i}${s}`:`${n}${s}`}).join(`
|
|
10
|
+
`)}function Ye(e,t){if(`~standard`in e){let n=e[`~standard`].validate(t);return n instanceof Promise?n.then(e=>e.issues?.at(0)?.message):n.issues?.at(0)?.message}return e(t)}var Xe=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=/* @__PURE__ */ new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;get accessible(){return ze(this.opts.accessible)}constructor(e,t=!0){let{input:n=f,output:r=p,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(Ue);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=h.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),We(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(I.cursor.show),this.output.off(`resize`,this.render),We(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(I.cursor.show),this.output.off(`resize`,this.render),We(this.input,!1),e(Ue)})})}_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(``)}async onKeypress(e,t){if(this.state!==`validating`){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&&L.aliases.has(t.name)&&this.emit(`cursor`,L.aliases.get(t.name)),L.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,t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=Ye(this.opts.validate,this.value),t;e instanceof Promise?(this.state=`validating`,this.render(),t=await e):t=e,t&&(this.error=t instanceof Error?t.message:t,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}Be([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
11
|
+
`),We(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=F(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
12
|
+
`).length-1;this.output.write(I.cursor.move(-999,e*-1))}render(){let e=F(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(I.cursor.hide);else{let t=Ve(this._prevFrame,e),n=qe(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(I.cursor.move(0,a-i)),this.output.write(I.erase.lines(1));let t=e.split(`
|
|
13
|
+
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(I.cursor.move(0,t.length-a-1));return}if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(I.cursor.move(0,e))}this.output.write(I.erase.down());let t=e.split(`
|
|
14
14
|
`).slice(a);this.output.write(t.join(`
|
|
15
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
16
|
-
`);_.push(
|
|
15
|
+
`)),this._prevFrame=e;return}}this.output.write(I.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},Ze=class extends Xe{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(I.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}};let Qe=class extends Xe{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.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?Re(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=Re(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=Re(this.cursor,1,this.options)}this.changeValue()})}};var $e=class extends Xe{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=e.slice(this.cursor,this.cursor+1),r=e.slice(this.cursor+1);return`${t}${u(`inverse`,n)}${r}`}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 et(){return d.platform===`win32`?!!d.env.CI||!!d.env.WT_SESSION||!!d.env.TERMINUS_SUBLIME||d.env.ConEmuTask===`{cmd::Cmder}`||d.env.TERM_PROGRAM===`Terminus-Sublime`||d.env.TERM_PROGRAM===`vscode`||d.env.TERM===`xterm-256color`||d.env.TERM===`alacritty`||d.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:d.env.TERM!==`linux`}const tt=et(),nt=()=>process.env.CI===`true`,z=(e,t)=>tt?e:t,rt=z(`◆`,`*`),it=z(`■`,`x`),at=z(`▲`,`x`),ot=z(`◇`,`o`),B=z(`│`,`|`),V=z(`└`,`—`),st=z(`●`,`>`),ct=z(`○`,` `),lt=z(`─`,`-`),ut=z(`╮`,`+`),dt=z(`├`,`+`),ft=z(`╯`,`+`),pt=z(`╰`,`+`),mt=e=>{switch(e){case`initial`:case`active`:return u(`cyan`,rt);case`cancel`:return u(`red`,it);case`error`:return u(`yellow`,at);case`submit`:return u(`green`,ot);case`validating`:return u(`dim`,rt)}},ht=e=>{switch(e){case`initial`:case`active`:return u(`cyan`,B);case`cancel`:return u(`red`,B);case`error`:return u(`yellow`,B);case`submit`:return u(`green`,B)}};function gt(e,t){let n=[`${t?`${u(`cyan`,B)} `:``}${e.join(` • `)}`];return t&&n.push(u(`cyan`,V)),n}const _t=(e,t,n,r,i,a=!1)=>{let o=t,s=0;if(a)for(let t=r-1;t>=n;t--){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}else for(let t=n;t<r;t++){let n=e[t];if(n&&(o-=n.length),s++,o<=i)break}return{lineCount:o,removals:s}},vt=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:a=0,rowPadding:o=4})=>{let s=Ke(r)-a,c=qe(r),l=u(`dim`,`...`),d=Math.max(c-o,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=t[r],a=F(i?n(i,r===e):``,s,{hard:!0,trim:!1}).split(`
|
|
16
|
+
`);_.push(a),v+=a.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=d,o=()=>_t(_,r,0,i,a),s=()=>_t(_,r,i+1,_.length,a,!0);m?({lineCount:r,removals:t}=o(),r>a&&(h||--a,{lineCount:r,removals:n}=s())):(h||--a,{lineCount:r,removals:n}=s(),r>a&&(--a,{lineCount:r,removals:t}=o())),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(l);for(let e of _)for(let t of e)x.push(t);return h&&x.push(l),x},H=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new Ze({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??L.withGuide,i=`${mt(this.state)} `,a=r?`${u(`gray`,B)} `:``,o=Je(e.output,e.message,a,i),s=`${r?`${u(`gray`,B)}
|
|
17
17
|
`:``}${o}
|
|
18
|
-
`,c=this.value?t:n;switch(this.state){case`submit`:return`${s}${r?`${
|
|
19
|
-
${
|
|
20
|
-
${
|
|
21
|
-
`:` ${
|
|
18
|
+
`,c=this.value?t:n;switch(this.state){case`submit`:return`${s}${r?`${u(`gray`,B)} `:``}${u(`dim`,c)}`;case`cancel`:return`${s}${r?`${u(`gray`,B)} `:``}${u([`strikethrough`,`dim`],c)}${r?`
|
|
19
|
+
${u(`gray`,B)}`:``}`;default:{let i=r?`${u(`cyan`,B)} `:``,a=r?u(`cyan`,V):``;return`${s}${i}${this.value?`${u(`green`,st)} ${t}`:`${u(`dim`,ct)} ${u(`dim`,t)}`}${e.vertical?r?`
|
|
20
|
+
${u(`cyan`,B)} `:`
|
|
21
|
+
`:` ${u(`dim`,`/`)} `}${this.value?`${u(`dim`,ct)} ${u(`dim`,n)}`:`${u(`green`,st)} ${n}`}
|
|
22
22
|
${a}
|
|
23
|
-
`}}}}).prompt()}
|
|
24
|
-
`);if(f.length>0){let[e,...r]=f;e.length>0?o.push(`${l}${e}`):o.push(s?t:``);for(let e of r)e.length>0?o.push(`${u}${e}`):o.push(s?n:``)}r.write(`${o.join(`
|
|
25
|
-
`)}
|
|
26
|
-
`)},info:(e,t)=>{G.message(e,{...t,symbol:d(`blue`,dt)})},success:(e,t)=>{G.message(e,{...t,symbol:d(`green`,ft)})},step:(e,t)=>{G.message(e,{...t,symbol:d(`green`,V)})},warn:(e,t)=>{G.message(e,{...t,symbol:d(`yellow`,pt)})},warning:(e,t)=>{G.warn(e,t)},error:(e,t)=>{G.message(e,{...t,symbol:d(`red`,mt)})}},yt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??R.withGuide?`${d(`gray`,U)} `:``;n.write(`${r}${d(`red`,e)}
|
|
23
|
+
`}}}}).prompt()};`${u(`dim`,`↑/↓`)}`,`${u(`dim`,`Space:`)}`,`${u(`dim`,`Enter:`)}`;const yt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??L.withGuide?`${u(`gray`,V)} `:``;n.write(`${r}${u(`red`,e)}
|
|
27
24
|
|
|
28
|
-
`)},bt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??
|
|
29
|
-
${
|
|
25
|
+
`)},bt=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??L.withGuide?`${u(`gray`,B)}
|
|
26
|
+
${u(`gray`,V)} `:``;n.write(`${r}${e}
|
|
30
27
|
|
|
31
|
-
`)},xt=e=>
|
|
32
|
-
`),a=i.reduce((e,t)=>Math.max(
|
|
33
|
-
`).map(a),``],s=
|
|
34
|
-
`),
|
|
35
|
-
`:``,p=i?
|
|
28
|
+
`)},xt=e=>e,St=(e,t,n)=>{let r={hard:!0,trim:!1},i=F(e,t,r).split(`
|
|
29
|
+
`),a=i.reduce((e,t)=>Math.max(P(t),e),0);return F(e,t-(i.map(n).reduce((e,t)=>Math.max(P(t),e),0)-a),r)},Ct=(e=``,t=``,n)=>{let r=n?.output??d.stdout,i=n?.withGuide??L.withGuide,a=n?.format??xt,o=[``,...St(e,Ke(r)-6,a).split(`
|
|
30
|
+
`).map(a),``],s=P(t),c=Math.max(o.reduce((e,t)=>{let n=P(t);return n>e?n:e},0),s)+2,l=o.map(e=>`${u(`gray`,B)} ${e}${` `.repeat(c-P(e))}${u(`gray`,B)}`).join(`
|
|
31
|
+
`),f=i?`${u(`gray`,B)}
|
|
32
|
+
`:``,p=i?dt:pt;r.write(`${f}${u(`green`,ot)} ${u(`reset`,t)} ${u(`gray`,lt.repeat(Math.max(c-s-1,1))+ut)}
|
|
36
33
|
${l}
|
|
37
|
-
${
|
|
38
|
-
`)},wt=e=>
|
|
39
|
-
`);let e=
|
|
40
|
-
`);e.length>1&&n.write(
|
|
41
|
-
`);let r=0,i=0;C(),f=setInterval(()=>{if(l&&h===g)return;T(),g=h;let t=y(a[r]),o;if(l)o=`${t} ${h}...`;else if(e===`timer`)o=`${t} ${h} ${
|
|
34
|
+
${u(`gray`,p+lt.repeat(c+2)+ft)}
|
|
35
|
+
`)},wt=e=>u(`magenta`,e),Tt=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:a=tt?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:o=tt?80:120,signal:s,...c}={})=>{let l=nt(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ke(n),y=c?.styleFrame??wt,b=e=>{let n=e>1?i??L.messages.error:r??L.messages.cancel;m=e===1,p&&(O(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),s&&s.addEventListener(`abort`,S)},w=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),s&&s.removeEventListener(`abort`,S)},T=()=>{if(g===void 0)return;l&&n.write(`
|
|
36
|
+
`);let e=F(g,v,{hard:!0,trim:!1}).split(`
|
|
37
|
+
`);e.length>1&&n.write(I.cursor.up(e.length-1)),n.write(I.cursor.to(0)),n.write(I.erase.down())},ee=e=>e.replace(/\.+$/,``),E=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},D=c.withGuide??L.withGuide,te=(t=``)=>{p=!0,d=Ge({output:n}),h=ee(t),_=performance.now(),D&&n.write(`${u(`gray`,B)}
|
|
38
|
+
`);let r=0,i=0;C(),f=setInterval(()=>{if(l&&h===g)return;T(),g=h;let t=y(a[r]),o;if(l)o=`${t} ${h}...`;else if(e===`timer`)o=`${t} ${h} ${E(_)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);o=`${t} ${h}${e}`}let s=F(o,v,{hard:!0,trim:!1});n.write(s),r=r+1<a.length?r+1:0,i=i<4?i+.125:0},o)},O=(t=``,r=0,i=!1)=>{if(!p)return;p=!1,clearInterval(f),T();let a=r===0?u(`green`,ot):r===1?u(`red`,it):u(`red`,at);h=t??h,i||(e===`timer`?n.write(`${a} ${h} ${E(_)}
|
|
42
39
|
`):n.write(`${a} ${h}
|
|
43
|
-
`)),w(),
|
|
40
|
+
`)),w(),d()};return{start:te,stop:(e=``)=>O(e,0),message:(e=``)=>{h=ee(e??h)},cancel:(e=``)=>O(e,1),error:(e=``)=>O(e,2),clear:()=>O(``,0,!0),get isCancelled(){return m}}},Et=[`${u(`dim`,`↑/↓`)} to navigate`,`${u(`dim`,`Enter:`)} confirm`],Dt=(e,t)=>e.includes(`
|
|
44
41
|
`)?e.split(`
|
|
45
42
|
`).map(e=>t(e)).join(`
|
|
46
|
-
`):t(e),
|
|
47
|
-
`:``}${
|
|
48
|
-
`;switch(this.state){case`submit`:{let r
|
|
49
|
-
${
|
|
50
|
-
`).length,
|
|
51
|
-
${
|
|
52
|
-
${i}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
${
|
|
56
|
-
`)
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
`)},info:e=>K.message(e,{symbol:d(`blue`,dt)}),success:e=>K.message(e,{symbol:d(`green`,ft)}),step:e=>K.message(e,{symbol:d(`green`,V)}),warn:e=>K.message(e,{symbol:d(`yellow`,pt)}),warning:e=>K.warn(e),error:e=>K.message(e,{symbol:d(`red`,mt)})},kt=e=>new Ze({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??R.withGuide,n=`${`${t?`${d(`gray`,H)}
|
|
60
|
-
`:``}${ht(this.state)} `}${e.message}
|
|
61
|
-
`,r=e.placeholder?d(`inverse`,e.placeholder[0])+d(`dim`,e.placeholder.slice(1)):d([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,a=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${d(`yellow`,this.error)}`:``,r=t?`${d(`yellow`,H)} `:``,a=t?d(`yellow`,U):``;return`${n.trim()}
|
|
43
|
+
`):t(e),U=e=>{let t=(e,t)=>{if(e===void 0)return``;let n=e.label??String(e.value);switch(t){case`disabled`:return`${u(`gray`,ct)} ${Dt(n,e=>u(`gray`,e))}${e.hint?` ${u(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${Dt(n,e=>u(`dim`,e))}`;case`active`:return`${u(`green`,st)} ${n}${e.hint?` ${u(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${Dt(n,e=>u([`strikethrough`,`dim`],e))}`;default:return`${u(`dim`,ct)} ${Dt(n,e=>u(`dim`,e))}`}},n=e.showInstructions??!0;return new Qe({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??L.withGuide,i=`${mt(this.state)} `,a=`${ht(this.state)} `,o=Je(e.output,e.message,a,i),s=`${r?`${u(`gray`,B)}
|
|
44
|
+
`:``}${o}
|
|
45
|
+
`;switch(this.state){case`submit`:{let n=r?`${u(`gray`,B)} `:``;return`${s}${Je(e.output,t(this.options[this.cursor],`selected`),n)}`}case`cancel`:{let n=r?`${u(`gray`,B)} `:``;return`${s}${Je(e.output,t(this.options[this.cursor],`cancelled`),n)}${r?`
|
|
46
|
+
${u(`gray`,B)}`:``}`}default:{let i=r?`${u(`cyan`,B)} `:``,a=s.split(`
|
|
47
|
+
`).length,o=n?gt(Et,r):r?[u(`cyan`,V)]:[],c=o.join(`
|
|
48
|
+
`),l=o.length+1;return`${s}${i}${vt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:a+l,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
|
|
49
|
+
${i}`)}
|
|
50
|
+
${c}
|
|
51
|
+
`}}}}).prompt()};`${u(`gray`,B)}`;const Ot=e=>new $e({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??L.withGuide,n=`${`${t?`${u(`gray`,B)}
|
|
52
|
+
`:``}${mt(this.state)} `}${e.message}
|
|
53
|
+
`,r=e.placeholder&&e.placeholder.length>0?u(`inverse`,e.placeholder[0])+u(`dim`,e.placeholder.slice(1)):u([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,a=this.value??``;switch(this.state){case`validating`:{let e=t?`${u(`cyan`,B)} `:``,r=t?u(`cyan`,V):``;return`${n}${e}${u(`dim`,i)}
|
|
54
|
+
${r} ${u(`dim`,`Validating...`)}
|
|
55
|
+
`}case`error`:{let e=this.error?` ${u(`yellow`,this.error)}`:``,r=t?`${u(`yellow`,B)} `:``,a=t?u(`yellow`,V):``;return`${n.trim()}
|
|
62
56
|
${r}${i}
|
|
63
57
|
${a}${e}
|
|
64
|
-
`}case`submit`:{let e=a?` ${
|
|
65
|
-
${r}`:``}`}default:return`${n}${t?`${
|
|
66
|
-
${t?
|
|
67
|
-
`}}}).prompt();var At=class{info(e){process.stdout.write(`${j.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${j.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${j.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${j.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){Ct(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return Tt()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`${j.default.red(`✘ ${e}`)}\n`)}fatal(e,t,n){if(process.stderr.write(`${j.default.red(`✘ ${e}`)}\n`),t){let e=`${j.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){bt(e)}reportCompleted(e){e.exitCode===0&&this.success(`Environment variables are valid`)}reportErrored(e){this.error(e.error.summary),e.error.why&&this.warn(e.error.why)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},jt=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.reporter?this.reporter=e.reporter:e.isJson?this.reporter=new me:e.isQuiet?this.reporter=new he:this.reporter=new At}get isJson(){return this.options.isJson}debug(e){this.reporter.log(e)}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){!this.options.isJson||this.options.isYes||(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e,t=`cli`){this.reporter.cancel(e,t)}fatal(e,t,n=`cli`){this.reporter.fatal(e,t,n)}refuse(e,t=`init`){this.reporter.refuse(e,t)}finish(e,t,n=`init`){this.reporter.finish(e,t,n)}reportCompleted(e){this.reporter.reportCompleted(e)}reportErrored(e){this.reporter.reportErrored(e)}async flush(){await this.reporter.flush()}};function Mt(e,t){return Object.keys(e).includes(t)}function Nt(e){if(typeof e==`string`)return/=\s*\S/.test(e);if(!e||typeof e!=`object`)return!1;let t=e;if(Mt(t,`default`)||Mt(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 Nt(e.innerType)}return!1}function Pt(e){return e.endsWith(`?`)?e.slice(0,-1):e}function Ft(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:Mt(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&&Mt(e,`default`))}),n[r]=a}}}function It(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0}function Lt(t){let n=[],r={};for(let i of t){if(!i||typeof i!=`object`&&typeof i!=`function`)return{extractable:!1};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)&&(Ft(e.required,n,r),Ft(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)){if(typeof i==`function`)return{extractable:!1};if(!It(i)){if(Object.keys(t).length===0)return{extractable:!1};for(let[e,i]of Object.entries(t)){let t=Pt(e);n.push({name:t,schema:i,hasDefault:Nt(i)}),r[t]=i}}}}return{extractable:!0,keys:n,schema:r}}async function Rt(e,t,n,r){if(r){let n=v.resolve(e,r);return await t.exists(n)?n:void 0}let i=[v.resolve(e,`env.ts`),v.resolve(e,`src/env.ts`),v.resolve(e,`env.js`),v.resolve(e,`src/env.js`),v.resolve(e,`env.mjs`),v.resolve(e,`src/env.mjs`)],a=await n.suggestDefaultEnvPath(e);a&&i.unshift(v.resolve(e,a));for(let e of i)if(await t.exists(e))return e}const q={ERR_INSPECT_NO_CALL:`ERR_INSPECT_NO_CALL`,ERR_INSPECT_UNSUPPORTED:`ERR_INSPECT_UNSUPPORTED`,ERR_INSPECT_UNEXTRACTABLE:`ERR_INSPECT_UNEXTRACTABLE`,ERR_INSPECT_EVAL_THROW:`ERR_INSPECT_EVAL_THROW`};function zt(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 Bt(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 Vt(e){return`No arkenv() schema definition was found in "${e}". No arkenv() definition was found. Ensure arkenv() is called at the top level of the schema module.`}function Ht(e,t){return`Failed to inspect schema module at "${e}": ${t instanceof Error?t.message:String(t)} Upgrade @arkenv/core or @arkenv/standard so the CLI can inspect the schema without validating the environment.`}function Ut(e){return`Failed to inspect schema module at "${e}": Cannot extract keys from the captured definition. Ensure the schema is a supported static map.`}function Wt(e,t){let n=t instanceof Error?t.message:String(t),r=`Failed to load schema module at "${e}": ${n}`;return Bt(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 Gt=class{constructor(e={}){this.options=e}async load(e){s();try{this.evaluateModule(e.schemaPath);let t=i();if(t.length===0)return{ok:!1,code:q.ERR_INSPECT_NO_CALL,message:Vt(e.schemaPath)};let n=Lt(t);return n.extractable?{ok:!0,keys:n.keys,schema:n.schema}:{ok:!1,code:q.ERR_INSPECT_UNEXTRACTABLE,message:Ut(e.schemaPath)}}catch(t){return i(),zt(t)?{ok:!1,code:q.ERR_INSPECT_UNSUPPORTED,message:Ht(e.schemaPath,t),cause:t}:{ok:!1,code:q.ERR_INSPECT_EVAL_THROW,message:Wt(e.schemaPath,t),cause:t}}}async validate(e,t){let n={...process.env};for(let e of Object.keys(process.env))(!(e in t)||t[e]===void 0)&&delete process.env[e];for(let[e,n]of Object.entries(t))n!==void 0&&(process.env[e]=n);try{return this.evaluateModule(e.schemaPath),{ok:!0}}catch(t){if(zt(t)){let e=t&&typeof t==`object`&&`issues`in t?t.issues??[]:[];return{ok:!1,kind:`validation`,message:t instanceof Error?t.message:String(t),issues:e}}return{ok:!1,kind:`load`,code:q.ERR_INSPECT_EVAL_THROW,message:Wt(e.schemaPath,t),cause:t}}finally{for(let e of Object.keys(process.env))e in n||delete process.env[e];for(let[e,t]of Object.entries(n))t!==void 0&&(process.env[e]=t)}}evaluateModule(e){let t={moduleCache:!1,fsCache:!1,tsconfigPaths:!0,...this.options.jitiAliases?{alias:this.options.jitiAliases}:{}};try{y(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;y(e,{...t,tsconfigPaths:!1})(e)}}};async function Kt(e,t=[]){try{let n=await S.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 Kt(v.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(v.join(e,r.name))}catch{}return t}function qt(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 Jt(e,t,n){if(e.startsWith(`.`))return[v.resolve(v.dirname(n),e)];if(v.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||v.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 v.resolve(i,t)})}return r.baseUrl?[v.resolve(i,e)]:[]}async function Yt(e,t,n){let r=[],i=await Kt(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await S.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=Jt(i,t,e):i.startsWith(`.`)&&(s=[v.resolve(v.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 Xt(e=process.cwd(),t,n){let r=v.join(e,`.env.example`);try{let e=qt(await S.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await Yt(e,t,n);return i.length>0?{keys:i,source:`project`}:null}const Zt=c(import.meta.url).resolve;async function Qt(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==v.parse(n).root;){for(let e of t){let t=v.join(n,e);try{return await S.access(t),t}catch{}}n=v.dirname(n)}return null}async function $t(e,t=new Set){let n=v.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await S.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=T(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(`.`)||v.isAbsolute(r))n=v.resolve(v.dirname(e),r);else try{n=Zt(r,{paths:[v.dirname(e)]})}catch{n=v.resolve(v.dirname(e),`node_modules`,r)}let i={...(await $t(n,t)).compilerOptions};i.baseUrl&&=v.resolve(v.dirname(n),i.baseUrl),i.rootDir&&=v.resolve(v.dirname(n),i.rootDir),o={...o,...i}}}let s={...a};return s.baseUrl&&=v.resolve(v.dirname(e),s.baseUrl),s.rootDir&&=v.resolve(v.dirname(e),s.rootDir),o={...o,...s},{...i,path:e,compilerOptions:o}}async function en(e=process.cwd()){let t=await Qt(e);if(!t)return{status:`not_found`};let n=v.basename(t);try{let e=await $t(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}async function tn(e,t){for(let n of t)try{return await S.access(v.join(e,n)),!0}catch{}return!1}async function nn(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=v.join(e,`package.json`),n=await S.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i[`@tanstack/react-start`]||i[`@tanstack/start`]||i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`;if(i[`@rsbuild/core`])return`rsbuild`}catch{}return await tn(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await tn(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await tn(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:await tn(e,[`rsbuild.config.ts`,`rsbuild.config.js`,`rsbuild.config.mjs`,`rsbuild.config.cjs`,`rsbuild.config.mts`])?`rsbuild`:(await rn(e,t)).length>0?`bun-fullstack`:`vanilla`}async function rn(e=process.cwd(),t){let n=[];try{let t=v.join(e,`bunfig.toml`),r=await S.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 r=await Kt(e),i=n.includes(`serve`),a=n.includes(`build`);for(let e of r)try{let t=await S.readFile(e,`utf-8`);if(!i&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(i=!0,n.push(`serve`)),!a&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(a=!0,n.push(`build`)),i&&a)break}catch{}return n}async function an(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?v.dirname(t.path):e;for(;r!==v.parse(r).root;){try{let e=v.join(r,`package.json`),t=await S.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 S.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=v.dirname(r)}return`npm`}async function on(e=process.cwd(),t){let n=t;if(!n){let t=await Qt(e);t&&(n=await $t(t))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=v.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!v.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await S.access(v.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}function sn(e){let t=e.trim().replace(/^v/,``),n=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/);if(!n){let e=t.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/);if(!e)return null;let n=Number.parseInt(e[1],10),r=e[2]===void 0?0:Number.parseInt(e[2],10),i=e[3]===void 0?0:Number.parseInt(e[3],10),a=e[4],o=e[5];return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?null:{major:n,minor:r,patch:i,prerelease:a?a.split(`.`).map(e=>/^\d+$/.test(e)?Number.parseInt(e,10):e):[],build:o}}let r=Number.parseInt(n[1],10),i=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),o=n[4],s=n[5];return Number.isNaN(r)||Number.isNaN(i)||Number.isNaN(a)?null:{major:r,minor:i,patch:a,prerelease:o?o.split(`.`).map(e=>/^\d+$/.test(e)?Number.parseInt(e,10):e):[],build:s}}function cn(e,t){let n=sn(e),r=sn(t);if(!n||!r)return 0;if(n.major!==r.major)return n.major>r.major?1:-1;if(n.minor!==r.minor)return n.minor>r.minor?1:-1;if(n.patch!==r.patch)return n.patch>r.patch?1:-1;let i=n.prerelease.length>0,a=r.prerelease.length>0;if(!i&&a)return 1;if(i&&!a)return-1;if(!i&&!a)return 0;let o=Math.min(n.prerelease.length,r.prerelease.length);for(let e=0;e<o;e++){let t=n.prerelease[e],i=r.prerelease[e];if(t===i)continue;let a=typeof t==`number`,o=typeof i==`number`;return a&&!o?-1:!a&&o?1:a&&o?t>i?1:-1:t<i?-1:1}return n.prerelease.length===r.prerelease.length?0:n.prerelease.length>r.prerelease.length?1:-1}function ln(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function un(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=ln(r[1]);return e!==null&&cn(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=ln(i);return a&&(r===`>=`||r===`>`||r===`=`)?cn(a,t)>=0:!1})}async function dn(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;cn(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=v.join(e,`package.json`),r=await S.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?un(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 en(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 fn=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await S.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await S.access(v.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return Qt(e)}async loadTsConfig(e,t=new Set){return $t(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return Xt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return on(e,t)}async checkTsConfig(e=process.cwd()){return en(e)}async checkRequirements(e=process.cwd()){return dn(e)}async detectFramework(e=process.cwd(),t){return nn(e,t)}async detectBunFeatures(e=process.cwd(),t){return rn(e,t)}async detectPackageManager(e=process.cwd(),t){return an(e,t)}async hasSkill(e=process.cwd()){try{let t=v.join(e,`skills-lock.json`),n=await S.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 S.access(v.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return b(`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`}}}};const J=e=>j.default.cyan(e),pn=j.default.blue(`⛯`);function mn(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function hn(e,t){return t.endsWith(`
|
|
58
|
+
`}case`submit`:{let e=a?`${t?` `:``}${u(`dim`,a)}`:``;return`${n}${t?u(`gray`,B):``}${e}`}case`cancel`:{let e=a?` ${u([`strikethrough`,`dim`],a)}`:``,r=t?u(`gray`,B):``;return`${n}${r}${e}${a.trim()?`
|
|
59
|
+
${r}`:``}`}default:return`${n}${t?`${u(`cyan`,B)} `:``}${i}
|
|
60
|
+
${t?u(`cyan`,V):``}
|
|
61
|
+
`}}}).prompt();var kt=class{info(e){process.stdout.write(`${k.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${k.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${k.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${k.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){Ct(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return Tt()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e,t){process.stderr.write(`${k.default.red(`✘ ${e}`)}\n`)}fatal(e,t,n){if(process.stderr.write(`${k.default.red(`✘ ${e}`)}\n`),t){let e=`${k.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}refuse(e,t){}finish(e,t,n){bt(e)}reportCompleted(e){e.exitCode===0&&this.success(`Environment variables are valid`)}reportErrored(e){this.error(e.error.summary),e.error.why&&this.warn(e.error.why)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},At=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,this.reporter=e.reporter?e.reporter:e.isJson?new me:e.isQuiet?new he:new kt}get isJson(){return this.options.isJson}debug(e){this.reporter.log(e)}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){this.options.isJson&&!this.options.isYes&&(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e,t=`cli`){this.reporter.cancel(e,t)}fatal(e,t,n=`cli`){this.reporter.fatal(e,t,n)}refuse(e,t=`init`){this.reporter.refuse(e,t)}finish(e,t,n=`init`){this.reporter.finish(e,t,n)}reportCompleted(e){this.reporter.reportCompleted(e)}reportErrored(e){this.reporter.reportErrored(e)}async flush(){await this.reporter.flush()}};function jt(e,t){return Object.keys(e).includes(t)}function Mt(e){if(typeof e==`string`)return/=\s*\S/.test(e);if(!e||typeof e!=`object`)return!1;let t=e;if(jt(t,`default`)||jt(t,`fallback`))return!0;let n=t._def;if(n&&typeof n==`object`){let e=n;if(`defaultValue`in e||e.typeName===`ZodDefault`||e.type==="default")return!0;if(`innerType`in e)return Mt(e.innerType)}return!1}function Nt(e){return e.endsWith(`?`)?e.slice(0,-1):e}function Pt(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:jt(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&&jt(e,`default`))}),n[r]=a}}}function Ft(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===0}function It(t){let n=[],r={};for(let i of t){if(!i||typeof i!=`object`&&typeof i!=`function`)return{extractable:!1};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)&&(Pt(e.required,n,r),Pt(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)){if(typeof i==`function`)return{extractable:!1};if(!Ft(i)){if(Object.keys(t).length===0)return{extractable:!1};for(let[e,i]of Object.entries(t)){let t=Nt(e);n.push({name:t,schema:i,hasDefault:Mt(i)}),r[t]=i}}}}return{extractable:!0,keys:n,schema:r}}async function Lt(e,t,n,r){if(r){let n=_.resolve(e,r);return await t.exists(n)?n:void 0}let i=[_.resolve(e,`env.ts`),_.resolve(e,`src/env.ts`)],a=await n.suggestDefaultEnvPath(e);a&&i.unshift(_.resolve(e,a));for(let e of i)if(await t.exists(e))return e}const W={ERR_INSPECT_NO_CALL:`ERR_INSPECT_NO_CALL`,ERR_INSPECT_UNSUPPORTED:`ERR_INSPECT_UNSUPPORTED`,ERR_INSPECT_UNEXTRACTABLE:`ERR_INSPECT_UNEXTRACTABLE`,ERR_INSPECT_EVAL_THROW:`ERR_INSPECT_EVAL_THROW`};function Rt(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 zt(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 Bt(e){return`No arkenv() schema definition was found in "${e}". No arkenv() definition was found. Ensure arkenv() is called at the top level of the schema module.`}function Vt(e,t){return`Failed to inspect schema module at "${e}": ${t instanceof Error?t.message:String(t)} Upgrade @arkenv/core or @arkenv/standard so the CLI can inspect the schema without validating the environment.`}function Ht(e){return`Failed to inspect schema module at "${e}": Cannot extract keys from the captured definition. Ensure the schema is a supported static map.`}function Ut(e,t){let n=t instanceof Error?t.message:String(t),r=`Failed to load schema module at "${e}": ${n}`;return zt(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 Wt=class{constructor(e={}){this.options=e}async load(e){s();try{this.evaluateModule(e.schemaPath);let t=i();if(t.length===0)return{ok:!1,code:W.ERR_INSPECT_NO_CALL,message:Bt(e.schemaPath)};let n=It(t);return n.extractable?{ok:!0,keys:n.keys,schema:n.schema}:{ok:!1,code:W.ERR_INSPECT_UNEXTRACTABLE,message:Ht(e.schemaPath)}}catch(t){return i(),Rt(t)?{ok:!1,code:W.ERR_INSPECT_UNSUPPORTED,message:Vt(e.schemaPath,t),cause:t}:{ok:!1,code:W.ERR_INSPECT_EVAL_THROW,message:Ut(e.schemaPath,t),cause:t}}}async validate(e,t){let n={...process.env};for(let e of Object.keys(process.env))(!(e in t)||t[e]===void 0)&&delete process.env[e];for(let[e,n]of Object.entries(t))n!==void 0&&(process.env[e]=n);try{return this.evaluateModule(e.schemaPath),{ok:!0}}catch(t){if(Rt(t)){let e=t&&typeof t==`object`&&`issues`in t?t.issues??[]:[];return{ok:!1,kind:`validation`,message:t instanceof Error?t.message:String(t),issues:e}}return{ok:!1,kind:`load`,code:W.ERR_INSPECT_EVAL_THROW,message:Ut(e.schemaPath,t),cause:t}}finally{for(let e of Object.keys(process.env))e in n||delete process.env[e];for(let[e,t]of Object.entries(n))t!==void 0&&(process.env[e]=t)}}evaluateModule(e){let t={moduleCache:!1,fsCache:!1,tsconfigPaths:!0,...this.options.jitiAliases?{alias:this.options.jitiAliases}:{}};try{v(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;v(e,{...t,tsconfigPaths:!1})(e)}}};async function Gt(e,t=[]){try{let n=await x.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 Gt(_.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(_.join(e,r.name))}catch{}return t}function Kt(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 qt(e,t,n){if(e.startsWith(`.`))return[_.resolve(_.dirname(n),e)];if(_.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||_.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 _.resolve(i,t)})}return r.baseUrl?[_.resolve(i,e)]:[]}async function Jt(e,t,n){let r=[],i=await Gt(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await x.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=qt(i,t,e):i.startsWith(`.`)&&(s=[_.resolve(_.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 Yt(e=process.cwd(),t,n){let r=_.join(e,`.env.example`);try{let e=Kt(await x.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await Jt(e,t,n);return i.length>0?{keys:i,source:`project`}:null}const Xt=c(import.meta.url).resolve;async function G(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==_.parse(n).root;){for(let e of t){let t=_.join(n,e);try{return await x.access(t),t}catch{}}n=_.dirname(n)}return null}async function Zt(e,t=/* @__PURE__ */ new Set){let n=_.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await x.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=w(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(`.`)||_.isAbsolute(r))n=_.resolve(_.dirname(e),r);else try{n=Xt(r,{paths:[_.dirname(e)]})}catch{n=_.resolve(_.dirname(e),`node_modules`,r)}let i={...(await Zt(n,t)).compilerOptions};i.baseUrl&&=_.resolve(_.dirname(n),i.baseUrl),i.rootDir&&=_.resolve(_.dirname(n),i.rootDir),o={...o,...i}}}let s={...a};return s.baseUrl&&=_.resolve(_.dirname(e),s.baseUrl),s.rootDir&&=_.resolve(_.dirname(e),s.rootDir),o={...o,...s},{...i,path:e,compilerOptions:o}}async function Qt(e=process.cwd()){let t=await G(e);if(!t)return{status:`not_found`};let n=_.basename(t);try{let e=await Zt(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}async function $t(e,t){for(let n of t)try{return await x.access(_.join(e,n)),!0}catch{}return!1}async function en(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=_.join(e,`package.json`),n=await x.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i[`@tanstack/react-start`]||i[`@tanstack/start`]||i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`;if(i[`@rsbuild/core`])return`rsbuild`}catch{}return await $t(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await $t(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await $t(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:await $t(e,[`rsbuild.config.ts`,`rsbuild.config.js`,`rsbuild.config.mjs`,`rsbuild.config.cjs`,`rsbuild.config.mts`])?`rsbuild`:(await tn(e,t)).length>0?`bun-fullstack`:`vanilla`}async function tn(e=process.cwd(),t){let n=[];try{let t=_.join(e,`bunfig.toml`),r=await x.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 r=await Gt(e),i=n.includes(`serve`),a=n.includes(`build`);for(let e of r)try{let t=await x.readFile(e,`utf-8`);if(!i&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(i=!0,n.push(`serve`)),!a&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(a=!0,n.push(`build`)),i&&a)break}catch{}return n}async function nn(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?_.dirname(t.path):e;for(;r!==_.parse(r).root;){try{let e=_.join(r,`package.json`),t=await x.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 x.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=_.dirname(r)}return`npm`}async function rn(e=process.cwd(),t){let n=t;if(!n){let t=await G(e);t&&(n=await Zt(t))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=_.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!_.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await x.access(_.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}function an(e){let t=e.trim().replace(/^v/,``),n=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/);if(!n){let e=t.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/);if(!e)return null;let n=Number.parseInt(e[1],10),r=e[2]===void 0?0:Number.parseInt(e[2],10),i=e[3]===void 0?0:Number.parseInt(e[3],10),a=e[4],o=e[5];return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?null:{major:n,minor:r,patch:i,prerelease:a?a.split(`.`).map(e=>/^\d+$/.test(e)?Number.parseInt(e,10):e):[],build:o}}let r=Number.parseInt(n[1],10),i=Number.parseInt(n[2],10),a=Number.parseInt(n[3],10),o=n[4],s=n[5];return Number.isNaN(r)||Number.isNaN(i)||Number.isNaN(a)?null:{major:r,minor:i,patch:a,prerelease:o?o.split(`.`).map(e=>/^\d+$/.test(e)?Number.parseInt(e,10):e):[],build:s}}function on(e,t){let n=an(e),r=an(t);if(!n||!r)return 0;if(n.major!==r.major)return n.major>r.major?1:-1;if(n.minor!==r.minor)return n.minor>r.minor?1:-1;if(n.patch!==r.patch)return n.patch>r.patch?1:-1;let i=n.prerelease.length>0,a=r.prerelease.length>0;if(!i&&a)return 1;if(i&&!a)return-1;if(!i&&!a)return 0;let o=Math.min(n.prerelease.length,r.prerelease.length);for(let e=0;e<o;e++){let t=n.prerelease[e],i=r.prerelease[e];if(t===i)continue;let a=typeof t==`number`,o=typeof i==`number`;return a&&!o?-1:!a&&o?1:a&&o?t>i?1:-1:t<i?-1:1}return n.prerelease.length===r.prerelease.length?0:n.prerelease.length>r.prerelease.length?1:-1}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=_.join(e,`package.json`),r=await x.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 Qt(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 x.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await x.access(_.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return G(e)}async loadTsConfig(e,t=/* @__PURE__ */ new Set){return Zt(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return Yt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return rn(e,t)}async checkTsConfig(e=process.cwd()){return Qt(e)}async checkRequirements(e=process.cwd()){return ln(e)}async detectFramework(e=process.cwd(),t){return en(e,t)}async detectBunFeatures(e=process.cwd(),t){return tn(e,t)}async detectPackageManager(e=process.cwd(),t){return nn(e,t)}async hasSkill(e=process.cwd()){try{let t=_.join(e,`skills-lock.json`),n=await x.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 x.access(_.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return y(`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`}}}};const K=e=>k.default.cyan(e),dn=k.default.blue(`⛯`);function fn(e){return e!==`arktype`}function q(e,t,n){return`${e}${t?`/standard`:``}${n?`/${n}`:``}`}function J(e,t,n){return q(e,t===!0,n)}const pn=[`@arkenv/vite-plugin`,`@arkenv/vite-plugin/standard`],mn=[`@arkenv/rsbuild-plugin`,`@arkenv/rsbuild-plugin/standard`],hn=[`@arkenv/nextjs/config`,`@arkenv/nextjs/standard/config`],gn=[`@arkenv/nuxt/module`,`@arkenv/nuxt/standard/module`];function _n(e,t,n){let r=!1;for(let i of e??[])i.from&&t.includes(i.from)&&i.from!==n&&(i.from=n,r=!0);return r}function vn(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function yn(e,t){return t.endsWith(`
|
|
68
62
|
`)&&!e.endsWith(`
|
|
69
|
-
`)?`${e}\n`:e}function
|
|
70
|
-
${
|
|
71
|
-
Access validated variables via your ${
|
|
72
|
-
Primarily used for ${
|
|
63
|
+
`)?`${e}\n`:e}function bn(e){try{let t=te(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`){let t=e.$ast?.arguments?.[0];if(t?.type===`ArrowFunctionExpression`||t?.type===`FunctionExpression`)return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};let n=e.$args?.[0];if(n&&typeof n==`object`&&`$type`in n&&(n.$type===`arrow-function-expression`||n.$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=n}}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||(r.plugins=[]),Array.isArray(r.plugins)){let i=/\barkenv(?:Vite)?Plugin\b/.test(n),a=J(`@arkenv/vite-plugin`,e.standard);if(i){if(!_n(t.imports.$items,pn,a))return{success:!0,updated:!1}}else t.imports.$add({from:a,local:`arkenvPlugin`,imported:`default`}),r.plugins.push(`__ARK_PLUGIN_PLACEHOLDER__`)}else return{success:!1,updated:!1,error:`The 'plugins' property in your Vite config is not an array.`};let i=D(t,{format:E(n)}).code;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,`arkenvPlugin()`),i=vn(i),i=yn(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 xn(e){try{let t=te(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`){let t=e.$ast?.arguments?.[0];if(t?.type===`ArrowFunctionExpression`||t?.type===`FunctionExpression`)return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};let n=e.$args?.[0];if(n&&typeof n==`object`&&`$type`in n&&(n.$type===`arrow-function-expression`||n.$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=n}}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Rsbuild config`};if(r.plugins||(r.plugins=[]),Array.isArray(r.plugins)){let n=/* @__PURE__ */ new Set;for(let e of t.imports.$items||[])e.from&&e.from.startsWith(`@arkenv/rsbuild-plugin`)&&n.add(e.local);n.add(`arkenvPlugin`),n.add(`arkenvRsbuildPlugin`);let i=Array.from(r.plugins).some(e=>typeof e!=`object`||!e||!(`$type`in e)?!1:e.$type===`function-call`?typeof e.$callee==`string`&&n.has(e.$callee):e.$type===`identifier`&&e.$ast?.type===`Identifier`&&n.has(e.$ast.name)),a=J(`@arkenv/rsbuild-plugin`,e.standard);if(i){if(!_n(t.imports.$items,mn,a))return{success:!0,updated:!1}}else{let e=(t.imports.$items||[]).filter(e=>e.from&&e.from.startsWith(`@arkenv/rsbuild-plugin`)),n=e.find(e=>e.imported===`arkenvPlugin`||e.imported===`arkenvRsbuildPlugin`||e.imported==="default")||e[0],i=n?.local||`arkenvPlugin`;n?_n(t.imports.$items,mn,a):t.imports.$add({from:a,local:`arkenvPlugin`,imported:`arkenvPlugin`});let o=i===`arkenvPlugin`?`__ARK_PLUGIN__`:`__ARK_PLUGIN__:${i}`;r.plugins.push(o)}}else return{success:!1,updated:!1,error:`The 'plugins' property in your Rsbuild config is not an array.`};let i=D(t,{format:E(n)}).code;return i=i.replace(/['"]__ARK_PLUGIN__(?::(.+?))?['"]/g,(e,t)=>t?`${t}()`:`arkenvPlugin()`),i=vn(i),i=yn(i,n),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Rsbuild config: ${e instanceof Error?e.message:String(e)}`}}}function Sn(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=te(t);if(!n.exports.default)return{success:!1,updated:!1,error:`Could not find default export in Next.js config`};let r=J(`@arkenv/nextjs`,e.standard,`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)){if(!_n(n.imports.$items,hn,r))return{success:!0,updated:!1}}else n.imports.$add({from:r,imported:`withArkEnv`}),e.disableCodegen?n.exports.default=ee.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=ee.functionCall(`withArkEnv`,n.exports.default);let i=D(n,{format:E(t)}).code;return i=vn(i),i=yn(i,t),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Next.js config: ${e instanceof Error?e.message:String(e)}`}}}function Cn(e){try{let t=e.code,n=te(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||(r.modules=[]),Array.isArray(r.modules)){let t=J(`@arkenv/nuxt`,e.standard,`module`),n=r.modules.includes(t),i=!1;for(let e=r.modules.length-1;e>=0;e--){let n=r.modules[e];typeof n==`string`&&gn.includes(n)&&n!==t&&(r.modules.splice(e,1),i=!0)}if(!n)r.modules.push(t);else if(!i)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=D(n,{format:E(t)}).code;return i=vn(i),i=yn(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)}`}}}async function wn(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=_.resolve(e,t);try{return await x.access(n),n}catch{}}return null}async function Tn(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=_.resolve(e,t);try{return await x.access(n),n}catch{}}return null}async function En(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=_.resolve(e,t);try{return await x.access(n),n}catch{}}return null}async function Dn(e,t,n,r){try{let i=Sn({code:await e.readFile(t),disableCodegen:n,standard:r?.standard});return i.success&&i.updated&&i.code&&await e.writeFile(t,i.code),i.success?i.updated===void 0?{success:!0}:{success:!0,updated:i.updated}:{success:!1,error:i.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function On(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=_.resolve(e,t);try{return await x.access(n),n}catch{}}return null}async function kn(e,t,n){try{let r=Cn({code:await e.readFile(t),standard:n?.standard});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 An(e,t,n,r){try{let n=bn({code:await e.readFile(t),standard:r?.standard});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 jn(e=process.cwd()){for(let t of[`rsbuild.config.ts`,`rsbuild.config.js`,`rsbuild.config.mjs`,`rsbuild.config.cjs`,`rsbuild.config.mts`]){let n=_.resolve(e,t);try{return await x.access(n),n}catch{}}return null}async function Mn(e,t,n){try{let r=xn({code:await e.readFile(t),standard:n?.standard});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 Nn(e,t,n){if(!t||t.length===0)return{success:!0,instructions:T`
|
|
64
|
+
${k.default.green(`✔`)} Use ${k.default.bold(`Vanilla`)} Bun runtime integration.
|
|
65
|
+
Access validated variables via your ${K(`env`)} object for typesafety.
|
|
66
|
+
Primarily used for ${k.default.cyan(`server-side`)} or runtime-only validation.
|
|
73
67
|
No plugins are required.
|
|
74
|
-
`};let
|
|
75
|
-
${
|
|
76
|
-
To inline environment variables (e.g. ${
|
|
68
|
+
`};let r=t.includes(`serve`),i=t.includes(`build`),a=J(`@arkenv/bun-plugin`,n?.standard),o=``;return r&&(o+=T`
|
|
69
|
+
${k.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
|
|
70
|
+
To inline environment variables (e.g. ${K(`PUBLIC_*`)}) in your ${k.default.cyan(`client-side`)} code, add the plugin to ${K(`bunfig.toml`)}:
|
|
77
71
|
|
|
78
72
|
[serve.static]
|
|
79
|
-
plugins = ["
|
|
73
|
+
plugins = ["${a}"]
|
|
80
74
|
|
|
81
|
-
`),
|
|
82
|
-
`),
|
|
83
|
-
${
|
|
84
|
-
To inline environment variables (e.g. ${
|
|
75
|
+
`),i&&(o&&(o+=`
|
|
76
|
+
`),o+=T`
|
|
77
|
+
${k.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
|
|
78
|
+
To inline environment variables (e.g. ${K(`PUBLIC_*`)}) in your custom ${k.default.cyan(`client-side`)} build script, add the plugin to your ${K(`Bun.build`)} call:
|
|
85
79
|
|
|
86
|
-
${
|
|
80
|
+
${K(`import arkenvPlugin from "${a}";`)}
|
|
87
81
|
|
|
88
82
|
await Bun.build({
|
|
89
83
|
entrypoints: ["./index.ts"],
|
|
90
84
|
outdir: "./dist",
|
|
91
|
-
${
|
|
85
|
+
${k.default.green(`plugins: [arkenvPlugin]`)}
|
|
92
86
|
});
|
|
93
|
-
`),{success:!0,instructions:i.trim()}}async function An(e,t){let n=t||await Qt();if(!n)return{status:`not_found`};let r=v.basename(n);try{let t=await e.readFile(n);if(T(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=C(t,w(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,i),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}const jn=`@/.arkenv`,Mn=[`./.arkenv/index.ts`],Nn=`.arkenv/**/*.ts`,Pn={insertSpaces:!0,tabSize:2};async function Fn(e,t){let n=t||await Qt();if(!n)return{status:`not_found`};let r=v.basename(n);try{let t=await e.readFile(n),i=T(t),a=!1,o=i?.compilerOptions?.paths?.[jn];if(!o||o[0]!==Mn[0]){let e=w(t,[`compilerOptions`,`paths`,jn],Mn,{formattingOptions:Pn});t=C(t,e),a=!0}let s=Array.isArray(i?.include)?i.include:[];if(!s.includes(Nn)){let e=w(t,[`include`],[...s,Nn],{formattingOptions:Pn});t=C(t,e),a=!0}return a?(await e.writeFile(n,t),{status:`updated`,file:r}):{status:`already_configured`,file:r}}catch{return{status:`error`,file:r}}}var In=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await S.access(e),!0}catch{return!1}}async readFile(e){return S.readFile(e,`utf-8`)}async writeFile(e,t){await S.writeFile(e,t,`utf-8`)}async mkdir(e,t){await S.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=x(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${j.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${j.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return An(this,e)}async ensureNextjsArkEnvTsConfig(e){return Fn(this,e)}async findViteConfig(e){return bn(e)}async findBunConfig(e){return xn(e)}async findNextjsConfig(e){return Sn(e)}async findNuxtConfig(e){return wn(e)}async findRsbuildConfig(e){return Dn(e)}async bootstrapViteConfig(e,t){return En(this,e,t)}async bootstrapBunConfig(e,t){return kn(e,t)}async bootstrapNextjsConfig(e,t){return Cn(this,e,t)}async bootstrapNuxtConfig(e){return Tn(this,e)}async bootstrapRsbuildConfig(e){return On(this,e)}async appendMissingEnvExampleKeys(e,t){let n=v.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(`
|
|
94
|
-
`)
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
`);return a.endsWith(`
|
|
98
|
-
`)
|
|
99
|
-
`)
|
|
100
|
-
`),o===a?!1:(await this.writeFile(r,o),!0)}};async function Ln(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await W({message:j.default.yellow(`An existing ArkEnv configuration was found at ${J(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return z(e)||!e?null:e}return!0}async function Rn(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await W({message:n===`.env.example`?`Detected ${J(`.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 z(i)?null:i}return!1}async function zn(e){let t=await Dt({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return z(t)?null:t}async function Bn(e){let t=await Dt({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`},{value:`rsbuild`,label:`Rsbuild${e.framework===`rsbuild`?` (Detected)`:``}`,hint:`Rspack-based build tool with client-side and static inlining validation`}]});return z(t)?null:t}async function Vn(e){let t=await W({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return z(t)?null:t}async function Hn(){let e=await Dt({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 z(e)?null:e}async function Un(e){let t=await W({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return z(t)?null:t}const Y={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 Wn(e){return e===`none`||Object.keys(Y).includes(e)}function Gn(e,t){if(e===`none`)return[];let n=Y[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function Kn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=Y[n].fields;return r in i?i[r]:void 0}function qn(e,t,n){let r=Gn(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}async function Jn(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(Y).map(([e,t])=>({value:e,label:t.label,hint:t.hint}))],n=await Dt({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return z(n)?null:n}async function Yn(e){let t=await W({message:`Use default config path (${J(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return z(t)?null:t}async function Xn(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await kt({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(z(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const X={example:zn,overwriteEnvSchemaFile:Ln,framework:Bn,bunBuild:Vn,nextjsCodegen:Un,useDefaultPath:Yn,path:Xn,validator:Hn,hostPreset:Jn,useEnvExample:Rn};async function Zn(e,t=!1){return(e?.mode||`existing`)===`new`?Qn(e,t):$n(e,t)}async function Qn(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||v.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Z(await kt({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||v.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Z(await X.example({examples:n})):!a&&t&&(a=`basic`);let o=n.find(e=>e.id===a);if(!o){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:o.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:o.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof er)return null;throw e}}async function $n(e,t=!1){let n=e?.defaultEnvPath||`./src/env.ts`,r=e?.envKeys||null,i=e?.envKeysSource||`.env.example`;if(t){let t=e?.framework||`vanilla`;return l({mode:`existing`,path:n,validator:`arktype`,framework:t,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=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:n})),a=Z(await X.framework({framework:e?.framework})),o;if(a===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);o=Z(await X.bunBuild({initialValue:t}))}let s=e?.disableCodegen;a===`nuxt`?s=!0:a===`nextjs`&&s===void 0&&(s=!Z(await X.nextjsCodegen({initialValue:!0,framework:a})));let c;if(a===`nextjs`&&!s){let e=await W({message:`Would you like to wrap your Next.js config with ${J(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(z(e))throw yt(`Operation cancelled`),new er;c=e}let u=Z(await X.useDefaultPath({defaultEnvPath:n})),d=Z(await X.path({useDefaultPath:u,defaultEnvPath:n})),f=Z(await X.validator()),p=e?.hostPreset===void 0?Z(await X.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,m=Z(await X.useEnvExample({detectedKeys:r,keysSource:i}));return l({mode:`existing`,overwriteEnvSchemaFile:t,framework:a,path:d,validator:f,hostPreset:p,bunFeatures:a===`bun-fullstack`?o?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:m?r??void 0:void 0,disableCodegen:s,wrapNextjsConfig:c})}catch(e){if(e instanceof er)return null;throw e}}var er=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||z(e))throw yt(`Operation cancelled`),new er;return e}var tr=class{async confirm(e,t=!0,n,r){let i=await W(l({message:e,initialValue:t,active:n,inactive:r}));return z(i)?null:i}async runWizard(e,t=!1){return Zn(e,t)}async select(e,t,n){let r=await Dt({message:e,options:t,initialValue:n});return z(r)?null:r}};const Q={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:``,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:``,kind:`value`},noCodegen:{long:`--no-codegen`,short:``,kind:`boolean`},preset:{long:`--preset`,short:`-P`,kind:`value`},schema:{long:`--schema`,short:`-s`,kind:`value`},envFile:{long:`--env-file`,short:``,kind:`value`},verifyExample:{long:`--verify-example`,short:``,kind:`optional-value`}},nr=new Set(Object.values(Q).flatMap(e=>[e.long,e.short].filter(Boolean))),rr=new Set(Object.values(Q).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var ir=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(rr.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}`);rr.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(!nr.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(e===Q.verifyExample.long)a+1<this.args.length&&!this.args[a+1].startsWith(`-`)?(this.verifyExampleValue=this.args[a+1],a+=2):(this.verifyExampleValue=!0,a+=1);else if(rr.has(e))if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}else a+=1}else o.push(e),a+=1}if(!this.validationError){let e=this.getFlagValue(Q.preset.long,Q.preset.short);e!==void 0&&!Wn(e)&&(this.validationError=`Invalid host preset: ${e}`)}this.positionalArgs=o,this.validationError||(this.command===`check`?o.length>0&&(this.validationError=`Unknown argument: ${o[0]}`):o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0]),this.logger=t.logger||new jt({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=Q.example;return this.getFlagValue(e.long,e.short)}get noCodegen(){return this.hasFlag(`noCodegen`)}get schema(){let e=Q.schema;return this.getFlagValue(e.long,e.short)}get envFiles(){let e=Q.envFile;return this.getFlagValues(e.long,e.short)}get verifyExample(){return this.verifyExampleValue}get hostPreset(){let e=this.getFlagValue(Q.preset.long,Q.preset.short);if(e&&Wn(e))return e}hasFlag(e){let t=Q[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),this.hostPreset!==void 0&&(e.hostPreset=this.hostPreset),e}get checkInput(){return{...this.schema===void 0?{}:{schema:this.schema,file:this.schema},...this.envFiles.length>0?{envFiles:this.envFiles}:{},...this.verifyExample===void 0?{}:{verifyExample:this.verifyExample},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent,isYes:this.isYes,isForce:this.isForce}}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}getFlagValues(e,t){let n=[];for(let r=0;r<this.args.length-1;r++){let i=this.args[r];(i===e||t&&i===t)&&!this.args[r+1].startsWith(`-`)&&n.push(this.args[r+1])}return n}};function ar(e){return e.replace(/\\([nrtbfv0"\\])/g,(e,t)=>{switch(t){case`n`:return`
|
|
101
|
-
`;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`0`:return`\0`;case`"`:return`"`;case`\\`:return`\\`;default:return`\\${t}`}})}function or(e,t){for(let n=0;n<e.length;n++){if(t===`"`&&e[n]===`\\`){n++;continue}if(e[n]===t)return n}return-1}function sr(e){let t={},n=e.split(/\r?\n/),r=null,i=``,a=null;for(let e=0;e<n.length;e++){let o=n[e];if(a!==null){let e=or(o,a);if(e!==-1){i+=`
|
|
102
|
-
`+o.slice(0,e);let n=a===`"`?ar(i):i;r!==null&&(t[r]=n),r=null,i=``,a=null}else i+=`
|
|
103
|
-
`+o;continue}let s=o.trimStart();if(!s||s.startsWith(`#`))continue;s.startsWith(`export `)&&(s=s.slice(7).trimStart());let c=s.indexOf(`=`);if(c===-1)continue;let l=s.slice(0,c).trim();if(!l||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))continue;let u=s.slice(c+1).trimStart(),d=u[0];if(d===`"`||d===`'`||d==="`"){let e=u.slice(1),n=or(e,d);if(n!==-1){let r=e.slice(0,n);t[l]=d===`"`?ar(r):r}else r=l,i=e,a=d}else{let e=u.indexOf(` #`);e!==-1&&(u=u.slice(0,e)),t[l]=u.trimEnd()}}return t}var cr=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let i=e.cwd??process.cwd(),s=e.schema??e.file,c=!!(this.logger.isJson||e.isJson||e.isAgent),l=`.env`;try{await this.scanner.detectFramework(i)===`nextjs`&&(l=`.env.local`)}catch{}let u=await Rt(i,this.workspace,this.scanner,s);if(!u){let e=s?`Schema file not found at "${v.resolve(i,s)}".`:`Could not locate your schema file. Place it at a convention path (env.ts, src/env.ts, …) or specify --schema <path>.`,t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,why:`The schema file could not be found via --schema or convention paths.`,docsUrl:`https://arkenv.js.org/docs/reference/check`,nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let d=v.relative(i,u)||u,f=await this.schemaLoader.load({schemaPath:u});if(!f.ok){let e=P(f.message);if(f.code===q.ERR_INSPECT_NO_CALL){let t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,where:{path:d},nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let t=f.cause?P(f.cause instanceof Error?f.cause.stack??f.cause.message:String(f.cause)):void 0,n=[{kind:`edit-file`,label:`Fix errors in ${d}`,where:{path:d}}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,...t?{why:t}:{},where:{path:d},nextActions:n},diagnostics:[],nextActions:n}):(this.logger.error(e),t&&this.logger.warn(t)),2}if(e.verifyExample!==void 0){let t=typeof e.verifyExample==`string`?e.verifyExample:`.env.example`,n=v.resolve(i,t),r=v.relative(i,n)||t,a=``;await this.workspace.exists(n)&&(a=await this.workspace.readFile(n));let o=sr(a),s=f.keys.map(e=>e.name),l=s.filter(e=>!(e in o));if(l.length>0){let e=l.map(e=>{let t=`${e} is declared in schema but missing in ${r}`,n=[{kind:`edit-file`,label:`Add ${e} to ${r}`,where:{path:r},meta:{targetFile:r,key:e}}];return{code:N.ENV_MISSING_VARIABLE,severity:`error`,summary:t,where:{path:r},meta:{key:e,targetFile:r},nextActions:n}}),t=e.flatMap(e=>e.nextActions);if(c)this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d},file:{path:r},keys:{declared:s.length,missing:l.length}},exitCode:4,diagnostics:e,nextActions:t});else{let e=l.length===1?`key`:`keys`,t=l.map(e=>` - ${e}`).join(`
|
|
104
|
-
`);this.logger.error(`Missing ${l.length} ${e} in ${r}:\n${t}\n\nPlease add the missing ${e} to ${r}.`)}return 4}return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d},file:{path:r},keys:{declared:s.length,missing:0}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — ${r} matches the schema`),0}let p={...process.env};if(e.envFiles&&e.envFiles.length>0)for(let t of e.envFiles){let e=v.resolve(i,t);if(!await this.workspace.exists(e)){let n=`Environment file not found at "${e}".`;return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_INVALID_ARGUMENT,severity:`error`,summary:n,where:{path:t},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(n),2}let n=sr(await this.workspace.readFile(e));Object.assign(p,n)}let m=await this.schemaLoader.validate({schemaPath:u},p);if(m.ok)return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — your environment matches the schema`),0;if(m.kind===`validation`){let e=m.issues??[],i=e.map(e=>{let n=e.code===`MISSING_VARIABLE`||e.received===void 0,i=n?N.ENV_MISSING_VARIABLE:N.ENV_INVALID_VALUE,a=r(e.path)&&!o(),s;s=a?n?`missing`:`[REDACTED]`:n||e.received===void 0?`missing`:typeof e.received==`string`?e.received:t(e.received,e.path);let c=P(e.message.startsWith(e.path)?e.message:`${e.path} ${e.message.trimStart()}`,e.path),u=[{kind:`edit-file`,label:`Set ${e.path} in ${l}`,where:{path:l},meta:{targetFile:l,key:e.path,...e.expected===void 0?{}:{expected:e.expected}}}],f={key:e.path,...e.expected===void 0?{}:{expected:e.expected},received:s,issueCode:e.code,...e.meta?e.meta:{}};return{code:i,severity:`error`,summary:c,where:{path:d},meta:f,nextActions:u}}),s=i.flatMap(e=>e.nextActions);return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d}},exitCode:4,diagnostics:i,nextActions:s}):this.logger.error(`Errors found while validating environment variables:\n${a(n(e))}`),4}let h=m.message,g=P(h);return m.cause&&!(m.cause instanceof SyntaxError)&&!/syntax|cannot find module/i.test(h)?(c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_INTERNAL_ERROR,severity:`error`,summary:g,where:{path:d},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to validate environment: ${g}`),1):(c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:N.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:g,where:{path:d},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to load schema file at ${d}: ${g}`),2)}},lr=`arkenv`,ur=`1.0.0-rc.2`;function dr(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 fr=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{left:`arkenv check`,right:`Validate the environment against the schema`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--agent`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--help, -h`,right:`Show this help message`}],n=[{left:`--example`,right:`Specify an example name when creating a new project`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--no-codegen`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--preset, -P <preset>`,right:`Specify a hosting provider preset (none, vercel, netlify, cloudflare, railway, render, fly)`}],r=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides convention discovery)`},{left:`--env-file <file>`,right:`Path to .env file to load (repeatable; merged in order over process.env)`},{left:`--verify-example [file]`,right:`Verify that all declared schema keys are present in .env.example (or custom file)`}];this.logger.log(`ArkEnv CLI v${ur}`),this.logger.log(`\n${j.default.bold(`Usage:`)}`);for(let t of dr(e))this.logger.log(t);this.logger.log(`\n${j.default.bold(`Global options:`)}`);for(let e of dr(t))this.logger.log(e);this.logger.log(`\n${j.default.bold(`init options:`)}`);for(let e of dr(n))this.logger.log(e);this.logger.log(`\n${j.default.bold(`check options:`)}`);for(let e of dr(r))this.logger.log(e)}};async function pr(e,t){let n=t.targetDir??process.cwd(),r=v.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=v.join(r,i),o=await S.readdir(a),s=[];for(let t of o){let r=v.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 mr(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await S.rm(v.join(n,e),{force:!0});let c=v.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 S.rm(r,{recursive:!0,force:!0})}}async function mr(e,t){let n=await S.readdir(e);await Promise.all(n.map(n=>S.cp(v.join(e,n),v.join(t,n),{recursive:!0,force:!1})))}function hr(){return`yamcodes/arkenv`}const gr=hr();function _r(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 vr(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=E`
|
|
105
|
-
Inside your AI assistant (e.g. Claude Code), use:
|
|
106
|
-
${J(`/arkenv`)} - automatically refine your schema and configure integrations.
|
|
107
|
-
`;return i?(a+=`
|
|
108
|
-
|
|
109
|
-
`,a+=`Also, wrap your Next.js config with ${J(`withArkEnv`)}:\n`,a+=` ${J(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${J(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${J(`import { env } from "${e.metadata.importPath}"`)}\n`):r&&(a+=`
|
|
110
|
-
|
|
111
|
-
`,a+=`Import and use: ${J(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:a,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,i=e.skill?.packageName||gr,a=``,o=1,s=e.metadata.displayPath;a+=`${o++}. Check ${J(s)} and refine your environment schema.\n`;let c=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`nextjs`&&(e.metadata.disableCodegen||c&&(a+=`${o++}. Wrap your Next.js config with ${J(`withArkEnv`)} inside ${J(`next.config.ts`)}:\n`,a+=` ${J(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${J(`export default withArkEnv(nextConfig);`)}\n`)),a+=`${o++}. Import and use: ${J(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${J(`${r} skills add ${i}`)}\n`,a+=` Then run ${J(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const yr=[`esbuild`];var br=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 ${J(e.clone.example)}...`),await pr(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files)t.action===`create`&&await this.workspace.exists(t.path)||(await this.workspace.mkdir(v.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content));if(t.stop(`Configuration scaffolded!`),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 ${J(e.install.packageManager)}...`);let[t,n]=_r(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 ${J(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${J(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 ${J(v.basename(t))}`):(this.reporter.warn(`Could not automatically update ${J(v.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${J(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${J(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let t=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(process.cwd(), '.arkenv', 'env.gen.ts'); runCodegen(schemaPath, outputPath); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,t],e.cwd),this.reporter.info(`Generated ${J(`.arkenv/env.gen.ts`)} for Next.js`);let n=await this.workspace.ensureNextjsArkEnvTsConfig(e.tsConfig?.path);n.status===`updated`&&this.reporter.info(`Mapped ${J(`@/.arkenv`)} in ${J(n.file||`tsconfig.json`)}`)}catch{this.reporter.warn(`Failed to automatically generate ${J(`.arkenv/env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let n=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen);n.success?n.updated?(this.reporter.info(`Updated ${J(v.basename(t))}`),r=!0):(this.reporter.info(`${J(v.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${J(v.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${J(`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 ${J(v.basename(t))}`):this.reporter.info(`${J(v.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${J(v.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${J(`@arkenv/nuxt/module`)} manually.`)}else if(e.bootstrap.framework===`rsbuild`){this.reporter.step(`Bootstrapping Rsbuild plugin...`);let t=await this.workspace.findRsbuildConfig(e.cwd);if(t){let e=await this.workspace.bootstrapRsbuildConfig(t);e.success?(e.updated?this.reporter.info(`Updated ${J(v.basename(t))}`):this.reporter.info(`${J(v.basename(t))} already registers @arkenv/rsbuild-plugin`),r=!0):(this.reporter.warn(`Could not automatically update ${J(v.basename(t))}: ${e.error}`),this.reporter.info(`Please add ${J(`@arkenv/rsbuild-plugin`)} manually.`))}else this.reporter.info(`No Rsbuild config found - please add ${J(`@arkenv/rsbuild-plugin`)} to your Rsbuild config 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=vr(e,i,r);this.reporter.note(a.message,a.title),this.reporter.finish(`${pn} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i},`init`)}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=v.join(e,`pnpm-workspace.yaml`),n=``;if(await this.workspace.exists(t))try{n=await this.workspace.readFile(t)}catch{}let r=this.updatePnpmWorkspaceYaml(n);try{await this.workspace.writeFile(t,r)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=te(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if(ee(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),ee(n))for(let e of yr)n.get(e)!==!0&&n.set(e,!0);return String(t)}};const xr={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 Sr(e){if(e===`nextjs`||e===`nuxt`)return xr[e]}function Cr(e){return e===`nextjs`||e===`nuxt`}const wr={nextjs:xr.nextjs.clientPrefix,nuxt:xr.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``,rsbuild:`PUBLIC_`};function Tr(e,t){let n=Sr(e.framework);return{framework:e.framework,clientPrefix:wr[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const Er={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`};function Dr(e){let t={};for(let n of e)t[n]=Er[n]??``;return t}function Or(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?v.dirname(n.path):e,a=v.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 kr(e,t){if(!(!Cr(t.framework)||t.disableCodegen)){if(t.framework===`nextjs`)return`@/.arkenv`;if(e.tsConfig?.parsed)return Or(e.cwd,v.join(e.targetDir,`generated`),e.tsConfig.parsed)}}function Ar(e,t,n,r){let i=Tr(t,r),a=e.getSimpleTemplate(t.envKeys??[],i),o=n.existingFiles.includes(n.targetPath);return!o||t.overwriteEnvSchemaFile!==!1?[{path:n.targetPath,content:a,action:o?`overwrite`:`create`,label:`environment schema`}]:[]}const jr={clientPrefix:wr[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?Dr(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 l({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return Ar(e,t,n)}};function Mr(e){let{id:t,packageName:n,clientPrefix:r,supportsWrapNextjsConfig:i}=e,a=`${r}API_URL`;return{clientPrefix:r,getEnvDefaults(e){return e&&e.length>0?Dr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[a]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[n]},requiresArktypePeer(){return!0},bootstrap(e){return l({framework:t,...i&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){return Ar(e,t,n,kr(n,t))}}}const Nr=Mr(xr.nextjs),Pr=Mr(xr.nuxt),Fr={clientPrefix:wr.rsbuild,getEnvDefaults(e){return e&&e.length>0?Dr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[`@arkenv/rsbuild-plugin`]},requiresArktypePeer(){return!0},bootstrap(){return l({framework:`rsbuild`})},getSchemaFiles(e,t,n){return Ar(e,t,n)}},Ir={clientPrefix:wr.vanilla,getEnvDefaults(e){return e&&e.length>0?Dr(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return Ar(e,t,n)}},Lr={vite:{clientPrefix:wr.vite,getEnvDefaults(e){return e&&e.length>0?Dr(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 l({framework:`vite`})},getSchemaFiles(e,t,n){return Ar(e,t,n)}},"bun-fullstack":jr,nextjs:Nr,nuxt:Pr,vanilla:Ir,rsbuild:Fr},Rr={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-zod":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-vite-react-zod":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-tanstack-start":{DATABASE_URL:`postgres://localhost:5432/tanstackstart`,PORT:`3000`,VITE_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-tanstack-start-rsbuild":{DATABASE_URL:`postgres://localhost:5432/tanstackstartrsbuild`,PORT:`3000`,PUBLIC_API_URL:`https://api.example.com`,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 zr(e,t){return Rr[e]??t()}function Br(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function Vr(e,t,n,r){if(!r||r===`none`)return;let i=Gn(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 Hr(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 Ur(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 Hr(n))o(e);for(let e of r)o(e);return i}function Wr(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,hostPreset:o}=e,{clientPrefix:s}=r,c=[],l=[],u=[];if(t&&t.length>0)for(let e of t)e.startsWith(s)?l.push(`\t\t${n.formatCodegenField(e,`client`,s,o)}`):e===`NODE_ENV`?u.push(`\t\t${n.formatCodegenField(e,`shared`,s,o)}`):c.push(`\t\t${n.formatCodegenField(e,`server`,s,o)}`);else{let e=n.getDefaultCodegenFields(s);c.push(...e.serverFields),l.push(...e.clientFields),u.push(...e.sharedFields),Vr({serverFields:c,clientFields:l},n,s,o)}return Gr({serverFields:c,clientFields:l,sharedFields:u,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,hostPreset:o})}function Gr(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=Gn(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)}`)}let o=Y[l]?.label??l;g=[...e,...e.length>0?[``]:[],`\t// ${o} environment variables`,...i]}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=Ur(i,u,n,_);v.push(`\truntimeEnv: {\n${e.join(`
|
|
112
|
-
`)}\n\t}`)}let y=v.length>0?`, {\n${v.join(`,
|
|
113
|
-
`)}\n}`:``;return`${[`import arkenv from "${p===`nuxt`||c?d:s||`@/.arkenv`}";`,...m?[m]:[]].join(`
|
|
87
|
+
`),{success:!0,instructions:o.trim()}}async function Pn(e,t){let n=t||await G();if(!n)return{status:`not_found`};let r=_.basename(n);try{let t=await e.readFile(n);if(w(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=C(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}),a=S(t,i);return await e.writeFile(n,a),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}const Fn=`@/.arkenv`,In=[`./.arkenv/index.ts`],Ln=`.arkenv/**/*.ts`,Rn={insertSpaces:!0,tabSize:2};async function zn(e,t){let n=t||await G();if(!n)return{status:`not_found`};let r=_.basename(n);try{let t=await e.readFile(n),i=w(t),a=!1,o=i?.compilerOptions?.paths?.[Fn];if(!o||o[0]!==In[0]){let e=C(t,[`compilerOptions`,`paths`,Fn],In,{formattingOptions:Rn});t=S(t,e),a=!0}let s=Array.isArray(i?.include)?i.include:[];if(!s.includes(Ln)){let e=C(t,[`include`],[...s,Ln],{formattingOptions:Rn});t=S(t,e),a=!0}return a?(await e.writeFile(n,t),{status:`updated`,file:r}):{status:`already_configured`,file:r}}catch{return{status:`error`,file:r}}}var Bn=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await x.access(e),!0}catch{return!1}}async readFile(e){return x.readFile(e,`utf-8`)}async writeFile(e,t){await x.writeFile(e,t,`utf-8`)}async mkdir(e,t){await x.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=b(e,t,{cwd:n,stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),o=``,s=``;this.isQuiet&&(a.stdout?.on(`data`,e=>{o=(o+e.toString()).slice(-1e4)}),a.stderr?.on(`data`,e=>{s=(s+e.toString()).slice(-1e4)})),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${k.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${k.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Pn(this,e)}async ensureNextjsArkEnvTsConfig(e){return zn(this,e)}async findViteConfig(e){return wn(e)}async findBunConfig(e){return Tn(e)}async findNextjsConfig(e){return En(e)}async findNuxtConfig(e){return On(e)}async findRsbuildConfig(e){return jn(e)}async bootstrapViteConfig(e,t,n){return An(this,e,t,n)}async bootstrapBunConfig(e,t,n){return Nn(e,t,n)}async bootstrapNextjsConfig(e,t,n){return Dn(this,e,t,n)}async bootstrapNuxtConfig(e,t){return kn(this,e,t)}async bootstrapRsbuildConfig(e,t){return Mn(this,e,t)}};async function Vn(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await H({message:k.default.yellow(`An existing ArkEnv configuration was found at ${K(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return R(e)||!e?null:e}return!0}async function Hn(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=n===`.env.example`?`Detected ${K(`.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?`,a=await H({message:i,active:`Yes (Recommended)`,initialValue:!0});return R(a)?null:a}return!1}async function Un(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 R(t)?null:t}async function Wn(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`},{value:`rsbuild`,label:`Rsbuild${e.framework===`rsbuild`?` (Detected)`:``}`,hint:`Rspack-based build tool with client-side and static inlining validation`}]});return R(t)?null:t}async function Gn(e){let t=await H({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return R(t)?null:t}async function Kn(){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 R(e)?null:e}async function qn(e){let t=e.framework===`nuxt`?`Nuxt`:`Next.js`,n=await H({message:`Enable automated ${t} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return R(n)?null:n}const Y={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 Jn(e){return e===`none`||Object.keys(Y).includes(e)}function Yn(e,t){if(e===`none`)return[];let n=Y[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function Xn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=Y[n].fields;return r in i?i[r]:void 0}function Zn(e,t,n){let r=Yn(t??`none`,n);if(e?.length||r.length!==0)return Array.from(/* @__PURE__ */ new Set([...e??[],...r]))}async function Qn(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(Y).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 R(n)?null:n}async function $n(e){let t=e.defaultEnvPath||`./src/env.ts`,n=await H({message:`Use default config path (${K(t)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return R(n)?null:n}async function er(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await Ot({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(R(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const X={example:Un,overwriteEnvSchemaFile:Vn,framework:Wn,bunBuild:Gn,nextjsCodegen:qn,useDefaultPath:$n,path:er,validator:Kn,hostPreset:Qn,useEnvExample:Hn};async function tr(e,t=!1){return(e?.mode||`existing`)===`new`?nr(e,t):rr(e,t)}async function nr(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||_.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Z(await Ot({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||_.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Z(await X.example({examples:n})):!a&&t&&(a=`basic`);let o=n.find(e=>e.id===a);if(!o){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:o.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:o.framework,language:`ts`}}catch(e){if(e instanceof ir)return null;throw e}}async function rr(e,t=!1){let n=e?.defaultEnvPath||`./src/env.ts`,r=e?.envKeys||null,i=e?.envKeysSource||`.env.example`;if(t){let t=e?.framework||`vanilla`;return l({mode:`existing`,path:n,validator:`arktype`,framework:t,bunFeatures:t===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,envKeys:r??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:t===`nextjs`||void 0,hostPreset:e?.hostPreset||`none`})}try{let t=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:n})),a=Z(await X.framework({framework:e?.framework})),o;if(a===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);o=Z(await X.bunBuild({initialValue:t}))}let s=e?.disableCodegen;a===`nuxt`?s=!0:a===`nextjs`&&s===void 0&&(s=!Z(await X.nextjsCodegen({initialValue:!0,framework:a})));let c;if(a===`nextjs`&&!s){let e=await H({message:`Would you like to wrap your Next.js config with ${K(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(R(e))throw yt(`Operation cancelled`),new ir;c=e}let u=Z(await X.useDefaultPath({defaultEnvPath:n})),d=Z(await X.path({useDefaultPath:u,defaultEnvPath:n})),f=Z(await X.validator()),p=e?.hostPreset===void 0?Z(await X.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,m=Z(await X.useEnvExample({detectedKeys:r,keysSource:i}));return l({mode:`existing`,overwriteEnvSchemaFile:t,framework:a,path:d,validator:f,hostPreset:p,bunFeatures:a===`bun-fullstack`?o?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,envKeys:m?r??void 0:void 0,disableCodegen:s,wrapNextjsConfig:c})}catch(e){if(e instanceof ir)return null;throw e}}var ir=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||typeof e==`symbol`||R(e))throw yt(`Operation cancelled`),new ir;return e}var ar=class{async confirm(e,t=!0,n,r){let i=await H(l({message:e,initialValue:t,active:n,inactive:r}));return R(i)?null:i}async runWizard(e,t=!1){return tr(e,t)}async select(e,t,n){let r=await U({message:e,options:t,initialValue:n});return R(r)?null:r}};const Q={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:``,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:``,kind:`value`},noCodegen:{long:`--no-codegen`,short:``,kind:`boolean`},preset:{long:`--preset`,short:`-P`,kind:`value`},schema:{long:`--schema`,short:`-s`,kind:`value`},envFile:{long:`--env-file`,short:``,kind:`value`},verifyExample:{long:`--verify-example`,short:``,kind:`optional-value`}},or=new Set(Object.values(Q).flatMap(e=>[e.long,e.short].filter(Boolean))),sr=new Set(Object.values(Q).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var cr=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(sr.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}`);sr.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(!or.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(e===Q.verifyExample.long)a+1<this.args.length&&!this.args[a+1].startsWith(`-`)?(this.verifyExampleValue=this.args[a+1],a+=2):(this.verifyExampleValue=!0,a+=1);else if(sr.has(e)){if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}}else a+=1}else o.push(e),a+=1}if(!this.validationError){let e=this.getFlagValue(Q.preset.long,Q.preset.short);e!==void 0&&!Jn(e)&&(this.validationError=`Invalid host preset: ${e}`)}this.positionalArgs=o,this.validationError||(this.command===`check`?o.length>0&&(this.validationError=`Unknown argument: ${o[0]}`):o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0]),this.logger=t.logger||new At({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=Q.example;return this.getFlagValue(e.long,e.short)}get noCodegen(){return this.hasFlag(`noCodegen`)}get schema(){let e=Q.schema;return this.getFlagValue(e.long,e.short)}get envFiles(){let e=Q.envFile;return this.getFlagValues(e.long,e.short)}get verifyExample(){return this.verifyExampleValue}get hostPreset(){let e=this.getFlagValue(Q.preset.long,Q.preset.short);if(e&&Jn(e))return e}hasFlag(e){let t=Q[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),this.hostPreset!==void 0&&(e.hostPreset=this.hostPreset),e}get checkInput(){return{...this.schema===void 0?{}:{schema:this.schema},...this.envFiles.length>0?{envFiles:this.envFiles}:{},...this.verifyExample===void 0?{}:{verifyExample:this.verifyExample},isQuiet:this.isQuiet,isJson:this.isJson,isAgent:this.isAgent,isYes:this.isYes,isForce:this.isForce}}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}getFlagValues(e,t){let n=[];for(let r=0;r<this.args.length-1;r++){let i=this.args[r];(i===e||t&&i===t)&&!this.args[r+1].startsWith(`-`)&&n.push(this.args[r+1])}return n}};function lr(e){return e.replace(/\\([nrtbfv0"\\])/g,(e,t)=>{switch(t){case`n`:return`
|
|
88
|
+
`;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`0`:return`\0`;case`"`:return`"`;case`\\`:return`\\`;default:return`\\${t}`}})}function ur(e,t){for(let n=0;n<e.length;n++){if(t===`"`&&e[n]===`\\`){n++;continue}if(e[n]===t)return n}return-1}function dr(e){let t={},n=e.split(/\r?\n/),r=null,i=``,a=null;for(let e=0;e<n.length;e++){let o=n[e];if(a!==null){let e=ur(o,a);if(e!==-1){i+=`
|
|
89
|
+
`+o.slice(0,e);let n=a===`"`?lr(i):i;r!==null&&(t[r]=n),r=null,i=``,a=null}else i+=`
|
|
90
|
+
`+o;continue}let s=o.trimStart();if(!s||s.startsWith(`#`))continue;s.startsWith(`export `)&&(s=s.slice(7).trimStart());let c=s.indexOf(`=`);if(c===-1)continue;let l=s.slice(0,c).trim();if(!l||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(l))continue;let u=s.slice(c+1).trimStart(),d=u[0];if(d===`"`||d===`'`||d==="`"){let e=u.slice(1),n=ur(e,d);if(n!==-1){let r=e.slice(0,n);t[l]=d===`"`?lr(r):r}else r=l,i=e,a=d}else{let e=u.indexOf(` #`);e!==-1&&(u=u.slice(0,e)),t[l]=u.trimEnd()}}return t}var fr=class{constructor(e,t,n,r){this.logger=e,this.workspace=t,this.scanner=n,this.schemaLoader=r}async execute(e){let i=e.cwd??process.cwd(),s=e.schema,c=!!(this.logger.isJson||e.isJson||e.isAgent),l=`.env`;try{await this.scanner.detectFramework(i)===`nextjs`&&(l=`.env.local`)}catch{}let u=await Lt(i,this.workspace,this.scanner,s);if(!u){let e=s?`Schema file not found at "${_.resolve(i,s)}".`:`Could not locate your schema file. Place it at a convention path (env.ts or src/env.ts) or specify --schema <path>.`,t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,why:`The schema file could not be found via --schema or convention paths.`,docsUrl:`https://arkenv.js.org/docs/reference/check`,nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let d=_.relative(i,u)||u,f=await this.schemaLoader.load({schemaPath:u});if(!f.ok){let e=N(f.message);if(f.code===W.ERR_INSPECT_NO_CALL){let t=[{kind:`run-command`,label:`Initialize a new ArkEnv schema`,command:`{bin} init`}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,where:{path:d},nextActions:t},diagnostics:[],nextActions:t}):this.logger.error(e),2}let t=f.cause?N(f.cause instanceof Error?f.cause.stack??f.cause.message:String(f.cause)):void 0,n=[{kind:`edit-file`,label:`Fix errors in ${d}`,where:{path:d}}];return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:e,...t?{why:t}:{},where:{path:d},nextActions:n},diagnostics:[],nextActions:n}):(this.logger.error(e),t&&this.logger.warn(t)),2}if(e.verifyExample!==void 0){let t=typeof e.verifyExample==`string`?e.verifyExample:`.env.example`,n=_.resolve(i,t),r=_.relative(i,n)||t,a=``;await this.workspace.exists(n)&&(a=await this.workspace.readFile(n));let o=dr(a),s=f.keys.map(e=>e.name),l=s.filter(e=>!(e in o));if(l.length>0){let e=l.map(e=>{let t=`${e} is declared in schema but missing in ${r}`,n=[{kind:`edit-file`,label:`Add ${e} to ${r}`,where:{path:r},meta:{targetFile:r,key:e}}];return{code:j.ENV_MISSING_VARIABLE,severity:`error`,summary:t,where:{path:r},meta:{key:e,targetFile:r},nextActions:n}}),t=e.flatMap(e=>e.nextActions);if(c)this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d},file:{path:r},keys:{declared:s.length,missing:l.length}},exitCode:4,diagnostics:e,nextActions:t});else{let e=l.length===1?`key`:`keys`,t=l.map(e=>` - ${e}`).join(`
|
|
91
|
+
`);this.logger.error(`Missing ${l.length} ${e} in ${r}:\n${t}\n\nPlease add the missing ${e} to ${r}.`)}return 4}return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d},file:{path:r},keys:{declared:s.length,missing:0}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — ${r} matches the schema`),0}let p={...process.env};if(e.envFiles&&e.envFiles.length>0)for(let t of e.envFiles){let e=_.resolve(i,t);if(!await this.workspace.exists(e)){let n=`Environment file not found at "${e}".`;return c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_INVALID_ARGUMENT,severity:`error`,summary:n,where:{path:t},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(n),2}let n=dr(await this.workspace.readFile(e));Object.assign(p,n)}let m=await this.schemaLoader.validate({schemaPath:u},p);if(m.ok)return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d}},exitCode:0,diagnostics:[],nextActions:[]}):this.logger.success(`No issues found — your environment matches the schema`),0;if(m.kind===`validation`){let e=m.issues??[],i=e.map(e=>{let n=e.code===`MISSING_VARIABLE`||e.received===void 0,i=n?j.ENV_MISSING_VARIABLE:j.ENV_INVALID_VALUE,a=r(e.path)&&!o(),s;s=a?n?`missing`:`[REDACTED]`:n||e.received===void 0?`missing`:typeof e.received==`string`?e.received:t(e.received,e.path);let c=N(e.message.startsWith(e.path)?e.message:`${e.path} ${e.message.trimStart()}`,e.path),u=[{kind:`edit-file`,label:`Set ${e.path} in ${l}`,where:{path:l},meta:{targetFile:l,key:e.path,...e.expected===void 0?{}:{expected:e.expected}}}],f={key:e.path,...e.expected===void 0?{}:{expected:e.expected},received:s,issueCode:e.code,...e.meta?e.meta:{}};return{code:i,severity:`error`,summary:c,where:{path:d},meta:f,nextActions:u}}),s=i.flatMap(e=>e.nextActions);return c?this.logger.reportCompleted({ok:!0,commandId:`check`,result:{schema:{path:d}},exitCode:4,diagnostics:i,nextActions:s}):this.logger.error(`Errors found while validating environment variables:\n${a(n(e))}`),4}let h=m.message,g=N(h);return m.cause&&!(m.cause instanceof SyntaxError)&&!/syntax|cannot find module/i.test(h)?(c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_INTERNAL_ERROR,severity:`error`,summary:g,where:{path:d},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to validate environment: ${g}`),1):(c?this.logger.reportErrored({ok:!1,commandId:`check`,error:{code:j.CLI_SCHEMA_NOT_FOUND,severity:`error`,summary:g,where:{path:d},nextActions:[]},diagnostics:[],nextActions:[]}):this.logger.error(`Failed to load schema file at ${d}: ${g}`),2)}},pr=`arkenv`,mr=`1.0.0-rc.3`;function hr(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 gr=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`},{left:`arkenv check`,right:`Validate the environment against the schema`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--agent`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--help, -h`,right:`Show this help message`}],n=[{left:`--example`,right:`Specify an example name when creating a new project`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--no-codegen`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--preset, -P <preset>`,right:`Specify a hosting provider preset (none, vercel, netlify, cloudflare, railway, render, fly)`}],r=[{left:`--schema, -s <path>`,right:`Path to schema file (overrides convention discovery)`},{left:`--env-file <file>`,right:`Path to .env file to load (repeatable; merged in order over process.env)`},{left:`--verify-example [file]`,right:`Verify that all declared schema keys are present in .env.example (or custom file)`}];this.logger.log(`ArkEnv CLI v${mr}`),this.logger.log(`\n${k.default.bold(`Usage:`)}`);for(let t of hr(e))this.logger.log(t);this.logger.log(`\n${k.default.bold(`Global options:`)}`);for(let e of hr(t))this.logger.log(e);this.logger.log(`\n${k.default.bold(`init options:`)}`);for(let e of hr(n))this.logger.log(e);this.logger.log(`\n${k.default.bold(`check options:`)}`);for(let e of hr(r))this.logger.log(e)}};async function _r(e,t){let n=t.targetDir??process.cwd(),r=_.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=_.join(r,i),o=await x.readdir(a),s=[];for(let t of o){let r=_.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 vr(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await x.rm(_.join(n,e),{force:!0});let c=_.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 x.rm(r,{recursive:!0,force:!0})}}async function vr(e,t){let n=await x.readdir(e);await Promise.all(n.map(n=>x.cp(_.join(e,n),_.join(t,n),{recursive:!0,force:!1})))}function yr(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 br(e,t){let n=``,r=1,i=e.metadata.displayPath;n+=`${r++}. Check ${K(i)} and refine your environment schema.\n`;let a=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!t;if(e.metadata.framework===`nextjs`){if(e.metadata.disableCodegen)n+=`${r++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`;else{if(a){let t=q(`@arkenv/nextjs`,fn(e.metadata.validator),`config`);n+=`${r++}. Wrap your Next.js config with ${K(`withArkEnv`)} inside ${K(`next.config.ts`)}:\n`,n+=` ${K(`import { withArkEnv } from "${t}";`)}\n`,n+=` ${K(`export default withArkEnv(nextConfig);`)}\n`}n+=`${r++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`}}else n+=`${r++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`;return e.metadata.skillDetected||(n+=`${r++}. (Recommended) Install the AI skill: ${K(`npx skills add yamcodes/arkenv`)}\n`),{message:n,title:`Next steps`}}const xr=[`esbuild`];var Sr=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 ${K(e.clone.example)}...`),await _r(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files)t.action===`create`&&await this.workspace.exists(t.path)||(await this.workspace.mkdir(_.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content));if(t.stop(`Configuration scaffolded!`),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 ${K(e.install.packageManager)}...`);let[t,n]=yr(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 ${K(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${K(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let r=!1;if(e.bootstrap){let t=fn(e.metadata.validator),n={standard:t};if(e.bootstrap.framework===`vite`){let r=await this.workspace.findViteConfig(e.cwd),i=q(`@arkenv/vite-plugin`,t);if(r){this.reporter.step(`Bootstrapping Vite plugin...`);let t=await this.workspace.bootstrapViteConfig(r,e.bootstrap.importPath||`./src/env`,n);t.success?t.updated&&this.reporter.info(`Updated ${K(_.basename(r))}`):(this.reporter.warn(`Could not automatically update ${K(_.basename(r))}: ${t.error}`),this.reporter.info(`Please add ${K(i)} manually.`))}else this.reporter.info(`No Vite config found - please add ${K(i)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),r=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures,n);r.success&&r.instructions?this.reporter.info(r.instructions):r.success||this.reporter.error(r.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let n=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(process.cwd(), '.arkenv', 'env.gen.ts'); runCodegen(schemaPath, outputPath, ${t}); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,n],e.cwd),this.reporter.info(`Generated ${K(`.arkenv/env.gen.ts`)} for Next.js`);let t=await this.workspace.ensureNextjsArkEnvTsConfig(e.tsConfig?.path);t.status===`updated`&&this.reporter.info(`Mapped ${K(`@/.arkenv`)} in ${K(t.file||`tsconfig.json`)}`)}catch{this.reporter.warn(`Failed to automatically generate ${K(`.arkenv/env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let i=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen,n);i.success?i.updated?(this.reporter.info(`Updated ${K(_.basename(t))}`),r=!0):(this.reporter.info(`${K(_.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${K(_.basename(t))}: ${i.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${K(`withArkEnv`)} manually.`)}}else if(e.bootstrap.framework===`nuxt`){this.reporter.step(`Bootstrapping Nuxt config...`);let i=q(`@arkenv/nuxt`,t,`module`),a=await this.workspace.findNuxtConfig(e.cwd);if(a){let e=await this.workspace.bootstrapNuxtConfig(a,n);e.success?(e.updated?this.reporter.info(`Updated ${K(_.basename(a))}`):this.reporter.info(`${K(_.basename(a))} already registers ${i}`),r=!0):this.reporter.warn(`Could not automatically update ${K(_.basename(a))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${K(i)} manually.`)}else if(e.bootstrap.framework===`rsbuild`){this.reporter.step(`Bootstrapping Rsbuild plugin...`);let i=q(`@arkenv/rsbuild-plugin`,t),a=await this.workspace.findRsbuildConfig(e.cwd);if(a){let e=await this.workspace.bootstrapRsbuildConfig(a,n);e.success?(e.updated?this.reporter.info(`Updated ${K(_.basename(a))}`):this.reporter.info(`${K(_.basename(a))} already registers ${i}`),r=!0):(this.reporter.warn(`Could not automatically update ${K(_.basename(a))}: ${e.error}`),this.reporter.info(`Please add ${K(i)} manually.`))}else this.reporter.info(`No Rsbuild config found - please add ${K(i)} to your Rsbuild config manually.`)}}let i=br(e,r);this.reporter.note(i.message,i.title),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},`init`)}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=_.join(e,`pnpm-workspace.yaml`),n=``;if(await this.workspace.exists(t))try{n=await this.workspace.readFile(t)}catch{}let r=this.updatePnpmWorkspaceYaml(n);try{await this.workspace.writeFile(t,r)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=ne(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if(O(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),O(n))for(let e of xr)n.get(e)!==!0&&n.set(e,!0);return String(t)}};const Cr={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 wr(e){if(e===`nextjs`||e===`nuxt`)return Cr[e]}function Tr(e){return e===`nextjs`||e===`nuxt`}const Er={nextjs:Cr.nextjs.clientPrefix,nuxt:Cr.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``,rsbuild:`PUBLIC_`};function Dr(e,t){let n=wr(e.framework);return{framework:e.framework,validator:e.validator,clientPrefix:Er[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const Or={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`};function kr(e){let t={};for(let n of e)t[n]=Or[n]??``;return t}function Ar(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?_.dirname(n.path):e,a=_.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 jr(e,t){if(Tr(t.framework)&&!t.disableCodegen){if(t.framework===`nextjs`)return`@/.arkenv`;if(e.tsConfig?.parsed)return Ar(e.cwd,_.join(e.targetDir,`generated`),e.tsConfig.parsed)}}function Mr(e,t,n,r){let i=Dr(t,r),a=e.getSimpleTemplate(t.envKeys??[],i),o=n.existingFiles.includes(n.targetPath);return!o||t.overwriteEnvSchemaFile!==!1?[{path:n.targetPath,content:a,action:o?`overwrite`:`create`,label:`environment schema`}]:[]}const Nr={clientPrefix:Er[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?kr(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`]:[]},bootstrap(e){return l({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return Mr(e,t,n)}};function Pr(e){let{id:t,packageName:n,clientPrefix:r,supportsWrapNextjsConfig:i}=e,a=`${r}API_URL`;return{clientPrefix:r,getEnvDefaults(e){return e&&e.length>0?kr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[a]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[n]},bootstrap(e){return l({framework:t,...i&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){return Mr(e,t,n,jr(n,t))}}}const Fr=Pr(Cr.nextjs),Ir=Pr(Cr.nuxt),Lr={clientPrefix:Er.rsbuild,getEnvDefaults(e){return e&&e.length>0?kr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[`@arkenv/rsbuild-plugin`]},bootstrap(){return l({framework:`rsbuild`})},getSchemaFiles(e,t,n){return Mr(e,t,n)}},Rr={clientPrefix:Er.vanilla,getEnvDefaults(e){return e&&e.length>0?kr(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},bootstrap(){},getSchemaFiles(e,t,n){return Mr(e,t,n)}},zr={vite:{clientPrefix:Er.vite,getEnvDefaults(e){return e&&e.length>0?kr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,VITE_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[`@arkenv/vite-plugin`]},bootstrap(){return l({framework:`vite`})},getSchemaFiles(e,t,n){return Mr(e,t,n)}},"bun-fullstack":Nr,nextjs:Fr,nuxt:Ir,vanilla:Rr,rsbuild:Lr},Br={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-zod":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-vite-react-zod":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-tanstack-start":{DATABASE_URL:`postgres://localhost:5432/tanstackstart`,PORT:`3000`,VITE_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-tanstack-start-rsbuild":{DATABASE_URL:`postgres://localhost:5432/tanstackstartrsbuild`,PORT:`3000`,PUBLIC_API_URL:`https://api.example.com`,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 Vr(e,t){return Br[e]??t()}function Hr(e,t,n,r){if(!r||r===`none`)return;let i=Yn(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=/* @__PURE__ */ 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,validator:r,config:i,importPath:a,disableCodegen:o,hostPreset:s}=e,{clientPrefix:c}=i,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 Kr({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,validator:r,config:i,nextjsImportPath:a,disableCodegen:o,hostPreset:s})}function Kr(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,validator:o,config:s,nextjsImportPath:c,disableCodegen:l,hostPreset:u}=e,{clientPrefix:d,packageName:f,displayName:p}=s,m=s.id,h=a.extraImport,g=Yn(u??`none`,d),_;if(u&&u!==`none`&&g.length>0){let e=[...t,...n,...r].filter(e=>{let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/)?.[1];return t&&!g.includes(t)}).map(e=>e.replace(/^\t\t/,` `)),i=[];for(let e of g){let t=d&&e.startsWith(d)?`client`:e===`NODE_ENV`?`shared`:`server`;i.push(`\t${a.formatCodegenField(e,t,d,u)}`)}let o=Y[u]?.label??u;_=[...e,...e.length>0?[``]:[],`\t// ${o} environment variables`,...i]}else _=[...t,...n,...r].map(e=>e.replace(/^\t\t/,` `));let v=[];for(let e of r){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&v.push(e)}}let y=[];if(v.length>0&&y.push(`\texposeToClient: [${v.map(e=>`"${e}"`).join(`, `)}]`),l&&m===`nextjs`){let e=Wr(i,d,n,v);y.push(`\truntimeEnv: {\n${e.join(`
|
|
92
|
+
`)}\n\t}`)}let b=y.length>0?`, {\n${y.join(`,
|
|
93
|
+
`)}\n}`:``,x=q(f,fn(o));return`${[`import arkenv from "${m===`nuxt`||l?x:c||`@/.arkenv`}";`,...h?[h]:[]].join(`
|
|
114
94
|
`)}
|
|
115
95
|
|
|
116
96
|
/**
|
|
117
97
|
* Environment variable schema.
|
|
118
|
-
* ${
|
|
98
|
+
* ${m===`nuxt`?`In ${p}, use \`${x}\` to validate variables at build-time and runtime.`:`In ${p}, import the generated \`arkenv\` from \`@/.arkenv\` to validate variables.`}
|
|
119
99
|
* Enforces client/server separation and prevents secret leaks.
|
|
120
100
|
*/
|
|
121
101
|
export const env = arkenv({
|
|
122
|
-
${
|
|
102
|
+
${_.join(`
|
|
123
103
|
`)}
|
|
124
|
-
}${
|
|
125
|
-
`}function
|
|
126
|
-
PORT: "number.port = 3000",`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(
|
|
127
|
-
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`\t\t${e}API_URL: "string = 'https://api.example.com'",`],sharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]}},assembleVanilla(e){return
|
|
104
|
+
}${b});
|
|
105
|
+
`}function qr(e,t,n){let r=Yn(n.hostPreset??`none`,n.clientPrefix),i=wr(n.framework);if(i){let a=t.length>0?Array.from(/* @__PURE__ */ new Set([...t,...r])):void 0;return`${Gr({...a===void 0?{}:{envKeys:a},dialect:e,validator:n.validator,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(n.hostPreset&&n.hostPreset!==`none`&&r.length>0){let i=`\t\t// ${Y[n.hostPreset]?.label??n.hostPreset} environment variables`,o=e.formatSimpleSchemaFields(r,n.clientPrefix,n.hostPreset),s=t.filter(e=>!r.includes(e));a=s.length>0?`${e.formatSimpleSchemaFields(s,n.clientPrefix,void 0)}\n\n${i}\n${o}`:`${e.defaultSimpleSchemaFields}\n\n${i}\n${o}`}else a=t.length>0?e.formatSimpleSchemaFields(t,n.clientPrefix,n.hostPreset):e.defaultSimpleSchemaFields;return`${e.assembleVanilla(a)}\n`}function Jr(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function $(e,t,n,r){let i=Xn(t,n,r);if(i)return Jr(e,i)}const Yr={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=$(Yr,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},defaultSimpleSchemaFields:` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
|
|
106
|
+
PORT: "number.port = 3000",`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Yr,e,t,n)??`"string?"`},`).join(`
|
|
107
|
+
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`\t\t${e}API_URL: "string = 'https://api.example.com'",`],sharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]}},assembleVanilla(e){return T`
|
|
128
108
|
import arkenv, { type } from "@arkenv/core";
|
|
129
109
|
|
|
130
110
|
/**
|
|
@@ -133,9 +113,9 @@ ${g.join(`
|
|
|
133
113
|
export const env = arkenv({
|
|
134
114
|
${e}
|
|
135
115
|
});
|
|
136
|
-
`}},
|
|
137
|
-
PORT: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(
|
|
138
|
-
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]}},assembleVanilla(e){return
|
|
116
|
+
`}},Xr={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=$(Xr,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},defaultSimpleSchemaFields:` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
|
|
117
|
+
PORT: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Xr,e,t,n)??`v.optional(v.string())`},`).join(`
|
|
118
|
+
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]}},assembleVanilla(e){return T`
|
|
139
119
|
import { arkenv } from "@arkenv/standard/valibot";
|
|
140
120
|
import * as v from "valibot";
|
|
141
121
|
|
|
@@ -145,9 +125,9 @@ ${e}
|
|
|
145
125
|
export const env = arkenv({
|
|
146
126
|
${e}
|
|
147
127
|
});
|
|
148
|
-
`}},
|
|
149
|
-
PORT: z.int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(
|
|
150
|
-
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},assembleVanilla(e){return
|
|
128
|
+
`}},Zr={extraImport:`import * as z from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=$(Zr,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
|
|
129
|
+
PORT: z.int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Zr,e,t,n)??`z.string().optional()`},`).join(`
|
|
130
|
+
`)},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},assembleVanilla(e){return T`
|
|
151
131
|
import arkenv from "@arkenv/standard";
|
|
152
132
|
import * as z from "zod";
|
|
153
133
|
|
|
@@ -157,9 +137,9 @@ ${e}
|
|
|
157
137
|
export const env = arkenv({
|
|
158
138
|
${e}
|
|
159
139
|
});
|
|
160
|
-
`}},
|
|
140
|
+
`}},Qr={arktype:Yr,zod:Zr,valibot:Xr};function $r(e){return{getSimpleTemplate(t,n){return qr(e,t,n)}}}const ei={arktype:$r(Qr.arktype),zod:$r(Qr.zod),valibot:$r(Qr.valibot)};function ti(e){return e.mode===`new`?si(e):ci(e)}function ni(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 ri(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
|
|
161
141
|
`)+`
|
|
162
|
-
`}function
|
|
142
|
+
`}function ii(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=zr[r.framework],o=_.join(n,`.env`),s=_.join(n,`.env.example`),c=i.includes(o),l=i.includes(s),u=Zn(r.envKeys,r.hostPreset,a.clientPrefix);if(!c){let e=r.envExampleContent===void 0?ri(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:ri(a.getEnvDefaults(u)),action:`create`,label:`environment variables template`})}function ai(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=_.join(n,`.gitignore`),o=i.includes(a),s=r.framework===`nextjs`;if(o&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=ni(e,`.env`),i=ni(e,`.env.local`),o=ni(e,`.arkenv`)||ni(e,`.arkenv/`);if(!n||!i||s&&!o){let e=``;(!n||!i)&&(e+=`
|
|
163
143
|
# Environment variables
|
|
164
144
|
`,n||(e+=`.env
|
|
165
145
|
`),i||(e+=`.env.local
|
|
@@ -173,4 +153,4 @@ ${e}
|
|
|
173
153
|
`;s&&(e+=`
|
|
174
154
|
# ArkEnv generated factory
|
|
175
155
|
.arkenv/
|
|
176
|
-
`),t.files.push({path:a,content:e,action:`create`,label:`.gitignore file`})}}function ai(e){let{mode:t,options:n,packageManager:r}=e,i=n.name&&n.name!==`.`?v.basename(n.name):void 0;return l({displayPath:``,framework:n.framework,validator:n.validator,packageManager:r,importPath:``,mode:t,example:n.example,name:i,skillDetected:n.skillDetected,disableCodegen:n.disableCodegen})}function oi(e,t){e.options.installSkill&&(t.skill={dlxCommand:Br(e.packageManager),packageName:gr,isYes:e.isYes})}function si(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!==`.`?v.join(r,t.name):void 0,a=t.name&&t.name!==`.`?v.basename(t.name):v.basename(r),o={files:[],cwd:r,metadata:ai(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=ni(zr(t.example,()=>Lr[t.framework].getEnvDefaults())),c=i??r;return o.files.push({path:v.join(c,`.env`),content:s,action:`create`,label:`local environment variables`},{path:v.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 ci(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,s=Lr[t.framework],c=$r[t.validator],l=v.resolve(a,t.path),u=v.dirname(l),d={files:[],cwd:a,metadata:ai(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)),ri(e,d),ii(e,d);let p=t.framework===`nextjs`||t.framework===`nuxt`?void 0:t.validator===`arktype`?`@arkenv/core`:`@arkenv/standard`,m=[...p?[p]:[],t.validator,...t.validator===`valibot`?[`@valibot/to-json-schema`]:[],...s.getDependencies(t)];s.requiresArktypePeer(t)&&!m.includes(`arktype`)&&m.push(`arktype`),d.install={packageManager:n,dependencies:Array.from(new Set(m))},i&&r.file&&(d.tsConfig={path:v.resolve(a,r.file),action:`strict`});let h=s.bootstrap(t);h&&(d.bootstrap=h),oi(e,d);let g=v.relative(a,l).replace(/\\/g,`/`),_=g.startsWith(`.`)?g:`./${g}`,y=_.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=_,d.metadata.importPath=y,d.bootstrap&&(d.bootstrap.importPath=y),d}var li=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/v1/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`}]}}}},ui=class{async checkFreshness(e){let{currentVersion:t,packageName:n=`arkenv`,timeoutMs:r=1e3}=e;try{let i=sn(t),a=typeof i?.prerelease[0]==`string`?i.prerelease[0]:`latest`,o=e.distTag||a,s=`https://registry.npmjs.org/${encodeURIComponent(n)}/${encodeURIComponent(o)}`,c=await fetch(s,{signal:AbortSignal.timeout(r),headers:{Accept:`application/json`}});if(!c.ok)return{isOutdated:!1};let l=(await c.json())?.version;return!l||typeof l!=`string`?{isOutdated:!1}:{isOutdated:cn(l,t)>0,latestVersion:l,distTag:o}}catch{return{isOutdated:!1}}}};function di(e,t,n=process.env.npm_config_user_agent||``,r=`latest`){let i=`${e}@${r}`;return n.includes(`pnpm`)?{command:`pnpm`,dlxArgs:[`dlx`,i,...t]}:n.includes(`bun`)?{command:`bunx`,dlxArgs:[i,...t]}:n.includes(`yarn`)?{command:`yarn`,dlxArgs:[`dlx`,i,...t]}:{command:`npx`,dlxArgs:[i,...t]}}async function fi(e){let{command:t,dlxArgs:n}=di(e.packageName,e.args,e.userAgent,e.tag),r=e.spawnFn??x;return new Promise((e,i)=>{let a=r(t,n,{stdio:`inherit`,shell:process.platform===`win32`}),o=()=>{a.kill(`SIGINT`)},s=()=>{a.kill(`SIGTERM`)};process.on(`SIGINT`,o),process.on(`SIGTERM`,s);let c=()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,s)};a.on(`error`,e=>{c(),i(e)}),a.on(`close`,(t,n)=>{if(c(),n===`SIGINT`){e(t??130);return}if(n===`SIGTERM`){e(t??143);return}if(n){e(t??1);return}e(t??0)})})}var pi=class{constructor(e,t,n,r,i=new li,a=new ui,o=fi,s=e=>process.exit(e)){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i,this.versionChecker=a,this.spawner=o,this.exit=s}async execute(e){if(!process.env.CI&&process.stdout.isTTY&&!e.isQuiet&&!e.isAgent&&!e.isYes){let e=await this.versionChecker.checkFreshness({currentVersion:ur,packageName:lr,timeoutMs:1e3});if(e.isOutdated&&e.latestVersion){let t=await this.prompt.confirm(`Version ${e.latestVersion} is available (running ${ur}). Run latest instead?`,!0,`Yes (Recommended)`);if(t===null)return this.logger.cancel(`Operation cancelled.`),!1;if(t){let t=process.argv.slice(2),n=t[0]===`init`?t:[`init`,...t],r=await this.spawner({packageName:lr,args:n,tag:e.distTag});return this.exit(r),!0}}}let t=await this.collect(e);if(!t)return!1;let n=ei(t),r=new br(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&&v.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?v.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 ${J(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${J(`arkenv init`)} in an empty directory or use ${J(`--force`)} to proceed anyway.`),this.logger.refuse({code:M.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,why:`To scaffold a new project, run arkenv init in an empty directory or use --force to proceed anyway.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,t){let{isYes:n,isForce:r,isQuiet:i,isAgent:a}=e,o=await this.scanner.checkRequirements(t),s=o.filter(e=>e.status===`fail`),c=o.filter(e=>e.status===`warn`);for(let e of c)this.logger.warn(`${e.requirement}: ${e.message}`);if(s.length>0)if(r){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of s)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of s)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:M.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,why:`Technical requirements (e.g. Node.js version) were not met.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass technical requirements`,command:`{bin} init --force`}],details:{requirements:s.map(e=>l({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}},`init`),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:M.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv init.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} init --force`}]},`init`),null;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 ${J(f.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${J(`strict`)} mode in your ${J(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 p=await this.scanner.detectFramework(t,f.parsed),m=p===`bun-fullstack`?await this.scanner.detectBunFeatures(t,f.parsed):void 0,h=await this.scanner.suggestDefaultEnvPath(t,f.parsed),g=v.resolve(t,h),_=await this.scanner.getEnvExampleKeys(t,f.parsed,g),y=await this.workspace.exists(g),b=await this.prompt.runWizard(l({mode:`existing`,framework:p,bunFeatures:m,defaultEnvPath:h,tsConfig:f.parsed??null,envKeys:_?.keys,envKeysSource:_?.source,hasEnvSchemaFile:y,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),n);if(b===null)return null;let x=await this.scanner.hasSkill(t);if(x&&(b.skillDetected=!0,!i&&!a&&this.logger.info(`ArkEnv agent skill detected.`)),x)b.installSkill=!1;else if(a)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=v.resolve(t,b.path);if(b.overwriteEnvSchemaFile===void 0&&await this.workspace.exists(S)){let e=v.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=[S],T=[];for(let e of w)await this.workspace.exists(e)&&T.push(e);let E=v.join(t,`.env`),D=v.join(t,`.env.example`);await this.workspace.exists(E)&&T.push(E),await this.workspace.exists(D)&&(T.push(D),b.envExampleContent=await this.workspace.readFile(D));let O=v.join(t,`.gitignore`);return await this.workspace.exists(O)&&(T.push(O),b.gitignoreContent=await this.workspace.readFile(O)),l({mode:`existing`,cwd:t,options:b,detectedFramework:p,detectedBunFeatures:m,packageManager:C,tsConfig:f,shouldUpdateTsConfig:d,existingFiles:T,isYes:n})}async collectNewProject(e,t=!0){let{isYes:n,example:r,name:i,isForce:a}=e,o=await this.registry.fetchRegistry(),s=await this.prompt.runWizard(l({mode:`new`,examples:o.examples,example:r,name:i}),n);if(s===null)return null;if(s.name===`.`&&!t&&!a)return this.logger.error(`Cannot scaffold into ${J(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${J(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:M.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,why:`Run arkenv init in an empty directory or choose a sub-directory name instead, or use --force.`,retryWith:[`--force`],nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null;let c=this.detectPackageManager();return l({mode:`new`,cwd:process.cwd(),options:s,detectedFramework:s.framework,packageManager:c,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 mi(e,t={}){let n=new ir(e),r=n.logger,i=new In(n.isQuiet,r.stdio,r),a=new tr,o=new fn(r),s=new Gt(t.jitiAliases?{jitiAliases:t.jitiAliases}:{});return{cli:n,logger:r,workspace:i,prompt:a,initUseCase:new pi(r,i,a,o),checkUseCase:new cr(r,i,o,s),helpUseCase:new fr(r),schemaLoader:s}}const hi=new jt({isQuiet:!1,isJson:!1});let gi,_i=!1;async function vi(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:t,initUseCase:n,helpUseCase:r,checkUseCase:i}=mi(process.argv);gi=t,yi(t,e.command),e.validationError&&(t.error(e.validationError),await r.execute(),await t.flush(),process.exit(2)),e.helpRequested&&(await r.execute(),await t.flush(),process.exit(0));let a=e.command?{init:()=>n.execute(l(e.initInput)),check:()=>i.execute(e.checkInput)}[e.command]:void 0;a||(e.command?t.error(`Unknown command: ${e.command}`):t.error(`Missing command.`),await r.execute(),await t.flush(),process.exit(2));try{let e=await a();typeof e==`number`&&(await t.flush(),process.exit(e)),e||(await t.flush(),process.exit(2)),await t.flush(),process.exit(0)}catch(n){try{t.fatal(`An unexpected error occurred`,n,e.command||`cli`)}catch{}await t.flush(),process.exit(1)}}function yi(e,t){let n=async n=>{_i&&process.exit(n),_i=!0,setTimeout(()=>{process.exit(n)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`,t),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(n===130?3:n)}};process.on(`SIGINT`,()=>n(130)),process.on(`SIGTERM`,()=>n(143))}vi(),process.on(`unhandledRejection`,async e=>{let t=gi??hi;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=gi??hi;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});export{};
|
|
156
|
+
`),t.files.push({path:a,content:e,action:`create`,label:`.gitignore file`})}}function oi(e){let{mode:t,options:n,packageManager:r}=e,i=n.name&&n.name!==`.`?_.basename(n.name):void 0;return l({displayPath:``,framework:n.framework,validator:n.validator,packageManager:r,importPath:``,mode:t,example:n.example,name:i,skillDetected:n.skillDetected,disableCodegen:n.disableCodegen})}function si(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!==`.`?_.join(r,t.name):void 0,a=t.name&&t.name!==`.`?_.basename(t.name):_.basename(r),o={files:[],cwd:r,metadata:oi(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}}},s=ri(Vr(t.example,()=>zr[t.framework].getEnvDefaults())),c=i??r;return o.files.push({path:_.join(c,`.env`),content:s,action:`create`,label:`local environment variables`},{path:_.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 ci(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:o}=e,s=zr[t.framework],c=ei[t.validator],l=_.resolve(a,t.path),u=_.dirname(l),d={files:[],cwd:a,metadata:oi(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)),ii(e,d),ai(e,d);let p=(t.framework===`nextjs`||t.framework===`nuxt`)&&t.validator===`arktype`,m=t.validator===`arktype`?`@arkenv/core`:`@arkenv/standard`,h=[...p?[]:[m],t.validator,...t.validator===`valibot`?[`@valibot/to-json-schema`]:[],...s.getDependencies(t)];d.install={packageManager:n,dependencies:Array.from(new Set(h))},i&&r.file&&(d.tsConfig={path:_.resolve(a,r.file),action:`strict`});let g=s.bootstrap(t);g&&(d.bootstrap=g);let v=_.relative(a,l).replace(/\\/g,`/`),y=v.startsWith(`.`)?v:`./${v}`,b=y.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=y,d.metadata.importPath=b,d.bootstrap&&(d.bootstrap.importPath=b),d}var li=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/v1/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`}]}}}},ui=class{async checkFreshness(e){let{currentVersion:t,packageName:n=`arkenv`,timeoutMs:r=1e3}=e;try{let i=an(t),a=typeof i?.prerelease[0]==`string`?i.prerelease[0]:`latest`,o=e.distTag||a,s=`https://registry.npmjs.org/${encodeURIComponent(n)}/${encodeURIComponent(o)}`,c=await fetch(s,{signal:AbortSignal.timeout(r),headers:{Accept:`application/json`}});if(!c.ok)return{isOutdated:!1};let l=(await c.json())?.version;return!l||typeof l!=`string`?{isOutdated:!1}:{isOutdated:on(l,t)>0,latestVersion:l,distTag:o}}catch{return{isOutdated:!1}}}};function di(e,t,n=process.env.npm_config_user_agent||``,r=`latest`){let i=`${e}@${r}`;return n.includes(`pnpm`)?{command:`pnpm`,dlxArgs:[`dlx`,i,...t]}:n.includes(`bun`)?{command:`bunx`,dlxArgs:[i,...t]}:n.includes(`yarn`)?{command:`yarn`,dlxArgs:[`dlx`,i,...t]}:{command:`npx`,dlxArgs:[i,...t]}}async function fi(e){let{command:t,dlxArgs:n}=di(e.packageName,e.args,e.userAgent,e.tag),r=e.spawnFn??b;return new Promise((e,i)=>{let a=r(t,n,{stdio:`inherit`,shell:process.platform===`win32`}),o=()=>{a.kill(`SIGINT`)},s=()=>{a.kill(`SIGTERM`)};process.on(`SIGINT`,o),process.on(`SIGTERM`,s);let c=()=>{process.off(`SIGINT`,o),process.off(`SIGTERM`,s)};a.on(`error`,e=>{c(),i(e)}),a.on(`close`,(t,n)=>{if(c(),n===`SIGINT`){e(t??130);return}if(n===`SIGTERM`){e(t??143);return}if(n){e(t??1);return}e(t??0)})})}var pi=class{constructor(e,t,n,r,i=new li,a=new ui,o=fi,s=e=>process.exit(e)){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i,this.versionChecker=a,this.spawner=o,this.exit=s}async execute(e){if(!process.env.CI&&process.stdout.isTTY&&!e.isQuiet&&!e.isAgent&&!e.isYes){let e=await this.versionChecker.checkFreshness({currentVersion:mr,packageName:pr,timeoutMs:1e3});if(e.isOutdated&&e.latestVersion){let t=await this.prompt.confirm(`Version ${e.latestVersion} is available (running ${mr}). Run latest instead?`,!0,`Yes (Recommended)`);if(t===null)return this.logger.cancel(`Operation cancelled.`),!1;if(t){let t=process.argv.slice(2),n=t[0]===`init`?t:[`init`,...t],r=await this.spawner({packageName:pr,args:n,tag:e.distTag});return this.exit(r),!0}}}let t=await this.collect(e);if(!t)return!1;let n=ti(t),r=new Sr(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&&_.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?_.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);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 ${K(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${K(`arkenv init`)} in an empty directory or use ${K(`--force`)} to proceed anyway.`),this.logger.refuse({code:A.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,why:`To scaffold a new project, run arkenv init in an empty directory or use --force to proceed anyway.`,nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null):await this.collectNewProject(n,o)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,t){let{isYes:n,isForce:r}=e,i=await this.scanner.checkRequirements(t),a=i.filter(e=>e.status===`fail`),o=i.filter(e=>e.status===`warn`);for(let e of o)this.logger.warn(`${e.requirement}: ${e.message}`);if(a.length>0){if(r){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of a)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of a)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:A.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,why:`Technical requirements (e.g. Node.js version) were not met.`,nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass technical requirements`,command:`{bin} init --force`}],details:{requirements:a.map(e=>l({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}},`init`),null}}let s=await this.scanner.checkGitStatus(t);if(s.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:A.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,why:`Commit or stash your changes before running arkenv init.`,nextActions:[{kind:`run-command`,label:`Re-run with --force to bypass git working tree check`,command:`{bin} init --force`}]},`init`),null}s.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let c=!1,u=await this.scanner.checkTsConfig(t);if(u.status===`not_strict`){if(n)c=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${K(u.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${K(`strict`)} mode in your ${K(u.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;c=!0}}let d=await this.scanner.detectFramework(t,u.parsed),f=d===`bun-fullstack`?await this.scanner.detectBunFeatures(t,u.parsed):void 0,p=await this.scanner.suggestDefaultEnvPath(t,u.parsed),m=_.resolve(t,p),h=await this.scanner.getEnvExampleKeys(t,u.parsed,m),g=await this.workspace.exists(m),v=await this.prompt.runWizard(l({mode:`existing`,framework:d,bunFeatures:f,defaultEnvPath:p,tsConfig:u.parsed??null,envKeys:h?.keys,envKeysSource:h?.source,hasEnvSchemaFile:g,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),n);if(v===null)return null;v.skillDetected=await this.scanner.hasSkill(t);let y=_.resolve(t,v.path);if(v.overwriteEnvSchemaFile===void 0&&await this.workspace.exists(y)){let e=_.basename(y),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;v.overwriteEnvSchemaFile=t}let b=await this.scanner.detectPackageManager(t,u.parsed),x=[y],S=[];for(let e of x)await this.workspace.exists(e)&&S.push(e);let C=_.join(t,`.env`),w=_.join(t,`.env.example`);await this.workspace.exists(C)&&S.push(C),await this.workspace.exists(w)&&(S.push(w),v.envExampleContent=await this.workspace.readFile(w));let T=_.join(t,`.gitignore`);return await this.workspace.exists(T)&&(S.push(T),v.gitignoreContent=await this.workspace.readFile(T)),l({mode:`existing`,cwd:t,options:v,detectedFramework:d,detectedBunFeatures:f,packageManager:b,tsConfig:u,shouldUpdateTsConfig:c,existingFiles:S,isYes:n})}async collectNewProject(e,t=!0){let{isYes:n,example:r,name:i,isForce:a}=e,o=await this.registry.fetchRegistry(),s=await this.prompt.runWizard(l({mode:`new`,examples:o.examples,example:r,name:i}),n);if(s===null)return null;if(s.name===`.`&&!t&&!a)return this.logger.error(`Cannot scaffold into ${K(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${K(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:A.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,why:`Run arkenv init in an empty directory or choose a sub-directory name instead, or use --force.`,nextActions:[{kind:`run-command`,label:`Re-run with --force to scaffold into non-empty directory`,command:`{bin} init --force`}]},`init`),null;let c=this.detectPackageManager();return l({mode:`new`,cwd:process.cwd(),options:s,detectedFramework:s.framework,packageManager:c,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 mi(e,t={}){let n=new cr(e),r=n.logger,i=new Bn(n.isQuiet,r.stdio,r),a=new ar,o=new un(r),s=new Wt(t.jitiAliases?{jitiAliases:t.jitiAliases}:{});return{cli:n,logger:r,workspace:i,prompt:a,initUseCase:new pi(r,i,a,o),checkUseCase:new fr(r,i,o,s),helpUseCase:new gr(r),schemaLoader:s}}const hi=new At({isQuiet:!1,isJson:!1});let gi,_i=!1;async function vi(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:t,initUseCase:n,helpUseCase:r,checkUseCase:i}=mi(process.argv);gi=t,yi(t,e.command),e.validationError&&(t.error(e.validationError),await r.execute(),await t.flush(),process.exit(2)),e.helpRequested&&(await r.execute(),await t.flush(),process.exit(0));let a=e.command?{init:()=>n.execute(l(e.initInput)),check:()=>i.execute(e.checkInput)}[e.command]:void 0;a||(e.command?t.error(`Unknown command: ${e.command}`):t.error(`Missing command.`),await r.execute(),await t.flush(),process.exit(2));try{let e=await a();typeof e==`number`&&(await t.flush(),process.exit(e)),e||(await t.flush(),process.exit(2)),await t.flush(),process.exit(0)}catch(n){try{t.fatal(`An unexpected error occurred`,n,e.command||`cli`)}catch{}await t.flush(),process.exit(1)}}function yi(e,t){let n=async n=>{_i&&process.exit(n),_i=!0,setTimeout(()=>{process.exit(n)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`,t),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(n===130?3:n)}};process.on(`SIGINT`,()=>n(130)),process.on(`SIGTERM`,()=>n(143))}vi(),process.on(`unhandledRejection`,async e=>{let t=gi??hi;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=gi??hi;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
const e=`ArkEnvError`,t=(e,t=2,{dontDetectNewlines:n=!1}={})=>n?`${` `.repeat(t)}${e}`:e.split(`
|
|
2
2
|
`).map(e=>`${` `.repeat(t)}${e}`).join(`
|
|
3
|
-
`),n={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`};function r(){try{let e=Reflect.get(globalThis,`process`);if(e&&typeof e==`object`)return e}catch{}}const i=()=>!!r()?.versions?.node,a=()=>{let e=r();if(!e?.versions?.node)return!0;let t=e.env??{};if(t.NO_COLOR!==void 0||t.CI!==void 0)return!0;let n=e.stdout;return
|
|
4
|
-
`)}Object.defineProperty(class extends Error{constructor(n,r=`Errors found while validating environment variables`){let i=s(n);super(`${o(`red`,r)}\n${t(i)}\n`),this.name=e,this.issues=n}}
|
|
3
|
+
`),n={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`};function r(){try{let e=Reflect.get(globalThis,`process`);if(e&&typeof e==`object`)return e}catch{}}const i=()=>!!r()?.versions?.node,a=()=>{let e=r();if(!e?.versions?.node)return!0;let t=e.env??{};if(t.NO_COLOR!==void 0||t.CI!==void 0)return!0;let n=e.stdout;return!(!n||n.isTTY)},o=(e,t)=>i()&&!a()?`${n[e]}${t}${n.reset}`:t;function s(e){return e.map(e=>`${o(`yellow`,e.path)} ${e.message.trimStart()}`).join(`
|
|
4
|
+
`)}Object.defineProperty(class extends Error{constructor(n,r=`Errors found while validating environment variables`){let i=s(n);super(`${o(`red`,r)}\n${t(i)}\n`),this.name=e,this.issues=n}},"name",{value:e});const c=/secret|(_|^)key(_|$)|token|(_|^)password(_|$)|(_|^)pass(_|$)|(_|^)auth(_|$)|jwt|cert|credential|database_url|db_url/i;function l(e){if(e!==void 0)return e;if(typeof process>`u`)return!1;let t=process.env.ARKENV_DEBUG_SECRETS;return t===`true`||t===`1`}function u(e){return c.test(e)&&!/public/i.test(e)}function d(e,t,n){let r=l(n?.debugSecrets);if(e===void 0)return`missing`;if(e===null)return`null`;if(!r&&u(t))return`[REDACTED]`;if(typeof e==`string`)return JSON.stringify(e);if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);if(typeof e==`symbol`)return e.toString();if(typeof e==`function`)return`[Function]`;if(e&&typeof e==`object`)try{if(Array.isArray(e)){let r=e.slice(0,3).map(e=>d(e,t,n));return e.length>3&&r.push(`...(+${e.length-3} more)`),`[${r.join(`, `)}]`}let r=Object.keys(e),i=r.slice(0,3).map(r=>`${r}: ${d(e[r],t,n)}`);return r.length>3&&i.push(`...(+${r.length-3} more)`),`{ ${i.join(`, `)} }`}catch{return Object.prototype.toString.call(e)}return String(e)}function f(e){if(!e||typeof e!=`object`&&typeof e!=`function`)return[];if(e.json&&typeof e.json==`object`&&e.json.domain===`object`){let t=[];if(Array.isArray(e.json.required))for(let n of e.json.required)n&&typeof n==`object`&&`key`in n&&t.push(n.key);if(Array.isArray(e.json.optional))for(let n of e.json.optional)n&&typeof n==`object`&&`key`in n&&t.push(n.key);return t}let t=e[`~standard`],n=typeof t?.jsonSchema?.input==`function`&&t.jsonSchema.input||typeof e.jsonSchema?.input==`function`&&e.jsonSchema.input;if(n)try{let e=n({target:`draft-07`});if(e&&typeof e==`object`&&e.properties)return Object.keys(e.properties)}catch{}if(typeof e.toJSONSchema==`function`)try{let t=e.toJSONSchema();if(t&&typeof t==`object`&&t.properties)return Object.keys(t.properties)}catch{}if(typeof e.toStandardJSONSchema?.v1==`function`)try{let t=e.toStandardJSONSchema.v1();if(t&&typeof t==`object`&&t.properties)return Object.keys(t.properties)}catch{}return Object.keys(e)}const p=Symbol.for(`arkenv.schemaCapture.v1`);function m(){let e=globalThis;return e[p]||(e[p]={capturing:!1,definitions:[]}),e[p]}function h(){let e=m();e.capturing=!0,e.definitions=[]}function g(){let e=m();e.capturing=!1;let t=e.definitions.slice();return e.definitions=[],t}function _(e){return`[ArkEnv] ${e}`}export{f as a,d as c,s as i,u as l,g as n,t as o,_ as r,l as s,h as t};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./dist-
|
|
1
|
+
import{r as e}from"./dist-waSn9fHo.js";throw Error(`🚨 ${e("You imported the 'arkenv' package as a library. Starting with v1.0.0, the 'arkenv' package is exclusively the interactive CLI. If you want to validate environment variables in your code, please install and import '@arkenv/core' (or '@arkenv/standard') instead, or run `npx arkenv init` to guide you through setup.")}`);export{};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arkenv",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.0.0-rc.
|
|
4
|
+
"version": "1.0.0-rc.3",
|
|
5
5
|
"description": "Interactive CLI for scaffolding ArkEnv projects",
|
|
6
6
|
"bin": {
|
|
7
7
|
"arkenv": "./bin.mjs"
|
|
@@ -62,8 +62,8 @@
|
|
|
62
62
|
"@repo/log": "0.0.1",
|
|
63
63
|
"@repo/utils": "0.1.3",
|
|
64
64
|
"@types/node": "24.12.2",
|
|
65
|
-
"tsdown": "0.
|
|
66
|
-
"typescript": "
|
|
65
|
+
"tsdown": "0.22.14",
|
|
66
|
+
"typescript": "7.0.2",
|
|
67
67
|
"vitest": "4.1.5"
|
|
68
68
|
}
|
|
69
69
|
}
|