@kizenapps/cli 1.6.3-ab1f449 → 1.7.0-3667650
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/index.js +30 -23
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/AppDetailPage-C0sXm8BK.js +1 -0
- package/dist/viewer/assets/{BootstrapContext-Caqxm0pS.js → BootstrapContext-CS2e3X9Y.js} +1 -1
- package/dist/viewer/assets/Card-Sa52PGkn.js +1 -0
- package/dist/viewer/assets/CodeStepsPage-C6gfmJey.js +1 -0
- package/dist/viewer/assets/{CodeViewer-BdEsrhvR.js → CodeViewer-270Os8MC.js} +2 -2
- package/dist/viewer/assets/ConfigurationPage-BPe2YfgC.js +1 -0
- package/dist/viewer/assets/CredentialsContext-Cwl_xyt_.js +1 -0
- package/dist/viewer/assets/DevSidebar-BRP2rhyU.js +1 -0
- package/dist/viewer/assets/{Dialog-D6sZ1i69.js → Dialog-C3QoiHOt.js} +1 -1
- package/dist/viewer/assets/{IconReferencePage-B4ayBaGk.js → IconReferencePage-DhoHxEaW.js} +1 -1
- package/dist/viewer/assets/SandboxPage-C1g2AVsQ.js +1 -0
- package/dist/viewer/assets/SecretsPage-B74hR1Yn.js +1 -0
- package/dist/viewer/assets/SidebarContext-q5sbcZXM.js +1 -0
- package/dist/viewer/assets/{SourceBrowserPage-H2pFRVF1.js → SourceBrowserPage-BM7YULjl.js} +1 -1
- package/dist/viewer/assets/{Tooltip-4dV1-FIG.js → Tooltip-JYkgiL8J.js} +1 -1
- package/dist/viewer/assets/VersionsPage-RisNLZx3.js +1 -0
- package/dist/viewer/assets/{WhenBadge-BTCs-6JK.js → WhenBadge-2kXXp2JS.js} +1 -1
- package/dist/viewer/assets/{api-LYugLsE_.js → api-Z7hihohh.js} +1 -1
- package/dist/viewer/assets/bootstrapQuery-qFpHSWE9.js +1 -0
- package/dist/viewer/assets/bundleQuery-BE1Gb8Ii.js +1 -0
- package/dist/viewer/assets/configStorage-Bmswf3bC.js +1 -0
- package/dist/viewer/assets/{fa-core-DteucspK.js → fa-core-BSqLAjHu.js} +1 -1
- package/dist/viewer/assets/{iconMap-BotklELY.js → iconMap-B-cS2yrx.js} +1 -1
- package/dist/viewer/assets/index-CjFi83Rf.js +5 -0
- package/dist/viewer/assets/index-Ty4403F6.css +2 -0
- package/dist/viewer/assets/{react-CGXpNBH3.js → react-C5hrIo29.js} +1 -1
- package/dist/viewer/assets/storageKeys-IkM_u7nJ.js +1 -0
- package/dist/viewer/assets/{useCriticalExceptionDialog-DNmzdRI0.js → useCriticalExceptionDialog-C60A18a6.js} +1 -1
- package/dist/viewer/assets/{useLocalStorage-gLSTo_Vv.js → useLocalStorage-CeqPEGCc.js} +1 -1
- package/dist/viewer/assets/useNavigate-BL0GTcH4.js +1 -0
- package/dist/viewer/assets/{bundleQuery-DnoDprqO.js → useParams-D3awshYI.js} +1 -1
- package/dist/viewer/assets/{useQuery-DLOWDn8s.js → useQuery-JKMI40WO.js} +1 -1
- package/dist/viewer/index.html +16 -13
- package/package.json +2 -2
- package/dist/viewer/assets/AppDetailPage-BTSBtvJb.js +0 -1
- package/dist/viewer/assets/Card-CKKHGdG4.js +0 -1
- package/dist/viewer/assets/CodeStepsPage-Krgx1XWT.js +0 -1
- package/dist/viewer/assets/ConfigurationPage-BNA5KrGT.js +0 -1
- package/dist/viewer/assets/DevSidebar-BBRPcthT.js +0 -1
- package/dist/viewer/assets/SandboxPage-CYnP7ZzD.js +0 -1
- package/dist/viewer/assets/SidebarContext-g2Wqf-42.js +0 -1
- package/dist/viewer/assets/VersionsPage-l_9K0iyg.js +0 -1
- package/dist/viewer/assets/configStorage-Db8RcPNR.js +0 -1
- package/dist/viewer/assets/index-BCe-a4I_.css +0 -2
- package/dist/viewer/assets/index-BN2If3Zu.js +0 -5
- package/dist/viewer/assets/storageKeys-Dv0AbTSJ.js +0 -1
- package/dist/viewer/assets/useNavigate-EsATq4C7.js +0 -1
- /package/dist/viewer/assets/{fa-pro-icons-CmhlYbxQ.js → fa-pro-icons-B6J9phvt.js} +0 -0
- /package/dist/viewer/assets/{formatBytes-BCP0hIUu.js → formatBytes-CrFJUAnr.js} +0 -0
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as
|
|
3
|
-
`).map(
|
|
2
|
+
import{readFileSync as Wi}from"fs";import{dirname as Gi,join as Ki}from"path";import{fileURLToPath as Yi}from"url";import{program as xe}from"commander";import{createElement as Wn}from"react";import{render as Gn}from"ink";import{useEffect as qn,useState as St}from"react";import{Box as je,Text as _e,useApp as Vn}from"ink";import{mkdir as Tn,writeFile as En}from"fs/promises";import{join as Pn}from"path";import{minifyFiles as kn,packagePlugin as _n,transformDeployablePlugin as In}from"@kizenapps/packager";import{readdir as xn,readFile as vt}from"fs/promises";import{join as qt,relative as wn}from"path";var vn=new Set([".png",".svg"]),Cn=new Set([".kzn"]),Sn=new Set([".DS_Store"]),Ze=new Set(["node_modules",".git",".kizenapp",".github"]);async function Vt(e,t){let o=await xn(e,{withFileTypes:!0}),n=[];for(let r of o)if(r.isDirectory()){if(Ze.has(r.name))continue;n.push(...await Vt(qt(e,r.name),t))}else r.isFile()&&(Sn.has(r.name)||n.push(qt(e,r.name)));return n}async function Qe(e){let t=await Vt(e,e);return Promise.all(t.map(async o=>{let n=wn(e,o).split("\\").join("/"),r=n.lastIndexOf("."),i=r>=0?n.slice(r).toLowerCase():"";if(vn.has(i)){let p=await vt(o);return{path:n,content:"",base64Image:p.toString("base64")}}if(Cn.has(i)){let p=await vt(o);return{path:n,content:"",binaryData:p}}let f=await vt(o,"utf-8");return{path:n,content:f}}))}var Nn=["name","api_name","version","entry"];function Jt(e,t){let o=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let n of Nn){let r=e[n];if(typeof r!="string"||r==="")throw new Error(`${o} is missing required field "${n}" (expected a non-empty string).`)}}function Bn(e){let t;try{t=JSON.parse(e)}catch(o){let n=o instanceof Error?o.message:String(o);throw new Error(`kizen.json is not valid JSON: ${n}`)}if(Array.isArray(t))return t.forEach((o,n)=>{if(typeof o!="object"||o===null)throw new Error(`kizen.json entry #${String(n+1)} is not a JSON object.`);Jt(o,n)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return Jt(t),t}var Rn=(e,t)=>({...e,thumbnail:e.thumbnail?Buffer.from(e.thumbnail).toString("base64"):null,kznFile:e.kznFile?Buffer.from(e.kznFile).toString("base64"):null,allReleaseNotes:t});async function et(e,t,o){await Tn(t,{recursive:!0}),o?.("reading-files");let n=await Qe(e);o?.("minifying");let r=await kn(n);o?.("packaging");let i=r.find(l=>l.path==="kizen.json");if(!i)throw new Error("kizen.json not found in plugin directory.");let f=Bn(i.content),p=_n(r,f),m=Object.values(p).map(In);o?.("writing-bundle");let g=m.map(l=>{let x=l.release_notes_directory?.replace(/\/$/,""),N=x?n.filter(I=>I.path.startsWith(x+"/")&&I.path.endsWith(".md")&&I.content).map(I=>({version:I.path.slice(I.path.lastIndexOf("/")+1,-3),notes:I.content})).sort((I,T)=>T.version.localeCompare(I.version,void 0,{numeric:!0})):[];return Rn(l,N)}),w=JSON.stringify(g,null,2),v=(l,x)=>l==="allReleaseNotes"?void 0:x,y=Buffer.byteLength(JSON.stringify(g,v,2),"utf-8");return await En(Pn(t,"bundle.json"),w,"utf-8"),{bundleSize:y}}function Oe(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as Fn,Text as On}from"ink";import{Box as Dn,Text as $n}from"ink";import{jsx as Wt}from"react/jsx-runtime";var Ln=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Gt=()=>Wt(Dn,{flexDirection:"column",children:Ln.map((e,t)=>Wt($n,{color:"cyan",children:e},t))});import{Fragment as jn,jsx as Ct,jsxs as An}from"react/jsx-runtime";var V=({marginBottom:e=0})=>An(jn,{children:[Ct(Gt,{}),Ct(Fn,{flexDirection:"column",marginTop:1,marginBottom:e,children:Ct(On,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as zn,useState as Mn}from"react";import{Text as Hn}from"ink";import{jsx as Un}from"react/jsx-runtime";var Kt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],pe=()=>{let[e,t]=Mn(0);return zn(()=>{let o=setInterval(()=>{t(n=>(n+1)%Kt.length)},80);return()=>{clearInterval(o)}},[]),Un(Hn,{color:"cyan",children:Kt[e]??"\u280B"})};import{Fragment as Jn,jsx as Ce,jsxs as Se}from"react/jsx-runtime";var Yt=["creating-dir","reading-files","minifying","packaging","writing-bundle"],tt={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},Xt=({outputDir:e,pluginDir:t})=>{let o=Vn(),[n,r]=St("creating-dir"),[i,f]=St(null),[p,m]=St(null);qn(()=>{et(t,e,r).then(({bundleSize:y})=>{m(y),r("done"),o.exit()}).catch(y=>{let l=y instanceof Error?y.message:String(y);f(l),r("error"),o.exit()})},[e,t,o]);let g=Yt.indexOf(n),w=n==="error",v=n==="done";return Se(je,{flexDirection:"column",paddingY:1,paddingX:2,children:[Ce(V,{marginBottom:1}),Se(je,{flexDirection:"column",gap:0,children:[Yt.map((y,l)=>{let x=n===y,N=v||g>l;return Ce(je,{gap:1,children:w&&l===g?Se(_e,{color:"red",children:["\u2717 ",tt[y]]}):N?Se(_e,{color:"green",children:["\u2713 ",tt[y]]}):x?Se(Jn,{children:[Ce(pe,{}),Ce(_e,{children:tt[y]})]}):Se(_e,{dimColor:!0,children:[" ",tt[y]]})},y)}),v&&p!==null&&Ce(je,{marginTop:1,gap:1,children:Se(_e,{color:"green",children:["\u2713 bundle \u2014 ",Oe(p)]})}),i!==null&&Ce(je,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Ce(_e,{color:"red",children:i})})]})]})};import*as Ie from"fs";import*as Zt from"path";function Ne(e){let t=Zt.join(e,".gitignore"),o=".kizenapp/",n="";if(Ie.existsSync(t)){n=Ie.readFileSync(t,"utf8");let i=n.split(`
|
|
3
|
+
`).map(f=>f.trim());if(i.includes(o)||i.includes(".kizenapp"))return}let r=n.endsWith(`
|
|
4
4
|
`)?o+`
|
|
5
5
|
`:`
|
|
6
6
|
`+o+`
|
|
7
|
-
`;
|
|
8
|
-
`,"utf-8"),await mt(pe(e.targetDir,"src"),{recursive:!0}),await mt(pe(e.targetDir,"releaseNotes"),{recursive:!0}),xe(e.targetDir)}import{jsx as P,jsxs as j}from"react/jsx-runtime";var fe=["name","apiName","externalLink","description","developerBusinessId"],Jt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Wt=["name","apiName"];function In(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var ve=({text:e})=>P(I,{dimColor:!0,children:e});function Bn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Gt=({parentDir:e,defaultBusinessId:t})=>{let o=Tn(),[n,r]=Ee({type:"target-select",cursor:0}),[i,p]=Ee("in-place"),[d,C]=Ee(()=>Bn(t)),[b,y]=Ee(""),[v,h]=Ee(e),l=Ge((S,g)=>{p(S),y(g.name),r({type:"field-entry",field:0,values:g})},[]),x=Ge(async S=>{let g=await qt(S);if(g!=="ok"){r({type:"precheck-error",targetDir:S,reason:g});return}h(S),l("in-place",d)},[d,l]),T=Ge(async S=>{try{let g=await Ut(e,S.apiName);h(g),r({type:"confirm",values:S})}catch(g){r({type:"error",message:g instanceof Error?g.message:String(g)})}},[e]),R=Ge(async(S,g)=>{try{await Vt({targetDir:g,name:S.name,apiName:S.apiName,externalLink:S.externalLink,description:S.description,developerBusinessId:S.developerBusinessId}),r({type:"done",targetDir:g})}catch(f){r({type:"error",message:f instanceof Error?f.message:String(f)})}},[]);if(En((S,g)=>{if(g.ctrl&&S==="c"){o.exit();return}if(n.type==="target-select"){g.upArrow?r({type:"target-select",cursor:0}):g.downArrow?r({type:"target-select",cursor:1}):g.return?n.cursor===0?x(e):l("sub-dir",d):g.escape&&o.exit();return}if(n.type==="precheck-error"){(g.return||g.escape)&&o.exit();return}if(n.type==="field-entry"){let{field:f,values:_}=n,a=fe[f];if(!a)return;if(g.escape){o.exit();return}if(g.backspace||g.delete){y(s=>s.slice(0,-1));return}if(g.upArrow&&f>0){let s={..._,[a]:b},c=f-1,u=fe[c];r({type:"field-entry",field:c,values:s}),C(s),y(u?s[u]:"");return}if(g.return||g.tab||g.downArrow){let s=b.trim();if(Wt.includes(a)&&!s){r({type:"field-entry",field:f,values:_,fieldError:`${Jt[a]} is required`});return}let u=a==="description"?b:s,m={..._,[a]:u};C(m);let F=f+1;if(F>=fe.length)y(""),i==="sub-dir"?(r({type:"resolving-target"}),T(m)):r({type:"confirm",values:m});else{let E=fe[F],D=E?m[E]:"",A=E==="apiName"&&!D?In(m.name):D;r({type:"field-entry",field:F,values:m}),y(A)}return}S&&!g.ctrl&&!g.meta&&y(s=>s+S);return}if(n.type==="confirm"){if(g.escape){let f=fe.length-1,_=fe[f];r({type:"field-entry",field:f,values:n.values}),y(_?n.values[_]:"");return}g.return&&(r({type:"writing"}),R(n.values,v));return}(n.type==="done"||n.type==="error")&&(g.return||g.escape)&&o.exit()}),n.type==="target-select"){let S=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),j(M,{flexDirection:"column",gap:0,children:[P(I,{bold:!0,children:"Where should the new plugin live?"}),S.map((g,f)=>{let _=n.cursor===f;return j(M,{gap:2,children:[P(I,{..._&&{color:"cyan"},children:_?"\u276F":" "}),P(I,{bold:_,..._&&{color:"cyan"},children:g.label}),P(I,{dimColor:!0,children:g.desc})]},g.label)})]}),P(ve,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:S,reason:g}=n;return j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(I,{color:"red",bold:!0,children:"Cannot create plugin"}),j(M,{flexDirection:"column",gap:0,children:[j(I,{children:[S," already contains ",P(I,{bold:!0,children:g==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),P(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),P(ve,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:S,fieldError:g}=n,f=i==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${v}`;return j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),j(M,{flexDirection:"column",gap:0,children:[P(I,{bold:!0,children:"Plugin details"}),P(I,{dimColor:!0,children:f})]}),g!==void 0&&j(I,{color:"red",children:["Error: ",g]}),P(M,{flexDirection:"column",gap:0,children:fe.map((_,a)=>{let s=S===a,c=s?b:d[_],u=Wt.includes(_),m=`${Jt[_]}${u?"":" (optional)"}`;return j(M,{gap:2,children:[P(M,{width:24,children:P(I,{bold:s,...s&&{color:"cyan"},children:m})}),P(I,{...s&&{color:"cyan"},children:">"}),P(I,{children:c}),s&&P(I,{color:"cyan",children:"\u2588"})]},_)})}),P(ve,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let S=gt({targetDir:v,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),j(M,{flexDirection:"column",gap:0,children:[P(I,{bold:!0,children:"Ready to create"}),j(I,{dimColor:!0,children:["Target: ",v]})]}),j(M,{flexDirection:"column",gap:0,children:[P(I,{bold:!0,children:"kizen.json preview"}),P(I,{children:JSON.stringify(S,null,2)})]}),j(M,{flexDirection:"column",gap:0,children:[P(I,{dimColor:!0,children:"Also creates:"}),j(I,{dimColor:!0,children:[" ",ht(v,"src/")]}),j(I,{dimColor:!0,children:[" ",ht(v,"releaseNotes/")]}),j(I,{dimColor:!0,children:[" ",ht(v,".gitignore")," (adds .kizenapp/)"]})]}),P(ve,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?P(M,{paddingY:1,paddingX:2,children:P(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?P(M,{paddingY:1,paddingX:2,children:P(I,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),j(I,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),j(M,{flexDirection:"column",gap:0,children:[P(I,{dimColor:!0,children:"Next steps:"}),j(I,{children:[" ","cd ",n.targetDir]}),j(I,{children:[" ","appbuilder dev"]})]}),P(ve,{text:"Enter or Esc to exit"})]}):j(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(I,{color:"red",bold:!0,children:"Failed to create plugin"}),P(I,{children:n.message}),P(ve,{text:"Enter or Esc to exit"})]})};import{mkdir as Kt,readFile as Nn,readdir as Rn,writeFile as Xt}from"fs/promises";import{homedir as Dn}from"os";import{dirname as Ln,join as Ke}from"path";var K=["go","fmo","staging","integration","test1"];var me=Ke(Dn(),".kizenappbuilder"),we=Ke(me,"credentials.json"),oe="credentials";function $n(e){return K.includes(e)}function Fn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,o=t.environment;return{apiKey:typeof t.apiKey=="string"?t.apiKey:"",userId:typeof t.userId=="string"?t.userId:"",businessId:typeof t.businessId=="string"?t.businessId:"",environment:$n(o)?o:"go"}}async function Xe(e){let t=await Nn(e,"utf-8");return Fn(JSON.parse(t))}async function Y(){try{return await Xe(we)}catch{return null}}async function jn(e){await Kt(Ln(we),{recursive:!0,mode:448}),await Xt(we,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Yt(e){return Ke(me,`${e}.json`)}async function Ie(){let e=[{name:oe,path:we,isDefault:!0}];try{let t=await Rn(me);for(let o of t){if(!o.endsWith(".json"))continue;let n=o.slice(0,-5);n!==oe&&e.push({name:n,path:Ke(me,o),isDefault:!1})}}catch{}return e}async function Zt(e,t){if(e===oe){await jn(t);return}await Kt(me,{recursive:!0,mode:448}),await Xt(Yt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ce(e){try{return await Xe(Yt(e))}catch{return null}}function Qt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await Y())?.businessId??"",{waitUntilExit:r}=On(An(Gt,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as Pr}from"react";import{render as Tr}from"ink";import{useCallback as Se,useEffect as rt,useRef as te,useState as J}from"react";import{Box as U,Text as N,useInput as Lo}from"ink";import{watch as $o}from"fs";import{createServer as Fo}from"http";import{join as Sr}from"path";import{WebSocketServer as jo}from"ws";import{createReadStream as ur,realpathSync as io}from"fs";import{access as so,readdir as ao,readFile as lo,realpath as co,stat as pr}from"fs/promises";import{dirname as uo,extname as fr,join as $e,resolve as po,sep as Pt}from"path";import{fileURLToPath as fo}from"url";var zn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function yt(e){let t={};for(let[o,n]of Object.entries(e)){let r=o.toLowerCase();zn.has(r)||r.startsWith("access-control-")||(t[o]=n)}return t}var bt=10*1024*1024,Mn=6e4,Hn=200,Be=class extends Error{bytesRead;limit;constructor(t,o){super(`Upstream response exceeded ${String(o)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=o}};async function xt(e,t){let o=e.body;if(o===null)return Buffer.alloc(0);let n=[],r=0;for await(let i of o){if(r+=i.length,r>t)throw new Be(r,t);n.push(i)}return Buffer.concat(n)}function er(e={}){let t=new Map,{onChange:o}=e,n=()=>{o?.(t.size)},r=i=>{t.delete(i)&&n()};return{get(i,p){let d=t.get(i);if(d!==void 0){if(Date.now()-d.insertedAt<Mn)return d.promise.then(b=>({response:b,fromCache:!0}));r(i)}if(t.size>=Hn){let b=t.keys().next().value;b!==void 0&&r(b)}let C=p().then(async b=>{let y=yt(Object.fromEntries(b.headers)),v=await xt(b,bt);return{status:b.status,headers:y,body:v}}).catch(b=>{throw r(i),b});return t.set(i,{insertedAt:Date.now(),promise:C}),n(),C.then(b=>((b.status<200||b.status>=300)&&r(i),{response:b,fromCache:!1}))},clear(){t.clear(),n()}}}var vt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json"};import{mkdir as qn,readFile as Un,writeFile as Vn}from"fs/promises";import{join as tr}from"path";async function Ne(e){try{let t=await Un(tr(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function ge(e,t){await qn(e,{recursive:!0}),await Vn(tr(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as _t}from"child_process";import{writeFile as nr,rm as St,mkdtemp as Wn,access as Gn}from"fs/promises";import{join as De}from"path";import{tmpdir as Kn}from"os";var rr=`awslambdaric
|
|
7
|
+
`;Ie.writeFileSync(t,n+r)}function Qt(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),o=`${t}/.kizenapp`;Ne(t);let{waitUntilExit:n}=Gn(Wn(Xt,{outputDir:o,pluginDir:t}));await n()})}import{createElement as lo}from"react";import{render as co}from"ink";import{useCallback as nt,useState as Ae}from"react";import{Box as q,Text as R,useApp as Xn,useInput as Zn}from"ink";import{join as Pt}from"path";import{access as Kn,mkdir as Tt,writeFile as Yn}from"fs/promises";import{join as Te}from"path";async function rt(e){try{return await Kn(e),!0}catch{return!1}}async function er(e){return await rt(Te(e,"kizen.json"))?"has-manifest":await rt(Te(e,".kizenapp"))?"has-kizenapp":"ok"}async function tr(e,t){let o=Te(e,t);if(!await rt(o))return o;for(let n=1;n<1e3;n++){let r=Te(e,`${t}-${String(n)}`);if(!await rt(r))return r}throw new Error(`Could not find an available directory name for "${t}"`)}function Et(e){return{name:e.name,version:"1.0.0",published:!0,api_name:e.apiName,external_link:e.externalLink,description:e.description,entry:"src/",engine:"1.0.0",release_notes_directory:"releaseNotes/",release_environments:["prod"],config_template:{},base_config:{},developer_business_id:e.developerBusinessId}}async function rr(e){await Tt(e.targetDir,{recursive:!0});let t=Et(e);await Yn(Te(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
8
|
+
`,"utf-8"),await Tt(Te(e.targetDir,"src"),{recursive:!0}),await Tt(Te(e.targetDir,"releaseNotes"),{recursive:!0}),Ne(e.targetDir)}import{jsx as _,jsxs as z}from"react/jsx-runtime";var Ee=["name","apiName","externalLink","description","developerBusinessId"],nr={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},or=["name","apiName"];function Qn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var Be=({text:e})=>_(R,{dimColor:!0,children:e});function eo(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var ir=({parentDir:e,defaultBusinessId:t})=>{let o=Xn(),[n,r]=Ae({type:"target-select",cursor:0}),[i,f]=Ae("in-place"),[p,m]=Ae(()=>eo(t)),[g,w]=Ae(""),[v,y]=Ae(e),l=nt((T,h)=>{f(T),w(h.name),r({type:"field-entry",field:0,values:h})},[]),x=nt(async T=>{let h=await er(T);if(h!=="ok"){r({type:"precheck-error",targetDir:T,reason:h});return}y(T),l("in-place",p)},[p,l]),N=nt(async T=>{try{let h=await tr(e,T.apiName);y(h),r({type:"confirm",values:T})}catch(h){r({type:"error",message:h instanceof Error?h.message:String(h)})}},[e]),I=nt(async(T,h)=>{try{await rr({targetDir:h,name:T.name,apiName:T.apiName,externalLink:T.externalLink,description:T.description,developerBusinessId:T.developerBusinessId}),r({type:"done",targetDir:h})}catch(b){r({type:"error",message:b instanceof Error?b.message:String(b)})}},[]);if(Zn((T,h)=>{if(h.ctrl&&T==="c"){o.exit();return}if(n.type==="target-select"){h.upArrow?r({type:"target-select",cursor:0}):h.downArrow?r({type:"target-select",cursor:1}):h.return?n.cursor===0?x(e):l("sub-dir",p):h.escape&&o.exit();return}if(n.type==="precheck-error"){(h.return||h.escape)&&o.exit();return}if(n.type==="field-entry"){let{field:b,values:P}=n,d=Ee[b];if(!d)return;if(h.escape){o.exit();return}if(h.backspace||h.delete){w(a=>a.slice(0,-1));return}if(h.upArrow&&b>0){let a={...P,[d]:g},s=b-1,c=Ee[s];r({type:"field-entry",field:s,values:a}),m(a),w(c?a[c]:"");return}if(h.return||h.tab||h.downArrow){let a=g.trim();if(or.includes(d)&&!a){r({type:"field-entry",field:b,values:P,fieldError:`${nr[d]} is required`});return}let c=d==="description"?g:a,u={...P,[d]:c};m(u);let S=b+1;if(S>=Ee.length)w(""),i==="sub-dir"?(r({type:"resolving-target"}),N(u)):r({type:"confirm",values:u});else{let C=Ee[S],B=C?u[C]:"",A=C==="apiName"&&!B?Qn(u.name):B;r({type:"field-entry",field:S,values:u}),w(A)}return}T&&!h.ctrl&&!h.meta&&w(a=>a+T);return}if(n.type==="confirm"){if(h.escape){let b=Ee.length-1,P=Ee[b];r({type:"field-entry",field:b,values:n.values}),w(P?n.values[P]:"");return}h.return&&(r({type:"writing"}),I(n.values,v));return}(n.type==="done"||n.type==="error")&&(h.return||h.escape)&&o.exit()}),n.type==="target-select"){let T=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),z(q,{flexDirection:"column",gap:0,children:[_(R,{bold:!0,children:"Where should the new plugin live?"}),T.map((h,b)=>{let P=n.cursor===b;return z(q,{gap:2,children:[_(R,{...P&&{color:"cyan"},children:P?"\u276F":" "}),_(R,{bold:P,...P&&{color:"cyan"},children:h.label}),_(R,{dimColor:!0,children:h.desc})]},h.label)})]}),_(Be,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:T,reason:h}=n;return z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(R,{color:"red",bold:!0,children:"Cannot create plugin"}),z(q,{flexDirection:"column",gap:0,children:[z(R,{children:[T," already contains ",_(R,{bold:!0,children:h==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),_(R,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),_(Be,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:T,fieldError:h}=n,b=i==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${v}`;return z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),z(q,{flexDirection:"column",gap:0,children:[_(R,{bold:!0,children:"Plugin details"}),_(R,{dimColor:!0,children:b})]}),h!==void 0&&z(R,{color:"red",children:["Error: ",h]}),_(q,{flexDirection:"column",gap:0,children:Ee.map((P,d)=>{let a=T===d,s=a?g:p[P],c=or.includes(P),u=`${nr[P]}${c?"":" (optional)"}`;return z(q,{gap:2,children:[_(q,{width:24,children:_(R,{bold:a,...a&&{color:"cyan"},children:u})}),_(R,{...a&&{color:"cyan"},children:">"}),_(R,{children:s}),a&&_(R,{color:"cyan",children:"\u2588"})]},P)})}),_(Be,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let T=Et({targetDir:v,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),z(q,{flexDirection:"column",gap:0,children:[_(R,{bold:!0,children:"Ready to create"}),z(R,{dimColor:!0,children:["Target: ",v]})]}),z(q,{flexDirection:"column",gap:0,children:[_(R,{bold:!0,children:"kizen.json preview"}),_(R,{children:JSON.stringify(T,null,2)})]}),z(q,{flexDirection:"column",gap:0,children:[_(R,{dimColor:!0,children:"Also creates:"}),z(R,{dimColor:!0,children:[" ",Pt(v,"src/")]}),z(R,{dimColor:!0,children:[" ",Pt(v,"releaseNotes/")]}),z(R,{dimColor:!0,children:[" ",Pt(v,".gitignore")," (adds .kizenapp/)"]})]}),_(Be,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?_(q,{paddingY:1,paddingX:2,children:_(R,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?_(q,{paddingY:1,paddingX:2,children:_(R,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),z(R,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),z(q,{flexDirection:"column",gap:0,children:[_(R,{dimColor:!0,children:"Next steps:"}),z(R,{children:[" ","cd ",n.targetDir]}),z(R,{children:[" ","appbuilder dev"]})]}),_(Be,{text:"Enter or Esc to exit"})]}):z(q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(R,{color:"red",bold:!0,children:"Failed to create plugin"}),_(R,{children:n.message}),_(Be,{text:"Enter or Esc to exit"})]})};import{mkdir as sr,readFile as to,readdir as ro,writeFile as ar}from"fs/promises";import{homedir as no}from"os";import{dirname as oo,join as ot}from"path";var te=["go","fmo","staging","integration","test1"];var Pe=ot(no(),".kizenappbuilder"),Re=ot(Pe,"credentials.json"),fe="credentials";function io(e){return te.includes(e)}function so(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,o=t.environment;return{apiKey:typeof t.apiKey=="string"?t.apiKey:"",userId:typeof t.userId=="string"?t.userId:"",businessId:typeof t.businessId=="string"?t.businessId:"",environment:io(o)?o:"go"}}async function me(e){let t=await to(e,"utf-8");return so(JSON.parse(t))}async function K(){try{return await me(Re)}catch{return null}}async function ao(e){await sr(oo(Re),{recursive:!0,mode:448}),await ar(Re,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function lr(e){return ot(Pe,`${e}.json`)}async function ke(){let e=[{name:fe,path:Re,isDefault:!0}];try{let t=await ro(Pe);for(let o of t){if(!o.endsWith(".json"))continue;let n=o.slice(0,-5);n!==fe&&e.push({name:n,path:ot(Pe,o),isDefault:!1})}}catch{}return e}async function cr(e,t){if(e===fe){await ao(t);return}await sr(Pe,{recursive:!0,mode:448}),await ar(lr(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function ae(e){try{return await me(lr(e))}catch{return null}}function dr(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await K())?.businessId??"",{waitUntilExit:r}=co(lo(ir,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as zr}from"react";import{render as Mr}from"ink";import{useCallback as De,useEffect as ut,useRef as le,useState as Z}from"react";import{Box as W,Text as L,useInput as ai}from"ink";import{watch as li}from"fs";import{createServer as ci}from"http";import{join as Or}from"path";import{WebSocketServer as di}from"ws";import{createReadStream as Cr,realpathSync as No}from"fs";import{access as Bo,readdir as Ro,readFile as Do,realpath as $o,stat as Sr}from"fs/promises";import{dirname as Lo,extname as Tr,join as Ve,resolve as Fo,sep as Ft}from"path";import{fileURLToPath as Oo}from"url";var uo=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function it(e){let t={};for(let[o,n]of Object.entries(e)){let r=o.toLowerCase();uo.has(r)||r.startsWith("access-control-")||(t[o]=n)}return t}var kt=10*1024*1024,po=6e4,fo=200,ze=class extends Error{bytesRead;limit;constructor(t,o){super(`Upstream response exceeded ${String(o)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=o}};async function _t(e,t){let o=e.body;if(o===null)return Buffer.alloc(0);let n=[],r=0;for await(let i of o){if(r+=i.length,r>t)throw new ze(r,t);n.push(i)}return Buffer.concat(n)}function ur(e={}){let t=new Map,{onChange:o}=e,n=()=>{o?.(t.size)},r=i=>{t.delete(i)&&n()};return{get(i,f){let p=t.get(i);if(p!==void 0){if(Date.now()-p.insertedAt<po)return p.promise.then(g=>({response:g,fromCache:!0}));r(i)}if(t.size>=fo){let g=t.keys().next().value;g!==void 0&&r(g)}let m=f().then(async g=>{let w=it(Object.fromEntries(g.headers)),v=await _t(g,kt);return{status:g.status,headers:w,body:v}}).catch(g=>{throw r(i),g});return t.set(i,{insertedAt:Date.now(),promise:m}),n(),m.then(g=>((g.status<200||g.status>=300)&&r(i),{response:g,fromCache:!1}))},clear(){t.clear(),n()}}}var It={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json"};import{mkdir as mo,readFile as go,writeFile as yo}from"fs/promises";import{join as pr}from"path";async function ge(e){try{let t=await go(pr(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function ye(e,t){await mo(e,{recursive:!0}),await yo(pr(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}var Nt={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function Me(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Nt.prod:process.env.PLUGIN_WIZARD_URL_DEV!==void 0&&process.env.PLUGIN_WIZARD_URL_DEV!==""?process.env.PLUGIN_WIZARD_URL_DEV:process.env.APPBUILDER_LOCAL_DEV!==void 0&&process.env.APPBUILDER_LOCAL_DEV!==""?Nt.localDev:Nt.dev}import{spawn as $t}from"child_process";import{writeFile as mr,rm as Dt,mkdtemp as bo,access as xo}from"fs/promises";import{join as Ue}from"path";import{tmpdir as wo}from"os";var fr=`awslambdaric
|
|
9
9
|
bcrypt
|
|
10
10
|
fpdf2
|
|
11
11
|
lxml
|
|
@@ -22,7 +22,7 @@ pytz
|
|
|
22
22
|
requests
|
|
23
23
|
sqlalchemy>=2.0,<2.1
|
|
24
24
|
tzdata
|
|
25
|
-
`;var
|
|
25
|
+
`;var vo=`
|
|
26
26
|
import sys, json, os, traceback
|
|
27
27
|
|
|
28
28
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -182,23 +182,30 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
182
182
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
183
183
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
184
184
|
sys.stdout.flush()
|
|
185
|
-
`.trim(),
|
|
186
|
-
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}var
|
|
187
|
-
`);for(;l>=0;){let x=v.slice(0,l).replace(/\r$/,"");v=v.slice(l+1),
|
|
188
|
-
`)}}),
|
|
189
|
-
`).trim(),y=b.length>0?`: ${b}`:"";r(new Error(`${e} exited with code ${String(C)}${y}`))}})})}var Ct=null;function ro(e,t){if(Re)return t&&Ct?.add(t),Re;let o=new Set;t&&o.add(t),Ct=o;let n=i=>{for(let p of o)p(i)},r=De(Ye,"bin","python");return Re=(async()=>{try{let i=!1;try{await Gn(r);let p=await lr(r);i=p!==null&&ar(p)}catch{i=!1}if(!i){await St(Ye,{recursive:!0,force:!0}).catch(()=>{});let p=await to(e);await or(p,["-m","venv",Ye])}return n({kind:"start"}),await or(r,["-m","pip","install","--disable-pip-version-check",...sr],(p,d)=>{n({kind:"log",line:p,stream:d})}),n({kind:"complete"}),r}catch(i){let p=i instanceof Error?i.message:String(i);throw n({kind:"error",message:p}),Re=null,await St(Ye,{recursive:!0,force:!0}).catch(()=>{}),i}finally{Ct=null}})(),Re}function no(e){let t="__KIZEN_RESULT_START__",o="__KIZEN_RESULT_END__",n=e.indexOf(t),r=e.indexOf(o);if(n===-1||r===-1)return{userStdout:e,result:null};let i=e.slice(0,n).trimEnd(),p=e.slice(n+t.length,r).trim();try{let d=JSON.parse(p);return{userStdout:i,result:d}}catch{return{userStdout:e,result:null}}}function oo(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function cr(e){let t=e.timeout??Yn;if(!Zn(e.scriptRuntime))return oo(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${ir.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let o=await ro(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await Wn(De(Kn(),"kizen-step-"));let i=De(r,"wrapper.py"),p=De(r,"script.py");await Promise.all([nr(i,Xn,"utf-8"),nr(p,e.script,"utf-8")]);let d={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:p},{exitCode:C,stdout:b,stderr:y}=await new Promise(T=>{let R=[],S=[],g=!1,f=_t(o,[i],{env:d,cwd:r,stdio:["ignore","pipe","pipe"]}),_=setTimeout(()=>{f.kill("SIGKILL")},t);f.stdout.on("data",s=>{R.push(s)}),f.stderr.on("data",s=>{S.push(s)});let a=s=>{g||(g=!0,clearTimeout(_),T({exitCode:s??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(S).toString("utf-8")}))};f.on("close",a),f.on("error",s=>{g||(g=!0,clearTimeout(_),T({exitCode:1,stdout:"",stderr:s.message}))})}),v=Date.now()-n,{userStdout:h,result:l}=no(b);if(l){let T={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:h,stderr:y,exitCode:C,durationMs:v};return l.error!==null&&(T.error=l.error),l.httpRequests&&(T.httpRequests=l.httpRequests),T}let x={success:!1,outputValues:{},logs:[],stdout:h,stderr:y,exitCode:C,durationMs:v};return C!==0&&(x.error=`Process exited with code ${String(C)}`),x}finally{r&&St(r,{recursive:!0,force:!0})}}var dr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);function kt(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",o=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${o}${t}`}var mo=2*1024*1024,go=new Set([".DS_Store",".gitignore"]);function ho(e){if(e===void 0||e==="")return!1;let t=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??"";return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}var yo=["kizen.com","kizen.dev"];function bo(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return yo.some(n=>o===n||o.endsWith("."+n))}function xo(e){if(e===void 0||e==="")return!1;try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}async function mr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),n=po(e,o);if(n!==e&&!n.startsWith(e+Pt))return null;try{let r=await co(n);return r!==e&&!r.startsWith(e+Pt)?null:r}catch{return null}}function gr(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(Pt).some(r=>He.has(r))}function yr(){let e=fo(import.meta.url);return $e(uo(e),"viewer")}function hr(e,t,o){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let n=JSON.parse(o.toString("utf8"));return typeof n.status_code=="number"?n.status_code:void 0}catch{return}}async function Tt(e){try{return await so(e),!0}catch{return!1}}function br(e,t,o,n,r,i,p,d,C,b){let y=er({onChange:d}),v=io(b);return(h,l)=>{(async()=>{let x=h.url??"/";try{if(!ho(h.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((h.method==="POST"||h.method==="PATCH"||h.method==="DELETE")&&!xo(h.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${x}`),x==="/api/credentials"){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({credentials:n.current??null,activeProfile:r.current??null}));return}if(x==="/api/credential-profiles"&&h.method==="GET"){let a=await Ie();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:a,active:r.current}));return}if(x==="/api/credentials/switch"&&h.method==="POST"){let a=[];for await(let m of h)a.push(m);let c=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}").profile,u=c===void 0||c===""?await Y():await Ce(c);if(u!==null){n.current=u,r.current=c??void 0;let m=r.current;await ge(i,{credentialMode:"global",...m!==void 0&&{activeCredentialProfile:m}}),p({type:"credentials-updated",credentials:u,activeProfile:r.current??null})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:u!==null}));return}if(x==="/api/bundle"){let a=$e(process.cwd(),".kizenapp","bundle.json");try{let s=await lo(a,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(s)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(x==="/api/last-path"&&h.method==="POST"){let a=[];for await(let c of h)a.push(c);let s=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof s.path=="string"){C.current=s.path;let c=await Ne(i);await ge(i,{...c,lastPath:s.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x==="/api/execute-step"&&h.method==="POST"){let a=[];for await(let m of h)a.push(m);let s=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof s.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let c={script:s.script,scriptRuntime:s.scriptRuntime??"python-3-13",inputs:s.inputs??{},secrets:s.secrets??{},onInstallProgress:m=>{m.kind==="start"?p({type:"venv-install-start"}):m.kind==="log"?p({type:"venv-install-log",line:m.line,stream:m.stream}):m.kind==="complete"?p({type:"venv-install-complete"}):p({type:"venv-install-error",message:m.message})}};typeof s.timeout=="number"&&s.timeout>0&&(c.timeout=Math.min(s.timeout,300*1e3));let u=await cr(c);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(u));return}if(x==="/api/proxy-cache/clear"){y.clear(),o({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x.startsWith("/api/proxy")){let a=h.headers["x-proxy-target"];if(typeof a!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!bo(a)){l.writeHead(400),l.end("Invalid proxy target");return}let s=x.slice(10)||"/",c=`${a}${s}`,u=h.method??"GET",m=[];for await(let _e of h)m.push(_e);let{host:F,"x-proxy-target":E,...D}=h.headers;if(u==="GET"){let _e=`GET::${c}`,{response:ee,fromCache:ot}=await y.get(_e,()=>fetch(c,{method:"GET",headers:D}));o({kind:"request",method:"GET",status:ee.status,upstreamStatus:hr(s,ee.headers,ee.body),fromCache:ot,url:s}),l.writeHead(ee.status,ee.headers),l.end(ee.body);return}let A=m.length>0?Buffer.concat(m):void 0,H=A&&A.length>0?A:void 0,W=await fetch(c,{method:u,headers:D,...H!==void 0&&{body:H}}),Q=yt(Object.fromEntries(W.headers)),ae=await xt(W,bt);o({kind:"request",method:u,status:W.status,upstreamStatus:hr(s,Q,ae),fromCache:!1,url:s}),l.writeHead(W.status,Q),l.end(ae);return}if(x.startsWith("/api/source/tree")&&h.method==="GET"){let s=new URL(x,"http://localhost").searchParams.get("path")??"",c=await mr(v,s);if(c===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(gr(v,c)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let u=await ao(c,{withFileTypes:!0}),m=await Promise.all(u.filter(E=>E.isDirectory()?!He.has(E.name):E.isFile()?!go.has(E.name):!1).map(async E=>{let D=E.isDirectory()?"dir":"file",A={name:E.name,kind:D};if(D==="file")try{let H=await pr($e(c,E.name));A.size=H.size}catch{}return A}));m.sort((E,D)=>E.kind!==D.kind?E.kind==="dir"?-1:1:E.name.localeCompare(D.name));let F=c===v?"":c.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:F,entries:m}))}catch(u){let m=u instanceof Error?u.message:String(u);t(`source/tree failed (${s}): ${m}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(x.startsWith("/api/source/file")&&h.method==="GET"){let s=new URL(x,"http://localhost").searchParams.get("path")??"";if(s===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let c=await mr(v,s);if(c===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(gr(v,c)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let u=await pr(c);if(!u.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(u.size>mo){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:u.size}));return}let m=fr(c).toLowerCase(),F=vt[m],E=dr.has(m),D=F??(E?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":D,"Content-Length":String(u.size)}),ur(c).pipe(l)}catch(u){let m=u instanceof Error?u.message:String(u);t(`source/file failed (${s}): ${m}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let S=$e(e,x==="/"?"/index.html":x),g=await Tt(S)?S:$e(e,"index.html"),f=fr(g),_=vt[f]??"application/octet-stream";l.writeHead(200,{"Content-Type":_}),ur(g).pipe(l)}catch(T){if(x.startsWith("/api/proxy")){let R=x.slice(10)||"/",S=h.method??"GET";T instanceof Be?o({kind:"info",message:`${S} ${R} \u2192 502 (response exceeded ${String(T.limit)} bytes)`}):o({kind:"request",method:S,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${x}: ${T instanceof Error?T.message:String(T)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as vo}from"chrome-launcher";import{createRequire as wo}from"module";import{mkdirSync as Co}from"fs";import{readFile as So}from"fs/promises";import{dirname as _o,join as ko}from"path";import{fileURLToPath as Po}from"url";var xr=wo(import.meta.url)("chrome-remote-interface"),To=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),wr=["kizen.dev","kizen.com"];function vr(e){try{let{hostname:t}=new URL(e);return wr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}async function Eo(e){try{let t=ko(_o(Po(import.meta.url)),"viewer","icon.png"),o=await So(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function Cr(e){Co(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await vo({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),n=o.port,r=null,i=null,p=null,d=null,C=0,b=!1,y=f=>{e.debugLog?.(f)},v=f=>{e.verbose&&e.debugLog?.(f)},h=()=>{i!==null&&(clearInterval(i),i=null)},l=f=>f==="chrome://new-tab-page/"||f==="chrome://newtab/",x=async f=>{h(),p=null,await Eo(f),await f.Fetch.enable({patterns:wr.flatMap(a=>[{urlPattern:`*://${a}/*`,requestStage:"Response"},{urlPattern:`*://*.${a}/*`,requestStage:"Response"}])}),f.on("Fetch.requestPaused",a=>{(async()=>{let s=a,{requestId:c,request:u,responseHeaders:m,responseStatusCode:F}=s,E=u.url;v(`Fetch ${String(F??"?")} ${E}`);let D=[],A=!1;for(let H of m??[])if(!To.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&vr(E)){let W=H.value.split(`
|
|
190
|
-
`).map(
|
|
191
|
-
`);D.push({name:H.name,value:W}),A=!0}else D.push(H);A&&v(` rewrote Set-Cookie SameSite on ${E}`);try{let{body:H,base64Encoded:W}=await f.Fetch.getResponseBody({requestId:c});await f.Fetch.fulfillRequest({requestId:c,responseCode:F??200,responseHeaders:D,body:H,...W&&{base64Encoded:!0}})}catch(H){v(` fulfillRequest failed (${H.message}), falling through`);try{await f.Fetch.continueRequest({requestId:c})}catch(W){v(` continueRequest also failed (${W.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:a}=await f.Network.getAllCookies(),s=0;for(let c of a){if(!vr(`https://${c.domain??""}`)||c.sameSite==="None")continue;let u=c.domain??"",m=u.startsWith(".")?u.slice(1):u;await f.Network.setCookie({url:`https://${m}`,name:c.name,value:c.value,domain:u,path:c.path??"/",secure:!0,...c.httpOnly!==void 0&&{httpOnly:c.httpOnly},...c.expirationDate!==void 0&&{expires:c.expirationDate},sameSite:"None"}),s++}s>0&&v(`cookie-patch cycle: updated ${String(s)} cookie(s) to SameSite=None`)}catch(a){v(`cookie-patch cycle failed: ${a.message}`)}})()},2e3),await f.Target.setDiscoverTargets({discover:!0});let _=a=>{if(a.type==="page"){if(l(a.url)){y(`closed stray new-tab-page target ${a.targetId}`),p!==null&&f.Target.activateTarget({targetId:p}).catch(()=>{}),f.Target.closeTarget({targetId:a.targetId}).catch(()=>{});return}p===null&&(p=a.targetId,y(`captured main target ${a.targetId} (${a.url})`))}};f.on("Target.targetCreated",a=>{let{targetInfo:s}=a;v(`target +${s.type} ${s.targetId} ${s.url}`),_(s)}),f.on("Target.targetInfoChanged",a=>{let{targetInfo:s}=a;v(`target ~${s.type} ${s.targetId} ${s.url}`),_(s)}),f.on("disconnect",()=>{b||r!==f||(y("CDP disconnected"),r=null,h(),T())})},T=()=>{if(b||d!==null)return;let f=Math.min(1e3*2**C,1e4),_=C+1;C++,y(`CDP reconnect scheduled in ${String(f)}ms (attempt #${String(_)})`),d=setTimeout(()=>{d=null,(async()=>{let a;try{a=await xr({port:n})}catch{y(`CDP reconnect attempt #${String(_)} failed`),T();return}if(b){try{await a.close()}catch{}return}r=a;try{await x(a),y(`CDP reconnected after ${String(_)} attempt(s)`),C=0}catch{r===a&&(r=null);try{await a.close()}catch{}y(`CDP reconnect attempt #${String(_)} failed during setup`),T()}})()},f)},R=30,S=300;for(let f=0;f<R;f++){await new Promise(_=>setTimeout(_,S)),y(`CDP connect attempt ${String(f+1)}/${String(R)}`);try{let _=await xr({port:n});r=_,e.path&&_.send("Page.navigate",{url:`${t}${e.path}`});try{await x(_),y("CDP connected")}catch{r===_&&(r=null);try{await _.close()}catch{}y("CDP setup failed after connect")}break}catch{if(f===R-1){let _=`CDP unavailable after ${String(R)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return y(_),e.onWarn?.(_),{kill:()=>{o.kill()}}}}}return r?{kill:()=>{if(y("CDP kill requested \u2014 tearing down"),b=!0,d!==null&&(clearTimeout(d),d=null),h(),r!==null){try{r.close()}catch{}r=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as Io,useState as Bo}from"react";function Ze(e){let[t,o]=Bo([]),n=Io(r=>{o(i=>[...i,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as Qe,useEffect as Et,useState as et}from"react";import{Box as z,Text as B,useInput as No}from"ink";import{jsx as k,jsxs as q}from"react/jsx-runtime";var ie=["apiKey","userId","businessId"],Ro={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Fe=({text:e})=>k(B,{dimColor:!0,children:e}),tt=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:n})=>{let[r,i]=et(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[p,d]=et(""),[C,b]=et(null),[y,v]=et(void 0),h=Qe(a=>{if(a==="local"){o({mode:"local",credentials:null});return}i({type:"profile-loading"})},[o]),l=Qe(async a=>{if(a===null){i({type:"profile-loading"});let u=await Ie();i({type:"name-entry",nameBuffer:"",existingProfiles:u});return}v(a.isDefault?void 0:a.name),i({type:"loading"});let s=a.isDefault?await Y():await Ce(a.name),c=s?Math.max(0,K.indexOf(s.environment)):0;i({type:"creds-entry",field:0,values:s??{},envCursor:c})},[]),x=Qe(async(a,s)=>{let c=K[s]??"go",u={apiKey:a.apiKey??"",userId:a.userId??"",businessId:a.businessId??"",environment:c};i({type:"saving"});try{await Zt(y??oe,u),o({mode:"global",credentials:u,...y!==void 0&&{profileName:y}})}catch(m){b(m instanceof Error?m.message:String(m)),i({type:"creds-entry",field:0,values:a,envCursor:s})}},[o,y]);No((a,s)=>{if(s.ctrl&&a==="c"&&process.exit(0),s.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),T();return}n?.();return}if(r.type==="mode-select"){if(s.upArrow)i({type:"mode-select",cursor:0});else if(s.downArrow)i({type:"mode-select",cursor:1});else if(s.return){let c=r.cursor===0?"global":"local";h(c)}return}if(r.type==="profile-select"){let{profiles:c,cursor:u}=r,m=c.length,F=c.length+1;if(s.upArrow)i({...r,cursor:(u-1+F)%F});else if(s.downArrow)i({...r,cursor:(u+1)%F});else if(s.return)if(u===m)i({type:"name-entry",nameBuffer:"",existingProfiles:c});else{let E=c[u]??c[0];E&&l(E)}return}if(r.type==="name-entry"){let{nameBuffer:c,existingProfiles:u}=r;if(s.backspace||s.delete)i({type:"name-entry",nameBuffer:c.slice(0,-1),existingProfiles:u});else if(s.return){let m=c.trim();if(!m){i({...r,nameError:"Name cannot be empty"});return}if(m===oe){i({...r,nameError:`"${oe}" is reserved`});return}if(u.some(F=>F.name===m)){i({...r,nameError:`Profile "${m}" already exists`});return}v(m),i({type:"creds-entry",field:0,values:{},envCursor:0}),d("")}else a&&!s.ctrl&&!s.meta&&i({type:"name-entry",nameBuffer:c+a,existingProfiles:u});return}if(r.type==="creds-entry"){let{field:c,values:u,envCursor:m}=r;if(c===ie.length){s.leftArrow?i({...r,envCursor:(m-1+K.length)%K.length}):s.rightArrow?i({...r,envCursor:(m+1)%K.length}):s.upArrow?(i({...r,field:c-1}),d(u[ie[c-1]]??"")):s.return&&x(u,m);return}let E=ie[c];if(!E)return;if(s.backspace||s.delete)d(D=>D.slice(0,-1));else if(s.upArrow&&c>0){let D={...u,[E]:p},A=c-1;i({...r,field:A,values:D}),d(D[ie[A]]??"")}else if(s.return||s.tab||s.downArrow){let D={...u,[E]:p},A=c+1;i({...r,field:A,values:D}),A<ie.length?d(D[ie[A]]??""):d("")}else a&&!s.ctrl&&!s.meta&&d(D=>D+a)}});let T=Qe(async()=>{let a=await Ie();i({type:"profile-select",profiles:a,cursor:0})},[]);if(Et(()=>{r.type==="profile-loading"&&T()},[r.type,T]),Et(()=>{e==="global"&&!t&&(async()=>{let a=await Y(),s=a?Math.max(0,K.indexOf(a.environment)):0;i({type:"creds-entry",field:0,values:a??{},envCursor:s})})()},[]),Et(()=>{r.type==="creds-entry"&&r.field===0&&d(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let a=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return k(z,{paddingY:1,paddingX:2,children:k(B,{dimColor:!0,children:a})})}if(r.type==="done")return null;if(r.type==="mode-select")return q(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),q(z,{flexDirection:"column",gap:0,children:[k(B,{bold:!0,children:"Credential mode"}),[{label:"Global",desc:"~/.kizenappbuilder/credentials.json",mode:"global"},{label:"Local",desc:"Enter credentials in the browser dev tools",mode:"local"}].map((s,c)=>{let u=r.cursor===c;return q(z,{gap:2,children:[k(B,{...u&&{color:"cyan"},children:u?"\u276F":" "}),k(B,{bold:u,...u&&{color:"cyan"},children:s.label}),k(B,{dimColor:!0,children:s.desc})]},s.mode)})]}),k(Fe,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:a,cursor:s}=r,c=a.length;return q(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),q(z,{flexDirection:"column",gap:0,children:[k(B,{bold:!0,children:"Credential profiles"}),a.map((u,m)=>{let F=s===m;return q(z,{gap:2,children:[k(B,{...F&&{color:"cyan"},children:F?"\u276F":" "}),k(B,{bold:F,...F&&{color:"cyan"},children:u.isDefault?"Default":u.name}),k(B,{dimColor:!0,children:u.path})]},u.name)}),q(z,{gap:2,children:[k(B,{...s===c&&{color:"cyan"},children:s===c?"\u276F":" "}),k(B,{bold:s===c,...s===c&&{color:"cyan"},children:"+ Add new profile"})]})]}),k(Fe,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:a,nameError:s}=r;return q(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),k(z,{flexDirection:"column",gap:0,children:k(B,{bold:!0,children:"New credential profile"})}),s&&q(B,{color:"red",children:["Error: ",s]}),q(z,{gap:2,children:[k(z,{width:12,children:k(B,{bold:!0,color:"cyan",children:"Profile name"})}),k(B,{color:"cyan",children:">"}),k(B,{children:a}),k(B,{color:"cyan",children:"\u2588"})]}),k(Fe,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:S,envCursor:g}=r,f=R===ie.length,_=y??oe;return q(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),q(z,{flexDirection:"column",gap:0,children:[k(B,{bold:!0,children:y!==void 0?`Profile: ${y}`:"Global credentials"}),q(B,{dimColor:!0,children:["Saved to:"," ",y!==void 0?`~/.kizenappbuilder/${y}.json`:we]})]}),C&&q(B,{color:"red",children:["Error: ",C]}),q(z,{flexDirection:"column",gap:0,children:[ie.map((a,s)=>{let c=R===s,u=c?p:S[a]??"";return q(z,{gap:2,children:[k(z,{width:12,children:k(B,{bold:c,...c&&{color:"cyan"},children:Ro[a]})}),k(B,{...c&&{color:"cyan"},children:">"}),k(B,{children:u}),c&&k(B,{color:"cyan",children:"\u2588"})]},a)}),q(z,{gap:2,children:[k(z,{width:12,children:k(B,{bold:f,...f&&{color:"cyan"},children:"Environment"})}),k(B,{...f&&{color:"cyan"},children:">"}),k(z,{gap:1,children:K.map((a,s)=>{let c=s===g;return f?k(B,{bold:c,...c&&{color:"cyan"},children:c?`[${a}]`:a},a):k(B,{dimColor:!c,bold:c,children:a},a)})})]})]}),f?k(Fe,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):k(Fe,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),q(B,{dimColor:!0,children:["Profile: ",_]})]})};import{jsx as L,jsxs as O}from"react/jsx-runtime";var Ao=[".kizenapp",".git"],_r=({port:e,pluginDir:t,outputDir:o,credentials:n,credentialMode:r,activeCredentialProfile:i,lastPath:p,debug:d=!1,verbose:C=!1,autoViewer:b=!0})=>{let y=te(n),v=te(i),h=te(p),[l,x]=J("main"),[T,R]=J(r),[S,g]=J("starting"),[f,_]=J(null),[a,s]=Ze(50),[c,u]=Ze(50),[m,F]=Ze(50),[E,D]=J([]),[A,H]=J("pending"),[W,Q]=J(null),[ae,_e]=J(null),[ee,ot]=J(null),[it,st]=J(0),[Bt,zr]=J(0),[Mr,Hr]=J(0),[qr,Ur]=J(0),at=te(!1),Nt=te(!1),Ae=te(null),ke=te(null),re=te(new Set),Oe=te([]),G=Se(w=>{let $=JSON.stringify(w);if(re.current.size===0){Oe.current=[...Oe.current,$].slice(-50);return}let ne=!1;for(let X of re.current)if(X.readyState===1)try{X.send($)}catch{re.current.delete(X),ne=!0}ne&&st(re.current.size)},[]),ze=s,lt=Se(()=>{Ae.current?.kill(),Ae.current=null,Cr({port:e,userDataDir:Sr(o,".chrome"),broadcast:G,onWarn:w=>{s(`\u26A0 ${w}`)},...h.current!==void 0&&{path:h.current},...d&&{debugLog:F},...C&&{verbose:!0}}).then(w=>{Ae.current=w})},[e,o,G,d,C,F,s]);rt(()=>{let w=()=>{Ae.current?.kill()};return process.on("exit",w),()=>{process.off("exit",w)}},[]),Lo((w,$)=>{(w==="q"||$.ctrl&&w==="c")&&process.exit(0),w==="c"&&x("editing"),w==="v"&<()},{isActive:l==="main"}),rt(()=>{S!=="running"||Nt.current||!b||(Nt.current=!0,lt())},[S,b,lt]);let Vr=Se(w=>{y.current=w.credentials,v.current=w.profileName,x("main"),R(w.mode);let $=w.profileName;ge(o,{credentialMode:w.mode,...$!==void 0&&{activeCredentialProfile:$}}),G({type:"credentials-updated",credentials:w.credentials})},[o,G]),Rt=Se(w=>{D($=>[...$,`${new Date().toLocaleTimeString()}: ${kt(w)}`].slice(-50)),w.kind==="request"&&(w.fromCache?Hr($=>$+1):Ur($=>$+1)),G({type:"proxy-log",entry:w})},[G]),le=Se(w=>{u(w),G({type:"log",message:w})},[u,G]),ct=Se(()=>{at.current||(at.current=!0,H("building"),Q(null),le("Build started"),Ue(t,o).then(({bundleSize:w})=>{le(`Build finished \u2014 bundle: ${Pe(w)}`),H("done"),_e(new Date),ot(w),le("Notifying viewers to reload"),G({type:"rebuild"})}).catch(w=>{let $=w instanceof Error?w.message:String(w);Q($),H("error")}).finally(()=>{at.current=!1}))},[t,o,le,G]);if(rt(()=>{ct();let w=$o(t,{recursive:!0},($,ne)=>{if(!ne)return;let X=ne.replace(/\\/g,"/");Ao.some(Me=>X.startsWith(Me))||(le(`File change detected: ${ne}`),ke.current!==null&&clearTimeout(ke.current),ke.current=setTimeout(ct,150))});return w.on("error",$=>{le(`File watcher error \u2014 rebuilds have stopped: ${$.message}`)}),()=>{w.close(),ke.current!==null&&clearTimeout(ke.current)}},[t,ct,le]),rt(()=>{let w=yr();Tt(Sr(w,"index.html")).then($=>{if(!$){_("Viewer not built. Run 'pnpm build:viewer' first."),g("error");return}let ne=br(w,ze,Rt,y,v,o,G,zr,h,t),X=Fo(ne),Me=new jo({server:X});return Me.on("connection",ce=>{for(let Wr of Oe.current)ce.readyState===1&&ce.send(Wr);Oe.current=[],ze("Viewer connected for live reload"),re.current.add(ce),st(re.current.size),ce.on("close",()=>{re.current.delete(ce),st(re.current.size)})}),X.listen(e,"127.0.0.1",()=>{g("running"),ze(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",ce=>{_(ce.message),g("error")}),()=>{Me.close(),X.close()}})},[e,ze,Rt,G,o,t]),l==="editing")return L(tt,{...T!==void 0&&{initialMode:T},showProfileManager:T==="global",onComplete:Vr,onCancel:()=>{x("main")}});let dt=ae!==null?Math.round((Date.now()-ae.getTime())/1e3):null,Jr=dt===null?"":dt<5?" (just now)":` (${String(dt)}s ago)`;return O(U,{flexDirection:"column",paddingY:1,paddingX:2,children:[L(V,{marginBottom:1}),O(U,{flexDirection:"column",children:[O(U,{gap:2,marginBottom:0,children:[L(N,{bold:!0,dimColor:!0,children:"App Build"}),A==="pending"&&L(N,{dimColor:!0,children:"waiting\u2026"}),A==="building"&&O(U,{gap:1,children:[L(Ve,{}),L(N,{children:"Building plugin package\u2026"})]}),A==="done"&&O(U,{gap:1,children:[L(N,{color:"green",children:"\u2713 Built"}),ae!==null&&O(N,{dimColor:!0,children:["at ",ae.toLocaleTimeString(),Jr]}),ee!==null&&O(N,{dimColor:!0,children:["\xB7 bundle: ",Pe(ee)]})]}),A==="error"&&O(N,{color:"red",children:["\u2717 ",W??"unknown error"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:c.slice(-8).map((w,$)=>L(N,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(U,{marginTop:1,flexDirection:"column",children:[O(U,{gap:2,children:[L(N,{bold:!0,dimColor:!0,children:"Web Server"}),S==="starting"&&L(N,{dimColor:!0,children:"starting\u2026"}),S==="running"&&O(U,{gap:2,children:[L(N,{color:"green",children:"\u2713 Running"}),O(N,{dimColor:!0,children:["\u25CF ",it," viewer",it!==1?"s":""]})]}),S==="error"&&O(N,{color:"red",children:["\u2717 ",f??"Server error"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((w,$)=>L(N,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(U,{marginTop:1,flexDirection:"column",children:[O(U,{gap:2,children:[L(N,{bold:!0,dimColor:!0,children:"Network Proxy"}),L(N,{color:"green",children:"\u2713 Active"}),O(N,{dimColor:!0,children:["\u25CF ",Bt," key",Bt!==1?"s":""," in the network cache \xB7"," ",Mr," hit \xB7 ",qr," miss"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:E.length===0?L(N,{dimColor:!0,children:" No requests yet."}):E.slice(-8).map((w,$)=>L(N,{dimColor:!0,wrap:"truncate",children:w},$))})]}),d&&O(U,{marginTop:1,flexDirection:"column",children:[O(U,{gap:2,children:[L(N,{bold:!0,dimColor:!0,children:"CDP Debug"}),O(N,{dimColor:!0,children:["\u25CF ",m.length," event(s)"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.length===0?L(N,{dimColor:!0,children:" No CDP events yet."}):m.slice(-8).map((w,$)=>L(N,{dimColor:!0,wrap:"truncate",children:w},$))})]}),O(U,{marginTop:1,gap:1,children:[L(N,{dimColor:!0,children:"["}),L(N,{children:"q"}),L(N,{dimColor:!0,children:"] quit ["}),L(N,{children:"c"}),L(N,{dimColor:!0,children:"] credentials ["}),L(N,{children:"v"}),O(N,{dimColor:!0,children:["] ",it===0?"open viewer":"relaunch viewer"]})]})]})};async function kr(e){return new Promise(t=>{let o=null,n=i=>{o?.(),t(i)},{unmount:r}=Tr(Pr(tt,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});o=r})}function Er(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to a credentials JSON file").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").action(async t=>{let o=parseInt(t.port,10),n=process.cwd(),r=`${n}/.kizenapp`;xe(n);let i=null,p,d,{lastPath:C}=await Ne(r);if(t.credentials)i=await Xe(t.credentials);else{let l=await Ne(r);if(l.credentialMode==="local")p="local";else if(l.credentialMode==="global"){if(p="global",d=l.activeCredentialProfile,d?(i=await Ce(d),i||(i=await Y(),d=void 0)):i=await Y(),!i){let x=await kr("global");i=x.credentials,d=x.profileName}}else{let x=await kr();i=x.credentials,p=x.mode,d=x.profileName;let T=x.profileName;await ge(r,{credentialMode:x.mode,...T!==void 0&&{activeCredentialProfile:T}})}}let b=t.verbose===!0,y=b||t.debug===!0,v=t.viewer!==!1,{waitUntilExit:h}=Tr(Pr(_r,{port:o,pluginDir:n,outputDir:r,credentials:i,...p!==void 0&&{credentialMode:p},...d!==void 0&&{activeCredentialProfile:d},...C!==void 0&&{lastPath:C},debug:y,verbose:b,autoViewer:v}),{exitOnCtrlC:!1});await h()})}var Oo=new Set(["phone","envelope","pen-nib","calendar-days","paperclip","file","clipboard","pen","tag","book","print","pen-to-square","folder","folder-open","thumbtack","globe","city","briefcase","compass","address-book","business-time","computer-classic","pen-fancy","badge-check","mug-saucer","landmark","chart-simple","envelopes","diagram-venn","calendar","pencil","phone-volume","copy","table","building","network-wired","address-card","tags","registered","signature","phone-office","projector","sitemap","marker","badge","wallet","copyright","bullseye","calculator","certificate","percent","eraser","file-spreadsheet","glasses","industry","vault","user-tie-hair-long","user-tie-hair","user-hair-mullet","trademark","timeline-arrow","timeline","table-tree","table-rows","table-pivot","table-layout","table-columns","stapler","square-poll-vertical","square-poll-horizontal","square-phone-flip","square-phone","square-pen","square-kanban","square-envelope","socks","slot-machine","signature-slash","signature-lock","shredder","scissors","scanner-image","scale-unbalanced-flip","scale-unbalanced","scale-balanced","router","rectangle-pro","print-slash","print-magnifying-glass","presentation-screen","podium","phone-slash","phone-intercom","phone-flip","person-chalkboard","pen-nib-slash","pen-clip","paste","paperclip-vertical","notebook","note-sticky","money-check-pen","money-check-dollar-pen","magnifying-glass-chart","magnifying-glass-arrow-right","list-tree","list-timeline","list-radio","list-dropdown","list-check","laptop-file","lamp-desk","keynote","industry-windows","inboxes","inbox-full","house-laptop","highlighter","folders","folder-xmark","folder-tree","folder-plus","folder-minus","folder-arrow-up","folder-arrow-down","floppy-disk-circle-xmark","floppy-disk-circle-arrow-right","floppy-disk","file-user","file-lines","file-circle-plus","file-circle-info","file-chart-pie","file-chart-column","fax","envelope-open","envelope-dot","envelope-circle-check","coffee-pot","cloud-word","clipboard-question","chart-user","chart-tree-map","chart-simple-horizontal","chart-pyramid","chart-pie-simple","chart-pie","chart-line-up","chart-line-down","chart-line","cake-candles","cabinet-filing","bullhorn","briefcase-blank","briefcase-arrow-right","brain-arrow-curved-right","boxes-packing","box-archive","book-section","bars-staggered","bars-progress","badge-percent","badge-dollar","arrows-to-eye","arrows-to-dot","arrows-spin","sparkles","megaphone","block-question","lightbulb-slash","comments-dollar","comments","bullseye-pointer","lightbulb","user-group-crown","user-crown","signal-stream-slash","signal-stream","rectangle-ad","ranking-star","person-rays","people-group","messages-dollar","message-dollar","magnifying-glass-location","magnifying-glass-dollar","lightbulb-on","lightbulb-exclamation","lightbulb-dollar","lightbulb-cfl-on","lightbulb-cfl","hundred-points","group-arrows-rotate","gift-card","filter-circle-dollar","envelopes-bulk","envelope-open-text","envelope-open-dollar","comment-dollar","chart-mixed","bullseye-arrow","star","heart","camera-retro","truck-fast","bell","cart-shopping","gift","barcode","bookmark","camera","thumbs-up","thumbs-down","key","truck","balloons","handshake","shop","shirt","bag-shopping","moped","cart-plus","credit-card","store","cash-register","booth-curtain","trophy","receipt","truck-container","truck-clock","truck-bolt","trophy-star","store-slash","store-lock","star-exclamation","shop-slash","shop-lock","rectangle-barcode","person-booth","nfc-trash","nfc-symbol","nfc-slash","nfc-signal","nfc-pen","nfc-magnifying-glass","nfc-lock","nfc","money-check-dollar","money-check","mobile-signal-out","mobile-signal","hexagon-vertical-nft-slanted","hexagon-vertical-nft","hexagon-image","hand-holding-box","gifts","gem","credit-card-front","credit-card-blank","cart-xmark","cart-shopping-fast","cart-minus","cart-circle-xmark","cart-circle-plus","cart-circle-exclamation","cart-circle-check","cart-circle-arrow-up","cart-circle-arrow-down","cart-arrow-up","cart-arrow-down","box-open-full","basket-shopping-simple","basket-shopping","barcode-scan","barcode-read","balloon","bags-shopping","bars","browser","chart-bar","cog","database","calendar-alt","play","kizen-k","add","book-alt","form-entity","arrows-to-circle","question-circle","chevron-down","chevron-up","window-restore","forward"]),zo=[...Oo].sort(),Mo=new Set(["kizen-k","form-entity"]),Ir=[...zo,...[...Mo].sort()];function Br(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of Ir)console.log(t)})}import{mkdir as Ho,writeFile as Nr,readFile as qo}from"fs/promises";import{join as nt}from"path";var Uo=new Set(["developer_business_id"]);function Vo(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let o=t;if(typeof o.auth_credentials!="object"||o.auth_credentials===null)return o;let n=Object.fromEntries(Object.keys(o.auth_credentials).map(r=>[r,"*****"]));return{...o,auth_credentials:n}}):e}var Jo={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Dr(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let n=o.path.split("/"),r=t;n.forEach((i,p)=>{r.children.has(i)||r.children.set(i,{name:i,children:new Map,isFile:p===n.length-1,filePath:n.slice(0,p+1).join("/")});let d=r.children.get(i);d&&(r=d)})}return t}function It(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Lr(e){return`<ul>${[...e.children.values()].sort((n,r)=>n.isFile!==r.isFile?n.isFile?1:-1:n.name.localeCompare(r.name)).map(n=>n.isFile?`<li class="tf"><a href="#${It(n.filePath)}" data-id="${It(n.filePath)}">${Z(n.name)}</a></li>`:`<li class="td"><span class="dn">${Z(n.name)}/</span>${Lr(n)}</li>`).join("")}</ul>`}function $r(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function Wo(e){let t;return e.base64Image!==void 0?t=`<img src="data:${Jo[$r(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Z(e.path)}" style="max-width:100%">`:e.binaryData!==void 0?t=`<p class="bin">[Binary file: ${String(e.binaryData.length)} bytes]</p>`:t=`<pre><code>${Z(e.content)}</code></pre>`,`<section id="${It(e.path)}"><h2 class="fp">${Z(e.path)}</h2><div class="fb">${t}</div></section>`}var Go={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function Ko(e){return Go[$r(e)]??""}function Fr(e,t=""){let o=[...e.children.values()].sort((n,r)=>n.isFile!==r.isFile?n.isFile?1:-1:n.name.localeCompare(r.name));return o.map((n,r)=>{let i=r===o.length-1,p=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=i?" ":"\u2502 ";return n.isFile?`${t}${p}${n.name}`:`${t}${p}${n.name}/
|
|
192
|
-
|
|
193
|
-
`)
|
|
185
|
+
`.trim(),Co=3e4,st=Ue(process.cwd(),".kizenapp","venv"),yr=["python-3-12","python-3-13"];function So(e){return yr.includes(e)}function To(e){return e.split(`
|
|
186
|
+
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}var hr=To(fr);if(hr.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var He=null,qe=[3,10];function br([e,t]){return e>qe[0]||e===qe[0]&&t>=qe[1]}function Bt(e){return`${String(e[0])}.${String(e[1])}`}function Eo(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),o=t?.[1],n=t?.[2];return o!==void 0&&n!==void 0?`python${o}.${n}`:"python3"}function xr(e){return new Promise(t=>{let o=$t(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),n="";o.stdout.on("data",r=>{n+=r.toString("utf-8")}),o.on("error",()=>{t(null)}),o.on("close",r=>{let i=/(\d+)\.(\d+)/.exec(n);if(r!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Po(e){let t=Eo(e),o=t==="python3"?["python3"]:[t,"python3"],n=[];for(let r of o){let i=await xr(r);if(!i){n.push(`${r}: not found`);continue}if(br(i))return r;n.push(`${r}: ${Bt(i)} (too old)`)}throw new Error(`No Python >= ${Bt(qe)} found for runtime "${e}". The local runner needs Python ${Bt(qe)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${n.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}function gr(e,t,o){return new Promise((n,r)=>{let i=$t(e,t,{stdio:["ignore","pipe","pipe"]}),f=(m,g)=>{let w=[],v="";return m.on("data",y=>{v+=y.toString("utf-8");let l=v.indexOf(`
|
|
187
|
+
`);for(;l>=0;){let x=v.slice(0,l).replace(/\r$/,"");v=v.slice(l+1),w.push(x),o?.(x,g),l=v.indexOf(`
|
|
188
|
+
`)}}),m.on("end",()=>{if(v.length>0){let y=v.replace(/\r$/,"");w.push(y),o?.(y,g)}}),w},p=f(i.stderr,"stderr");f(i.stdout,"stdout"),i.on("error",r),i.on("close",m=>{if(m===0)n();else{let g=p.slice(-10).join(`
|
|
189
|
+
`).trim(),w=g.length>0?`: ${g}`:"";r(new Error(`${e} exited with code ${String(m)}${w}`))}})})}var Rt=null;function ko(e,t){if(He)return t&&Rt?.add(t),He;let o=new Set;t&&o.add(t),Rt=o;let n=i=>{for(let f of o)f(i)},r=Ue(st,"bin","python");return He=(async()=>{try{let i=!1;try{await xo(r);let f=await xr(r);i=f!==null&&br(f)}catch{i=!1}if(!i){await Dt(st,{recursive:!0,force:!0}).catch(()=>{});let f=await Po(e);await gr(f,["-m","venv",st])}return n({kind:"start"}),await gr(r,["-m","pip","install","--disable-pip-version-check",...hr],(f,p)=>{n({kind:"log",line:f,stream:p})}),n({kind:"complete"}),r}catch(i){let f=i instanceof Error?i.message:String(i);throw n({kind:"error",message:f}),He=null,await Dt(st,{recursive:!0,force:!0}).catch(()=>{}),i}finally{Rt=null}})(),He}function _o(e){let t="__KIZEN_RESULT_START__",o="__KIZEN_RESULT_END__",n=e.indexOf(t),r=e.indexOf(o);if(n===-1||r===-1)return{userStdout:e,result:null};let i=e.slice(0,n).trimEnd(),f=e.slice(n+t.length,r).trim();try{let p=JSON.parse(f);return{userStdout:i,result:p}}catch{return{userStdout:e,result:null}}}function Io(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function wr(e){let t=e.timeout??Co;if(!So(e.scriptRuntime))return Io(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${yr.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let o=await ko(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await bo(Ue(wo(),"kizen-step-"));let i=Ue(r,"wrapper.py"),f=Ue(r,"script.py");await Promise.all([mr(i,vo,"utf-8"),mr(f,e.script,"utf-8")]);let p={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:f},{exitCode:m,stdout:g,stderr:w}=await new Promise(N=>{let I=[],T=[],h=!1,b=$t(o,[i],{env:p,cwd:r,stdio:["ignore","pipe","pipe"]}),P=setTimeout(()=>{b.kill("SIGKILL")},t);b.stdout.on("data",a=>{I.push(a)}),b.stderr.on("data",a=>{T.push(a)});let d=a=>{h||(h=!0,clearTimeout(P),N({exitCode:a??1,stdout:Buffer.concat(I).toString("utf-8"),stderr:Buffer.concat(T).toString("utf-8")}))};b.on("close",d),b.on("error",a=>{h||(h=!0,clearTimeout(P),N({exitCode:1,stdout:"",stderr:a.message}))})}),v=Date.now()-n,{userStdout:y,result:l}=_o(g);if(l){let N={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:y,stderr:w,exitCode:m,durationMs:v};return l.error!==null&&(N.error=l.error),l.httpRequests&&(N.httpRequests=l.httpRequests),N}let x={success:!1,outputValues:{},logs:[],stdout:y,stderr:w,exitCode:m,durationMs:v};return m!==0&&(x.error=`Process exited with code ${String(m)}`),x}finally{r&&Dt(r,{recursive:!0,force:!0})}}var vr=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);import{CRYPTO_ALG as Er,CRYPTO_VERSION as Pr,deserializeEnvelope as jo,encrypt as Ao,serializeEnvelope as zo}from"@kizenapps/packager";function Lt(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",o=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${o}${t}`}var Mo=2*1024*1024,Ho=new Set([".DS_Store",".gitignore"]);function Uo(e){if(e===void 0||e==="")return!1;let t=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??"";return t==="localhost"||t==="127.0.0.1"||t==="[::1]"}var Nr=["kizen.com","kizen.dev"];function qo(e){let t;try{t=new URL(e)}catch{return!1}let o=t.hostname.toLowerCase();return o==="localhost"||o==="127.0.0.1"||o==="[::1]"?!0:t.protocol!=="https:"?!1:Nr.some(n=>o===n||o.endsWith("."+n))}function Vo(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return Nr.some(n=>o===n||o.endsWith("."+n))}function Jo(e){if(e===void 0||e==="")return!1;try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"||t==="::1"}catch{return!1}}async function kr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),n=Fo(e,o);if(n!==e&&!n.startsWith(e+Ft))return null;try{let r=await $o(n);return r!==e&&!r.startsWith(e+Ft)?null:r}catch{return null}}function _r(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(Ft).some(r=>Ze.has(r))}function Br(){let e=Oo(import.meta.url);return Ve(Lo(e),"viewer")}function Ir(e,t,o){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let n=JSON.parse(o.toString("utf8"));return typeof n.status_code=="number"?n.status_code:void 0}catch{return}}async function Ot(e){try{return await Bo(e),!0}catch{return!1}}function Rr(e,t,o,n,r,i,f,p,m,g){let w=ur({onChange:p}),v=No(g);return(y,l)=>{(async()=>{let x=y.url??"/";try{if(!Uo(y.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((y.method==="POST"||y.method==="PATCH"||y.method==="DELETE")&&!Jo(y.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${x}`),x==="/api/credentials"){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({credentials:n.current??null,activeProfile:r.current??null}));return}if(x==="/api/credential-profiles"&&y.method==="GET"){let d=await ke();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:d,active:r.current}));return}if(x==="/api/credentials/switch"&&y.method==="POST"){let d=[];for await(let u of y)d.push(u);let s=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}").profile,c=s===void 0||s===""?await K():await ae(s);if(c!==null){n.current=c,r.current=s??void 0;let u=r.current,S=await ge(i);await ye(i,{...S,credentialMode:"global",...u!==void 0&&{activeCredentialProfile:u}}),f({type:"credentials-updated",credentials:c,activeProfile:r.current??null})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:c!==null}));return}if(x==="/api/bundle"){let d=Ve(process.cwd(),".kizenapp","bundle.json");try{let a=await Do(d,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(a)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(x==="/api/last-path"&&y.method==="POST"){let d=[];for await(let s of y)d.push(s);let a=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}");if(typeof a.path=="string"){m.current=a.path;let s=await ge(i);await ye(i,{...s,lastPath:a.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x==="/api/encryption-target"&&y.method==="GET"){let a=(await ge(i)).encryptionTarget==="dev"?"dev":"prod";l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({target:a}));return}if(x==="/api/encryption-target"&&y.method==="POST"){let d=[];for await(let u of y)d.push(u);let a=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}"),s=a!==null&&typeof a=="object"?a:{};if(s.target!=="dev"&&s.target!=="prod"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let c=await ge(i);await ye(i,{...c,encryptionTarget:s.target}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x==="/api/execute-step"&&y.method==="POST"){let d=[];for await(let u of y)d.push(u);let a=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}");if(typeof a.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let s={script:a.script,scriptRuntime:a.scriptRuntime??"python-3-13",inputs:a.inputs??{},secrets:a.secrets??{},onInstallProgress:u=>{u.kind==="start"?f({type:"venv-install-start"}):u.kind==="log"?f({type:"venv-install-log",line:u.line,stream:u.stream}):u.kind==="complete"?f({type:"venv-install-complete"}):f({type:"venv-install-error",message:u.message})}};typeof a.timeout=="number"&&a.timeout>0&&(s.timeout=Math.min(a.timeout,300*1e3));let c=await wr(s);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(c));return}if(x==="/api/proxy-cache/clear"){w.clear(),o({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x==="/api/local/encrypt"&&y.method==="POST"){let d=[];for await(let s of y)d.push(s);let a=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}");if(typeof a.publicKeyPem!="string"||typeof a.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let s=Ao(a.value,a.publicKeyPem),c=zo(s);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(c))}catch(s){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:s.message}))}return}if(x==="/api/local/validate"&&y.method==="POST"){let d=[];for await(let C of y)d.push(C);let a=JSON.parse(Buffer.concat(d).toString("utf-8")||"{}");if(typeof a.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: value"}));return}let s,c;try{s=jo(a.value)}catch(C){c=C.message}if(c!==void 0||s===void 0){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:!1,checks:[],error:c}));return}let u=C=>Buffer.from(C,"base64").length,S=[{label:"Version",expected:String(Pr),actual:String(s.v),pass:s.v===Pr},{label:"Algorithm",expected:Er,actual:s.alg,pass:s.alg===Er},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(u(s.k))} bytes`,pass:u(s.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(u(s.iv))} bytes`,pass:u(s.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(u(s.tag))} bytes`,pass:u(s.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(u(s.ct))} bytes`,pass:u(s.ct)>=1}];l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:S.every(C=>C.pass),checks:S}));return}if(x.startsWith("/api/wizard")){let d=y.headers["x-encryption-target"],s=(Array.isArray(d)?d[0]:d)==="dev"?"dev":"prod",c=Me(s);if(!qo(c)){l.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:`Encryption API host is not allowed: ${c}`}));return}let u=x.slice(11)||"/",S=`${c}${u}`,C=y.method??"GET",B=[];for await(let ce of y)B.push(ce);let{host:A,"x-encryption-target":U,...Y}=y.headers,X=B.length>0?Buffer.concat(B):void 0,re=X&&X.length>0?X:void 0,ne;try{ne=await fetch(S,{method:C,headers:Y,...re!==void 0&&{body:re}})}catch(ce){let Le=ce.code==="ECONNREFUSED"?`plugin-wizard is not running at ${c}`:`Failed to reach plugin-wizard: ${ce.message}`;l.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:Le}));return}let ee=it(Object.fromEntries(ne.headers)),$e=await ne.arrayBuffer();l.writeHead(ne.status,ee),l.end(Buffer.from($e));return}if(x.startsWith("/api/proxy")){let d=y.headers["x-proxy-target"];if(typeof d!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!Vo(d)){l.writeHead(400),l.end("Invalid proxy target");return}let a=x.slice(10)||"/",s=`${d}${a}`,c=y.method??"GET",u=[];for await(let ne of y)u.push(ne);let{host:S,"x-proxy-target":C,...B}=y.headers;if(c==="GET"){let ne=`GET::${s}`,{response:ee,fromCache:$e}=await w.get(ne,()=>fetch(s,{method:"GET",headers:B}));o({kind:"request",method:"GET",status:ee.status,upstreamStatus:Ir(a,ee.headers,ee.body),fromCache:$e,url:a}),l.writeHead(ee.status,ee.headers),l.end(ee.body);return}let A=u.length>0?Buffer.concat(u):void 0,U=A&&A.length>0?A:void 0,Y=await fetch(s,{method:c,headers:B,...U!==void 0&&{body:U}}),X=it(Object.fromEntries(Y.headers)),re=await _t(Y,kt);o({kind:"request",method:c,status:Y.status,upstreamStatus:Ir(a,X,re),fromCache:!1,url:a}),l.writeHead(Y.status,X),l.end(re);return}if(x.startsWith("/api/source/tree")&&y.method==="GET"){let a=new URL(x,"http://localhost").searchParams.get("path")??"",s=await kr(v,a);if(s===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(_r(v,s)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let c=await Ro(s,{withFileTypes:!0}),u=await Promise.all(c.filter(C=>C.isDirectory()?!Ze.has(C.name):C.isFile()?!Ho.has(C.name):!1).map(async C=>{let B=C.isDirectory()?"dir":"file",A={name:C.name,kind:B};if(B==="file")try{let U=await Sr(Ve(s,C.name));A.size=U.size}catch{}return A}));u.sort((C,B)=>C.kind!==B.kind?C.kind==="dir"?-1:1:C.name.localeCompare(B.name));let S=s===v?"":s.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:S,entries:u}))}catch(c){let u=c instanceof Error?c.message:String(c);t(`source/tree failed (${a}): ${u}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(x.startsWith("/api/source/file")&&y.method==="GET"){let a=new URL(x,"http://localhost").searchParams.get("path")??"";if(a===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let s=await kr(v,a);if(s===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(_r(v,s)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let c=await Sr(s);if(!c.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(c.size>Mo){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:c.size}));return}let u=Tr(s).toLowerCase(),S=It[u],C=vr.has(u),B=S??(C?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":B,"Content-Length":String(c.size)}),Cr(s).pipe(l)}catch(c){let u=c instanceof Error?c.message:String(c);t(`source/file failed (${a}): ${u}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let T=Ve(e,x==="/"?"/index.html":x),h=await Ot(T)?T:Ve(e,"index.html"),b=Tr(h),P=It[b]??"application/octet-stream";l.writeHead(200,{"Content-Type":P}),Cr(h).pipe(l)}catch(N){if(x.startsWith("/api/proxy")){let I=x.slice(10)||"/",T=y.method??"GET";N instanceof ze?o({kind:"info",message:`${T} ${I} \u2192 502 (response exceeded ${String(N.limit)} bytes)`}):o({kind:"request",method:T,status:502,fromCache:!1,url:I})}else o({kind:"info",message:`Error handling ${x}: ${N instanceof Error?N.message:String(N)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as Wo}from"chrome-launcher";import{createRequire as Go}from"module";import{mkdirSync as Ko}from"fs";import{readFile as Yo}from"fs/promises";import{dirname as Xo,join as Zo}from"path";import{fileURLToPath as Qo}from"url";var Dr=Go(import.meta.url)("chrome-remote-interface"),ei=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Lr=["kizen.dev","kizen.com"];function $r(e){try{let{hostname:t}=new URL(e);return Lr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}async function ti(e){try{let t=Zo(Xo(Qo(import.meta.url)),"viewer","icon.png"),o=await Yo(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function Fr(e){Ko(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await Wo({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),n=o.port,r=null,i=null,f=null,p=null,m=0,g=!1,w=b=>{e.debugLog?.(b)},v=b=>{e.verbose&&e.debugLog?.(b)},y=()=>{i!==null&&(clearInterval(i),i=null)},l=b=>b==="chrome://new-tab-page/"||b==="chrome://newtab/",x=async b=>{y(),f=null,await ti(b),await b.Fetch.enable({patterns:Lr.flatMap(d=>[{urlPattern:`*://${d}/*`,requestStage:"Response"},{urlPattern:`*://*.${d}/*`,requestStage:"Response"}])}),b.on("Fetch.requestPaused",d=>{(async()=>{let a=d,{requestId:s,request:c,responseHeaders:u,responseStatusCode:S}=a,C=c.url;v(`Fetch ${String(S??"?")} ${C}`);let B=[],A=!1;for(let U of u??[])if(!ei.has(U.name.toLowerCase()))if(U.name.toLowerCase()==="set-cookie"&&$r(C)){let Y=U.value.split(`
|
|
190
|
+
`).map(X=>/SameSite=/i.test(X)?X.replace(/SameSite=\w+/i,"SameSite=None"):X+"; SameSite=None; Secure").join(`
|
|
191
|
+
`);B.push({name:U.name,value:Y}),A=!0}else B.push(U);A&&v(` rewrote Set-Cookie SameSite on ${C}`);try{let{body:U,base64Encoded:Y}=await b.Fetch.getResponseBody({requestId:s});await b.Fetch.fulfillRequest({requestId:s,responseCode:S??200,responseHeaders:B,body:U,...Y&&{base64Encoded:!0}})}catch(U){v(` fulfillRequest failed (${U.message}), falling through`);try{await b.Fetch.continueRequest({requestId:s})}catch(Y){v(` continueRequest also failed (${Y.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:d}=await b.Network.getAllCookies(),a=0;for(let s of d){if(!$r(`https://${s.domain??""}`)||s.sameSite==="None")continue;let c=s.domain??"",u=c.startsWith(".")?c.slice(1):c;await b.Network.setCookie({url:`https://${u}`,name:s.name,value:s.value,domain:c,path:s.path??"/",secure:!0,...s.httpOnly!==void 0&&{httpOnly:s.httpOnly},...s.expirationDate!==void 0&&{expires:s.expirationDate},sameSite:"None"}),a++}a>0&&v(`cookie-patch cycle: updated ${String(a)} cookie(s) to SameSite=None`)}catch(d){v(`cookie-patch cycle failed: ${d.message}`)}})()},2e3),await b.Target.setDiscoverTargets({discover:!0});let P=d=>{if(d.type==="page"){if(l(d.url)){w(`closed stray new-tab-page target ${d.targetId}`),f!==null&&b.Target.activateTarget({targetId:f}).catch(()=>{}),b.Target.closeTarget({targetId:d.targetId}).catch(()=>{});return}f===null&&(f=d.targetId,w(`captured main target ${d.targetId} (${d.url})`))}};b.on("Target.targetCreated",d=>{let{targetInfo:a}=d;v(`target +${a.type} ${a.targetId} ${a.url}`),P(a)}),b.on("Target.targetInfoChanged",d=>{let{targetInfo:a}=d;v(`target ~${a.type} ${a.targetId} ${a.url}`),P(a)}),b.on("disconnect",()=>{g||r!==b||(w("CDP disconnected"),r=null,y(),N())})},N=()=>{if(g||p!==null)return;let b=Math.min(1e3*2**m,1e4),P=m+1;m++,w(`CDP reconnect scheduled in ${String(b)}ms (attempt #${String(P)})`),p=setTimeout(()=>{p=null,(async()=>{let d;try{d=await Dr({port:n})}catch{w(`CDP reconnect attempt #${String(P)} failed`),N();return}if(g){try{await d.close()}catch{}return}r=d;try{await x(d),w(`CDP reconnected after ${String(P)} attempt(s)`),m=0}catch{r===d&&(r=null);try{await d.close()}catch{}w(`CDP reconnect attempt #${String(P)} failed during setup`),N()}})()},b)},I=30,T=300;for(let b=0;b<I;b++){await new Promise(P=>setTimeout(P,T)),w(`CDP connect attempt ${String(b+1)}/${String(I)}`);try{let P=await Dr({port:n});r=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await x(P),w("CDP connected")}catch{r===P&&(r=null);try{await P.close()}catch{}w("CDP setup failed after connect")}break}catch{if(b===I-1){let P=`CDP unavailable after ${String(I)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return w(P),e.onWarn?.(P),{kill:()=>{o.kill()}}}}}return r?{kill:()=>{if(w("CDP kill requested \u2014 tearing down"),g=!0,p!==null&&(clearTimeout(p),p=null),y(),r!==null){try{r.close()}catch{}r=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as ri,useState as ni}from"react";function at(e){let[t,o]=ni([]),n=ri(r=>{o(i=>[...i,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as lt,useEffect as jt,useState as ct}from"react";import{Box as H,Text as $,useInput as oi}from"ink";import{jsx as k,jsxs as J}from"react/jsx-runtime";var he=["apiKey","userId","businessId"],ii={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Je=({text:e})=>k($,{dimColor:!0,children:e}),dt=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:n})=>{let[r,i]=ct(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[f,p]=ct(""),[m,g]=ct(null),[w,v]=ct(void 0),y=lt(d=>{if(d==="local"){o({mode:"local",credentials:null});return}i({type:"profile-loading"})},[o]),l=lt(async d=>{if(d===null){i({type:"profile-loading"});let c=await ke();i({type:"name-entry",nameBuffer:"",existingProfiles:c});return}v(d.isDefault?void 0:d.name),i({type:"loading"});let a=d.isDefault?await K():await ae(d.name),s=a?Math.max(0,te.indexOf(a.environment)):0;i({type:"creds-entry",field:0,values:a??{},envCursor:s})},[]),x=lt(async(d,a)=>{let s=te[a]??"go",c={apiKey:d.apiKey??"",userId:d.userId??"",businessId:d.businessId??"",environment:s};i({type:"saving"});try{await cr(w??fe,c),o({mode:"global",credentials:c,...w!==void 0&&{profileName:w}})}catch(u){g(u instanceof Error?u.message:String(u)),i({type:"creds-entry",field:0,values:d,envCursor:a})}},[o,w]);oi((d,a)=>{if(a.ctrl&&d==="c"&&process.exit(0),a.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),N();return}n?.();return}if(r.type==="mode-select"){if(a.upArrow)i({type:"mode-select",cursor:0});else if(a.downArrow)i({type:"mode-select",cursor:1});else if(a.return){let s=r.cursor===0?"global":"local";y(s)}return}if(r.type==="profile-select"){let{profiles:s,cursor:c}=r,u=s.length,S=s.length+1;if(a.upArrow)i({...r,cursor:(c-1+S)%S});else if(a.downArrow)i({...r,cursor:(c+1)%S});else if(a.return)if(c===u)i({type:"name-entry",nameBuffer:"",existingProfiles:s});else{let C=s[c]??s[0];C&&l(C)}return}if(r.type==="name-entry"){let{nameBuffer:s,existingProfiles:c}=r;if(a.backspace||a.delete)i({type:"name-entry",nameBuffer:s.slice(0,-1),existingProfiles:c});else if(a.return){let u=s.trim();if(!u){i({...r,nameError:"Name cannot be empty"});return}if(u===fe){i({...r,nameError:`"${fe}" is reserved`});return}if(c.some(S=>S.name===u)){i({...r,nameError:`Profile "${u}" already exists`});return}v(u),i({type:"creds-entry",field:0,values:{},envCursor:0}),p("")}else d&&!a.ctrl&&!a.meta&&i({type:"name-entry",nameBuffer:s+d,existingProfiles:c});return}if(r.type==="creds-entry"){let{field:s,values:c,envCursor:u}=r;if(s===he.length){a.leftArrow?i({...r,envCursor:(u-1+te.length)%te.length}):a.rightArrow?i({...r,envCursor:(u+1)%te.length}):a.upArrow?(i({...r,field:s-1}),p(c[he[s-1]]??"")):a.return&&x(c,u);return}let C=he[s];if(!C)return;if(a.backspace||a.delete)p(B=>B.slice(0,-1));else if(a.upArrow&&s>0){let B={...c,[C]:f},A=s-1;i({...r,field:A,values:B}),p(B[he[A]]??"")}else if(a.return||a.tab||a.downArrow){let B={...c,[C]:f},A=s+1;i({...r,field:A,values:B}),A<he.length?p(B[he[A]]??""):p("")}else d&&!a.ctrl&&!a.meta&&p(B=>B+d)}});let N=lt(async()=>{let d=await ke();i({type:"profile-select",profiles:d,cursor:0})},[]);if(jt(()=>{r.type==="profile-loading"&&N()},[r.type,N]),jt(()=>{e==="global"&&!t&&(async()=>{let d=await K(),a=d?Math.max(0,te.indexOf(d.environment)):0;i({type:"creds-entry",field:0,values:d??{},envCursor:a})})()},[]),jt(()=>{r.type==="creds-entry"&&r.field===0&&p(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let d=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return k(H,{paddingY:1,paddingX:2,children:k($,{dimColor:!0,children:d})})}if(r.type==="done")return null;if(r.type==="mode-select")return J(H,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),J(H,{flexDirection:"column",gap:0,children:[k($,{bold:!0,children:"Credential mode"}),[{label:"Global",desc:"~/.kizenappbuilder/credentials.json",mode:"global"},{label:"Local",desc:"Enter credentials in the browser dev tools",mode:"local"}].map((a,s)=>{let c=r.cursor===s;return J(H,{gap:2,children:[k($,{...c&&{color:"cyan"},children:c?"\u276F":" "}),k($,{bold:c,...c&&{color:"cyan"},children:a.label}),k($,{dimColor:!0,children:a.desc})]},a.mode)})]}),k(Je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:d,cursor:a}=r,s=d.length;return J(H,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),J(H,{flexDirection:"column",gap:0,children:[k($,{bold:!0,children:"Credential profiles"}),d.map((c,u)=>{let S=a===u;return J(H,{gap:2,children:[k($,{...S&&{color:"cyan"},children:S?"\u276F":" "}),k($,{bold:S,...S&&{color:"cyan"},children:c.isDefault?"Default":c.name}),k($,{dimColor:!0,children:c.path})]},c.name)}),J(H,{gap:2,children:[k($,{...a===s&&{color:"cyan"},children:a===s?"\u276F":" "}),k($,{bold:a===s,...a===s&&{color:"cyan"},children:"+ Add new profile"})]})]}),k(Je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:d,nameError:a}=r;return J(H,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),k(H,{flexDirection:"column",gap:0,children:k($,{bold:!0,children:"New credential profile"})}),a&&J($,{color:"red",children:["Error: ",a]}),J(H,{gap:2,children:[k(H,{width:12,children:k($,{bold:!0,color:"cyan",children:"Profile name"})}),k($,{color:"cyan",children:">"}),k($,{children:d}),k($,{color:"cyan",children:"\u2588"})]}),k(Je,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:I,values:T,envCursor:h}=r,b=I===he.length,P=w??fe;return J(H,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[k(V,{}),J(H,{flexDirection:"column",gap:0,children:[k($,{bold:!0,children:w!==void 0?`Profile: ${w}`:"Global credentials"}),J($,{dimColor:!0,children:["Saved to:"," ",w!==void 0?`~/.kizenappbuilder/${w}.json`:Re]})]}),m&&J($,{color:"red",children:["Error: ",m]}),J(H,{flexDirection:"column",gap:0,children:[he.map((d,a)=>{let s=I===a,c=s?f:T[d]??"";return J(H,{gap:2,children:[k(H,{width:12,children:k($,{bold:s,...s&&{color:"cyan"},children:ii[d]})}),k($,{...s&&{color:"cyan"},children:">"}),k($,{children:c}),s&&k($,{color:"cyan",children:"\u2588"})]},d)}),J(H,{gap:2,children:[k(H,{width:12,children:k($,{bold:b,...b&&{color:"cyan"},children:"Environment"})}),k($,{...b&&{color:"cyan"},children:">"}),k(H,{gap:1,children:te.map((d,a)=>{let s=a===h;return b?k($,{bold:s,...s&&{color:"cyan"},children:s?`[${d}]`:d},d):k($,{dimColor:!s,bold:s,children:d},d)})})]})]}),b?k(Je,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):k(Je,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),J($,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as F,jsxs as M}from"react/jsx-runtime";var ui=[".kizenapp",".git"],jr=({port:e,pluginDir:t,outputDir:o,credentials:n,credentialMode:r,activeCredentialProfile:i,lastPath:f,debug:p=!1,verbose:m=!1,autoViewer:g=!0})=>{let w=le(n),v=le(i),y=le(f),[l,x]=Z("main"),[N,I]=Z(r),[T,h]=Z("starting"),[b,P]=Z(null),[d,a]=at(50),[s,c]=at(50),[u,S]=at(50),[C,B]=Z([]),[A,U]=Z("pending"),[Y,X]=Z(null),[re,ne]=Z(null),[ee,$e]=Z(null),[ce,Le]=Z(0),[Mt,un]=Z(0),[pn,fn]=Z(0),[mn,gn]=Z(0),ht=le(!1),Ht=le(!1),Ge=le(null),Fe=le(null),de=le(new Set),Ke=le([]),Q=De(E=>{let O=JSON.stringify(E);if(de.current.size===0){Ke.current=[...Ke.current,O].slice(-50);return}let ue=!1;for(let oe of de.current)if(oe.readyState===1)try{oe.send(O)}catch{de.current.delete(oe),ue=!0}ue&&Le(de.current.size)},[]),Ye=a,bt=De(()=>{Ge.current?.kill(),Ge.current=null,Fr({port:e,userDataDir:Or(o,".chrome"),broadcast:Q,onWarn:E=>{a(`\u26A0 ${E}`)},...y.current!==void 0&&{path:y.current},...p&&{debugLog:S},...m&&{verbose:!0}}).then(E=>{Ge.current=E})},[e,o,Q,p,m,S,a]);ut(()=>{let E=()=>{Ge.current?.kill()};return process.on("exit",E),()=>{process.off("exit",E)}},[]),ai((E,O)=>{(E==="q"||O.ctrl&&E==="c")&&process.exit(0),E==="c"&&x("editing"),E==="v"&&bt()},{isActive:l==="main"}),ut(()=>{T!=="running"||Ht.current||!g||(Ht.current=!0,bt())},[T,g,bt]);let yn=De(E=>{w.current=E.credentials,v.current=E.profileName,x("main"),I(E.mode);let O=E.profileName;ye(o,{credentialMode:E.mode,...O!==void 0&&{activeCredentialProfile:O}}),Q({type:"credentials-updated",credentials:E.credentials})},[o,Q]),Ut=De(E=>{B(O=>[...O,`${new Date().toLocaleTimeString()}: ${Lt(E)}`].slice(-50)),E.kind==="request"&&(E.fromCache?fn(O=>O+1):gn(O=>O+1)),Q({type:"proxy-log",entry:E})},[Q]),we=De(E=>{c(E),Q({type:"log",message:E})},[c,Q]),xt=De(()=>{ht.current||(ht.current=!0,U("building"),X(null),we("Build started"),et(t,o).then(({bundleSize:E})=>{we(`Build finished \u2014 bundle: ${Oe(E)}`),U("done"),ne(new Date),$e(E),we("Notifying viewers to reload"),Q({type:"rebuild"})}).catch(E=>{let O=E instanceof Error?E.message:String(E);X(O),U("error")}).finally(()=>{ht.current=!1}))},[t,o,we,Q]);if(ut(()=>{xt();let E=li(t,{recursive:!0},(O,ue)=>{if(!ue)return;let oe=ue.replace(/\\/g,"/");ui.some(Xe=>oe.startsWith(Xe))||(we(`File change detected: ${ue}`),Fe.current!==null&&clearTimeout(Fe.current),Fe.current=setTimeout(xt,150))});return E.on("error",O=>{we(`File watcher error \u2014 rebuilds have stopped: ${O.message}`)}),()=>{E.close(),Fe.current!==null&&clearTimeout(Fe.current)}},[t,xt,we]),ut(()=>{let E=Br();Ot(Or(E,"index.html")).then(O=>{if(!O){P("Viewer not built. Run 'pnpm build:viewer' first."),h("error");return}let ue=Rr(E,Ye,Ut,w,v,o,Q,un,y,t),oe=ci(ue),Xe=new di({server:oe});return Xe.on("connection",ve=>{for(let bn of Ke.current)ve.readyState===1&&ve.send(bn);Ke.current=[],Ye("Viewer connected for live reload"),de.current.add(ve),Le(de.current.size),ve.on("close",()=>{de.current.delete(ve),Le(de.current.size)})}),oe.listen(e,"127.0.0.1",()=>{h("running"),Ye(`Server started on 127.0.0.1:${String(e)}`)}),oe.on("error",ve=>{P(ve.message),h("error")}),()=>{Xe.close(),oe.close()}})},[e,Ye,Ut,Q,o,t]),l==="editing")return F(dt,{...N!==void 0&&{initialMode:N},showProfileManager:N==="global",onComplete:yn,onCancel:()=>{x("main")}});let wt=re!==null?Math.round((Date.now()-re.getTime())/1e3):null,hn=wt===null?"":wt<5?" (just now)":` (${String(wt)}s ago)`;return M(W,{flexDirection:"column",paddingY:1,paddingX:2,children:[F(V,{marginBottom:1}),M(W,{flexDirection:"column",children:[M(W,{gap:2,marginBottom:0,children:[F(L,{bold:!0,dimColor:!0,children:"App Build"}),A==="pending"&&F(L,{dimColor:!0,children:"waiting\u2026"}),A==="building"&&M(W,{gap:1,children:[F(pe,{}),F(L,{children:"Building plugin package\u2026"})]}),A==="done"&&M(W,{gap:1,children:[F(L,{color:"green",children:"\u2713 Built"}),re!==null&&M(L,{dimColor:!0,children:["at ",re.toLocaleTimeString(),hn]}),ee!==null&&M(L,{dimColor:!0,children:["\xB7 bundle: ",Oe(ee)]})]}),A==="error"&&M(L,{color:"red",children:["\u2717 ",Y??"unknown error"]})]}),F(W,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:s.slice(-8).map((E,O)=>F(L,{dimColor:!0,wrap:"truncate",children:E},O))})]}),M(W,{marginTop:1,flexDirection:"column",children:[M(W,{gap:2,children:[F(L,{bold:!0,dimColor:!0,children:"Web Server"}),T==="starting"&&F(L,{dimColor:!0,children:"starting\u2026"}),T==="running"&&M(W,{gap:2,children:[F(L,{color:"green",children:"\u2713 Running"}),M(L,{dimColor:!0,children:["\u25CF ",ce," viewer",ce!==1?"s":""]})]}),T==="error"&&M(L,{color:"red",children:["\u2717 ",b??"Server error"]})]}),F(W,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:d.slice(-8).map((E,O)=>F(L,{dimColor:!0,wrap:"truncate",children:E},O))})]}),M(W,{marginTop:1,flexDirection:"column",children:[M(W,{gap:2,children:[F(L,{bold:!0,dimColor:!0,children:"Network Proxy"}),F(L,{color:"green",children:"\u2713 Active"}),M(L,{dimColor:!0,children:["\u25CF ",Mt," key",Mt!==1?"s":""," in the network cache \xB7"," ",pn," hit \xB7 ",mn," miss"]})]}),F(W,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:C.length===0?F(L,{dimColor:!0,children:" No requests yet."}):C.slice(-8).map((E,O)=>F(L,{dimColor:!0,wrap:"truncate",children:E},O))})]}),p&&M(W,{marginTop:1,flexDirection:"column",children:[M(W,{gap:2,children:[F(L,{bold:!0,dimColor:!0,children:"CDP Debug"}),M(L,{dimColor:!0,children:["\u25CF ",u.length," event(s)"]})]}),F(W,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:u.length===0?F(L,{dimColor:!0,children:" No CDP events yet."}):u.slice(-8).map((E,O)=>F(L,{dimColor:!0,wrap:"truncate",children:E},O))})]}),M(W,{marginTop:1,gap:1,children:[F(L,{dimColor:!0,children:"["}),F(L,{children:"q"}),F(L,{dimColor:!0,children:"] quit ["}),F(L,{children:"c"}),F(L,{dimColor:!0,children:"] credentials ["}),F(L,{children:"v"}),M(L,{dimColor:!0,children:["] ",ce===0?"open viewer":"relaunch viewer"]})]})]})};async function Ar(e){return new Promise(t=>{let o=null,n=i=>{o?.(),t(i)},{unmount:r}=Mr(zr(dt,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});o=r})}function Hr(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to a credentials JSON file").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").action(async t=>{let o=parseInt(t.port,10),n=process.cwd(),r=`${n}/.kizenapp`;Ne(n);let i=null,f,p,{lastPath:m}=await ge(r);if(t.credentials)i=await me(t.credentials);else{let l=await ge(r);if(l.credentialMode==="local")f="local";else if(l.credentialMode==="global"){if(f="global",p=l.activeCredentialProfile,p?(i=await ae(p),i||(i=await K(),p=void 0)):i=await K(),!i){let x=await Ar("global");i=x.credentials,p=x.profileName}}else{let x=await Ar();i=x.credentials,f=x.mode,p=x.profileName;let N=x.profileName;await ye(r,{credentialMode:x.mode,...N!==void 0&&{activeCredentialProfile:N}})}}let g=t.verbose===!0,w=g||t.debug===!0,v=t.viewer!==!1,{waitUntilExit:y}=Mr(zr(jr,{port:o,pluginDir:n,outputDir:r,credentials:i,...f!==void 0&&{credentialMode:f},...p!==void 0&&{activeCredentialProfile:p},...m!==void 0&&{lastPath:m},debug:w,verbose:g,autoViewer:v}),{exitOnCtrlC:!1});await y()})}import{createElement as Ti}from"react";import{readFile as Ei,writeFile as Pi}from"fs/promises";import{join as ki}from"path";import{render as _i}from"ink";import{useCallback as ft,useEffect as Gr,useState as mt}from"react";import{Box as ie,Text as j,useApp as Ci,useInput as Si}from"ink";import{encrypt as pi,serializeEnvelope as fi}from"@kizenapps/packager";function mi(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Ur(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function qr(e,t,o){try{return await fetch(`${e}${t}`,o)}catch(n){throw new Error(mi(n)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${n.message}`)}}async function Vr(e){let t=await e.text();if(t==="")return{};try{let o=JSON.parse(t);return typeof o=="object"&&o!==null?o:{}}catch{return{}}}async function gi(e,t,o){let n=Me(e.stage),r=await qr(n,"/get-public-key",{method:"POST",headers:Ur(t),body:JSON.stringify({api_name:o})}),i=await Vr(r);if(!r.ok||typeof i.public_key!="string"){let f=typeof i.error=="string"?i.error:`HTTP ${String(r.status)}`;throw new Error(`Failed to fetch public key: ${f}`)}return i.public_key}function yi(e,t){let o=pi(t,e),n=fi(o);if(typeof n.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return n.value}async function hi(e,t,o,n){let r=Me(e.stage),i=await qr(r,"/encrypt",{method:"POST",headers:Ur(t),body:JSON.stringify({api_name:o,value:n})}),f=await Vr(i);if(!i.ok||f.encrypted!==!0||typeof f.value!="string"){let p=typeof f.error=="string"?f.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${p}`)}return f.value}async function pt(e,t,o,n,r){if(e.isRemote)return r?.("encrypting"),hi(e,t,o,n);r?.("fetching-key");let i=await gi(e,t,o);return r?.("encrypting"),yi(i,n)}import{spawn as bi}from"child_process";import{platform as Jr}from"process";function xi(){return Jr==="darwin"?[{cmd:"pbcopy",args:[]}]:Jr==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var wi=2e3;function vi(e,{cmd:t,args:o}){return new Promise(n=>{let r;try{r=bi(t,o,{stdio:["pipe","ignore","ignore"]})}catch{n(!1);return}let i=r,f=!1;function p(g){f||(f=!0,clearTimeout(m),n(g))}let m=setTimeout(()=>{i.kill(),p(!1)},wi);m.unref(),i.on("error",()=>{p(!1)}),i.on("close",g=>{p(g===0)}),i.stdin.on("error",()=>{p(!1)});try{i.stdin.end(e)}catch{p(!1)}})}async function Wr(e){for(let t of xi())if(await vi(e,t))return!0;return!1}import{Fragment as gt,jsx as D,jsxs as G}from"react/jsx-runtime";var At=({text:e})=>D(j,{dimColor:!0,children:e}),Kr=({ctx:e,stageDefaulted:t,credentialsPath:o,initialApiName:n,defaultApiName:r,initialValue:i,onDone:f})=>{let p=Ci(),[m,g]=mt({type:"loading"}),[w,v]=mt(null),[y,l]=mt(n??""),[x,N]=mt(i??""),I=ft(s=>{process.exitCode=1,g({type:"error",message:s instanceof Error?s.message:String(s)})},[]),T=ft(async(s,c,u)=>{try{let S=await pt(e,s,c,u,A=>{g(A==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),C=JSON.stringify({encrypted:!0,value:S},null,2);f?.(S);let B=await Wr(C);g({type:"done",envelope:C,copied:B})}catch(S){I(S)}},[e,I,f]),h=ft((s,c,u)=>{if(c.trim()===""){g({type:"api-name-entry",buffer:r??""});return}if(u===""){g({type:"value-entry",buffer:""});return}T(s,c.trim(),u)},[r,T]),b=ft(async s=>{try{g({type:"loading"});let c=s.isDefault?await K():await ae(s.name);if(c===null)throw new Error(`Could not load credential profile: ${s.name}`);v(c),h(c,y,x)}catch(c){I(c)}},[y,x,h,I]);Gr(()=>{(async()=>{try{if(o!==void 0){let u;try{u=await me(o)}catch(S){throw new Error(`Could not load credentials from ${o}: ${S instanceof Error?S.message:String(S)}`)}v(u),h(u,y,x);return}let s=await ke();if(s.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[c]=s;if(s.length===1&&c!==void 0){let u=c.isDefault?await K():await ae(c.name);if(u===null)throw new Error(`Could not load credential profile: ${c.name}`);v(u),h(u,y,x);return}g({type:"profile-select",profiles:s,cursor:0})}catch(s){I(s)}})()},[]),Gr(()=>{(m.type==="done"||m.type==="error")&&p.exit()},[m,p]),Si((s,c)=>{if(c.ctrl&&s==="c"){process.exitCode=130,p.exit();return}if(m.type==="profile-select"){let{profiles:u,cursor:S}=m;if(c.upArrow)g({...m,cursor:(S-1+u.length)%u.length});else if(c.downArrow)g({...m,cursor:(S+1)%u.length});else if(c.return){let C=u[S];C!==void 0&&b(C)}return}if(m.type==="api-name-entry"){let{buffer:u}=m;if(c.backspace||c.delete)g({type:"api-name-entry",buffer:u.slice(0,-1)});else if(c.return){let S=u.trim();if(S===""){g({type:"api-name-entry",buffer:u,error:"api_name cannot be empty"});return}l(S),w?h(w,S,x):I(new Error("Internal error: credentials were not loaded"))}else s&&!c.ctrl&&!c.meta&&g({type:"api-name-entry",buffer:u+s});return}if(m.type==="value-entry"){let{buffer:u}=m;if(c.backspace||c.delete)g({type:"value-entry",buffer:u.slice(0,-1)});else if(c.return){if(u===""){g({type:"value-entry",buffer:u,error:"secret cannot be empty"});return}N(u),w?h(w,y,u):I(new Error("Internal error: credentials were not loaded"))}else s&&!c.ctrl&&!c.meta&&g({type:"value-entry",buffer:u+s});return}});let P=e.isRemote?"remote Kizen API":"on-machine",d=t===!0?`${e.stage} (default)`:e.stage,a=s=>G(ie,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(V,{}),G(j,{dimColor:!0,children:["Mode: ",P," Stage: ",d]}),s]});if(m.type==="loading")return a(G(ie,{gap:1,children:[D(pe,{}),D(j,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(m.type==="profile-select"){let{profiles:s,cursor:c}=m;return a(G(gt,{children:[D(j,{bold:!0,children:"Credential profile"}),D(ie,{flexDirection:"column",children:s.map((u,S)=>{let C=c===S;return G(ie,{gap:2,children:[D(j,{...C&&{color:"cyan"},children:C?"\u276F":" "}),D(j,{bold:C,...C&&{color:"cyan"},children:u.isDefault?"Default":u.name}),D(j,{dimColor:!0,children:u.path})]},u.name)})}),D(At,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return m.type==="api-name-entry"?a(G(gt,{children:[D(j,{bold:!0,children:"Plugin api_name"}),m.error!==void 0&&G(j,{color:"red",children:["Error: ",m.error]}),G(ie,{gap:1,children:[D(j,{color:"cyan",children:">"}),D(j,{children:m.buffer}),D(j,{color:"cyan",children:"\u2588"})]}),D(At,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):m.type==="value-entry"?a(G(gt,{children:[D(j,{bold:!0,children:"Secret value"}),m.error!==void 0&&G(j,{color:"red",children:["Error: ",m.error]}),G(ie,{gap:1,children:[D(j,{color:"cyan",children:">"}),D(j,{children:"\u2022".repeat(m.buffer.length)}),D(j,{color:"cyan",children:"\u2588"})]}),D(At,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):m.type==="fetching-key"?a(G(ie,{gap:1,children:[D(pe,{}),G(j,{children:["Fetching ",e.stage," public key for ",D(j,{bold:!0,children:y}),"\u2026"]})]})):m.type==="encrypting"?a(G(ie,{gap:1,children:[D(pe,{}),D(j,{children:"Encrypting\u2026"})]})):m.type==="error"?a(G(ie,{gap:1,children:[D(j,{color:"red",children:"\u2717"}),D(j,{color:"red",children:m.message})]})):a(G(gt,{children:[G(ie,{gap:1,children:[D(j,{color:"green",children:"\u2713"}),D(j,{bold:!0,children:"Encrypted secret ready"})]}),m.copied?D(j,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):D(j,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),D(j,{children:m.envelope})]}))};function Yr(e){return{encrypted:!0,value:e}}function Ii(e){return JSON.stringify(Yr(e))}async function Xr(e,t){await Pi(e,`${JSON.stringify(Yr(t),null,2)}
|
|
192
|
+
`,"utf-8")}var Ni="prod";async function Bi(){try{let e=await Ei(ki(process.cwd(),"kizen.json"),"utf-8"),t=JSON.parse(e),o=Array.isArray(t)?t[0]:t,n=typeof o.api_name=="string"&&o.api_name!==""?o.api_name:void 0;return{...n!==void 0&&{apiName:n}}}catch{}return{}}async function Ri(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function Di(e,t,o,n){let r=t.credentials!==void 0?await me(t.credentials):await K();if(r===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let i=t.apiName??o.apiName;if(i===void 0||i.trim()==="")throw new Error("api_name is required in non-interactive mode. Pass --api-name or run inside a plugin directory.");n&&process.stderr.write(`No --stage given; defaulting to ${e.stage} encryption keys (pass --stage dev to override)
|
|
193
|
+
`);let f=t.value;if(f===void 0){if(process.stdin.isTTY)throw new Error('No secret provided and stdin is a terminal. Pass --value, or pipe the secret in (e.g. `printf %s "$SECRET" | appbuilder encrypt \u2026`).');process.stderr.write(`Reading secret from stdin (pass --value to skip)\u2026
|
|
194
|
+
`),f=(await Ri()).replace(/[\r\n]+$/,"")}if(f==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let p=await pt(e,r,i.trim(),f);if(process.stdout.write(`${Ii(p)}
|
|
195
|
+
`),t.out!==void 0)try{await Xr(t.out,p),process.stderr.write(`Wrote encrypted envelope to ${t.out}
|
|
196
|
+
`)}catch(m){process.stderr.write(`Error writing ${t.out}: ${m instanceof Error?m.message:String(m)}
|
|
197
|
+
`),process.exitCode=1}}function Zr(e){e.command("encrypt").description("Encrypt a secret for a plugin against its encryption keys").option("--remote","encrypt via the plugin-wizard's remote API instead of on-machine").option("-c, --credentials <path>","path to a credentials JSON file").option("-a, --api-name <name>","plugin api_name the secret belongs to").option("-v, --value <value>","plaintext secret value to encrypt").option("-s, --stage <stage>","which encryption API to use: dev or prod (default: prod)").option("-o, --out <path>","also write the encrypted envelope to a file").action(async t=>{t.stage!==void 0&&t.stage!=="dev"&&t.stage!=="prod"&&(console.error(`Error: --stage must be "dev" or "prod" (got: "${t.stage}")`),process.exit(1));let n=t.apiName===void 0?await Bi():{},r=t.stage===void 0,i=t.stage==="dev"||t.stage==="prod"?t.stage:Ni,f={isRemote:t.remote===!0,stage:i};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await Di(f,t,n,r)}catch(g){console.error(`Error: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}return}let p,{waitUntilExit:m}=_i(Ti(Kr,{ctx:f,stageDefaulted:r,onDone:g=>{p=g},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...n.apiName!==void 0&&{defaultApiName:n.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await m(),p!==void 0&&t.out!==void 0)try{await Xr(t.out,p),process.stderr.write(`Wrote encrypted envelope to ${t.out}
|
|
198
|
+
`)}catch(g){console.error(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}`),process.exitCode=1}})}var $i=new Set(["phone","envelope","pen-nib","calendar-days","paperclip","file","clipboard","pen","tag","book","print","pen-to-square","folder","folder-open","thumbtack","globe","city","briefcase","compass","address-book","business-time","computer-classic","pen-fancy","badge-check","mug-saucer","landmark","chart-simple","envelopes","diagram-venn","calendar","pencil","phone-volume","copy","table","building","network-wired","address-card","tags","registered","signature","phone-office","projector","sitemap","marker","badge","wallet","copyright","bullseye","calculator","certificate","percent","eraser","file-spreadsheet","glasses","industry","vault","user-tie-hair-long","user-tie-hair","user-hair-mullet","trademark","timeline-arrow","timeline","table-tree","table-rows","table-pivot","table-layout","table-columns","stapler","square-poll-vertical","square-poll-horizontal","square-phone-flip","square-phone","square-pen","square-kanban","square-envelope","socks","slot-machine","signature-slash","signature-lock","shredder","scissors","scanner-image","scale-unbalanced-flip","scale-unbalanced","scale-balanced","router","rectangle-pro","print-slash","print-magnifying-glass","presentation-screen","podium","phone-slash","phone-intercom","phone-flip","person-chalkboard","pen-nib-slash","pen-clip","paste","paperclip-vertical","notebook","note-sticky","money-check-pen","money-check-dollar-pen","magnifying-glass-chart","magnifying-glass-arrow-right","list-tree","list-timeline","list-radio","list-dropdown","list-check","laptop-file","lamp-desk","keynote","industry-windows","inboxes","inbox-full","house-laptop","highlighter","folders","folder-xmark","folder-tree","folder-plus","folder-minus","folder-arrow-up","folder-arrow-down","floppy-disk-circle-xmark","floppy-disk-circle-arrow-right","floppy-disk","file-user","file-lines","file-circle-plus","file-circle-info","file-chart-pie","file-chart-column","fax","envelope-open","envelope-dot","envelope-circle-check","coffee-pot","cloud-word","clipboard-question","chart-user","chart-tree-map","chart-simple-horizontal","chart-pyramid","chart-pie-simple","chart-pie","chart-line-up","chart-line-down","chart-line","cake-candles","cabinet-filing","bullhorn","briefcase-blank","briefcase-arrow-right","brain-arrow-curved-right","boxes-packing","box-archive","book-section","bars-staggered","bars-progress","badge-percent","badge-dollar","arrows-to-eye","arrows-to-dot","arrows-spin","sparkles","megaphone","block-question","lightbulb-slash","comments-dollar","comments","bullseye-pointer","lightbulb","user-group-crown","user-crown","signal-stream-slash","signal-stream","rectangle-ad","ranking-star","person-rays","people-group","messages-dollar","message-dollar","magnifying-glass-location","magnifying-glass-dollar","lightbulb-on","lightbulb-exclamation","lightbulb-dollar","lightbulb-cfl-on","lightbulb-cfl","hundred-points","group-arrows-rotate","gift-card","filter-circle-dollar","envelopes-bulk","envelope-open-text","envelope-open-dollar","comment-dollar","chart-mixed","bullseye-arrow","star","heart","camera-retro","truck-fast","bell","cart-shopping","gift","barcode","bookmark","camera","thumbs-up","thumbs-down","key","truck","balloons","handshake","shop","shirt","bag-shopping","moped","cart-plus","credit-card","store","cash-register","booth-curtain","trophy","receipt","truck-container","truck-clock","truck-bolt","trophy-star","store-slash","store-lock","star-exclamation","shop-slash","shop-lock","rectangle-barcode","person-booth","nfc-trash","nfc-symbol","nfc-slash","nfc-signal","nfc-pen","nfc-magnifying-glass","nfc-lock","nfc","money-check-dollar","money-check","mobile-signal-out","mobile-signal","hexagon-vertical-nft-slanted","hexagon-vertical-nft","hexagon-image","hand-holding-box","gifts","gem","credit-card-front","credit-card-blank","cart-xmark","cart-shopping-fast","cart-minus","cart-circle-xmark","cart-circle-plus","cart-circle-exclamation","cart-circle-check","cart-circle-arrow-up","cart-circle-arrow-down","cart-arrow-up","cart-arrow-down","box-open-full","basket-shopping-simple","basket-shopping","barcode-scan","barcode-read","balloon","bags-shopping","bars","browser","chart-bar","cog","database","calendar-alt","play","kizen-k","add","book-alt","form-entity","arrows-to-circle","question-circle","chevron-down","chevron-up","window-restore","forward"]),Li=[...$i].sort(),Fi=new Set(["kizen-k","form-entity"]),Qr=[...Li,...[...Fi].sort()];function en(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of Qr)console.log(t)})}import{mkdir as Oi,writeFile as tn,readFile as ji}from"fs/promises";import{join as yt}from"path";var Ai=new Set(["developer_business_id"]);function zi(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let o=t;if(typeof o.auth_credentials!="object"||o.auth_credentials===null)return o;let n=Object.fromEntries(Object.keys(o.auth_credentials).map(r=>[r,"*****"]));return{...o,auth_credentials:n}}):e}var Mi={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function nn(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let n=o.path.split("/"),r=t;n.forEach((i,f)=>{r.children.has(i)||r.children.set(i,{name:i,children:new Map,isFile:f===n.length-1,filePath:n.slice(0,f+1).join("/")});let p=r.children.get(i);p&&(r=p)})}return t}function zt(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function se(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function on(e){return`<ul>${[...e.children.values()].sort((n,r)=>n.isFile!==r.isFile?n.isFile?1:-1:n.name.localeCompare(r.name)).map(n=>n.isFile?`<li class="tf"><a href="#${zt(n.filePath)}" data-id="${zt(n.filePath)}">${se(n.name)}</a></li>`:`<li class="td"><span class="dn">${se(n.name)}/</span>${on(n)}</li>`).join("")}</ul>`}function sn(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function Hi(e){let t;return e.base64Image!==void 0?t=`<img src="data:${Mi[sn(e.path)]??"image/png"};base64,${e.base64Image}" alt="${se(e.path)}" style="max-width:100%">`:e.binaryData!==void 0?t=`<p class="bin">[Binary file: ${String(e.binaryData.length)} bytes]</p>`:t=`<pre><code>${se(e.content)}</code></pre>`,`<section id="${zt(e.path)}"><h2 class="fp">${se(e.path)}</h2><div class="fb">${t}</div></section>`}var Ui={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function qi(e){return Ui[sn(e)]??""}function an(e,t=""){let o=[...e.children.values()].sort((n,r)=>n.isFile!==r.isFile?n.isFile?1:-1:n.name.localeCompare(r.name));return o.map((n,r)=>{let i=r===o.length-1,f=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",p=i?" ":"\u2502 ";return n.isFile?`${t}${f}${n.name}`:`${t}${f}${n.name}/
|
|
199
|
+
${an(n,t+p)}`}).join(`
|
|
200
|
+
`)}function ln(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html")}function cn(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Ai.has(t)).map(([t,o])=>[t,t==="services"?zi(o):o]))}function Vi(e,t){let o=cn(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",f=ln(t),p=[];p.push(`# ${n}${r?` v${r}`:""}`),i&&p.push("",i),p.push("","## Configuration (`kizen.json`)","","```json",JSON.stringify(o,null,2),"```"),p.push("","## File Tree","","```",an(nn(f)),"```"),p.push("","## Files");for(let m of f)p.push("",`### \`${m.path}\``,""),m.base64Image!==void 0?p.push(`[Image file: ${m.path}]`):m.binaryData!==void 0?p.push(`[Binary file: ${String(m.binaryData.length)} bytes]`):p.push(`\`\`\`${qi(m.path)}`,m.content,"```");return p.join(`
|
|
194
201
|
`)+`
|
|
195
|
-
`}function
|
|
202
|
+
`}function Ji(e,t){let o=cn(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",f=ln(t),p=on(nn(f)),m=f.map(Hi).join(`
|
|
196
203
|
`);return`<!DOCTYPE html>
|
|
197
204
|
<html lang="en">
|
|
198
205
|
<head>
|
|
199
206
|
<meta charset="UTF-8">
|
|
200
207
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
201
|
-
<title>${
|
|
208
|
+
<title>${se(n)} \u2014 Plugin Report</title>
|
|
202
209
|
<style>
|
|
203
210
|
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
204
211
|
:root{
|
|
@@ -235,17 +242,17 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
235
242
|
</head>
|
|
236
243
|
<body>
|
|
237
244
|
<header>
|
|
238
|
-
<h1>${
|
|
239
|
-
${i?`<p>${
|
|
245
|
+
<h1>${se(n)}${r?` <span style="color:var(--mu);font-size:.8em">v${se(r)}</span>`:""}</h1>
|
|
246
|
+
${i?`<p>${se(i)}</p>`:""}
|
|
240
247
|
</header>
|
|
241
248
|
<div class="layout">
|
|
242
249
|
<nav>
|
|
243
250
|
<a href="#config" class="cfg" data-id="config">kizen.json (config)</a>
|
|
244
|
-
${
|
|
251
|
+
${p}
|
|
245
252
|
</nav>
|
|
246
253
|
<main>
|
|
247
|
-
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${
|
|
248
|
-
${
|
|
254
|
+
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${se(JSON.stringify(o,null,2))}</code></pre></div></section>
|
|
255
|
+
${m}
|
|
249
256
|
</main>
|
|
250
257
|
</div>
|
|
251
258
|
<script>
|
|
@@ -258,7 +265,7 @@ ${C}
|
|
|
258
265
|
})();
|
|
259
266
|
</script>
|
|
260
267
|
</body>
|
|
261
|
-
</html>`}var
|
|
268
|
+
</html>`}var rn=yt(Pe,"examples");function dn(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${rn}/<api_name>.html)`).action(async t=>{let o=process.cwd(),n;try{let m=await ji(yt(o,"kizen.json"),"utf-8"),g=JSON.parse(m);n=Array.isArray(g)?g[0]:g}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let r=typeof n.api_name=="string"?n.api_name:"plugin",i=t.output??yt(rn,`${r}.html`),f=i.replace(/\.html$/,".md"),p=await Qe(o);await Oi(yt(i,".."),{recursive:!0}),await Promise.all([tn(i,Ji(n,p),"utf-8"),tn(f,Vi(n,p),"utf-8")]),console.log(`Plugin report written to:
|
|
262
269
|
${i}
|
|
263
|
-
${
|
|
270
|
+
${f}`)})}var Xi=Ki(Gi(Yi(import.meta.url)),"..","package.json"),Zi=JSON.parse(Wi(Xi,"utf-8"));xe.name("appbuilder").description("Kizen plugin app builder").version(Zi.version);dr(xe);Qt(xe);Hr(xe);Zr(xe);dn(xe);en(xe);xe.parse();
|
|
264
271
|
//# sourceMappingURL=index.js.map
|