@kizenapps/cli 1.6.2-43e7a52 → 1.6.3-ab1f449

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.
Files changed (42) hide show
  1. package/dist/index.js +18 -18
  2. package/dist/index.js.map +1 -1
  3. package/dist/viewer/assets/{AppDetailPage-RmQ6eFrs.js → AppDetailPage-BTSBtvJb.js} +1 -1
  4. package/dist/viewer/assets/{BootstrapContext-BLyrI7bs.js → BootstrapContext-Caqxm0pS.js} +1 -1
  5. package/dist/viewer/assets/Card-CKKHGdG4.js +1 -0
  6. package/dist/viewer/assets/CodeStepsPage-Krgx1XWT.js +1 -0
  7. package/dist/viewer/assets/{CodeViewer-BbZIh-MU.js → CodeViewer-BdEsrhvR.js} +3 -3
  8. package/dist/viewer/assets/{ConfigurationPage-BqOmyoQr.js → ConfigurationPage-BNA5KrGT.js} +1 -1
  9. package/dist/viewer/assets/{DevSidebar-CUs-cHq1.js → DevSidebar-BBRPcthT.js} +1 -1
  10. package/dist/viewer/assets/{Dialog-BtHSr4rf.js → Dialog-D6sZ1i69.js} +1 -1
  11. package/dist/viewer/assets/{IconReferencePage-DrDFi3ph.js → IconReferencePage-B4ayBaGk.js} +1 -1
  12. package/dist/viewer/assets/SandboxPage-CYnP7ZzD.js +1 -0
  13. package/dist/viewer/assets/SidebarContext-g2Wqf-42.js +1 -0
  14. package/dist/viewer/assets/{SourceBrowserPage-C7hAR6YZ.js → SourceBrowserPage-H2pFRVF1.js} +1 -1
  15. package/dist/viewer/assets/{Tooltip-D9Le4Lgo.js → Tooltip-4dV1-FIG.js} +1 -1
  16. package/dist/viewer/assets/{VersionsPage-BOapKeT8.js → VersionsPage-l_9K0iyg.js} +1 -1
  17. package/dist/viewer/assets/{WhenBadge-DWsoo8Rf.js → WhenBadge-BTCs-6JK.js} +1 -1
  18. package/dist/viewer/assets/api-LYugLsE_.js +11 -0
  19. package/dist/viewer/assets/{bundleQuery-Bjqi6ox2.js → bundleQuery-DnoDprqO.js} +1 -1
  20. package/dist/viewer/assets/{calendarSource.worker-Cg0e7QEm.js → calendarSource.worker-D3Z5_7_3.js} +4 -4
  21. package/dist/viewer/assets/{configStorage-DcCxzQCu.js → configStorage-Db8RcPNR.js} +1 -1
  22. package/dist/viewer/assets/{fa-core-B7dAyAZA.js → fa-core-DteucspK.js} +1 -1
  23. package/dist/viewer/assets/{floatingFrame.worker-CAm1NVPN.js → floatingFrame.worker-Cehe8grH.js} +6 -6
  24. package/dist/viewer/assets/{generic.worker-NxsWBKFc.js → generic.worker-XzKOvCnC.js} +4 -4
  25. package/dist/viewer/assets/index-BCe-a4I_.css +2 -0
  26. package/dist/viewer/assets/{index-ByyMep3r.js → index-BN2If3Zu.js} +3 -3
  27. package/dist/viewer/assets/{react-j0eBFjQW.js → react-CGXpNBH3.js} +1 -1
  28. package/dist/viewer/assets/{recordDetail.worker-Cz1r24RX.js → recordDetail.worker-Cbp2XubL.js} +6 -6
  29. package/dist/viewer/assets/{storageKeys-CSWy3aiP.js → storageKeys-Dv0AbTSJ.js} +1 -1
  30. package/dist/viewer/assets/useCriticalExceptionDialog-DNmzdRI0.js +40 -0
  31. package/dist/viewer/assets/{useLocalStorage-oRuCYBcL.js → useLocalStorage-gLSTo_Vv.js} +1 -1
  32. package/dist/viewer/assets/{useNavigate-AMIImip9.js → useNavigate-EsATq4C7.js} +1 -1
  33. package/dist/viewer/assets/{useQuery-CHCkzQbK.js → useQuery-DLOWDn8s.js} +1 -1
  34. package/dist/viewer/index.html +13 -13
  35. package/package.json +2 -2
  36. package/dist/viewer/assets/Card-D66xMN4f.js +0 -1
  37. package/dist/viewer/assets/CodeStepsPage-BT2DWChv.js +0 -1
  38. package/dist/viewer/assets/SandboxPage-zjGzf2BO.js +0 -1
  39. package/dist/viewer/assets/SidebarContext-CENlTk-2.js +0 -1
  40. package/dist/viewer/assets/api-MJ8ypvzo.js +0 -11
  41. package/dist/viewer/assets/index-B39IGo54.css +0 -2
  42. package/dist/viewer/assets/useCriticalExceptionDialog-D82vwJ1-.js +0 -40
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as Vo}from"fs";import{dirname as Jo,join as Wo}from"path";import{fileURLToPath as Go}from"url";import{program as he}from"commander";import{createElement as bn}from"react";import{render as vn}from"ink";import{useEffect as hn,useState as pt}from"react";import{Box as Pe,Text as ye,useApp as yn}from"ink";import{mkdir as Kr,writeFile as Xr}from"fs/promises";import{join as Yr}from"path";import{minifyFiles as Zr,packagePlugin as Qr,transformDeployablePlugin as en}from"@kizenapps/packager";import{readdir as Ur,readFile as dt}from"fs/promises";import{join as Bt,relative as Vr}from"path";var Jr=new Set([".png",".svg"]),Wr=new Set([".kzn"]),Gr=new Set([".DS_Store"]),ze=new Set(["node_modules",".git",".kizenapp",".github"]);async function Nt(e,t){let o=await Ur(e,{withFileTypes:!0}),n=[];for(let r of o)if(r.isDirectory()){if(ze.has(r.name))continue;n.push(...await Nt(Bt(e,r.name),t))}else r.isFile()&&(Gr.has(r.name)||n.push(Bt(e,r.name)));return n}async function Me(e){let t=await Nt(e,e);return Promise.all(t.map(async o=>{let n=Vr(e,o).split("\\").join("/"),r=n.lastIndexOf("."),s=r>=0?n.slice(r).toLowerCase():"";if(Jr.has(s)){let d=await dt(o);return{path:n,content:"",base64Image:d.toString("base64")}}if(Wr.has(s)){let d=await dt(o);return{path:n,content:"",binaryData:d}}let g=await dt(o,"utf-8");return{path:n,content:g}}))}var tn=["name","api_name","version","entry"];function Rt(e,t){let o=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let n of tn){let r=e[n];if(typeof r!="string"||r==="")throw new Error(`${o} is missing required field "${n}" (expected a non-empty string).`)}}function rn(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.`);Rt(o,n)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return Rt(t),t}var nn=(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 He(e,t,o){await Kr(t,{recursive:!0}),o?.("reading-files");let n=await Me(e);o?.("minifying");let r=await Zr(n);o?.("packaging");let s=r.find(l=>l.path==="kizen.json");if(!s)throw new Error("kizen.json not found in plugin directory.");let g=rn(s.content),d=Qr(r,g),C=Object.values(d).map(en);o?.("writing-bundle");let x=C.map(l=>{let b=l.release_notes_directory?.replace(/\/$/,""),P=b?n.filter(R=>R.path.startsWith(b+"/")&&R.path.endsWith(".md")&&R.content).map(R=>({version:R.path.slice(R.path.lastIndexOf("/")+1,-3),notes:R.content})).sort((R,S)=>S.version.localeCompare(R.version,void 0,{numeric:!0})):[];return nn(l,P)}),y=JSON.stringify(x,null,2),v=(l,b)=>l==="allReleaseNotes"?void 0:b,h=Buffer.byteLength(JSON.stringify(x,v,2),"utf-8");return await Xr(Yr(t,"bundle.json"),y,"utf-8"),{bundleSize:h}}function Te(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as ln,Text as cn}from"ink";import{Box as on,Text as sn}from"ink";import{jsx as Dt}from"react/jsx-runtime";var an=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Lt=()=>Dt(on,{flexDirection:"column",children:an.map((e,t)=>Dt(sn,{color:"cyan",children:e},t))});import{Fragment as dn,jsx as ut,jsxs as un}from"react/jsx-runtime";var V=({marginBottom:e=0})=>un(dn,{children:[ut(Lt,{}),ut(ln,{flexDirection:"column",marginTop:1,marginBottom:e,children:ut(cn,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as pn,useState as fn}from"react";import{Text as mn}from"ink";import{jsx as gn}from"react/jsx-runtime";var Ft=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],qe=()=>{let[e,t]=fn(0);return pn(()=>{let o=setInterval(()=>{t(n=>(n+1)%Ft.length)},80);return()=>{clearInterval(o)}},[]),gn(mn,{color:"cyan",children:Ft[e]??"\u280B"})};import{Fragment as xn,jsx as de,jsxs as ue}from"react/jsx-runtime";var jt=["creating-dir","reading-files","minifying","packaging","writing-bundle"],Ue={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},$t=({outputDir:e,pluginDir:t})=>{let o=yn(),[n,r]=pt("creating-dir"),[s,g]=pt(null),[d,C]=pt(null);hn(()=>{He(t,e,r).then(({bundleSize:h})=>{C(h),r("done"),o.exit()}).catch(h=>{let l=h instanceof Error?h.message:String(h);g(l),r("error"),o.exit()})},[e,t,o]);let x=jt.indexOf(n),y=n==="error",v=n==="done";return ue(Pe,{flexDirection:"column",paddingY:1,paddingX:2,children:[de(V,{marginBottom:1}),ue(Pe,{flexDirection:"column",gap:0,children:[jt.map((h,l)=>{let b=n===h,P=v||x>l;return de(Pe,{gap:1,children:y&&l===x?ue(ye,{color:"red",children:["\u2717 ",Ue[h]]}):P?ue(ye,{color:"green",children:["\u2713 ",Ue[h]]}):b?ue(xn,{children:[de(qe,{}),de(ye,{children:Ue[h]})]}):ue(ye,{dimColor:!0,children:[" ",Ue[h]]})},h)}),v&&d!==null&&de(Pe,{marginTop:1,gap:1,children:ue(ye,{color:"green",children:["\u2713 bundle \u2014 ",Te(d)]})}),s!==null&&de(Pe,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:de(ye,{color:"red",children:s})})]})]})};import*as xe from"fs";import*as At from"path";function be(e){let t=At.join(e,".gitignore"),o=".kizenapp/",n="";if(xe.existsSync(t)){n=xe.readFileSync(t,"utf8");let s=n.split(`
3
- `).map(g=>g.trim());if(s.includes(o)||s.includes(".kizenapp"))return}let r=n.endsWith(`
2
+ import{readFileSync as Zo}from"fs";import{dirname as Qo,join as ei}from"path";import{fileURLToPath as ti}from"url";import{program as he}from"commander";import{createElement as Sn}from"react";import{render as _n}from"ink";import{useEffect as vn,useState as ft}from"react";import{Box as Te,Text as ye,useApp as wn}from"ink";import{mkdir as Qr,writeFile as en}from"fs/promises";import{join as tn}from"path";import{minifyFiles as rn,packagePlugin as nn,transformDeployablePlugin as on}from"@kizenapps/packager";import{readdir as Gr,readFile as ut}from"fs/promises";import{join as Dt,relative as Kr}from"path";var Xr=new Set([".png",".svg"]),Yr=new Set([".kzn"]),Zr=new Set([".DS_Store"]),He=new Set(["node_modules",".git",".kizenapp",".github"]);async function Lt(e,t){let o=await Gr(e,{withFileTypes:!0}),n=[];for(let r of o)if(r.isDirectory()){if(He.has(r.name))continue;n.push(...await Lt(Dt(e,r.name),t))}else r.isFile()&&(Zr.has(r.name)||n.push(Dt(e,r.name)));return n}async function qe(e){let t=await Lt(e,e);return Promise.all(t.map(async o=>{let n=Kr(e,o).split("\\").join("/"),r=n.lastIndexOf("."),i=r>=0?n.slice(r).toLowerCase():"";if(Xr.has(i)){let d=await ut(o);return{path:n,content:"",base64Image:d.toString("base64")}}if(Yr.has(i)){let d=await ut(o);return{path:n,content:"",binaryData:d}}let p=await ut(o,"utf-8");return{path:n,content:p}}))}var sn=["name","api_name","version","entry"];function $t(e,t){let o=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let n of sn){let r=e[n];if(typeof r!="string"||r==="")throw new Error(`${o} is missing required field "${n}" (expected a non-empty string).`)}}function an(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.`);$t(o,n)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return $t(t),t}var ln=(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 Ue(e,t,o){await Qr(t,{recursive:!0}),o?.("reading-files");let n=await qe(e);o?.("minifying");let r=await rn(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 p=an(i.content),d=nn(r,p),C=Object.values(d).map(on);o?.("writing-bundle");let b=C.map(l=>{let x=l.release_notes_directory?.replace(/\/$/,""),T=x?n.filter(R=>R.path.startsWith(x+"/")&&R.path.endsWith(".md")&&R.content).map(R=>({version:R.path.slice(R.path.lastIndexOf("/")+1,-3),notes:R.content})).sort((R,S)=>S.version.localeCompare(R.version,void 0,{numeric:!0})):[];return ln(l,T)}),y=JSON.stringify(b,null,2),v=(l,x)=>l==="allReleaseNotes"?void 0:x,h=Buffer.byteLength(JSON.stringify(b,v,2),"utf-8");return await en(tn(t,"bundle.json"),y,"utf-8"),{bundleSize:h}}function Pe(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as pn,Text as fn}from"ink";import{Box as cn,Text as dn}from"ink";import{jsx as Ft}from"react/jsx-runtime";var un=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],jt=()=>Ft(cn,{flexDirection:"column",children:un.map((e,t)=>Ft(dn,{color:"cyan",children:e},t))});import{Fragment as mn,jsx as pt,jsxs as gn}from"react/jsx-runtime";var V=({marginBottom:e=0})=>gn(mn,{children:[pt(jt,{}),pt(pn,{flexDirection:"column",marginTop:1,marginBottom:e,children:pt(fn,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as hn,useState as yn}from"react";import{Text as bn}from"ink";import{jsx as xn}from"react/jsx-runtime";var At=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ve=()=>{let[e,t]=yn(0);return hn(()=>{let o=setInterval(()=>{t(n=>(n+1)%At.length)},80);return()=>{clearInterval(o)}},[]),xn(bn,{color:"cyan",children:At[e]??"\u280B"})};import{Fragment as Cn,jsx as de,jsxs as ue}from"react/jsx-runtime";var Ot=["creating-dir","reading-files","minifying","packaging","writing-bundle"],Je={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},zt=({outputDir:e,pluginDir:t})=>{let o=wn(),[n,r]=ft("creating-dir"),[i,p]=ft(null),[d,C]=ft(null);vn(()=>{Ue(t,e,r).then(({bundleSize:h})=>{C(h),r("done"),o.exit()}).catch(h=>{let l=h instanceof Error?h.message:String(h);p(l),r("error"),o.exit()})},[e,t,o]);let b=Ot.indexOf(n),y=n==="error",v=n==="done";return ue(Te,{flexDirection:"column",paddingY:1,paddingX:2,children:[de(V,{marginBottom:1}),ue(Te,{flexDirection:"column",gap:0,children:[Ot.map((h,l)=>{let x=n===h,T=v||b>l;return de(Te,{gap:1,children:y&&l===b?ue(ye,{color:"red",children:["\u2717 ",Je[h]]}):T?ue(ye,{color:"green",children:["\u2713 ",Je[h]]}):x?ue(Cn,{children:[de(Ve,{}),de(ye,{children:Je[h]})]}):ue(ye,{dimColor:!0,children:[" ",Je[h]]})},h)}),v&&d!==null&&de(Te,{marginTop:1,gap:1,children:ue(ye,{color:"green",children:["\u2713 bundle \u2014 ",Pe(d)]})}),i!==null&&de(Te,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:de(ye,{color:"red",children:i})})]})]})};import*as be from"fs";import*as Mt from"path";function xe(e){let t=Mt.join(e,".gitignore"),o=".kizenapp/",n="";if(be.existsSync(t)){n=be.readFileSync(t,"utf8");let i=n.split(`
3
+ `).map(p=>p.trim());if(i.includes(o)||i.includes(".kizenapp"))return}let r=n.endsWith(`
4
4
  `)?o+`
5
5
  `:`
6
6
  `+o+`
7
- `;xe.writeFileSync(t,n+r)}function Ot(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),o=`${t}/.kizenapp`;be(t);let{waitUntilExit:n}=vn(bn($t,{outputDir:o,pluginDir:t}));await n()})}import{createElement as Ln}from"react";import{render as Fn}from"ink";import{useCallback as Je,useState as Ee}from"react";import{Box as M,Text as I,useApp as Sn,useInput as _n}from"ink";import{join as gt}from"path";import{access as wn,mkdir as ft,writeFile as Cn}from"fs/promises";import{join as pe}from"path";async function Ve(e){try{return await wn(e),!0}catch{return!1}}async function zt(e){return await Ve(pe(e,"kizen.json"))?"has-manifest":await Ve(pe(e,".kizenapp"))?"has-kizenapp":"ok"}async function Mt(e,t){let o=pe(e,t);if(!await Ve(o))return o;for(let n=1;n<1e3;n++){let r=pe(e,`${t}-${String(n)}`);if(!await Ve(r))return r}throw new Error(`Could not find an available directory name for "${t}"`)}function mt(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 Ht(e){await ft(e.targetDir,{recursive:!0});let t=mt(e);await Cn(pe(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
8
- `,"utf-8"),await ft(pe(e.targetDir,"src"),{recursive:!0}),await ft(pe(e.targetDir,"releaseNotes"),{recursive:!0}),be(e.targetDir)}import{jsx as T,jsxs as $}from"react/jsx-runtime";var fe=["name","apiName","externalLink","description","developerBusinessId"],qt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Ut=["name","apiName"];function kn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var ve=({text:e})=>T(I,{dimColor:!0,children:e});function Tn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Vt=({parentDir:e,defaultBusinessId:t})=>{let o=Sn(),[n,r]=Ee({type:"target-select",cursor:0}),[s,g]=Ee("in-place"),[d,C]=Ee(()=>Tn(t)),[x,y]=Ee(""),[v,h]=Ee(e),l=Je((S,m)=>{g(S),y(m.name),r({type:"field-entry",field:0,values:m})},[]),b=Je(async S=>{let m=await zt(S);if(m!=="ok"){r({type:"precheck-error",targetDir:S,reason:m});return}h(S),l("in-place",d)},[d,l]),P=Je(async S=>{try{let m=await Mt(e,S.apiName);h(m),r({type:"confirm",values:S})}catch(m){r({type:"error",message:m instanceof Error?m.message:String(m)})}},[e]),R=Je(async(S,m)=>{try{await Ht({targetDir:m,name:S.name,apiName:S.apiName,externalLink:S.externalLink,description:S.description,developerBusinessId:S.developerBusinessId}),r({type:"done",targetDir:m})}catch(p){r({type:"error",message:p instanceof Error?p.message:String(p)})}},[]);if(_n((S,m)=>{if(m.ctrl&&S==="c"){o.exit();return}if(n.type==="target-select"){m.upArrow?r({type:"target-select",cursor:0}):m.downArrow?r({type:"target-select",cursor:1}):m.return?n.cursor===0?b(e):l("sub-dir",d):m.escape&&o.exit();return}if(n.type==="precheck-error"){(m.return||m.escape)&&o.exit();return}if(n.type==="field-entry"){let{field:p,values:_}=n,a=fe[p];if(!a)return;if(m.escape){o.exit();return}if(m.backspace||m.delete){y(i=>i.slice(0,-1));return}if(m.upArrow&&p>0){let i={..._,[a]:x},c=p-1,u=fe[c];r({type:"field-entry",field:c,values:i}),C(i),y(u?i[u]:"");return}if(m.return||m.tab||m.downArrow){let i=x.trim();if(Ut.includes(a)&&!i){r({type:"field-entry",field:p,values:_,fieldError:`${qt[a]} is required`});return}let u=a==="description"?x:i,f={..._,[a]:u};C(f);let j=p+1;if(j>=fe.length)y(""),s==="sub-dir"?(r({type:"resolving-target"}),P(f)):r({type:"confirm",values:f});else{let E=fe[j],D=E?f[E]:"",A=E==="apiName"&&!D?kn(f.name):D;r({type:"field-entry",field:j,values:f}),y(A)}return}S&&!m.ctrl&&!m.meta&&y(i=>i+S);return}if(n.type==="confirm"){if(m.escape){let p=fe.length-1,_=fe[p];r({type:"field-entry",field:p,values:n.values}),y(_?n.values[_]:"");return}m.return&&(r({type:"writing"}),R(n.values,v));return}(n.type==="done"||n.type==="error")&&(m.return||m.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 $(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),$(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Where should the new plugin live?"}),S.map((m,p)=>{let _=n.cursor===p;return $(M,{gap:2,children:[T(I,{..._&&{color:"cyan"},children:_?"\u276F":" "}),T(I,{bold:_,..._&&{color:"cyan"},children:m.label}),T(I,{dimColor:!0,children:m.desc})]},m.label)})]}),T(ve,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:S,reason:m}=n;return $(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(I,{color:"red",bold:!0,children:"Cannot create plugin"}),$(M,{flexDirection:"column",gap:0,children:[$(I,{children:[S," already contains ",T(I,{bold:!0,children:m==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),T(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),T(ve,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:S,fieldError:m}=n,p=s==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${v}`;return $(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),$(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Plugin details"}),T(I,{dimColor:!0,children:p})]}),m!==void 0&&$(I,{color:"red",children:["Error: ",m]}),T(M,{flexDirection:"column",gap:0,children:fe.map((_,a)=>{let i=S===a,c=i?x:d[_],u=Ut.includes(_),f=`${qt[_]}${u?"":" (optional)"}`;return $(M,{gap:2,children:[T(M,{width:24,children:T(I,{bold:i,...i&&{color:"cyan"},children:f})}),T(I,{...i&&{color:"cyan"},children:">"}),T(I,{children:c}),i&&T(I,{color:"cyan",children:"\u2588"})]},_)})}),T(ve,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let S=mt({targetDir:v,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return $(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),$(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Ready to create"}),$(I,{dimColor:!0,children:["Target: ",v]})]}),$(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"kizen.json preview"}),T(I,{children:JSON.stringify(S,null,2)})]}),$(M,{flexDirection:"column",gap:0,children:[T(I,{dimColor:!0,children:"Also creates:"}),$(I,{dimColor:!0,children:[" ",gt(v,"src/")]}),$(I,{dimColor:!0,children:[" ",gt(v,"releaseNotes/")]}),$(I,{dimColor:!0,children:[" ",gt(v,".gitignore")," (adds .kizenapp/)"]})]}),T(ve,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?T(M,{paddingY:1,paddingX:2,children:T(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?T(M,{paddingY:1,paddingX:2,children:T(I,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?$(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),$(I,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),$(M,{flexDirection:"column",gap:0,children:[T(I,{dimColor:!0,children:"Next steps:"}),$(I,{children:[" ","cd ",n.targetDir]}),$(I,{children:[" ","appbuilder dev"]})]}),T(ve,{text:"Enter or Esc to exit"})]}):$(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(I,{color:"red",bold:!0,children:"Failed to create plugin"}),T(I,{children:n.message}),T(ve,{text:"Enter or Esc to exit"})]})};import{mkdir as Jt,readFile as Pn,readdir as En,writeFile as Wt}from"fs/promises";import{homedir as In}from"os";import{dirname as Bn,join as We}from"path";var K=["go","fmo","staging","integration","test1"];var me=We(In(),".kizenappbuilder"),we=We(me,"credentials.json"),oe="credentials";function Nn(e){return K.includes(e)}function Rn(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:Nn(o)?o:"go"}}async function Ge(e){let t=await Pn(e,"utf-8");return Rn(JSON.parse(t))}async function Y(){try{return await Ge(we)}catch{return null}}async function Dn(e){await Jt(Bn(we),{recursive:!0,mode:448}),await Wt(we,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Gt(e){return We(me,`${e}.json`)}async function Ie(){let e=[{name:oe,path:we,isDefault:!0}];try{let t=await En(me);for(let o of t){if(!o.endsWith(".json"))continue;let n=o.slice(0,-5);n!==oe&&e.push({name:n,path:We(me,o),isDefault:!1})}}catch{}return e}async function Kt(e,t){if(e===oe){await Dn(t);return}await Jt(me,{recursive:!0,mode:448}),await Wt(Gt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ce(e){try{return await Ge(Gt(e))}catch{return null}}function Xt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await Y())?.businessId??"",{waitUntilExit:r}=Fn(Ln(Vt,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as Cr}from"react";import{render as Sr}from"ink";import{useCallback as Se,useEffect as tt,useRef as te,useState as J}from"react";import{Box as U,Text as N,useInput as Po}from"ink";import{watch as Eo}from"fs";import{createServer as Io}from"http";import{join as br}from"path";import{WebSocketServer as Bo}from"ws";import{createReadStream as ar,realpathSync as Zn}from"fs";import{access as Qn,readdir as eo,readFile as to,realpath as ro,stat as lr}from"fs/promises";import{dirname as no,extname as cr,join as De,resolve as oo,sep as St}from"path";import{fileURLToPath as io}from"url";var jn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ht(e){let t={};for(let[o,n]of Object.entries(e)){let r=o.toLowerCase();jn.has(r)||r.startsWith("access-control-")||(t[o]=n)}return t}var yt=10*1024*1024,$n=6e4,An=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 s of o){if(r+=s.length,r>t)throw new Be(r,t);n.push(s)}return Buffer.concat(n)}function Yt(e={}){let t=new Map,{onChange:o}=e,n=()=>{o?.(t.size)},r=s=>{t.delete(s)&&n()};return{get(s,g){let d=t.get(s);if(d!==void 0){if(Date.now()-d.insertedAt<$n)return d.promise.then(x=>({response:x,fromCache:!0}));r(s)}if(t.size>=An){let x=t.keys().next().value;x!==void 0&&r(x)}let C=g().then(async x=>{let y=ht(Object.fromEntries(x.headers)),v=await xt(x,yt);return{status:x.status,headers:y,body:v}}).catch(x=>{throw r(s),x});return t.set(s,{insertedAt:Date.now(),promise:C}),n(),C.then(x=>((x.status<200||x.status>=300)&&r(s),{response:x,fromCache:!1}))},clear(){t.clear(),n()}}}var bt={".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 On,readFile as zn,writeFile as Mn}from"fs/promises";import{join as Zt}from"path";async function Ne(e){try{let t=await zn(Zt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function ge(e,t){await On(e,{recursive:!0}),await Mn(Zt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as rr}from"child_process";import{writeFile as er,rm as nr,mkdtemp as qn,access as Un}from"fs/promises";import{join as Re}from"path";import{tmpdir as Vn}from"os";var Qt=`awslambdaric
7
+ `;be.writeFileSync(t,n+r)}function Ht(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),o=`${t}/.kizenapp`;xe(t);let{waitUntilExit:n}=_n(Sn(zt,{outputDir:o,pluginDir:t}));await n()})}import{createElement as An}from"react";import{render as On}from"ink";import{useCallback as Ge,useState as Ee}from"react";import{Box as M,Text as I,useApp as Tn,useInput as En}from"ink";import{join as ht}from"path";import{access as kn,mkdir as mt,writeFile as Pn}from"fs/promises";import{join as pe}from"path";async function We(e){try{return await kn(e),!0}catch{return!1}}async function qt(e){return await We(pe(e,"kizen.json"))?"has-manifest":await We(pe(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ut(e,t){let o=pe(e,t);if(!await We(o))return o;for(let n=1;n<1e3;n++){let r=pe(e,`${t}-${String(n)}`);if(!await We(r))return r}throw new Error(`Could not find an available directory name for "${t}"`)}function gt(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 Vt(e){await mt(e.targetDir,{recursive:!0});let t=gt(e);await Pn(pe(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
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
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 Jn=`
25
+ `;var Xn=`
26
26
  import sys, json, os, traceback
27
27
 
28
28
  # --- Inputs proxy (attribute access) ---
@@ -182,17 +182,17 @@ 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(),Wn=3e4,vt=Re(process.cwd(),".kizenapp","venv");function Gn(e){return e.split(`
186
- `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}var or=Gn(Qt);if(or.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var Ke=null;function Kn(e){let t=/^python-(\d+\.\d+)$/.exec(e);return t?.[1]?`python${t[1]}`:"python3"}function tr(e,t,o){return new Promise((n,r)=>{let s=rr(e,t,{stdio:["ignore","pipe","pipe"]}),g=(C,x)=>{let y=[],v="";return C.on("data",h=>{v+=h.toString("utf-8");let l=v.indexOf(`
187
- `);for(;l>=0;){let b=v.slice(0,l).replace(/\r$/,"");v=v.slice(l+1),y.push(b),o?.(b,x),l=v.indexOf(`
188
- `)}}),C.on("end",()=>{if(v.length>0){let h=v.replace(/\r$/,"");y.push(h),o?.(h,x)}}),y},d=g(s.stderr,"stderr");g(s.stdout,"stdout"),s.on("error",r),s.on("close",C=>{if(C===0)n();else{let x=d.slice(-10).join(`
189
- `).trim(),y=x.length>0?`: ${x}`:"";r(new Error(`${e} exited with code ${String(C)}${y}`))}})})}var wt=new Set;function Xe(e){for(let t of wt)t(e)}function Xn(e,t){return t&&wt.add(t),Ke||(Ke=(async()=>{let o=Re(vt,"bin","python");try{await Un(o)}catch{let n=Kn(e);await tr(n,["-m","venv",vt])}Xe({kind:"start"});try{await tr(o,["-m","pip","install","--disable-pip-version-check",...or],(n,r)=>{Xe({kind:"log",line:n,stream:r})}),Xe({kind:"complete"})}catch(n){let r=n instanceof Error?n.message:String(n);throw Xe({kind:"error",message:r}),Ke=null,await nr(vt,{recursive:!0,force:!0}).catch(()=>{}),n}finally{wt.clear()}return o})()),Ke}function Yn(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 s=e.slice(0,n).trimEnd(),g=e.slice(n+t.length,r).trim();try{let d=JSON.parse(g);return{userStdout:s,result:d}}catch{return{userStdout:e,result:null}}}async function ir(e){let t=e.timeout??Wn,o=await Xn(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await qn(Re(Vn(),"kizen-step-"));let s=Re(r,"wrapper.py"),g=Re(r,"script.py");await Promise.all([er(s,Jn,"utf-8"),er(g,e.script,"utf-8")]);let d={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:g},{exitCode:C,stdout:x,stderr:y}=await new Promise(P=>{let R=[],S=[],m=!1,p=rr(o,[s],{env:d,cwd:r,stdio:["ignore","pipe","pipe"]}),_=setTimeout(()=>{p.kill("SIGKILL")},t);p.stdout.on("data",i=>{R.push(i)}),p.stderr.on("data",i=>{S.push(i)});let a=i=>{m||(m=!0,clearTimeout(_),P({exitCode:i??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(S).toString("utf-8")}))};p.on("close",a),p.on("error",i=>{m||(m=!0,clearTimeout(_),P({exitCode:1,stdout:"",stderr:i.message}))})}),v=Date.now()-n,{userStdout:h,result:l}=Yn(x);if(l){let P={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:h,stderr:y,exitCode:C,durationMs:v};return l.error!==null&&(P.error=l.error),l.httpRequests&&(P.httpRequests=l.httpRequests),P}let b={success:!1,outputValues:{},logs:[],stdout:h,stderr:y,exitCode:C,durationMs:v};return C!==0&&(b.error=`Process exited with code ${String(C)}`),b}finally{r&&nr(r,{recursive:!0,force:!0})}}var sr=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 Ct(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 so=2*1024*1024,ao=new Set([".DS_Store",".gitignore"]);function lo(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 co=["kizen.com","kizen.dev"];function uo(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return co.some(n=>o===n||o.endsWith("."+n))}function po(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 dr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),n=oo(e,o);if(n!==e&&!n.startsWith(e+St))return null;try{let r=await ro(n);return r!==e&&!r.startsWith(e+St)?null:r}catch{return null}}function ur(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(St).some(r=>ze.has(r))}function fr(){let e=io(import.meta.url);return De(no(e),"viewer")}function pr(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 _t(e){try{return await Qn(e),!0}catch{return!1}}function mr(e,t,o,n,r,s,g,d,C,x){let y=Yt({onChange:d}),v=Zn(x);return(h,l)=>{(async()=>{let b=h.url??"/";try{if(!lo(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")&&!po(h.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${b}`),b==="/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(b==="/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(b==="/api/credentials/switch"&&h.method==="POST"){let a=[];for await(let f of h)a.push(f);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 f=r.current;await ge(s,{credentialMode:"global",...f!==void 0&&{activeCredentialProfile:f}}),g({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(b==="/api/bundle"){let a=De(process.cwd(),".kizenapp","bundle.json");try{let i=await to(a,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(i)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(b==="/api/last-path"&&h.method==="POST"){let a=[];for await(let c of h)a.push(c);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.path=="string"){C.current=i.path;let c=await Ne(s);await ge(s,{...c,lastPath:i.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(b==="/api/execute-step"&&h.method==="POST"){let a=[];for await(let f of h)a.push(f);let i=JSON.parse(Buffer.concat(a).toString("utf-8")||"{}");if(typeof i.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:i.script,scriptRuntime:i.scriptRuntime??"python-3.9",inputs:i.inputs??{},secrets:i.secrets??{},onInstallProgress:f=>{f.kind==="start"?g({type:"venv-install-start"}):f.kind==="log"?g({type:"venv-install-log",line:f.line,stream:f.stream}):f.kind==="complete"?g({type:"venv-install-complete"}):g({type:"venv-install-error",message:f.message})}};typeof i.timeout=="number"&&i.timeout>0&&(c.timeout=Math.min(i.timeout,300*1e3));let u=await ir(c);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(u));return}if(b==="/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(b.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(!uo(a)){l.writeHead(400),l.end("Invalid proxy target");return}let i=b.slice(10)||"/",c=`${a}${i}`,u=h.method??"GET",f=[];for await(let _e of h)f.push(_e);let{host:j,"x-proxy-target":E,...D}=h.headers;if(u==="GET"){let _e=`GET::${c}`,{response:ee,fromCache:nt}=await y.get(_e,()=>fetch(c,{method:"GET",headers:D}));o({kind:"request",method:"GET",status:ee.status,upstreamStatus:pr(i,ee.headers,ee.body),fromCache:nt,url:i}),l.writeHead(ee.status,ee.headers),l.end(ee.body);return}let A=f.length>0?Buffer.concat(f):void 0,H=A&&A.length>0?A:void 0,W=await fetch(c,{method:u,headers:D,...H!==void 0&&{body:H}}),Q=ht(Object.fromEntries(W.headers)),ae=await xt(W,yt);o({kind:"request",method:u,status:W.status,upstreamStatus:pr(i,Q,ae),fromCache:!1,url:i}),l.writeHead(W.status,Q),l.end(ae);return}if(b.startsWith("/api/source/tree")&&h.method==="GET"){let i=new URL(b,"http://localhost").searchParams.get("path")??"",c=await dr(v,i);if(c===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(ur(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 eo(c,{withFileTypes:!0}),f=await Promise.all(u.filter(E=>E.isDirectory()?!ze.has(E.name):E.isFile()?!ao.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 lr(De(c,E.name));A.size=H.size}catch{}return A}));f.sort((E,D)=>E.kind!==D.kind?E.kind==="dir"?-1:1:E.name.localeCompare(D.name));let j=c===v?"":c.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:j,entries:f}))}catch(u){let f=u instanceof Error?u.message:String(u);t(`source/tree failed (${i}): ${f}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(b.startsWith("/api/source/file")&&h.method==="GET"){let i=new URL(b,"http://localhost").searchParams.get("path")??"";if(i===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let c=await dr(v,i);if(c===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(ur(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 lr(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>so){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:u.size}));return}let f=cr(c).toLowerCase(),j=bt[f],E=sr.has(f),D=j??(E?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":D,"Content-Length":String(u.size)}),ar(c).pipe(l)}catch(u){let f=u instanceof Error?u.message:String(u);t(`source/file failed (${i}): ${f}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let S=De(e,b==="/"?"/index.html":b),m=await _t(S)?S:De(e,"index.html"),p=cr(m),_=bt[p]??"application/octet-stream";l.writeHead(200,{"Content-Type":_}),ar(m).pipe(l)}catch(P){if(b.startsWith("/api/proxy")){let R=b.slice(10)||"/",S=h.method??"GET";P instanceof Be?o({kind:"info",message:`${S} ${R} \u2192 502 (response exceeded ${String(P.limit)} bytes)`}):o({kind:"request",method:S,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${b}: ${P instanceof Error?P.message:String(P)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as fo}from"chrome-launcher";import{createRequire as mo}from"module";import{mkdirSync as go}from"fs";import{readFile as ho}from"fs/promises";import{dirname as yo,join as xo}from"path";import{fileURLToPath as bo}from"url";var gr=mo(import.meta.url)("chrome-remote-interface"),vo=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),yr=["kizen.dev","kizen.com"];function hr(e){try{let{hostname:t}=new URL(e);return yr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}async function wo(e){try{let t=xo(yo(bo(import.meta.url)),"viewer","icon.png"),o=await ho(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function xr(e){go(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await fo({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,s=null,g=null,d=null,C=0,x=!1,y=p=>{e.debugLog?.(p)},v=p=>{e.verbose&&e.debugLog?.(p)},h=()=>{s!==null&&(clearInterval(s),s=null)},l=p=>p==="chrome://new-tab-page/"||p==="chrome://newtab/",b=async p=>{h(),g=null,await wo(p),await p.Fetch.enable({patterns:yr.flatMap(a=>[{urlPattern:`*://${a}/*`,requestStage:"Response"},{urlPattern:`*://*.${a}/*`,requestStage:"Response"}])}),p.on("Fetch.requestPaused",a=>{(async()=>{let i=a,{requestId:c,request:u,responseHeaders:f,responseStatusCode:j}=i,E=u.url;v(`Fetch ${String(j??"?")} ${E}`);let D=[],A=!1;for(let H of f??[])if(!vo.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&hr(E)){let W=H.value.split(`
185
+ `.trim(),Yn=3e4,Ye=De(process.cwd(),".kizenapp","venv"),ir=["python-3-12","python-3-13"];function Zn(e){return ir.includes(e)}function Qn(e){return e.split(`
186
+ `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}var sr=Qn(rr);if(sr.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var Re=null,Le=[3,10];function ar([e,t]){return e>Le[0]||e===Le[0]&&t>=Le[1]}function wt(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 lr(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 to(e){let t=eo(e),o=t==="python3"?["python3"]:[t,"python3"],n=[];for(let r of o){let i=await lr(r);if(!i){n.push(`${r}: not found`);continue}if(ar(i))return r;n.push(`${r}: ${wt(i)} (too old)`)}throw new Error(`No Python >= ${wt(Le)} found for runtime "${e}". The local runner needs Python ${wt(Le)}+ 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 or(e,t,o){return new Promise((n,r)=>{let i=_t(e,t,{stdio:["ignore","pipe","pipe"]}),p=(C,b)=>{let y=[],v="";return C.on("data",h=>{v+=h.toString("utf-8");let l=v.indexOf(`
187
+ `);for(;l>=0;){let x=v.slice(0,l).replace(/\r$/,"");v=v.slice(l+1),y.push(x),o?.(x,b),l=v.indexOf(`
188
+ `)}}),C.on("end",()=>{if(v.length>0){let h=v.replace(/\r$/,"");y.push(h),o?.(h,b)}}),y},d=p(i.stderr,"stderr");p(i.stdout,"stdout"),i.on("error",r),i.on("close",C=>{if(C===0)n();else{let b=d.slice(-10).join(`
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
190
  `).map(Q=>/SameSite=/i.test(Q)?Q.replace(/SameSite=\w+/i,"SameSite=None"):Q+"; SameSite=None; Secure").join(`
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 p.Fetch.getResponseBody({requestId:c});await p.Fetch.fulfillRequest({requestId:c,responseCode:j??200,responseHeaders:D,body:H,...W&&{base64Encoded:!0}})}catch(H){v(` fulfillRequest failed (${H.message}), falling through`);try{await p.Fetch.continueRequest({requestId:c})}catch(W){v(` continueRequest also failed (${W.message})`)}}})()}),s=setInterval(()=>{(async()=>{try{let{cookies:a}=await p.Network.getAllCookies(),i=0;for(let c of a){if(!hr(`https://${c.domain??""}`)||c.sameSite==="None")continue;let u=c.domain??"",f=u.startsWith(".")?u.slice(1):u;await p.Network.setCookie({url:`https://${f}`,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"}),i++}i>0&&v(`cookie-patch cycle: updated ${String(i)} cookie(s) to SameSite=None`)}catch(a){v(`cookie-patch cycle failed: ${a.message}`)}})()},2e3),await p.Target.setDiscoverTargets({discover:!0});let _=a=>{if(a.type==="page"){if(l(a.url)){y(`closed stray new-tab-page target ${a.targetId}`),g!==null&&p.Target.activateTarget({targetId:g}).catch(()=>{}),p.Target.closeTarget({targetId:a.targetId}).catch(()=>{});return}g===null&&(g=a.targetId,y(`captured main target ${a.targetId} (${a.url})`))}};p.on("Target.targetCreated",a=>{let{targetInfo:i}=a;v(`target +${i.type} ${i.targetId} ${i.url}`),_(i)}),p.on("Target.targetInfoChanged",a=>{let{targetInfo:i}=a;v(`target ~${i.type} ${i.targetId} ${i.url}`),_(i)}),p.on("disconnect",()=>{x||r!==p||(y("CDP disconnected"),r=null,h(),P())})},P=()=>{if(x||d!==null)return;let p=Math.min(1e3*2**C,1e4),_=C+1;C++,y(`CDP reconnect scheduled in ${String(p)}ms (attempt #${String(_)})`),d=setTimeout(()=>{d=null,(async()=>{let a;try{a=await gr({port:n})}catch{y(`CDP reconnect attempt #${String(_)} failed`),P();return}if(x){try{await a.close()}catch{}return}r=a;try{await b(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`),P()}})()},p)},R=30,S=300;for(let p=0;p<R;p++){await new Promise(_=>setTimeout(_,S)),y(`CDP connect attempt ${String(p+1)}/${String(R)}`);try{let _=await gr({port:n});r=_,e.path&&_.send("Page.navigate",{url:`${t}${e.path}`});try{await b(_),y("CDP connected")}catch{r===_&&(r=null);try{await _.close()}catch{}y("CDP setup failed after connect")}break}catch{if(p===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"),x=!0,d!==null&&(clearTimeout(d),d=null),h(),r!==null){try{r.close()}catch{}r=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as Co,useState as So}from"react";function Ye(e){let[t,o]=So([]),n=Co(r=>{o(s=>[...s,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as Ze,useEffect as kt,useState as Qe}from"react";import{Box as z,Text as B,useInput as _o}from"ink";import{jsx as k,jsxs as q}from"react/jsx-runtime";var ie=["apiKey","userId","businessId"],ko={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Le=({text:e})=>k(B,{dimColor:!0,children:e}),et=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:n})=>{let[r,s]=Qe(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[g,d]=Qe(""),[C,x]=Qe(null),[y,v]=Qe(void 0),h=Ze(a=>{if(a==="local"){o({mode:"local",credentials:null});return}s({type:"profile-loading"})},[o]),l=Ze(async a=>{if(a===null){s({type:"profile-loading"});let u=await Ie();s({type:"name-entry",nameBuffer:"",existingProfiles:u});return}v(a.isDefault?void 0:a.name),s({type:"loading"});let i=a.isDefault?await Y():await Ce(a.name),c=i?Math.max(0,K.indexOf(i.environment)):0;s({type:"creds-entry",field:0,values:i??{},envCursor:c})},[]),b=Ze(async(a,i)=>{let c=K[i]??"go",u={apiKey:a.apiKey??"",userId:a.userId??"",businessId:a.businessId??"",environment:c};s({type:"saving"});try{await Kt(y??oe,u),o({mode:"global",credentials:u,...y!==void 0&&{profileName:y}})}catch(f){x(f instanceof Error?f.message:String(f)),s({type:"creds-entry",field:0,values:a,envCursor:i})}},[o,y]);_o((a,i)=>{if(i.ctrl&&a==="c"&&process.exit(0),i.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){s({type:"profile-loading"}),P();return}n?.();return}if(r.type==="mode-select"){if(i.upArrow)s({type:"mode-select",cursor:0});else if(i.downArrow)s({type:"mode-select",cursor:1});else if(i.return){let c=r.cursor===0?"global":"local";h(c)}return}if(r.type==="profile-select"){let{profiles:c,cursor:u}=r,f=c.length,j=c.length+1;if(i.upArrow)s({...r,cursor:(u-1+j)%j});else if(i.downArrow)s({...r,cursor:(u+1)%j});else if(i.return)if(u===f)s({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(i.backspace||i.delete)s({type:"name-entry",nameBuffer:c.slice(0,-1),existingProfiles:u});else if(i.return){let f=c.trim();if(!f){s({...r,nameError:"Name cannot be empty"});return}if(f===oe){s({...r,nameError:`"${oe}" is reserved`});return}if(u.some(j=>j.name===f)){s({...r,nameError:`Profile "${f}" already exists`});return}v(f),s({type:"creds-entry",field:0,values:{},envCursor:0}),d("")}else a&&!i.ctrl&&!i.meta&&s({type:"name-entry",nameBuffer:c+a,existingProfiles:u});return}if(r.type==="creds-entry"){let{field:c,values:u,envCursor:f}=r;if(c===ie.length){i.leftArrow?s({...r,envCursor:(f-1+K.length)%K.length}):i.rightArrow?s({...r,envCursor:(f+1)%K.length}):i.upArrow?(s({...r,field:c-1}),d(u[ie[c-1]]??"")):i.return&&b(u,f);return}let E=ie[c];if(!E)return;if(i.backspace||i.delete)d(D=>D.slice(0,-1));else if(i.upArrow&&c>0){let D={...u,[E]:g},A=c-1;s({...r,field:A,values:D}),d(D[ie[A]]??"")}else if(i.return||i.tab||i.downArrow){let D={...u,[E]:g},A=c+1;s({...r,field:A,values:D}),A<ie.length?d(D[ie[A]]??""):d("")}else a&&!i.ctrl&&!i.meta&&d(D=>D+a)}});let P=Ze(async()=>{let a=await Ie();s({type:"profile-select",profiles:a,cursor:0})},[]);if(kt(()=>{r.type==="profile-loading"&&P()},[r.type,P]),kt(()=>{e==="global"&&!t&&(async()=>{let a=await Y(),i=a?Math.max(0,K.indexOf(a.environment)):0;s({type:"creds-entry",field:0,values:a??{},envCursor:i})})()},[]),kt(()=>{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((i,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:i.label}),k(B,{dimColor:!0,children:i.desc})]},i.mode)})]}),k(Le,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:a,cursor:i}=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,f)=>{let j=i===f;return q(z,{gap:2,children:[k(B,{...j&&{color:"cyan"},children:j?"\u276F":" "}),k(B,{bold:j,...j&&{color:"cyan"},children:u.isDefault?"Default":u.name}),k(B,{dimColor:!0,children:u.path})]},u.name)}),q(z,{gap:2,children:[k(B,{...i===c&&{color:"cyan"},children:i===c?"\u276F":" "}),k(B,{bold:i===c,...i===c&&{color:"cyan"},children:"+ Add new profile"})]})]}),k(Le,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:a,nameError:i}=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"})}),i&&q(B,{color:"red",children:["Error: ",i]}),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(Le,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:S,envCursor:m}=r,p=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,i)=>{let c=R===i,u=c?g:S[a]??"";return q(z,{gap:2,children:[k(z,{width:12,children:k(B,{bold:c,...c&&{color:"cyan"},children:ko[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:p,...p&&{color:"cyan"},children:"Environment"})}),k(B,{...p&&{color:"cyan"},children:">"}),k(z,{gap:1,children:K.map((a,i)=>{let c=i===m;return p?k(B,{bold:c,...c&&{color:"cyan"},children:c?`[${a}]`:a},a):k(B,{dimColor:!c,bold:c,children:a},a)})})]})]}),p?k(Le,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):k(Le,{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 No=[".kizenapp",".git"],vr=({port:e,pluginDir:t,outputDir:o,credentials:n,credentialMode:r,activeCredentialProfile:s,lastPath:g,debug:d=!1,verbose:C=!1,autoViewer:x=!0})=>{let y=te(n),v=te(s),h=te(g),[l,b]=J("main"),[P,R]=J(r),[S,m]=J("starting"),[p,_]=J(null),[a,i]=Ye(50),[c,u]=Ye(50),[f,j]=Ye(50),[E,D]=J([]),[A,H]=J("pending"),[W,Q]=J(null),[ae,_e]=J(null),[ee,nt]=J(null),[ot,it]=J(0),[Pt,jr]=J(0),[$r,Ar]=J(0),[Or,zr]=J(0),st=te(!1),Et=te(!1),je=te(null),ke=te(null),re=te(new Set),$e=te([]),G=Se(w=>{let F=JSON.stringify(w);if(re.current.size===0){$e.current=[...$e.current,F].slice(-50);return}let ne=!1;for(let X of re.current)if(X.readyState===1)try{X.send(F)}catch{re.current.delete(X),ne=!0}ne&&it(re.current.size)},[]),Ae=i,at=Se(()=>{je.current?.kill(),je.current=null,xr({port:e,userDataDir:br(o,".chrome"),broadcast:G,onWarn:w=>{i(`\u26A0 ${w}`)},...h.current!==void 0&&{path:h.current},...d&&{debugLog:j},...C&&{verbose:!0}}).then(w=>{je.current=w})},[e,o,G,d,C,j,i]);tt(()=>{let w=()=>{je.current?.kill()};return process.on("exit",w),()=>{process.off("exit",w)}},[]),Po((w,F)=>{(w==="q"||F.ctrl&&w==="c")&&process.exit(0),w==="c"&&b("editing"),w==="v"&&at()},{isActive:l==="main"}),tt(()=>{S!=="running"||Et.current||!x||(Et.current=!0,at())},[S,x,at]);let Mr=Se(w=>{y.current=w.credentials,v.current=w.profileName,b("main"),R(w.mode);let F=w.profileName;ge(o,{credentialMode:w.mode,...F!==void 0&&{activeCredentialProfile:F}}),G({type:"credentials-updated",credentials:w.credentials})},[o,G]),It=Se(w=>{D(F=>[...F,`${new Date().toLocaleTimeString()}: ${Ct(w)}`].slice(-50)),w.kind==="request"&&(w.fromCache?Ar(F=>F+1):zr(F=>F+1)),G({type:"proxy-log",entry:w})},[G]),le=Se(w=>{u(w),G({type:"log",message:w})},[u,G]),lt=Se(()=>{st.current||(st.current=!0,H("building"),Q(null),le("Build started"),He(t,o).then(({bundleSize:w})=>{le(`Build finished \u2014 bundle: ${Te(w)}`),H("done"),_e(new Date),nt(w),le("Notifying viewers to reload"),G({type:"rebuild"})}).catch(w=>{let F=w instanceof Error?w.message:String(w);Q(F),H("error")}).finally(()=>{st.current=!1}))},[t,o,le,G]);if(tt(()=>{lt();let w=Eo(t,{recursive:!0},(F,ne)=>{if(!ne)return;let X=ne.replace(/\\/g,"/");No.some(Oe=>X.startsWith(Oe))||(le(`File change detected: ${ne}`),ke.current!==null&&clearTimeout(ke.current),ke.current=setTimeout(lt,150))});return w.on("error",F=>{le(`File watcher error \u2014 rebuilds have stopped: ${F.message}`)}),()=>{w.close(),ke.current!==null&&clearTimeout(ke.current)}},[t,lt,le]),tt(()=>{let w=fr();_t(br(w,"index.html")).then(F=>{if(!F){_("Viewer not built. Run 'pnpm build:viewer' first."),m("error");return}let ne=mr(w,Ae,It,y,v,o,G,jr,h,t),X=Io(ne),Oe=new Bo({server:X});return Oe.on("connection",ce=>{for(let qr of $e.current)ce.readyState===1&&ce.send(qr);$e.current=[],Ae("Viewer connected for live reload"),re.current.add(ce),it(re.current.size),ce.on("close",()=>{re.current.delete(ce),it(re.current.size)})}),X.listen(e,"127.0.0.1",()=>{m("running"),Ae(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",ce=>{_(ce.message),m("error")}),()=>{Oe.close(),X.close()}})},[e,Ae,It,G,o,t]),l==="editing")return L(et,{...P!==void 0&&{initialMode:P},showProfileManager:P==="global",onComplete:Mr,onCancel:()=>{b("main")}});let ct=ae!==null?Math.round((Date.now()-ae.getTime())/1e3):null,Hr=ct===null?"":ct<5?" (just now)":` (${String(ct)}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(qe,{}),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(),Hr]}),ee!==null&&O(N,{dimColor:!0,children:["\xB7 bundle: ",Te(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,F)=>L(N,{dimColor:!0,wrap:"truncate",children:w},F))})]}),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 ",ot," viewer",ot!==1?"s":""]})]}),S==="error"&&O(N,{color:"red",children:["\u2717 ",p??"Server error"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((w,F)=>L(N,{dimColor:!0,wrap:"truncate",children:w},F))})]}),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 ",Pt," key",Pt!==1?"s":""," in the network cache \xB7"," ",$r," hit \xB7 ",Or," 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,F)=>L(N,{dimColor:!0,wrap:"truncate",children:w},F))})]}),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 ",f.length," event(s)"]})]}),L(U,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.length===0?L(N,{dimColor:!0,children:" No CDP events yet."}):f.slice(-8).map((w,F)=>L(N,{dimColor:!0,wrap:"truncate",children:w},F))})]}),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:["] ",ot===0?"open viewer":"relaunch viewer"]})]})]})};async function wr(e){return new Promise(t=>{let o=null,n=s=>{o?.(),t(s)},{unmount:r}=Sr(Cr(et,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});o=r})}function _r(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`;be(n);let s=null,g,d,{lastPath:C}=await Ne(r);if(t.credentials)s=await Ge(t.credentials);else{let l=await Ne(r);if(l.credentialMode==="local")g="local";else if(l.credentialMode==="global"){if(g="global",d=l.activeCredentialProfile,d?(s=await Ce(d),s||(s=await Y(),d=void 0)):s=await Y(),!s){let b=await wr("global");s=b.credentials,d=b.profileName}}else{let b=await wr();s=b.credentials,g=b.mode,d=b.profileName;let P=b.profileName;await ge(r,{credentialMode:b.mode,...P!==void 0&&{activeCredentialProfile:P}})}}let x=t.verbose===!0,y=x||t.debug===!0,v=t.viewer!==!1,{waitUntilExit:h}=Sr(Cr(vr,{port:o,pluginDir:n,outputDir:r,credentials:s,...g!==void 0&&{credentialMode:g},...d!==void 0&&{activeCredentialProfile:d},...C!==void 0&&{lastPath:C},debug:y,verbose:x,autoViewer:v}),{exitOnCtrlC:!1});await h()})}var Ro=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"]),Do=[...Ro].sort(),Lo=new Set(["kizen-k","form-entity"]),kr=[...Do,...[...Lo].sort()];function Tr(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of kr)console.log(t)})}import{mkdir as Fo,writeFile as Pr,readFile as jo}from"fs/promises";import{join as rt}from"path";var $o=new Set(["developer_business_id"]);function Ao(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 Oo={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Ir(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let n=o.path.split("/"),r=t;n.forEach((s,g)=>{r.children.has(s)||r.children.set(s,{name:s,children:new Map,isFile:g===n.length-1,filePath:n.slice(0,g+1).join("/")});let d=r.children.get(s);d&&(r=d)})}return t}function Tt(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Br(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="#${Tt(n.filePath)}" data-id="${Tt(n.filePath)}">${Z(n.name)}</a></li>`:`<li class="td"><span class="dn">${Z(n.name)}/</span>${Br(n)}</li>`).join("")}</ul>`}function Nr(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function zo(e){let t;return e.base64Image!==void 0?t=`<img src="data:${Oo[Nr(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="${Tt(e.path)}"><h2 class="fp">${Z(e.path)}</h2><div class="fb">${t}</div></section>`}var Mo={".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 Ho(e){return Mo[Nr(e)]??""}function Rr(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 s=r===o.length-1,g=s?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=s?" ":"\u2502 ";return n.isFile?`${t}${g}${n.name}`:`${t}${g}${n.name}/
192
- ${Rr(n,t+d)}`}).join(`
193
- `)}function Dr(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html")}function Lr(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!$o.has(t)).map(([t,o])=>[t,t==="services"?Ao(o):o]))}function qo(e,t){let o=Lr(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",s=typeof e.description=="string"?e.description:"",g=Dr(t),d=[];d.push(`# ${n}${r?` v${r}`:""}`),s&&d.push("",s),d.push("","## Configuration (`kizen.json`)","","```json",JSON.stringify(o,null,2),"```"),d.push("","## File Tree","","```",Rr(Ir(g)),"```"),d.push("","## Files");for(let C of g)d.push("",`### \`${C.path}\``,""),C.base64Image!==void 0?d.push(`[Image file: ${C.path}]`):C.binaryData!==void 0?d.push(`[Binary file: ${String(C.binaryData.length)} bytes]`):d.push(`\`\`\`${Ho(C.path)}`,C.content,"```");return d.join(`
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"&&lt()},{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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}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
+ ${Fr(n,t+d)}`}).join(`
193
+ `)}function jr(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html")}function Ar(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Uo.has(t)).map(([t,o])=>[t,t==="services"?Vo(o):o]))}function Xo(e,t){let o=Ar(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",p=jr(t),d=[];d.push(`# ${n}${r?` v${r}`:""}`),i&&d.push("",i),d.push("","## Configuration (`kizen.json`)","","```json",JSON.stringify(o,null,2),"```"),d.push("","## File Tree","","```",Fr(Dr(p)),"```"),d.push("","## Files");for(let C of p)d.push("",`### \`${C.path}\``,""),C.base64Image!==void 0?d.push(`[Image file: ${C.path}]`):C.binaryData!==void 0?d.push(`[Binary file: ${String(C.binaryData.length)} bytes]`):d.push(`\`\`\`${Ko(C.path)}`,C.content,"```");return d.join(`
194
194
  `)+`
195
- `}function Uo(e,t){let o=Lr(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",s=typeof e.description=="string"?e.description:"",g=Dr(t),d=Br(Ir(g)),C=g.map(zo).join(`
195
+ `}function Yo(e,t){let o=Ar(e),n=typeof e.name=="string"?e.name:"Plugin",r=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",p=jr(t),d=Lr(Dr(p)),C=p.map(Wo).join(`
196
196
  `);return`<!DOCTYPE html>
197
197
  <html lang="en">
198
198
  <head>
@@ -236,7 +236,7 @@ img{border:1px solid var(--bd);border-radius:4px}
236
236
  <body>
237
237
  <header>
238
238
  <h1>${Z(n)}${r?` <span style="color:var(--mu);font-size:.8em">v${Z(r)}</span>`:""}</h1>
239
- ${s?`<p>${Z(s)}</p>`:""}
239
+ ${i?`<p>${Z(i)}</p>`:""}
240
240
  </header>
241
241
  <div class="layout">
242
242
  <nav>
@@ -258,7 +258,7 @@ ${C}
258
258
  })();
259
259
  </script>
260
260
  </body>
261
- </html>`}var Er=rt(me,"examples");function Fr(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Er}/<api_name>.html)`).action(async t=>{let o=process.cwd(),n;try{let C=await jo(rt(o,"kizen.json"),"utf-8"),x=JSON.parse(C);n=Array.isArray(x)?x[0]:x}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",s=t.output??rt(Er,`${r}.html`),g=s.replace(/\.html$/,".md"),d=await Me(o);await Fo(rt(s,".."),{recursive:!0}),await Promise.all([Pr(s,Uo(n,d),"utf-8"),Pr(g,qo(n,d),"utf-8")]),console.log(`Plugin report written to:
262
- ${s}
263
- ${g}`)})}var Ko=Wo(Jo(Go(import.meta.url)),"..","package.json"),Xo=JSON.parse(Vo(Ko,"utf-8"));he.name("appbuilder").description("Kizen plugin app builder").version(Xo.version);Xt(he);Ot(he);_r(he);Fr(he);Tr(he);he.parse();
261
+ </html>`}var Rr=nt(me,"examples");function Or(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Rr}/<api_name>.html)`).action(async t=>{let o=process.cwd(),n;try{let C=await qo(nt(o,"kizen.json"),"utf-8"),b=JSON.parse(C);n=Array.isArray(b)?b[0]:b}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??nt(Rr,`${r}.html`),p=i.replace(/\.html$/,".md"),d=await qe(o);await Ho(nt(i,".."),{recursive:!0}),await Promise.all([Nr(i,Yo(n,d),"utf-8"),Nr(p,Xo(n,d),"utf-8")]),console.log(`Plugin report written to:
262
+ ${i}
263
+ ${p}`)})}var ri=ei(Qo(ti(import.meta.url)),"..","package.json"),ni=JSON.parse(Zo(ri,"utf-8"));he.name("appbuilder").description("Kizen plugin app builder").version(ni.version);Qt(he);Ht(he);Er(he);Or(he);Br(he);he.parse();
264
264
  //# sourceMappingURL=index.js.map