@kizenapps/cli 0.16.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +78 -12
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/{CodeStepsPage-DoQTFAvB.js → CodeStepsPage-bUqixBkt.js} +1 -1
- package/dist/viewer/assets/{ConfigurationPage-WvAn-eE3.js → ConfigurationPage-egBHLNoe.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-DiL1N1bn.js → SandboxPage-CWOkZs5g.js} +1 -1
- package/dist/viewer/assets/{WhenBadge-DiiQ6XoK.js → WhenBadge-P9aN2Qd7.js} +1 -1
- package/dist/viewer/assets/{configStorage-Bnv2jFLx.js → configStorage-DcQWEL9-.js} +1 -1
- package/dist/viewer/assets/{index-DqBLj4Is.js → index-BXPMaCXm.js} +2 -2
- package/dist/viewer/assets/{useCriticalExceptionDialog-ruFjUSi0.js → useCriticalExceptionDialog-BI_gNDBK.js} +2 -2
- package/dist/viewer/index.html +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as
|
|
3
|
-
`).map(
|
|
4
|
-
`)?
|
|
2
|
+
import{readFileSync as No}from"fs";import{dirname as jo,join as Fo}from"path";import{fileURLToPath as Lo}from"url";import{program as Se}from"commander";import{createElement as cn}from"react";import{render as dn}from"ink";import{useEffect as sn,useState as ft}from"react";import{Box as Ee,Text as ye,useApp as an}from"ink";import{mkdir as Or,writeFile as zr}from"fs/promises";import{join as Mr}from"path";import{minifyFiles as Hr,packagePlugin as Ur,transformDeployablePlugin as qr}from"@kizenapps/packager";import{readdir as jr,readFile as ut}from"fs/promises";import{join as Dt,relative as Fr}from"path";var Lr=new Set([".png",".svg"]),Ar=new Set([".kzn"]),$r=new Set([".DS_Store"]),ze=new Set(["node_modules",".git",".kizenapp",".github"]);async function Rt(e,t){let o=await jr(e,{withFileTypes:!0}),r=[];for(let n of o)if(n.isDirectory()){if(ze.has(n.name))continue;r.push(...await Rt(Dt(e,n.name),t))}else n.isFile()&&($r.has(n.name)||r.push(Dt(e,n.name)));return r}async function Me(e){let t=await Rt(e,e);return Promise.all(t.map(async o=>{let r=Fr(e,o).split("\\").join("/"),n=r.lastIndexOf("."),l=n>=0?r.slice(n).toLowerCase():"";if(Lr.has(l)){let f=await ut(o);return{path:r,content:"",base64Image:f.toString("base64")}}if(Ar.has(l)){let f=await ut(o);return{path:r,content:"",binaryData:f}}let v=await ut(o,"utf-8");return{path:r,content:v}}))}var Vr=["name","api_name","version","entry"];function Nt(e,t){let o=t===void 0?"kizen.json":`kizen.json entry #${String(t+1)}`;for(let r of Vr){let n=e[r];if(typeof n!="string"||n==="")throw new Error(`${o} is missing required field "${r}" (expected a non-empty string).`)}}function Jr(e){let t;try{t=JSON.parse(e)}catch(o){let r=o instanceof Error?o.message:String(o);throw new Error(`kizen.json is not valid JSON: ${r}`)}if(Array.isArray(t))return t.forEach((o,r)=>{if(typeof o!="object"||o===null)throw new Error(`kizen.json entry #${String(r+1)} is not a JSON object.`);Nt(o,r)}),t;if(typeof t!="object"||t===null)throw new Error("kizen.json must be a JSON object (or array of objects).");return Nt(t),t}var Wr=(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 Or(t,{recursive:!0}),o?.("reading-files");let r=await Me(e);o?.("minifying");let n=await Hr(r);o?.("packaging");let l=n.find(c=>c.path==="kizen.json");if(!l)throw new Error("kizen.json not found in plugin directory.");let v=Jr(l.content),f=Ur(n,v),T=Object.values(f).map(qr);o?.("writing-bundle");let m=T.map(c=>{let b=c.release_notes_directory?.replace(/\/$/,""),E=b?r.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,C)=>C.version.localeCompare(R.version,void 0,{numeric:!0})):[];return Wr(c,E)}),h=JSON.stringify(m,null,2),x=(c,b)=>c==="allReleaseNotes"?void 0:b,y=Buffer.byteLength(JSON.stringify(m,x,2),"utf-8");return await zr(Mr(t,"bundle.json"),h,"utf-8"),{bundleSize:y}}function _e(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as Yr,Text as Zr}from"ink";import{Box as Gr,Text as Kr}from"ink";import{jsx as jt}from"react/jsx-runtime";var Xr=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ft=()=>jt(Gr,{flexDirection:"column",children:Xr.map((e,t)=>jt(Kr,{color:"cyan",children:e},t))});import{Fragment as Qr,jsx as pt,jsxs as en}from"react/jsx-runtime";var V=({marginBottom:e=0})=>en(Qr,{children:[pt(Ft,{}),pt(Yr,{flexDirection:"column",marginTop:1,marginBottom:e,children:pt(Zr,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as tn,useState as rn}from"react";import{Text as nn}from"ink";import{jsx as on}from"react/jsx-runtime";var Lt=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ue=()=>{let[e,t]=rn(0);return tn(()=>{let o=setInterval(()=>{t(r=>(r+1)%Lt.length)},80);return()=>{clearInterval(o)}},[]),on(nn,{color:"cyan",children:Lt[e]??"\u280B"})};import{Fragment as ln,jsx as ce,jsxs as de}from"react/jsx-runtime";var At=["creating-dir","reading-files","minifying","packaging","writing-bundle"],qe={"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=an(),[r,n]=ft("creating-dir"),[l,v]=ft(null),[f,T]=ft(null);sn(()=>{He(t,e,n).then(({bundleSize:y})=>{T(y),n("done"),o.exit()}).catch(y=>{let c=y instanceof Error?y.message:String(y);v(c),n("error"),o.exit()})},[e,t,o]);let m=At.indexOf(r),h=r==="error",x=r==="done";return de(Ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[ce(V,{marginBottom:1}),de(Ee,{flexDirection:"column",gap:0,children:[At.map((y,c)=>{let b=r===y,E=x||m>c;return ce(Ee,{gap:1,children:h&&c===m?de(ye,{color:"red",children:["\u2717 ",qe[y]]}):E?de(ye,{color:"green",children:["\u2713 ",qe[y]]}):b?de(ln,{children:[ce(Ue,{}),ce(ye,{children:qe[y]})]}):de(ye,{dimColor:!0,children:[" ",qe[y]]})},y)}),x&&f!==null&&ce(Ee,{marginTop:1,gap:1,children:de(ye,{color:"green",children:["\u2713 bundle \u2014 ",_e(f)]})}),l!==null&&ce(Ee,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:ce(ye,{color:"red",children:l})})]})]})};import*as he from"fs";import*as Ot from"path";function xe(e){let t=Ot.join(e,".gitignore"),o=".kizenapp/",r="";if(he.existsSync(t)){r=he.readFileSync(t,"utf8");let l=r.split(`
|
|
3
|
+
`).map(v=>v.trim());if(l.includes(o)||l.includes(".kizenapp"))return}let n=r.endsWith(`
|
|
4
|
+
`)?o+`
|
|
5
5
|
`:`
|
|
6
|
-
`+
|
|
7
|
-
`;
|
|
8
|
-
`,"utf-8"),await ut(de(e.targetDir,"src"),{recursive:!0}),await ut(de(e.targetDir,"releaseNotes"),{recursive:!0}),ye(e.targetDir)}import{jsx as T,jsxs as A}from"react/jsx-runtime";var ue=["name","apiName","externalLink","description","developerBusinessId"],Mt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Ht=["name","apiName"];function ln(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var he=({text:e})=>T(I,{dimColor:!0,children:e});function cn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Ut=({parentDir:e,defaultBusinessId:t})=>{let i=sn(),[n,r]=Te({type:"target-select",cursor:0}),[c,S]=Te("in-place"),[g,_]=Te(()=>cn(t)),[v,h]=Te(""),[y,m]=Te(e),l=qe((C,f)=>{S(C),h(f.name),r({type:"field-entry",field:0,values:f})},[]),x=qe(async C=>{let f=await Ot(C);if(f!=="ok"){r({type:"precheck-error",targetDir:C,reason:f});return}m(C),l("in-place",g)},[g,l]),E=qe(async C=>{try{let f=await $t(e,C.apiName);m(f),r({type:"confirm",values:C})}catch(f){r({type:"error",message:f instanceof Error?f.message:String(f)})}},[e]),R=qe(async(C,f)=>{try{await zt({targetDir:f,name:C.name,apiName:C.apiName,externalLink:C.externalLink,description:C.description,developerBusinessId:C.developerBusinessId}),r({type:"done",targetDir:f})}catch(u){r({type:"error",message:u instanceof Error?u.message:String(u)})}},[]);if(an((C,f)=>{if(f.ctrl&&C==="c"){i.exit();return}if(n.type==="target-select"){f.upArrow?r({type:"target-select",cursor:0}):f.downArrow?r({type:"target-select",cursor:1}):f.return?n.cursor===0?x(e):l("sub-dir",g):f.escape&&i.exit();return}if(n.type==="precheck-error"){(f.return||f.escape)&&i.exit();return}if(n.type==="field-entry"){let{field:u,values:w}=n,s=ue[u];if(!s)return;if(f.escape){i.exit();return}if(f.backspace||f.delete){h(o=>o.slice(0,-1));return}if(f.upArrow&&u>0){let o={...w,[s]:v},a=u-1,d=ue[a];r({type:"field-entry",field:a,values:o}),_(o),h(d?o[d]:"");return}if(f.return||f.tab||f.downArrow){let o=v.trim();if(Ht.includes(s)&&!o){r({type:"field-entry",field:u,values:w,fieldError:`${Mt[s]} is required`});return}let d=s==="description"?v:o,p={...w,[s]:d};_(p);let j=u+1;if(j>=ue.length)h(""),c==="sub-dir"?(r({type:"resolving-target"}),E(p)):r({type:"confirm",values:p});else{let k=ue[j],N=k?p[k]:"",O=k==="apiName"&&!N?ln(p.name):N;r({type:"field-entry",field:j,values:p}),h(O)}return}C&&!f.ctrl&&!f.meta&&h(o=>o+C);return}if(n.type==="confirm"){if(f.escape){let u=ue.length-1,w=ue[u];r({type:"field-entry",field:u,values:n.values}),h(w?n.values[w]:"");return}f.return&&(r({type:"writing"}),R(n.values,y));return}(n.type==="done"||n.type==="error")&&(f.return||f.escape)&&i.exit()}),n.type==="target-select"){let C=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Where should the new plugin live?"}),C.map((f,u)=>{let w=n.cursor===u;return A(M,{gap:2,children:[T(I,{...w&&{color:"cyan"},children:w?"\u276F":" "}),T(I,{bold:w,...w&&{color:"cyan"},children:f.label}),T(I,{dimColor:!0,children:f.desc})]},f.label)})]}),T(he,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:C,reason:f}=n;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),T(I,{color:"red",bold:!0,children:"Cannot create plugin"}),A(M,{flexDirection:"column",gap:0,children:[A(I,{children:[C," already contains ",T(I,{bold:!0,children:f==="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(he,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:C,fieldError:f}=n,u=c==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${y}`;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Plugin details"}),T(I,{dimColor:!0,children:u})]}),f!==void 0&&A(I,{color:"red",children:["Error: ",f]}),T(M,{flexDirection:"column",gap:0,children:ue.map((w,s)=>{let o=C===s,a=o?v:g[w],d=Ht.includes(w),p=`${Mt[w]}${d?"":" (optional)"}`;return A(M,{gap:2,children:[T(M,{width:24,children:T(I,{bold:o,...o&&{color:"cyan"},children:p})}),T(I,{...o&&{color:"cyan"},children:">"}),T(I,{children:a}),o&&T(I,{color:"cyan",children:"\u2588"})]},w)})}),T(he,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="confirm"){let C=pt({targetDir:y,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId});return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"Ready to create"}),A(I,{dimColor:!0,children:["Target: ",y]})]}),A(M,{flexDirection:"column",gap:0,children:[T(I,{bold:!0,children:"kizen.json preview"}),T(I,{children:JSON.stringify(C,null,2)})]}),A(M,{flexDirection:"column",gap:0,children:[T(I,{dimColor:!0,children:"Also creates:"}),A(I,{dimColor:!0,children:[" ",ft(y,"src/")]}),A(I,{dimColor:!0,children:[" ",ft(y,"releaseNotes/")]}),A(I,{dimColor:!0,children:[" ",ft(y,".gitignore")," (adds .kizenapp/)"]})]}),T(he,{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"?A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(V,{}),A(I,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),A(M,{flexDirection:"column",gap:0,children:[T(I,{dimColor:!0,children:"Next steps:"}),A(I,{children:[" ","cd ",n.targetDir]}),A(I,{children:[" ","appbuilder dev"]})]}),T(he,{text:"Enter or Esc to exit"})]}):A(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(he,{text:"Enter or Esc to exit"})]})};import{mkdir as qt,readFile as dn,readdir as un,writeFile as Vt}from"fs/promises";import{homedir as pn}from"os";import{dirname as fn,join as Ve}from"path";var G=["go","fmo","staging","integration","test1"];var _e=Ve(pn(),".kizenappbuilder"),xe=Ve(_e,"credentials.json"),re="credentials";function mn(e){return G.includes(e)}function gn(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,i=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:mn(i)?i:"go"}}async function Je(e){let t=await dn(e,"utf-8");return gn(JSON.parse(t))}async function Y(){try{return await Je(xe)}catch{return null}}async function yn(e){await qt(fn(xe),{recursive:!0,mode:448}),await Vt(xe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Jt(e){return Ve(_e,`${e}.json`)}async function Ee(){let e=[{name:re,path:xe,isDefault:!0}];try{let t=await un(_e);for(let i of t){if(!i.endsWith(".json"))continue;let n=i.slice(0,-5);n!==re&&e.push({name:n,path:Ve(_e,i),isDefault:!1})}}catch{}return e}async function Wt(e,t){if(e===re){await yn(t);return}await qt(_e,{recursive:!0,mode:448}),await Vt(Jt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function be(e){try{return await Je(Jt(e))}catch{return null}}function Kt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),n=(await Y())?.businessId??"",{waitUntilExit:r}=xn(hn(Ut,{parentDir:t,defaultBusinessId:n}),{exitOnCtrlC:!1});await r()})}import{createElement as hr}from"react";import{render as xr}from"ink";import{useCallback as ve,useEffect as et,useRef as Z,useState as J}from"react";import{Box as q,Text as D,useInput as uo}from"ink";import{watch as po}from"fs";import{createServer as fo}from"http";import{join as mr}from"path";import{WebSocketServer as mo}from"ws";import{createReadStream as nr,realpathSync as Ln}from"fs";import{access as jn,readdir as Fn,readFile as An,realpath as On,stat as or}from"fs/promises";import{dirname as $n,extname as ir,join as De,resolve as zn,sep as Ct}from"path";import{fileURLToPath as Mn}from"url";var bn=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function mt(e){let t={};for(let[i,n]of Object.entries(e)){let r=i.toLowerCase();bn.has(r)||r.startsWith("access-control-")||(t[i]=n)}return t}var gt=10*1024*1024,vn=6e4,Cn=200,ke=class extends Error{bytesRead;limit;constructor(t,i){super(`Upstream response exceeded ${String(i)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=i}};async function yt(e,t){let i=e.body;if(i===null)return Buffer.alloc(0);let n=[],r=0;for await(let c of i){if(r+=c.length,r>t)throw new ke(r,t);n.push(c)}return Buffer.concat(n)}function Gt(e={}){let t=new Map,{onChange:i}=e,n=()=>{i?.(t.size)},r=c=>{t.delete(c)&&n()};return{get(c,S){let g=t.get(c);if(g!==void 0){if(Date.now()-g.insertedAt<vn)return g.promise.then(v=>({response:v,fromCache:!0}));r(c)}if(t.size>=Cn){let v=t.keys().next().value;v!==void 0&&r(v)}let _=S().then(async v=>{let h=mt(Object.fromEntries(v.headers)),y=await yt(v,gt);return{status:v.status,headers:h,body:y}}).catch(v=>{throw r(c),v});return t.set(c,{insertedAt:Date.now(),promise:_}),n(),_.then(v=>((v.status<200||v.status>=300)&&r(c),{response:v,fromCache:!1}))},clear(){t.clear(),n()}}}var ht={".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 wn,readFile as Sn,writeFile as Pn}from"fs/promises";import{join as Xt}from"path";async function Ie(e){try{let t=await Sn(Xt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function pe(e,t){await wn(e,{recursive:!0}),await Pn(Xt(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{spawn as Qt}from"child_process";import{writeFile as Yt,rm as er,mkdtemp as Tn,access as _n}from"fs/promises";import{join as Be}from"path";import{tmpdir as En}from"os";var kn=`
|
|
6
|
+
`+o+`
|
|
7
|
+
`;he.writeFileSync(t,r+n)}function zt(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:r}=dn(cn($t,{outputDir:o,pluginDir:t}));await r()})}import{createElement as Pn}from"react";import{render as Tn}from"ink";import{useCallback as Je,useState as ke}from"react";import{Box as M,Text as I,useApp as fn,useInput as mn}from"ink";import{join as yt}from"path";import{access as un,mkdir as mt,writeFile as pn}from"fs/promises";import{join as ue}from"path";async function Ve(e){try{return await un(e),!0}catch{return!1}}async function Mt(e){return await Ve(ue(e,"kizen.json"))?"has-manifest":await Ve(ue(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ht(e,t){let o=ue(e,t);if(!await Ve(o))return o;for(let r=1;r<1e3;r++){let n=ue(e,`${t}-${String(r)}`);if(!await Ve(n))return n}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 Ut(e){await mt(e.targetDir,{recursive:!0});let t=gt(e);await pn(ue(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
8
|
+
`,"utf-8"),await mt(ue(e.targetDir,"src"),{recursive:!0}),await mt(ue(e.targetDir,"releaseNotes"),{recursive:!0}),xe(e.targetDir)}import{jsx as _,jsxs as A}from"react/jsx-runtime";var pe=["name","apiName","externalLink","description","developerBusinessId"],qt={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Vt=["name","apiName"];function gn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}var be=({text:e})=>_(I,{dimColor:!0,children:e});function yn(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}var Jt=({parentDir:e,defaultBusinessId:t})=>{let o=fn(),[r,n]=ke({type:"target-select",cursor:0}),[l,v]=ke("in-place"),[f,T]=ke(()=>yn(t)),[m,h]=ke(""),[x,y]=ke(e),c=Je((C,g)=>{v(C),h(g.name),n({type:"field-entry",field:0,values:g})},[]),b=Je(async C=>{let g=await Mt(C);if(g!=="ok"){n({type:"precheck-error",targetDir:C,reason:g});return}y(C),c("in-place",f)},[f,c]),E=Je(async C=>{try{let g=await Ht(e,C.apiName);y(g),n({type:"confirm",values:C})}catch(g){n({type:"error",message:g instanceof Error?g.message:String(g)})}},[e]),R=Je(async(C,g)=>{try{await Ut({targetDir:g,name:C.name,apiName:C.apiName,externalLink:C.externalLink,description:C.description,developerBusinessId:C.developerBusinessId}),n({type:"done",targetDir:g})}catch(u){n({type:"error",message:u instanceof Error?u.message:String(u)})}},[]);if(mn((C,g)=>{if(g.ctrl&&C==="c"){o.exit();return}if(r.type==="target-select"){g.upArrow?n({type:"target-select",cursor:0}):g.downArrow?n({type:"target-select",cursor:1}):g.return?r.cursor===0?b(e):c("sub-dir",f):g.escape&&o.exit();return}if(r.type==="precheck-error"){(g.return||g.escape)&&o.exit();return}if(r.type==="field-entry"){let{field:u,values:S}=r,s=pe[u];if(!s)return;if(g.escape){o.exit();return}if(g.backspace||g.delete){h(i=>i.slice(0,-1));return}if(g.upArrow&&u>0){let i={...S,[s]:m},a=u-1,d=pe[a];n({type:"field-entry",field:a,values:i}),T(i),h(d?i[d]:"");return}if(g.return||g.tab||g.downArrow){let i=m.trim();if(Vt.includes(s)&&!i){n({type:"field-entry",field:u,values:S,fieldError:`${qt[s]} is required`});return}let d=s==="description"?m:i,p={...S,[s]:d};T(p);let F=u+1;if(F>=pe.length)h(""),l==="sub-dir"?(n({type:"resolving-target"}),E(p)):n({type:"confirm",values:p});else{let k=pe[F],N=k?p[k]:"",$=k==="apiName"&&!N?gn(p.name):N;n({type:"field-entry",field:F,values:p}),h($)}return}C&&!g.ctrl&&!g.meta&&h(i=>i+C);return}if(r.type==="confirm"){if(g.escape){let u=pe.length-1,S=pe[u];n({type:"field-entry",field:u,values:r.values}),h(S?r.values[S]:"");return}g.return&&(n({type:"writing"}),R(r.values,x));return}(r.type==="done"||r.type==="error")&&(g.return||g.escape)&&o.exit()}),r.type==="target-select"){let C=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Where should the new plugin live?"}),C.map((g,u)=>{let S=r.cursor===u;return A(M,{gap:2,children:[_(I,{...S&&{color:"cyan"},children:S?"\u276F":" "}),_(I,{bold:S,...S&&{color:"cyan"},children:g.label}),_(I,{dimColor:!0,children:g.desc})]},g.label)})]}),_(be,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="precheck-error"){let{targetDir:C,reason:g}=r;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Cannot create plugin"}),A(M,{flexDirection:"column",gap:0,children:[A(I,{children:[C," already contains ",_(I,{bold:!0,children:g==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),_(I,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),_(be,{text:"Enter or Esc to exit"})]})}if(r.type==="field-entry"){let{field:C,fieldError:g}=r,u=l==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${x}`;return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Plugin details"}),_(I,{dimColor:!0,children:u})]}),g!==void 0&&A(I,{color:"red",children:["Error: ",g]}),_(M,{flexDirection:"column",gap:0,children:pe.map((S,s)=>{let i=C===s,a=i?m:f[S],d=Vt.includes(S),p=`${qt[S]}${d?"":" (optional)"}`;return A(M,{gap:2,children:[_(M,{width:24,children:_(I,{bold:i,...i&&{color:"cyan"},children:p})}),_(I,{...i&&{color:"cyan"},children:">"}),_(I,{children:a}),i&&_(I,{color:"cyan",children:"\u2588"})]},S)})}),_(be,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(r.type==="confirm"){let C=gt({targetDir:x,name:r.values.name,apiName:r.values.apiName,externalLink:r.values.externalLink,description:r.values.description,developerBusinessId:r.values.developerBusinessId});return A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"Ready to create"}),A(I,{dimColor:!0,children:["Target: ",x]})]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{bold:!0,children:"kizen.json preview"}),_(I,{children:JSON.stringify(C,null,2)})]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Also creates:"}),A(I,{dimColor:!0,children:[" ",yt(x,"src/")]}),A(I,{dimColor:!0,children:[" ",yt(x,"releaseNotes/")]}),A(I,{dimColor:!0,children:[" ",yt(x,".gitignore")," (adds .kizenapp/)"]})]}),_(be,{text:"Enter to create \xB7 Esc to go back"})]})}return r.type==="resolving-target"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):r.type==="writing"?_(M,{paddingY:1,paddingX:2,children:_(I,{dimColor:!0,children:"Creating plugin\u2026"})}):r.type==="done"?A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),A(I,{color:"green",bold:!0,children:["Plugin created at ",r.targetDir]}),A(M,{flexDirection:"column",gap:0,children:[_(I,{dimColor:!0,children:"Next steps:"}),A(I,{children:[" ","cd ",r.targetDir]}),A(I,{children:[" ","appbuilder dev"]})]}),_(be,{text:"Enter or Esc to exit"})]}):A(M,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[_(V,{}),_(I,{color:"red",bold:!0,children:"Failed to create plugin"}),_(I,{children:r.message}),_(be,{text:"Enter or Esc to exit"})]})};import{mkdir as Wt,readFile as hn,readdir as xn,writeFile as Gt}from"fs/promises";import{homedir as bn}from"os";import{dirname as vn,join as We}from"path";var K=["go","fmo","staging","integration","test1"];var fe=We(bn(),".kizenappbuilder"),ve=We(fe,"credentials.json"),ne="credentials";function wn(e){return K.includes(e)}function Cn(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:wn(o)?o:"go"}}async function Ge(e){let t=await hn(e,"utf-8");return Cn(JSON.parse(t))}async function Y(){try{return await Ge(ve)}catch{return null}}async function Sn(e){await Wt(vn(ve),{recursive:!0,mode:448}),await Gt(ve,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Kt(e){return We(fe,`${e}.json`)}async function Ie(){let e=[{name:ne,path:ve,isDefault:!0}];try{let t=await xn(fe);for(let o of t){if(!o.endsWith(".json"))continue;let r=o.slice(0,-5);r!==ne&&e.push({name:r,path:We(fe,o),isDefault:!1})}}catch{}return e}async function Xt(e,t){if(e===ne){await Sn(t);return}await Wt(fe,{recursive:!0,mode:448}),await Gt(Kt(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function we(e){try{return await Ge(Kt(e))}catch{return null}}function Yt(e){e.command("create").description("Scaffold a new Kizen plugin project").action(async()=>{let t=process.cwd(),r=(await Y())?.businessId??"",{waitUntilExit:n}=Tn(Pn(Jt,{parentDir:t,defaultBusinessId:r}),{exitOnCtrlC:!1});await n()})}import{createElement as vr}from"react";import{render as wr}from"ink";import{useCallback as Ce,useEffect as rt,useRef as Q,useState as J}from"react";import{Box as q,Text as D,useInput as xo}from"ink";import{watch as bo}from"fs";import{createServer as vo}from"http";import{join as hr}from"path";import{WebSocketServer as wo}from"ws";import{createReadStream as sr,realpathSync as Mn}from"fs";import{access as Hn,readdir as Un,readFile as qn,realpath as Vn,stat as ar}from"fs/promises";import{dirname as Jn,extname as lr,join as Ne,resolve as Wn,sep as Pt}from"path";import{fileURLToPath as Gn}from"url";var _n=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,r]of Object.entries(e)){let n=o.toLowerCase();_n.has(n)||n.startsWith("access-control-")||(t[o]=r)}return t}var xt=10*1024*1024,En=6e4,kn=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 bt(e,t){let o=e.body;if(o===null)return Buffer.alloc(0);let r=[],n=0;for await(let l of o){if(n+=l.length,n>t)throw new Be(n,t);r.push(l)}return Buffer.concat(r)}function Zt(e={}){let t=new Map,{onChange:o}=e,r=()=>{o?.(t.size)},n=l=>{t.delete(l)&&r()};return{get(l,v){let f=t.get(l);if(f!==void 0){if(Date.now()-f.insertedAt<En)return f.promise.then(m=>({response:m,fromCache:!0}));n(l)}if(t.size>=kn){let m=t.keys().next().value;m!==void 0&&n(m)}let T=v().then(async m=>{let h=ht(Object.fromEntries(m.headers)),x=await bt(m,xt);return{status:m.status,headers:h,body:x}}).catch(m=>{throw n(l),m});return t.set(l,{insertedAt:Date.now(),promise:T}),r(),T.then(m=>((m.status<200||m.status>=300)&&n(l),{response:m,fromCache:!1}))},clear(){t.clear(),r()}}}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 In,readFile as Bn,writeFile as Dn}from"fs/promises";import{join as Qt}from"path";async function De(e){try{let t=await Bn(Qt(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function me(e,t){await In(e,{recursive:!0}),await Dn(Qt(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 Rn,access as Nn}from"fs/promises";import{join as Re}from"path";import{tmpdir as jn}from"os";var Fn=`
|
|
9
9
|
import sys, json, os, traceback
|
|
10
10
|
|
|
11
11
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -165,10 +165,76 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
165
165
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
166
166
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
167
167
|
sys.stdout.flush()
|
|
168
|
-
`.trim(),
|
|
169
|
-
`);for(;
|
|
170
|
-
`)}}),
|
|
171
|
-
`).trim(),h=v.length>0?`: ${v}`:"";r(new Error(`${e} exited with code ${String(_)}${h}`))}})})}var bt=new Set;function Ke(e){for(let t of bt)t(e)}function Rn(e,t){return t&&bt.add(t),We||(We=(async()=>{let i=Be(xt,"bin","python");try{await _n(i)}catch{let n=Dn(e);await Zt(n,["-m","venv",xt])}Ke({kind:"start"});try{await Zt(i,["-m","pip","install","--disable-pip-version-check",...Bn],(n,r)=>{Ke({kind:"log",line:n,stream:r})}),Ke({kind:"complete"})}catch(n){let r=n instanceof Error?n.message:String(n);throw Ke({kind:"error",message:r}),We=null,await er(xt,{recursive:!0,force:!0}).catch(()=>{}),n}finally{bt.clear()}return i})()),We}function Nn(e){let t="__KIZEN_RESULT_START__",i="__KIZEN_RESULT_END__",n=e.indexOf(t),r=e.indexOf(i);if(n===-1||r===-1)return{userStdout:e,result:null};let c=e.slice(0,n).trimEnd(),S=e.slice(n+t.length,r).trim();try{let g=JSON.parse(S);return{userStdout:c,result:g}}catch{return{userStdout:e,result:null}}}async function tr(e){let t=e.timeout??In,i=await Rn(e.scriptRuntime,e.onInstallProgress),n=Date.now(),r;try{r=await Tn(Be(En(),"kizen-step-"));let c=Be(r,"wrapper.py"),S=Be(r,"script.py");await Promise.all([Yt(c,kn,"utf-8"),Yt(S,e.script,"utf-8")]);let g={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:S},{exitCode:_,stdout:v,stderr:h}=await new Promise(E=>{let R=[],C=[],f=!1,u=Qt(i,[c],{env:g,cwd:r,stdio:["ignore","pipe","pipe"]}),w=setTimeout(()=>{u.kill("SIGKILL")},t);u.stdout.on("data",o=>{R.push(o)}),u.stderr.on("data",o=>{C.push(o)});let s=o=>{f||(f=!0,clearTimeout(w),E({exitCode:o??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};u.on("close",s),u.on("error",o=>{f||(f=!0,clearTimeout(w),E({exitCode:1,stdout:"",stderr:o.message}))})}),y=Date.now()-n,{userStdout:m,result:l}=Nn(v);if(l){let E={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:m,stderr:h,exitCode:_,durationMs:y};return l.error!==null&&(E.error=l.error),l.httpRequests&&(E.httpRequests=l.httpRequests),E}let x={success:!1,outputValues:{},logs:[],stdout:m,stderr:h,exitCode:_,durationMs:y};return _!==0&&(x.error=`Process exited with code ${String(_)}`),x}finally{r&&er(r,{recursive:!0,force:!0})}}var rr=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 vt(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}var Hn=2*1024*1024,Un=new Set([".DS_Store",".gitignore"]);function qn(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 Vn=["kizen.com","kizen.dev"];function Jn(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let i=t.hostname.toLowerCase();return Vn.some(n=>i===n||i.endsWith("."+n))}function Wn(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 sr(e,t){if(t.includes("\0"))return null;let i=t.replace(/^\/+/,""),n=zn(e,i);if(n!==e&&!n.startsWith(e+Ct))return null;try{let r=await On(n);return r!==e&&!r.startsWith(e+Ct)?null:r}catch{return null}}function ar(e,t){let i=t===e?"":t.slice(e.length+1);return i===""?!1:i.split(Ct).some(r=>$e.has(r))}function lr(){let e=Mn(import.meta.url);return De($n(e),"viewer")}async function wt(e){try{return await jn(e),!0}catch{return!1}}function cr(e,t,i,n,r,c,S,g,_,v){let h=Gt({onChange:g}),y=Ln(v);return(m,l)=>{(async()=>{let x=m.url??"/";try{if(!qn(m.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((m.method==="POST"||m.method==="PATCH"||m.method==="DELETE")&&!Wn(m.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(n.current!==null?JSON.stringify(n.current):"{}");return}if(x==="/api/credential-profiles"&&m.method==="GET"){let s=await Ee();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:s,active:r.current}));return}if(x==="/api/credentials/switch"&&m.method==="POST"){let s=[];for await(let p of m)s.push(p);let a=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}").profile,d=a===void 0||a===""?await Y():await be(a);if(d!==null){n.current=d,r.current=a??void 0;let p=r.current;await pe(c,{credentialMode:"global",...p!==void 0&&{activeCredentialProfile:p}}),S({type:"credentials-updated",credentials:d})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:d!==null}));return}if(x==="/api/bundle"){let s=De(process.cwd(),".kizenapp","bundle.json");try{let o=await An(s,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(o)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(x==="/api/last-path"&&m.method==="POST"){let s=[];for await(let a of m)s.push(a);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.path=="string"){_.current=o.path;let a=await Ie(c);await pe(c,{...a,lastPath:o.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(x==="/api/execute-step"&&m.method==="POST"){let s=[];for await(let p of m)s.push(p);let o=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof o.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let a={script:o.script,scriptRuntime:o.scriptRuntime??"python-3.9",inputs:o.inputs??{},secrets:o.secrets??{},onInstallProgress:p=>{p.kind==="start"?S({type:"venv-install-start"}):p.kind==="log"?S({type:"venv-install-log",line:p.line,stream:p.stream}):p.kind==="complete"?S({type:"venv-install-complete"}):S({type:"venv-install-error",message:p.message})}};typeof o.timeout=="number"&&o.timeout>0&&(a.timeout=Math.min(o.timeout,300*1e3));let d=await tr(a);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(d));return}if(x==="/api/proxy-cache/clear"){h.clear(),i({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 s=m.headers["x-proxy-target"];if(typeof s!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!Jn(s)){l.writeHead(400),l.end("Invalid proxy target");return}let o=x.slice(10)||"/",a=`${s}${o}`,d=m.method??"GET",p=[];for await(let Ce of m)p.push(Ce);let{host:j,"x-proxy-target":k,...N}=m.headers;if(d==="GET"){let Ce=`GET::${a}`,{response:ie,fromCache:tt}=await h.get(Ce,()=>fetch(a,{method:"GET",headers:N}));i({kind:"request",method:"GET",status:ie.status,fromCache:tt,url:o}),l.writeHead(ie.status,ie.headers),l.end(ie.body);return}let O=p.length>0?Buffer.concat(p):void 0,H=O&&O.length>0?O:void 0,W=await fetch(a,{method:d,headers:N,...H!==void 0&&{body:H}}),Q=mt(Object.fromEntries(W.headers)),fe=await yt(W,gt);i({kind:"request",method:d,status:W.status,fromCache:!1,url:o}),l.writeHead(W.status,Q),l.end(fe);return}if(x.startsWith("/api/source/tree")&&m.method==="GET"){let o=new URL(x,"http://localhost").searchParams.get("path")??"",a=await sr(y,o);if(a===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(ar(y,a)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Fn(a,{withFileTypes:!0}),p=await Promise.all(d.filter(k=>k.isDirectory()?!$e.has(k.name):k.isFile()?!Un.has(k.name):!1).map(async k=>{let N=k.isDirectory()?"dir":"file",O={name:k.name,kind:N};if(N==="file")try{let H=await or(De(a,k.name));O.size=H.size}catch{}return O}));p.sort((k,N)=>k.kind!==N.kind?k.kind==="dir"?-1:1:k.name.localeCompare(N.name));let j=a===y?"":a.slice(y.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:j,entries:p}))}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/tree failed (${o}): ${p}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(x.startsWith("/api/source/file")&&m.method==="GET"){let o=new URL(x,"http://localhost").searchParams.get("path")??"";if(o===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let a=await sr(y,o);if(a===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(ar(y,a)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await or(a);if(!d.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(d.size>Hn){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:d.size}));return}let p=ir(a).toLowerCase(),j=ht[p],k=rr.has(p),N=j??(k?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":N,"Content-Length":String(d.size)}),nr(a).pipe(l)}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/file failed (${o}): ${p}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let C=De(e,x==="/"?"/index.html":x),f=await wt(C)?C:De(e,"index.html"),u=ir(f),w=ht[u]??"application/octet-stream";l.writeHead(200,{"Content-Type":w}),nr(f).pipe(l)}catch(E){if(x.startsWith("/api/proxy")){let R=x.slice(10)||"/",C=m.method??"GET";E instanceof ke?i({kind:"info",message:`${C} ${R} \u2192 502 (response exceeded ${String(E.limit)} bytes)`}):i({kind:"request",method:C,status:502,fromCache:!1,url:R})}else i({kind:"info",message:`Error handling ${x}: ${E instanceof Error?E.message:String(E)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as Kn}from"chrome-launcher";import{createRequire as Gn}from"module";import{mkdirSync as Xn}from"fs";import{readFile as Yn}from"fs/promises";import{dirname as Zn,join as Qn}from"path";import{fileURLToPath as eo}from"url";var dr=Gn(import.meta.url)("chrome-remote-interface"),to=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),pr=["kizen.dev","kizen.com"];function ur(e){try{let{hostname:t}=new URL(e);return pr.some(i=>t===i||t.endsWith("."+i))}catch{return!1}}function Ge(e){if(e.type==="number")return Number(e.value);if(e.type==="boolean")return e.value==="true";if(e.type!=="undefined"){if(e.type==="object"&&e.value==="null")return null;if(e.type==="object"&&e.valuePreview){let{valuePreview:t}=e;if(t.subtype==="array")return t.properties.filter(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.value??`[${e.type}]`}}function ro(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(n=>/^\d+$/.test(n.name)).sort((n,r)=>parseInt(n.name)-parseInt(r.name)).map(Ge);let i={};for(let n of t.properties)i[n.name]=Ge(n);return i}return e.description??`[${e.type}]`}async function no(e,t){if(t.type==="object"&&t.objectId)try{let n=(await e.Runtime.callFunctionOn({objectId:t.objectId,functionDeclaration:'function() { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); }',returnByValue:!0})).result.value;if(typeof n=="string")return JSON.parse(n)}catch{}return ro(t)}async function oo(e){try{let t=Qn(Zn(eo(import.meta.url)),"viewer","icon.png"),i=await Yn(t);await e.Browser.setDockTile({image:i.toString("base64")})}catch{}}async function fr(e){Xn(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,i=await Kn({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),n=i.port,r=null,c=null,S=null,g=null,_=0,v=!1,h=u=>{e.debugLog?.(u)},y=u=>{e.verbose&&e.debugLog?.(u)},m=()=>{c!==null&&(clearInterval(c),c=null)},l=u=>u==="chrome://new-tab-page/"||u==="chrome://newtab/",x=async u=>{m(),S=null,await oo(u),await u.Fetch.enable({patterns:pr.flatMap(s=>[{urlPattern:`*://${s}/*`,requestStage:"Response"},{urlPattern:`*://*.${s}/*`,requestStage:"Response"}])}),u.on("Fetch.requestPaused",s=>{(async()=>{let o=s,{requestId:a,request:d,responseHeaders:p,responseStatusCode:j}=o,k=d.url;y(`Fetch ${String(j??"?")} ${k}`);let N=[],O=!1;for(let H of p??[])if(!to.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&ur(k)){let W=H.value.split(`
|
|
172
|
-
`).map(
|
|
173
|
-
`);N.push({name:H.name,value:W}),O=!0}else N.push(H);O&&y(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:H,base64Encoded:W}=await u.Fetch.getResponseBody({requestId:a});await u.Fetch.fulfillRequest({requestId:a,responseCode:j??200,responseHeaders:N,body:H,...W&&{base64Encoded:!0}})}catch(H){y(` fulfillRequest failed (${H.message}), falling through`);try{await u.Fetch.continueRequest({requestId:a})}catch(W){y(` continueRequest also failed (${W.message})`)}}})()}),c=setInterval(()=>{(async()=>{try{let{cookies:s}=await u.Network.getAllCookies(),o=0;for(let a of s){if(!ur(`https://${a.domain??""}`)||a.sameSite==="None")continue;let d=a.domain??"",p=d.startsWith(".")?d.slice(1):d;await u.Network.setCookie({url:`https://${p}`,name:a.name,value:a.value,domain:d,path:a.path??"/",secure:!0,...a.httpOnly!==void 0&&{httpOnly:a.httpOnly},...a.expirationDate!==void 0&&{expires:a.expirationDate},sameSite:"None"}),o++}o>0&&y(`cookie-patch cycle: updated ${String(o)} cookie(s) to SameSite=None`)}catch(s){y(`cookie-patch cycle failed: ${s.message}`)}})()},2e3),await u.send("Runtime.enable",{generatePreview:!0}),u.on("Target.attachedToTarget",s=>{let o=s,{sessionId:a,targetInfo:d}=o;y(`attached session ${a} (${d.type} ${d.url})`),u.send("Runtime.enable",{generatePreview:!0},a).catch(p=>{y(` Runtime.enable on session ${a} failed: ${p.message}`)})}),await u.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await u.Target.setDiscoverTargets({discover:!0});let w=s=>{if(s.type==="page"){if(l(s.url)){h(`closed stray new-tab-page target ${s.targetId}`),S!==null&&u.Target.activateTarget({targetId:S}).catch(()=>{}),u.Target.closeTarget({targetId:s.targetId}).catch(()=>{});return}S===null&&(S=s.targetId,h(`captured main target ${s.targetId} (${s.url})`))}};u.on("Target.targetCreated",s=>{let{targetInfo:o}=s;y(`target +${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Target.targetInfoChanged",s=>{let{targetInfo:o}=s;y(`target ~${o.type} ${o.targetId} ${o.url}`),w(o)}),u.on("Runtime.consoleAPICalled",s=>{(async()=>{let{type:o,args:a}=s;if(a[0]?.type==="string"&&String(a[0].value).includes("Chrome Security"))return;let d=o==="warning"?"warn":["log","warn","error","info"].includes(o)?o:"log";y(`console.${d} (${String(a.length)} arg(s))`);let p=await Promise.all(a.map(j=>no(u,j)));e.broadcast({type:"console-message",level:d,args:p})})().catch(o=>{y(`console serialization failed: ${o.message}`)})}),u.on("disconnect",()=>{v||r!==u||(h("CDP disconnected"),r=null,m(),E())})},E=()=>{if(v||g!==null)return;let u=Math.min(1e3*2**_,1e4),w=_+1;_++,h(`CDP reconnect scheduled in ${String(u)}ms (attempt #${String(w)})`),g=setTimeout(()=>{g=null,(async()=>{let s;try{s=await dr({port:n})}catch{h(`CDP reconnect attempt #${String(w)} failed`),E();return}if(v){try{await s.close()}catch{}return}r=s;try{await x(s),h(`CDP reconnected after ${String(w)} attempt(s)`),_=0}catch{r===s&&(r=null);try{await s.close()}catch{}h(`CDP reconnect attempt #${String(w)} failed during setup`),E()}})()},u)},R=30,C=300;for(let u=0;u<R;u++){await new Promise(w=>setTimeout(w,C)),h(`CDP connect attempt ${String(u+1)}/${String(R)}`);try{let w=await dr({port:n});r=w,e.path&&w.send("Page.navigate",{url:`${t}${e.path}`});try{await x(w),h("CDP connected")}catch{r===w&&(r=null);try{await w.close()}catch{}h("CDP setup failed after connect")}break}catch{if(u===R-1){let w=`CDP unavailable after ${String(R)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(w),e.onWarn?.(w),{kill:()=>{i.kill()}}}}}return r?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),v=!0,g!==null&&(clearTimeout(g),g=null),m(),r!==null){try{r.close()}catch{}r=null}i.kill()}}:{kill:()=>{i.kill()}}}import{useCallback as io,useState as so}from"react";function Xe(e){let[t,i]=so([]),n=io(r=>{i(c=>[...c,`${new Date().toLocaleTimeString()}: ${r}`].slice(-e))},[e]);return[t,n]}import{useCallback as Ye,useEffect as St,useState as Ze}from"react";import{Box as z,Text as B,useInput as ao}from"ink";import{jsx as P,jsxs as U}from"react/jsx-runtime";var ne=["apiKey","userId","businessId"],lo={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Re=({text:e})=>P(B,{dimColor:!0,children:e}),Qe=({initialMode:e,showProfileManager:t,onComplete:i,onCancel:n})=>{let[r,c]=Ze(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[S,g]=Ze(""),[_,v]=Ze(null),[h,y]=Ze(void 0),m=Ye(s=>{if(s==="local"){i({mode:"local",credentials:null});return}c({type:"profile-loading"})},[i]),l=Ye(async s=>{if(s===null){c({type:"profile-loading"});let d=await Ee();c({type:"name-entry",nameBuffer:"",existingProfiles:d});return}y(s.isDefault?void 0:s.name),c({type:"loading"});let o=s.isDefault?await Y():await be(s.name),a=o?Math.max(0,G.indexOf(o.environment)):0;c({type:"creds-entry",field:0,values:o??{},envCursor:a})},[]),x=Ye(async(s,o)=>{let a=G[o]??"go",d={apiKey:s.apiKey??"",userId:s.userId??"",businessId:s.businessId??"",environment:a};c({type:"saving"});try{await Wt(h??re,d),i({mode:"global",credentials:d,...h!==void 0&&{profileName:h}})}catch(p){v(p instanceof Error?p.message:String(p)),c({type:"creds-entry",field:0,values:s,envCursor:o})}},[i,h]);ao((s,o)=>{if(o.ctrl&&s==="c"&&process.exit(0),o.escape){if((r.type==="creds-entry"||r.type==="name-entry")&&e==="global"&&t){c({type:"profile-loading"}),E();return}n?.();return}if(r.type==="mode-select"){if(o.upArrow)c({type:"mode-select",cursor:0});else if(o.downArrow)c({type:"mode-select",cursor:1});else if(o.return){let a=r.cursor===0?"global":"local";m(a)}return}if(r.type==="profile-select"){let{profiles:a,cursor:d}=r,p=a.length,j=a.length+1;if(o.upArrow)c({...r,cursor:(d-1+j)%j});else if(o.downArrow)c({...r,cursor:(d+1)%j});else if(o.return)if(d===p)c({type:"name-entry",nameBuffer:"",existingProfiles:a});else{let k=a[d]??a[0];k&&l(k)}return}if(r.type==="name-entry"){let{nameBuffer:a,existingProfiles:d}=r;if(o.backspace||o.delete)c({type:"name-entry",nameBuffer:a.slice(0,-1),existingProfiles:d});else if(o.return){let p=a.trim();if(!p){c({...r,nameError:"Name cannot be empty"});return}if(p===re){c({...r,nameError:`"${re}" is reserved`});return}if(d.some(j=>j.name===p)){c({...r,nameError:`Profile "${p}" already exists`});return}y(p),c({type:"creds-entry",field:0,values:{},envCursor:0}),g("")}else s&&!o.ctrl&&!o.meta&&c({type:"name-entry",nameBuffer:a+s,existingProfiles:d});return}if(r.type==="creds-entry"){let{field:a,values:d,envCursor:p}=r;if(a===ne.length){o.leftArrow?c({...r,envCursor:(p-1+G.length)%G.length}):o.rightArrow?c({...r,envCursor:(p+1)%G.length}):o.upArrow?(c({...r,field:a-1}),g(d[ne[a-1]]??"")):o.return&&x(d,p);return}let k=ne[a];if(!k)return;if(o.backspace||o.delete)g(N=>N.slice(0,-1));else if(o.upArrow&&a>0){let N={...d,[k]:S},O=a-1;c({...r,field:O,values:N}),g(N[ne[O]]??"")}else if(o.return||o.tab||o.downArrow){let N={...d,[k]:S},O=a+1;c({...r,field:O,values:N}),O<ne.length?g(N[ne[O]]??""):g("")}else s&&!o.ctrl&&!o.meta&&g(N=>N+s)}});let E=Ye(async()=>{let s=await Ee();c({type:"profile-select",profiles:s,cursor:0})},[]);if(St(()=>{r.type==="profile-loading"&&E()},[r.type,E]),St(()=>{e==="global"&&!t&&(async()=>{let s=await Y(),o=s?Math.max(0,G.indexOf(s.environment)):0;c({type:"creds-entry",field:0,values:s??{},envCursor:o})})()},[]),St(()=>{r.type==="creds-entry"&&r.field===0&&g(r.values.apiKey??"")},[r.type]),r.type==="loading"||r.type==="saving"||r.type==="profile-loading"){let s=r.type==="saving"?"Saving credentials\u2026":r.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return P(z,{paddingY:1,paddingX:2,children:P(B,{dimColor:!0,children:s})})}if(r.type==="done")return null;if(r.type==="mode-select")return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(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((o,a)=>{let d=r.cursor===a;return U(z,{gap:2,children:[P(B,{...d&&{color:"cyan"},children:d?"\u276F":" "}),P(B,{bold:d,...d&&{color:"cyan"},children:o.label}),P(B,{dimColor:!0,children:o.desc})]},o.mode)})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(r.type==="profile-select"){let{profiles:s,cursor:o}=r,a=s.length;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:"Credential profiles"}),s.map((d,p)=>{let j=o===p;return U(z,{gap:2,children:[P(B,{...j&&{color:"cyan"},children:j?"\u276F":" "}),P(B,{bold:j,...j&&{color:"cyan"},children:d.isDefault?"Default":d.name}),P(B,{dimColor:!0,children:d.path})]},d.name)}),U(z,{gap:2,children:[P(B,{...o===a&&{color:"cyan"},children:o===a?"\u276F":" "}),P(B,{bold:o===a,...o===a&&{color:"cyan"},children:"+ Add new profile"})]})]}),P(Re,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(r.type==="name-entry"){let{nameBuffer:s,nameError:o}=r;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(z,{flexDirection:"column",gap:0,children:P(B,{bold:!0,children:"New credential profile"})}),o&&U(B,{color:"red",children:["Error: ",o]}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:!0,color:"cyan",children:"Profile name"})}),P(B,{color:"cyan",children:">"}),P(B,{children:s}),P(B,{color:"cyan",children:"\u2588"})]}),P(Re,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:C,envCursor:f}=r,u=R===ne.length,w=h??re;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),U(B,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:xe]})]}),_&&U(B,{color:"red",children:["Error: ",_]}),U(z,{flexDirection:"column",gap:0,children:[ne.map((s,o)=>{let a=R===o,d=a?S:C[s]??"";return U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:a,...a&&{color:"cyan"},children:lo[s]})}),P(B,{...a&&{color:"cyan"},children:">"}),P(B,{children:d}),a&&P(B,{color:"cyan",children:"\u2588"})]},s)}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:u,...u&&{color:"cyan"},children:"Environment"})}),P(B,{...u&&{color:"cyan"},children:">"}),P(z,{gap:1,children:G.map((s,o)=>{let a=o===f;return u?P(B,{bold:a,...a&&{color:"cyan"},children:a?`[${s}]`:s},s):P(B,{dimColor:!a,bold:a,children:s},s)})})]})]}),u?P(Re,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):P(Re,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),U(B,{dimColor:!0,children:["Profile: ",w]})]})};import{jsx as L,jsxs as $}from"react/jsx-runtime";var go=[".kizenapp",".git"],gr=({port:e,pluginDir:t,outputDir:i,credentials:n,credentialMode:r,activeCredentialProfile:c,lastPath:S,debug:g=!1,verbose:_=!1,autoViewer:v=!0})=>{let h=Z(n),y=Z(c),m=Z(S),[l,x]=J("main"),[E,R]=J(r),[C,f]=J("starting"),[u,w]=J(null),[s,o]=Xe(50),[a,d]=Xe(50),[p,j]=Xe(50),[k,N]=J([]),[O,H]=J("pending"),[W,Q]=J(null),[fe,Ce]=J(null),[ie,tt]=J(null),[rt,nt]=J(0),[Pt,vr]=J(0),[Cr,wr]=J(0),[Sr,Pr]=J(0),ot=Z(!1),Tt=Z(!1),je=Z(null),we=Z(null),ee=Z(new Set),Fe=Z([]),K=ve(b=>{let F=JSON.stringify(b);if(ee.current.size===0){Fe.current=[...Fe.current,F].slice(-50);return}let te=!1;for(let X of ee.current)if(X.readyState===1)try{X.send(F)}catch{ee.current.delete(X),te=!0}te&&nt(ee.current.size)},[]),Ae=o,it=ve(()=>{je.current?.kill(),je.current=null,fr({port:e,userDataDir:mr(i,".chrome"),broadcast:K,onWarn:b=>{o(`\u26A0 ${b}`)},...m.current!==void 0&&{path:m.current},...g&&{debugLog:j},..._&&{verbose:!0}}).then(b=>{je.current=b})},[e,i,K,g,_,j,o]);et(()=>{let b=()=>{je.current?.kill()};return process.on("exit",b),()=>{process.off("exit",b)}},[]),uo((b,F)=>{(b==="q"||F.ctrl&&b==="c")&&process.exit(0),b==="c"&&x("editing"),b==="v"&&it()},{isActive:l==="main"}),et(()=>{C!=="running"||Tt.current||!v||(Tt.current=!0,it())},[C,v,it]);let Tr=ve(b=>{h.current=b.credentials,y.current=b.profileName,x("main"),R(b.mode);let F=b.profileName;pe(i,{credentialMode:b.mode,...F!==void 0&&{activeCredentialProfile:F}}),K({type:"credentials-updated",credentials:b.credentials})},[i,K]),_t=ve(b=>{N(F=>[...F,`${new Date().toLocaleTimeString()}: ${vt(b)}`].slice(-50)),b.kind==="request"&&(b.fromCache?wr(F=>F+1):Pr(F=>F+1)),K({type:"proxy-log",entry:b})},[K]),se=ve(b=>{d(b),K({type:"log",message:b})},[d,K]),st=ve(()=>{ot.current||(ot.current=!0,H("building"),Q(null),se("Build started"),ze(t,i).then(({bundleSize:b})=>{se(`Build finished \u2014 bundle: ${Se(b)}`),H("done"),Ce(new Date),tt(b),se("Notifying viewers to reload"),K({type:"rebuild"})}).catch(b=>{let F=b instanceof Error?b.message:String(b);Q(F),H("error")}).finally(()=>{ot.current=!1}))},[t,i,se,K]);if(et(()=>{st();let b=po(t,{recursive:!0},(F,te)=>{if(!te)return;let X=te.replace(/\\/g,"/");go.some(Oe=>X.startsWith(Oe))||(se(`File change detected: ${te}`),we.current!==null&&clearTimeout(we.current),we.current=setTimeout(st,150))});return b.on("error",F=>{se(`File watcher error \u2014 rebuilds have stopped: ${F.message}`)}),()=>{b.close(),we.current!==null&&clearTimeout(we.current)}},[t,st,se]),et(()=>{let b=lr();wt(mr(b,"index.html")).then(F=>{if(!F){w("Viewer not built. Run 'pnpm build:viewer' first."),f("error");return}let te=cr(b,Ae,_t,h,y,i,K,vr,m,t),X=fo(te),Oe=new mo({server:X});return Oe.on("connection",ae=>{for(let Er of Fe.current)ae.readyState===1&&ae.send(Er);Fe.current=[],Ae("Viewer connected for live reload"),ee.current.add(ae),nt(ee.current.size),ae.on("close",()=>{ee.current.delete(ae),nt(ee.current.size)})}),X.listen(e,"127.0.0.1",()=>{f("running"),Ae(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",ae=>{w(ae.message),f("error")}),()=>{Oe.close(),X.close()}})},[e,Ae,_t,K,i,t]),l==="editing")return L(Qe,{...E!==void 0&&{initialMode:E},showProfileManager:E==="global",onComplete:Tr,onCancel:()=>{x("main")}});let at=fe!==null?Math.round((Date.now()-fe.getTime())/1e3):null,_r=at===null?"":at<5?" (just now)":` (${String(at)}s ago)`;return $(q,{flexDirection:"column",paddingY:1,paddingX:2,children:[L(V,{marginBottom:1}),$(q,{flexDirection:"column",children:[$(q,{gap:2,marginBottom:0,children:[L(D,{bold:!0,dimColor:!0,children:"App Build"}),O==="pending"&&L(D,{dimColor:!0,children:"waiting\u2026"}),O==="building"&&$(q,{gap:1,children:[L(Me,{}),L(D,{children:"Building plugin package\u2026"})]}),O==="done"&&$(q,{gap:1,children:[L(D,{color:"green",children:"\u2713 Built"}),fe!==null&&$(D,{dimColor:!0,children:["at ",fe.toLocaleTimeString(),_r]}),ie!==null&&$(D,{dimColor:!0,children:["\xB7 bundle: ",Se(ie)]})]}),O==="error"&&$(D,{color:"red",children:["\u2717 ",W??"unknown error"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((b,F)=>L(D,{dimColor:!0,wrap:"truncate",children:b},F))})]}),$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(D,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&L(D,{dimColor:!0,children:"starting\u2026"}),C==="running"&&$(q,{gap:2,children:[L(D,{color:"green",children:"\u2713 Running"}),$(D,{dimColor:!0,children:["\u25CF ",rt," viewer",rt!==1?"s":""]})]}),C==="error"&&$(D,{color:"red",children:["\u2717 ",u??"Server error"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:s.slice(-8).map((b,F)=>L(D,{dimColor:!0,wrap:"truncate",children:b},F))})]}),$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(D,{bold:!0,dimColor:!0,children:"Network Proxy"}),L(D,{color:"green",children:"\u2713 Active"}),$(D,{dimColor:!0,children:["\u25CF ",Pt," key",Pt!==1?"s":""," in the network cache \xB7"," ",Cr," hit \xB7 ",Sr," miss"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:k.length===0?L(D,{dimColor:!0,children:" No requests yet."}):k.slice(-8).map((b,F)=>L(D,{dimColor:!0,wrap:"truncate",children:b},F))})]}),g&&$(q,{marginTop:1,flexDirection:"column",children:[$(q,{gap:2,children:[L(D,{bold:!0,dimColor:!0,children:"CDP Debug"}),$(D,{dimColor:!0,children:["\u25CF ",p.length," event(s)"]})]}),L(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:p.length===0?L(D,{dimColor:!0,children:" No CDP events yet."}):p.slice(-8).map((b,F)=>L(D,{dimColor:!0,wrap:"truncate",children:b},F))})]}),$(q,{marginTop:1,gap:1,children:[L(D,{dimColor:!0,children:"["}),L(D,{children:"q"}),L(D,{dimColor:!0,children:"] quit ["}),L(D,{children:"c"}),L(D,{dimColor:!0,children:"] credentials ["}),L(D,{children:"v"}),$(D,{dimColor:!0,children:["] ",rt===0?"open viewer":"relaunch viewer"]})]})]})};async function yr(e){return new Promise(t=>{let i=null,n=c=>{i?.(),t(c)},{unmount:r}=xr(hr(Qe,{...e!==void 0&&{initialMode:e},onComplete:n}),{exitOnCtrlC:!1});i=r})}function br(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 i=parseInt(t.port,10),n=process.cwd(),r=`${n}/.kizenapp`;ye(n);let c=null,S,g,{lastPath:_}=await Ie(r);if(t.credentials)c=await Je(t.credentials);else{let l=await Ie(r);if(l.credentialMode==="local")S="local";else if(l.credentialMode==="global"){if(S="global",g=l.activeCredentialProfile,g?(c=await be(g),c||(c=await Y(),g=void 0)):c=await Y(),!c){let x=await yr("global");c=x.credentials,g=x.profileName}}else{let x=await yr();c=x.credentials,S=x.mode,g=x.profileName;let E=x.profileName;await pe(r,{credentialMode:x.mode,...E!==void 0&&{activeCredentialProfile:E}})}}let v=t.verbose===!0,h=v||t.debug===!0,y=t.viewer!==!1,{waitUntilExit:m}=xr(hr(gr,{port:i,pluginDir:n,outputDir:r,credentials:c,...S!==void 0&&{credentialMode:S},...g!==void 0&&{activeCredentialProfile:g},..._!==void 0&&{lastPath:_},debug:h,verbose:v,autoViewer:y}),{exitOnCtrlC:!1});await m()})}var vo=xo(ho(bo(import.meta.url)),"..","package.json"),Co=JSON.parse(yo(vo,"utf-8"));Le.name("appbuilder").description("Kizen plugin app builder").version(Co.version);Kt(Le);At(Le);br(Le);Le.parse();
|
|
168
|
+
`.trim(),Ln=3e4,wt=Re(process.cwd(),".kizenapp","venv"),An=["awslambdaric","bcrypt","fpdf2","lxml","msgpack","numpy","paramiko","pyjwt","pypdf","pytz","requests","tzdata"],Ke=null;function $n(e){let t=/^python-(\d+\.\d+)$/.exec(e);return t?.[1]?`python${t[1]}`:"python3"}function tr(e,t,o){return new Promise((r,n)=>{let l=rr(e,t,{stdio:["ignore","pipe","pipe"]}),v=(T,m)=>{let h=[],x="";return T.on("data",y=>{x+=y.toString("utf-8");let c=x.indexOf(`
|
|
169
|
+
`);for(;c>=0;){let b=x.slice(0,c).replace(/\r$/,"");x=x.slice(c+1),h.push(b),o?.(b,m),c=x.indexOf(`
|
|
170
|
+
`)}}),T.on("end",()=>{if(x.length>0){let y=x.replace(/\r$/,"");h.push(y),o?.(y,m)}}),h},f=v(l.stderr,"stderr");v(l.stdout,"stdout"),l.on("error",n),l.on("close",T=>{if(T===0)r();else{let m=f.slice(-10).join(`
|
|
171
|
+
`).trim(),h=m.length>0?`: ${m}`:"";n(new Error(`${e} exited with code ${String(T)}${h}`))}})})}var Ct=new Set;function Xe(e){for(let t of Ct)t(e)}function On(e,t){return t&&Ct.add(t),Ke||(Ke=(async()=>{let o=Re(wt,"bin","python");try{await Nn(o)}catch{let r=$n(e);await tr(r,["-m","venv",wt])}Xe({kind:"start"});try{await tr(o,["-m","pip","install","--disable-pip-version-check",...An],(r,n)=>{Xe({kind:"log",line:r,stream:n})}),Xe({kind:"complete"})}catch(r){let n=r instanceof Error?r.message:String(r);throw Xe({kind:"error",message:n}),Ke=null,await nr(wt,{recursive:!0,force:!0}).catch(()=>{}),r}finally{Ct.clear()}return o})()),Ke}function zn(e){let t="__KIZEN_RESULT_START__",o="__KIZEN_RESULT_END__",r=e.indexOf(t),n=e.indexOf(o);if(r===-1||n===-1)return{userStdout:e,result:null};let l=e.slice(0,r).trimEnd(),v=e.slice(r+t.length,n).trim();try{let f=JSON.parse(v);return{userStdout:l,result:f}}catch{return{userStdout:e,result:null}}}async function or(e){let t=e.timeout??Ln,o=await On(e.scriptRuntime,e.onInstallProgress),r=Date.now(),n;try{n=await Rn(Re(jn(),"kizen-step-"));let l=Re(n,"wrapper.py"),v=Re(n,"script.py");await Promise.all([er(l,Fn,"utf-8"),er(v,e.script,"utf-8")]);let f={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:v},{exitCode:T,stdout:m,stderr:h}=await new Promise(E=>{let R=[],C=[],g=!1,u=rr(o,[l],{env:f,cwd:n,stdio:["ignore","pipe","pipe"]}),S=setTimeout(()=>{u.kill("SIGKILL")},t);u.stdout.on("data",i=>{R.push(i)}),u.stderr.on("data",i=>{C.push(i)});let s=i=>{g||(g=!0,clearTimeout(S),E({exitCode:i??1,stdout:Buffer.concat(R).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};u.on("close",s),u.on("error",i=>{g||(g=!0,clearTimeout(S),E({exitCode:1,stdout:"",stderr:i.message}))})}),x=Date.now()-r,{userStdout:y,result:c}=zn(m);if(c){let E={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:y,stderr:h,exitCode:T,durationMs:x};return c.error!==null&&(E.error=c.error),c.httpRequests&&(E.httpRequests=c.httpRequests),E}let b={success:!1,outputValues:{},logs:[],stdout:y,stderr:h,exitCode:T,durationMs:x};return T!==0&&(b.error=`Process exited with code ${String(T)}`),b}finally{n&&nr(n,{recursive:!0,force:!0})}}var ir=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 St(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${t}`}var Kn=2*1024*1024,Xn=new Set([".DS_Store",".gitignore"]);function Yn(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 Zn=["kizen.com","kizen.dev"];function Qn(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let o=t.hostname.toLowerCase();return Zn.some(r=>o===r||o.endsWith("."+r))}function eo(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 cr(e,t){if(t.includes("\0"))return null;let o=t.replace(/^\/+/,""),r=Wn(e,o);if(r!==e&&!r.startsWith(e+Pt))return null;try{let n=await Vn(r);return n!==e&&!n.startsWith(e+Pt)?null:n}catch{return null}}function dr(e,t){let o=t===e?"":t.slice(e.length+1);return o===""?!1:o.split(Pt).some(n=>ze.has(n))}function ur(){let e=Gn(import.meta.url);return Ne(Jn(e),"viewer")}async function Tt(e){try{return await Hn(e),!0}catch{return!1}}function pr(e,t,o,r,n,l,v,f,T,m){let h=Zt({onChange:f}),x=Mn(m);return(y,c)=>{(async()=>{let b=y.url??"/";try{if(!Yn(y.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((y.method==="POST"||y.method==="PATCH"||y.method==="DELETE")&&!eo(y.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${b}`),b==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(r.current!==null?JSON.stringify(r.current):"{}");return}if(b==="/api/credential-profiles"&&y.method==="GET"){let s=await Ie();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:s,active:n.current}));return}if(b==="/api/credentials/switch"&&y.method==="POST"){let s=[];for await(let p of y)s.push(p);let a=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}").profile,d=a===void 0||a===""?await Y():await we(a);if(d!==null){r.current=d,n.current=a??void 0;let p=n.current;await me(l,{credentialMode:"global",...p!==void 0&&{activeCredentialProfile:p}}),v({type:"credentials-updated",credentials:d})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:d!==null}));return}if(b==="/api/bundle"){let s=Ne(process.cwd(),".kizenapp","bundle.json");try{let i=await qn(s,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(i)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(b==="/api/last-path"&&y.method==="POST"){let s=[];for await(let a of y)s.push(a);let i=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof i.path=="string"){T.current=i.path;let a=await De(l);await me(l,{...a,lastPath:i.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b==="/api/execute-step"&&y.method==="POST"){let s=[];for await(let p of y)s.push(p);let i=JSON.parse(Buffer.concat(s).toString("utf-8")||"{}");if(typeof i.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let a={script:i.script,scriptRuntime:i.scriptRuntime??"python-3.9",inputs:i.inputs??{},secrets:i.secrets??{},onInstallProgress:p=>{p.kind==="start"?v({type:"venv-install-start"}):p.kind==="log"?v({type:"venv-install-log",line:p.line,stream:p.stream}):p.kind==="complete"?v({type:"venv-install-complete"}):v({type:"venv-install-error",message:p.message})}};typeof i.timeout=="number"&&i.timeout>0&&(a.timeout=Math.min(i.timeout,300*1e3));let d=await or(a);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(d));return}if(b==="/api/proxy-cache/clear"){h.clear(),o({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(b.startsWith("/api/proxy")){let s=y.headers["x-proxy-target"];if(typeof s!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!Qn(s)){c.writeHead(400),c.end("Invalid proxy target");return}let i=b.slice(10)||"/",a=`${s}${i}`,d=y.method??"GET",p=[];for await(let Pe of y)p.push(Pe);let{host:F,"x-proxy-target":k,...N}=y.headers;if(d==="GET"){let Pe=`GET::${a}`,{response:se,fromCache:ot}=await h.get(Pe,()=>fetch(a,{method:"GET",headers:N}));o({kind:"request",method:"GET",status:se.status,fromCache:ot,url:i}),c.writeHead(se.status,se.headers),c.end(se.body);return}let $=p.length>0?Buffer.concat(p):void 0,H=$&&$.length>0?$:void 0,W=await fetch(a,{method:d,headers:N,...H!==void 0&&{body:H}}),ee=ht(Object.fromEntries(W.headers)),ge=await bt(W,xt);o({kind:"request",method:d,status:W.status,fromCache:!1,url:i}),c.writeHead(W.status,ee),c.end(ge);return}if(b.startsWith("/api/source/tree")&&y.method==="GET"){let i=new URL(b,"http://localhost").searchParams.get("path")??"",a=await cr(x,i);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(x,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await Un(a,{withFileTypes:!0}),p=await Promise.all(d.filter(k=>k.isDirectory()?!ze.has(k.name):k.isFile()?!Xn.has(k.name):!1).map(async k=>{let N=k.isDirectory()?"dir":"file",$={name:k.name,kind:N};if(N==="file")try{let H=await ar(Ne(a,k.name));$.size=H.size}catch{}return $}));p.sort((k,N)=>k.kind!==N.kind?k.kind==="dir"?-1:1:k.name.localeCompare(N.name));let F=a===x?"":a.slice(x.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:F,entries:p}))}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/tree failed (${i}): ${p}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(b.startsWith("/api/source/file")&&y.method==="GET"){let i=new URL(b,"http://localhost").searchParams.get("path")??"";if(i===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let a=await cr(x,i);if(a===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(dr(x,a)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let d=await ar(a);if(!d.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(d.size>Kn){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:d.size}));return}let p=lr(a).toLowerCase(),F=vt[p],k=ir.has(p),N=F??(k?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":N,"Content-Length":String(d.size)}),sr(a).pipe(c)}catch(d){let p=d instanceof Error?d.message:String(d);t(`source/file failed (${i}): ${p}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let C=Ne(e,b==="/"?"/index.html":b),g=await Tt(C)?C:Ne(e,"index.html"),u=lr(g),S=vt[u]??"application/octet-stream";c.writeHead(200,{"Content-Type":S}),sr(g).pipe(c)}catch(E){if(b.startsWith("/api/proxy")){let R=b.slice(10)||"/",C=y.method??"GET";E instanceof Be?o({kind:"info",message:`${C} ${R} \u2192 502 (response exceeded ${String(E.limit)} bytes)`}):o({kind:"request",method:C,status:502,fromCache:!1,url:R})}else o({kind:"info",message:`Error handling ${b}: ${E instanceof Error?E.message:String(E)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as to}from"chrome-launcher";import{createRequire as ro}from"module";import{mkdirSync as no}from"fs";import{readFile as oo}from"fs/promises";import{dirname as io,join as so}from"path";import{fileURLToPath as ao}from"url";var fr=ro(import.meta.url)("chrome-remote-interface"),lo=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),gr=["kizen.dev","kizen.com"];function mr(e){try{let{hostname:t}=new URL(e);return gr.some(o=>t===o||t.endsWith("."+o))}catch{return!1}}function Ye(e){if(e.type==="number")return Number(e.value);if(e.type==="boolean")return e.value==="true";if(e.type!=="undefined"){if(e.type==="object"&&e.value==="null")return null;if(e.type==="object"&&e.valuePreview){let{valuePreview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.value??`[${e.type}]`}}function co(e){if(e.value!==void 0)return e.value;if(e.preview){let{preview:t}=e;if(t.subtype==="array")return t.properties.filter(r=>/^\d+$/.test(r.name)).sort((r,n)=>parseInt(r.name)-parseInt(n.name)).map(Ye);let o={};for(let r of t.properties)o[r.name]=Ye(r);return o}return e.description??`[${e.type}]`}async function uo(e,t){if(t.type==="object"&&t.objectId)try{let r=(await e.Runtime.callFunctionOn({objectId:t.objectId,functionDeclaration:'function() { const seen = new WeakSet(); return JSON.stringify(this, function(k,v) { if (typeof v === "object" && v !== null) { if (seen.has(v)) return "[Circular]"; seen.add(v); } return v; }); }',returnByValue:!0})).result.value;if(typeof r=="string")return JSON.parse(r)}catch{}return co(t)}async function po(e){try{let t=so(io(ao(import.meta.url)),"viewer","icon.png"),o=await oo(t);await e.Browser.setDockTile({image:o.toString("base64")})}catch{}}async function yr(e){no(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,o=await to({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=o.port,n=null,l=null,v=null,f=null,T=0,m=!1,h=u=>{e.debugLog?.(u)},x=u=>{e.verbose&&e.debugLog?.(u)},y=()=>{l!==null&&(clearInterval(l),l=null)},c=u=>u==="chrome://new-tab-page/"||u==="chrome://newtab/",b=async u=>{y(),v=null,await po(u),await u.Fetch.enable({patterns:gr.flatMap(s=>[{urlPattern:`*://${s}/*`,requestStage:"Response"},{urlPattern:`*://*.${s}/*`,requestStage:"Response"}])}),u.on("Fetch.requestPaused",s=>{(async()=>{let i=s,{requestId:a,request:d,responseHeaders:p,responseStatusCode:F}=i,k=d.url;x(`Fetch ${String(F??"?")} ${k}`);let N=[],$=!1;for(let H of p??[])if(!lo.has(H.name.toLowerCase()))if(H.name.toLowerCase()==="set-cookie"&&mr(k)){let W=H.value.split(`
|
|
172
|
+
`).map(ee=>/SameSite=/i.test(ee)?ee.replace(/SameSite=\w+/i,"SameSite=None"):ee+"; SameSite=None; Secure").join(`
|
|
173
|
+
`);N.push({name:H.name,value:W}),$=!0}else N.push(H);$&&x(` rewrote Set-Cookie SameSite on ${k}`);try{let{body:H,base64Encoded:W}=await u.Fetch.getResponseBody({requestId:a});await u.Fetch.fulfillRequest({requestId:a,responseCode:F??200,responseHeaders:N,body:H,...W&&{base64Encoded:!0}})}catch(H){x(` fulfillRequest failed (${H.message}), falling through`);try{await u.Fetch.continueRequest({requestId:a})}catch(W){x(` continueRequest also failed (${W.message})`)}}})()}),l=setInterval(()=>{(async()=>{try{let{cookies:s}=await u.Network.getAllCookies(),i=0;for(let a of s){if(!mr(`https://${a.domain??""}`)||a.sameSite==="None")continue;let d=a.domain??"",p=d.startsWith(".")?d.slice(1):d;await u.Network.setCookie({url:`https://${p}`,name:a.name,value:a.value,domain:d,path:a.path??"/",secure:!0,...a.httpOnly!==void 0&&{httpOnly:a.httpOnly},...a.expirationDate!==void 0&&{expires:a.expirationDate},sameSite:"None"}),i++}i>0&&x(`cookie-patch cycle: updated ${String(i)} cookie(s) to SameSite=None`)}catch(s){x(`cookie-patch cycle failed: ${s.message}`)}})()},2e3),await u.send("Runtime.enable",{generatePreview:!0}),u.on("Target.attachedToTarget",s=>{let i=s,{sessionId:a,targetInfo:d}=i;x(`attached session ${a} (${d.type} ${d.url})`),u.send("Runtime.enable",{generatePreview:!0},a).catch(p=>{x(` Runtime.enable on session ${a} failed: ${p.message}`)})}),await u.Target.setAutoAttach({autoAttach:!0,waitForDebuggerOnStart:!1,flatten:!0}),await u.Target.setDiscoverTargets({discover:!0});let S=s=>{if(s.type==="page"){if(c(s.url)){h(`closed stray new-tab-page target ${s.targetId}`),v!==null&&u.Target.activateTarget({targetId:v}).catch(()=>{}),u.Target.closeTarget({targetId:s.targetId}).catch(()=>{});return}v===null&&(v=s.targetId,h(`captured main target ${s.targetId} (${s.url})`))}};u.on("Target.targetCreated",s=>{let{targetInfo:i}=s;x(`target +${i.type} ${i.targetId} ${i.url}`),S(i)}),u.on("Target.targetInfoChanged",s=>{let{targetInfo:i}=s;x(`target ~${i.type} ${i.targetId} ${i.url}`),S(i)}),u.on("Runtime.consoleAPICalled",s=>{(async()=>{let{type:i,args:a}=s;if(a[0]?.type==="string"&&String(a[0].value).includes("Chrome Security"))return;let d=i==="warning"?"warn":["log","warn","error","info"].includes(i)?i:"log";x(`console.${d} (${String(a.length)} arg(s))`);let p=await Promise.all(a.map(F=>uo(u,F)));e.broadcast({type:"console-message",level:d,args:p})})().catch(i=>{x(`console serialization failed: ${i.message}`)})}),u.on("disconnect",()=>{m||n!==u||(h("CDP disconnected"),n=null,y(),E())})},E=()=>{if(m||f!==null)return;let u=Math.min(1e3*2**T,1e4),S=T+1;T++,h(`CDP reconnect scheduled in ${String(u)}ms (attempt #${String(S)})`),f=setTimeout(()=>{f=null,(async()=>{let s;try{s=await fr({port:r})}catch{h(`CDP reconnect attempt #${String(S)} failed`),E();return}if(m){try{await s.close()}catch{}return}n=s;try{await b(s),h(`CDP reconnected after ${String(S)} attempt(s)`),T=0}catch{n===s&&(n=null);try{await s.close()}catch{}h(`CDP reconnect attempt #${String(S)} failed during setup`),E()}})()},u)},R=30,C=300;for(let u=0;u<R;u++){await new Promise(S=>setTimeout(S,C)),h(`CDP connect attempt ${String(u+1)}/${String(R)}`);try{let S=await fr({port:r});n=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await b(S),h("CDP connected")}catch{n===S&&(n=null);try{await S.close()}catch{}h("CDP setup failed after connect")}break}catch{if(u===R-1){let S=`CDP unavailable after ${String(R)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(S),e.onWarn?.(S),{kill:()=>{o.kill()}}}}}return n?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),m=!0,f!==null&&(clearTimeout(f),f=null),y(),n!==null){try{n.close()}catch{}n=null}o.kill()}}:{kill:()=>{o.kill()}}}import{useCallback as fo,useState as mo}from"react";function Ze(e){let[t,o]=mo([]),r=fo(n=>{o(l=>[...l,`${new Date().toLocaleTimeString()}: ${n}`].slice(-e))},[e]);return[t,r]}import{useCallback as Qe,useEffect as _t,useState as et}from"react";import{Box as z,Text as B,useInput as go}from"ink";import{jsx as P,jsxs as U}from"react/jsx-runtime";var oe=["apiKey","userId","businessId"],yo={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},je=({text:e})=>P(B,{dimColor:!0,children:e}),tt=({initialMode:e,showProfileManager:t,onComplete:o,onCancel:r})=>{let[n,l]=et(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[v,f]=et(""),[T,m]=et(null),[h,x]=et(void 0),y=Qe(s=>{if(s==="local"){o({mode:"local",credentials:null});return}l({type:"profile-loading"})},[o]),c=Qe(async s=>{if(s===null){l({type:"profile-loading"});let d=await Ie();l({type:"name-entry",nameBuffer:"",existingProfiles:d});return}x(s.isDefault?void 0:s.name),l({type:"loading"});let i=s.isDefault?await Y():await we(s.name),a=i?Math.max(0,K.indexOf(i.environment)):0;l({type:"creds-entry",field:0,values:i??{},envCursor:a})},[]),b=Qe(async(s,i)=>{let a=K[i]??"go",d={apiKey:s.apiKey??"",userId:s.userId??"",businessId:s.businessId??"",environment:a};l({type:"saving"});try{await Xt(h??ne,d),o({mode:"global",credentials:d,...h!==void 0&&{profileName:h}})}catch(p){m(p instanceof Error?p.message:String(p)),l({type:"creds-entry",field:0,values:s,envCursor:i})}},[o,h]);go((s,i)=>{if(i.ctrl&&s==="c"&&process.exit(0),i.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){l({type:"profile-loading"}),E();return}r?.();return}if(n.type==="mode-select"){if(i.upArrow)l({type:"mode-select",cursor:0});else if(i.downArrow)l({type:"mode-select",cursor:1});else if(i.return){let a=n.cursor===0?"global":"local";y(a)}return}if(n.type==="profile-select"){let{profiles:a,cursor:d}=n,p=a.length,F=a.length+1;if(i.upArrow)l({...n,cursor:(d-1+F)%F});else if(i.downArrow)l({...n,cursor:(d+1)%F});else if(i.return)if(d===p)l({type:"name-entry",nameBuffer:"",existingProfiles:a});else{let k=a[d]??a[0];k&&c(k)}return}if(n.type==="name-entry"){let{nameBuffer:a,existingProfiles:d}=n;if(i.backspace||i.delete)l({type:"name-entry",nameBuffer:a.slice(0,-1),existingProfiles:d});else if(i.return){let p=a.trim();if(!p){l({...n,nameError:"Name cannot be empty"});return}if(p===ne){l({...n,nameError:`"${ne}" is reserved`});return}if(d.some(F=>F.name===p)){l({...n,nameError:`Profile "${p}" already exists`});return}x(p),l({type:"creds-entry",field:0,values:{},envCursor:0}),f("")}else s&&!i.ctrl&&!i.meta&&l({type:"name-entry",nameBuffer:a+s,existingProfiles:d});return}if(n.type==="creds-entry"){let{field:a,values:d,envCursor:p}=n;if(a===oe.length){i.leftArrow?l({...n,envCursor:(p-1+K.length)%K.length}):i.rightArrow?l({...n,envCursor:(p+1)%K.length}):i.upArrow?(l({...n,field:a-1}),f(d[oe[a-1]]??"")):i.return&&b(d,p);return}let k=oe[a];if(!k)return;if(i.backspace||i.delete)f(N=>N.slice(0,-1));else if(i.upArrow&&a>0){let N={...d,[k]:v},$=a-1;l({...n,field:$,values:N}),f(N[oe[$]]??"")}else if(i.return||i.tab||i.downArrow){let N={...d,[k]:v},$=a+1;l({...n,field:$,values:N}),$<oe.length?f(N[oe[$]]??""):f("")}else s&&!i.ctrl&&!i.meta&&f(N=>N+s)}});let E=Qe(async()=>{let s=await Ie();l({type:"profile-select",profiles:s,cursor:0})},[]);if(_t(()=>{n.type==="profile-loading"&&E()},[n.type,E]),_t(()=>{e==="global"&&!t&&(async()=>{let s=await Y(),i=s?Math.max(0,K.indexOf(s.environment)):0;l({type:"creds-entry",field:0,values:s??{},envCursor:i})})()},[]),_t(()=>{n.type==="creds-entry"&&n.field===0&&f(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let s=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return P(z,{paddingY:1,paddingX:2,children:P(B,{dimColor:!0,children:s})})}if(n.type==="done")return null;if(n.type==="mode-select")return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(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,a)=>{let d=n.cursor===a;return U(z,{gap:2,children:[P(B,{...d&&{color:"cyan"},children:d?"\u276F":" "}),P(B,{bold:d,...d&&{color:"cyan"},children:i.label}),P(B,{dimColor:!0,children:i.desc})]},i.mode)})]}),P(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:s,cursor:i}=n,a=s.length;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:"Credential profiles"}),s.map((d,p)=>{let F=i===p;return U(z,{gap:2,children:[P(B,{...F&&{color:"cyan"},children:F?"\u276F":" "}),P(B,{bold:F,...F&&{color:"cyan"},children:d.isDefault?"Default":d.name}),P(B,{dimColor:!0,children:d.path})]},d.name)}),U(z,{gap:2,children:[P(B,{...i===a&&{color:"cyan"},children:i===a?"\u276F":" "}),P(B,{bold:i===a,...i===a&&{color:"cyan"},children:"+ Add new profile"})]})]}),P(je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:s,nameError:i}=n;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),P(z,{flexDirection:"column",gap:0,children:P(B,{bold:!0,children:"New credential profile"})}),i&&U(B,{color:"red",children:["Error: ",i]}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:!0,color:"cyan",children:"Profile name"})}),P(B,{color:"cyan",children:">"}),P(B,{children:s}),P(B,{color:"cyan",children:"\u2588"})]}),P(je,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:R,values:C,envCursor:g}=n,u=R===oe.length,S=h??ne;return U(z,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[P(V,{}),U(z,{flexDirection:"column",gap:0,children:[P(B,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),U(B,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:ve]})]}),T&&U(B,{color:"red",children:["Error: ",T]}),U(z,{flexDirection:"column",gap:0,children:[oe.map((s,i)=>{let a=R===i,d=a?v:C[s]??"";return U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:a,...a&&{color:"cyan"},children:yo[s]})}),P(B,{...a&&{color:"cyan"},children:">"}),P(B,{children:d}),a&&P(B,{color:"cyan",children:"\u2588"})]},s)}),U(z,{gap:2,children:[P(z,{width:12,children:P(B,{bold:u,...u&&{color:"cyan"},children:"Environment"})}),P(B,{...u&&{color:"cyan"},children:">"}),P(z,{gap:1,children:K.map((s,i)=>{let a=i===g;return u?P(B,{bold:a,...a&&{color:"cyan"},children:a?`[${s}]`:s},s):P(B,{dimColor:!a,bold:a,children:s},s)})})]})]}),u?P(je,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):P(je,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),U(B,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as j,jsxs as O}from"react/jsx-runtime";var Co=[".kizenapp",".git"],xr=({port:e,pluginDir:t,outputDir:o,credentials:r,credentialMode:n,activeCredentialProfile:l,lastPath:v,debug:f=!1,verbose:T=!1,autoViewer:m=!0})=>{let h=Q(r),x=Q(l),y=Q(v),[c,b]=J("main"),[E,R]=J(n),[C,g]=J("starting"),[u,S]=J(null),[s,i]=Ze(50),[a,d]=Ze(50),[p,F]=Ze(50),[k,N]=J([]),[$,H]=J("pending"),[W,ee]=J(null),[ge,Pe]=J(null),[se,ot]=J(null),[it,st]=J(0),[kt,_r]=J(0),[Er,kr]=J(0),[Ir,Br]=J(0),at=Q(!1),It=Q(!1),Le=Q(null),Te=Q(null),te=Q(new Set),Ae=Q([]),G=Ce(w=>{let L=JSON.stringify(w);if(te.current.size===0){Ae.current=[...Ae.current,L].slice(-50);return}let re=!1;for(let X of te.current)if(X.readyState===1)try{X.send(L)}catch{te.current.delete(X),re=!0}re&&st(te.current.size)},[]),$e=i,lt=Ce(()=>{Le.current?.kill(),Le.current=null,yr({port:e,userDataDir:hr(o,".chrome"),broadcast:G,onWarn:w=>{i(`\u26A0 ${w}`)},...y.current!==void 0&&{path:y.current},...f&&{debugLog:F},...T&&{verbose:!0}}).then(w=>{Le.current=w})},[e,o,G,f,T,F,i]);rt(()=>{let w=()=>{Le.current?.kill()};return process.on("exit",w),()=>{process.off("exit",w)}},[]),xo((w,L)=>{(w==="q"||L.ctrl&&w==="c")&&process.exit(0),w==="c"&&b("editing"),w==="v"&<()},{isActive:c==="main"}),rt(()=>{C!=="running"||It.current||!m||(It.current=!0,lt())},[C,m,lt]);let Dr=Ce(w=>{h.current=w.credentials,x.current=w.profileName,b("main"),R(w.mode);let L=w.profileName;me(o,{credentialMode:w.mode,...L!==void 0&&{activeCredentialProfile:L}}),G({type:"credentials-updated",credentials:w.credentials})},[o,G]),Bt=Ce(w=>{N(L=>[...L,`${new Date().toLocaleTimeString()}: ${St(w)}`].slice(-50)),w.kind==="request"&&(w.fromCache?kr(L=>L+1):Br(L=>L+1)),G({type:"proxy-log",entry:w})},[G]),ae=Ce(w=>{d(w),G({type:"log",message:w})},[d,G]),ct=Ce(()=>{at.current||(at.current=!0,H("building"),ee(null),ae("Build started"),He(t,o).then(({bundleSize:w})=>{ae(`Build finished \u2014 bundle: ${_e(w)}`),H("done"),Pe(new Date),ot(w),ae("Notifying viewers to reload"),G({type:"rebuild"})}).catch(w=>{let L=w instanceof Error?w.message:String(w);ee(L),H("error")}).finally(()=>{at.current=!1}))},[t,o,ae,G]);if(rt(()=>{ct();let w=bo(t,{recursive:!0},(L,re)=>{if(!re)return;let X=re.replace(/\\/g,"/");Co.some(Oe=>X.startsWith(Oe))||(ae(`File change detected: ${re}`),Te.current!==null&&clearTimeout(Te.current),Te.current=setTimeout(ct,150))});return w.on("error",L=>{ae(`File watcher error \u2014 rebuilds have stopped: ${L.message}`)}),()=>{w.close(),Te.current!==null&&clearTimeout(Te.current)}},[t,ct,ae]),rt(()=>{let w=ur();Tt(hr(w,"index.html")).then(L=>{if(!L){S("Viewer not built. Run 'pnpm build:viewer' first."),g("error");return}let re=pr(w,$e,Bt,h,x,o,G,_r,y,t),X=vo(re),Oe=new wo({server:X});return Oe.on("connection",le=>{for(let Nr of Ae.current)le.readyState===1&&le.send(Nr);Ae.current=[],$e("Viewer connected for live reload"),te.current.add(le),st(te.current.size),le.on("close",()=>{te.current.delete(le),st(te.current.size)})}),X.listen(e,"127.0.0.1",()=>{g("running"),$e(`Server started on 127.0.0.1:${String(e)}`)}),X.on("error",le=>{S(le.message),g("error")}),()=>{Oe.close(),X.close()}})},[e,$e,Bt,G,o,t]),c==="editing")return j(tt,{...E!==void 0&&{initialMode:E},showProfileManager:E==="global",onComplete:Dr,onCancel:()=>{b("main")}});let dt=ge!==null?Math.round((Date.now()-ge.getTime())/1e3):null,Rr=dt===null?"":dt<5?" (just now)":` (${String(dt)}s ago)`;return O(q,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(V,{marginBottom:1}),O(q,{flexDirection:"column",children:[O(q,{gap:2,marginBottom:0,children:[j(D,{bold:!0,dimColor:!0,children:"App Build"}),$==="pending"&&j(D,{dimColor:!0,children:"waiting\u2026"}),$==="building"&&O(q,{gap:1,children:[j(Ue,{}),j(D,{children:"Building plugin package\u2026"})]}),$==="done"&&O(q,{gap:1,children:[j(D,{color:"green",children:"\u2713 Built"}),ge!==null&&O(D,{dimColor:!0,children:["at ",ge.toLocaleTimeString(),Rr]}),se!==null&&O(D,{dimColor:!0,children:["\xB7 bundle: ",_e(se)]})]}),$==="error"&&O(D,{color:"red",children:["\u2717 ",W??"unknown error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:a.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&j(D,{dimColor:!0,children:"starting\u2026"}),C==="running"&&O(q,{gap:2,children:[j(D,{color:"green",children:"\u2713 Running"}),O(D,{dimColor:!0,children:["\u25CF ",it," viewer",it!==1?"s":""]})]}),C==="error"&&O(D,{color:"red",children:["\u2717 ",u??"Server error"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:s.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(D,{color:"green",children:"\u2713 Active"}),O(D,{dimColor:!0,children:["\u25CF ",kt," key",kt!==1?"s":""," in the network cache \xB7"," ",Er," hit \xB7 ",Ir," miss"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:k.length===0?j(D,{dimColor:!0,children:" No requests yet."}):k.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),f&&O(q,{marginTop:1,flexDirection:"column",children:[O(q,{gap:2,children:[j(D,{bold:!0,dimColor:!0,children:"CDP Debug"}),O(D,{dimColor:!0,children:["\u25CF ",p.length," event(s)"]})]}),j(q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:p.length===0?j(D,{dimColor:!0,children:" No CDP events yet."}):p.slice(-8).map((w,L)=>j(D,{dimColor:!0,wrap:"truncate",children:w},L))})]}),O(q,{marginTop:1,gap:1,children:[j(D,{dimColor:!0,children:"["}),j(D,{children:"q"}),j(D,{dimColor:!0,children:"] quit ["}),j(D,{children:"c"}),j(D,{dimColor:!0,children:"] credentials ["}),j(D,{children:"v"}),O(D,{dimColor:!0,children:["] ",it===0?"open viewer":"relaunch viewer"]})]})]})};async function br(e){return new Promise(t=>{let o=null,r=l=>{o?.(),t(l)},{unmount:n}=wr(vr(tt,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});o=n})}function Cr(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),r=process.cwd(),n=`${r}/.kizenapp`;xe(r);let l=null,v,f,{lastPath:T}=await De(n);if(t.credentials)l=await Ge(t.credentials);else{let c=await De(n);if(c.credentialMode==="local")v="local";else if(c.credentialMode==="global"){if(v="global",f=c.activeCredentialProfile,f?(l=await we(f),l||(l=await Y(),f=void 0)):l=await Y(),!l){let b=await br("global");l=b.credentials,f=b.profileName}}else{let b=await br();l=b.credentials,v=b.mode,f=b.profileName;let E=b.profileName;await me(n,{credentialMode:b.mode,...E!==void 0&&{activeCredentialProfile:E}})}}let m=t.verbose===!0,h=m||t.debug===!0,x=t.viewer!==!1,{waitUntilExit:y}=wr(vr(xr,{port:o,pluginDir:r,outputDir:n,credentials:l,...v!==void 0&&{credentialMode:v},...f!==void 0&&{activeCredentialProfile:f},...T!==void 0&&{lastPath:T},debug:h,verbose:m,autoViewer:x}),{exitOnCtrlC:!1});await y()})}import{mkdir as So,writeFile as Po,readFile as To}from"fs/promises";import{join as nt}from"path";var _o=new Set(["developer_business_id"]);function Eo(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 r=Object.fromEntries(Object.keys(o.auth_credentials).map(n=>[n,"*****"]));return{...o,auth_credentials:r}}):e}var ko={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Io(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let o of e){let r=o.path.split("/"),n=t;r.forEach((l,v)=>{n.children.has(l)||n.children.set(l,{name:l,children:new Map,isFile:v===r.length-1,filePath:r.slice(0,v+1).join("/")});let f=n.children.get(l);f&&(n=f)})}return t}function Et(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Z(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Pr(e){return`<ul>${[...e.children.values()].sort((r,n)=>r.isFile!==n.isFile?r.isFile?1:-1:r.name.localeCompare(n.name)).map(r=>r.isFile?`<li class="tf"><a href="#${Et(r.filePath)}" data-id="${Et(r.filePath)}">${Z(r.name)}</a></li>`:`<li class="td"><span class="dn">${Z(r.name)}/</span>${Pr(r)}</li>`).join("")}</ul>`}function Bo(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function Do(e){let t;return e.base64Image!==void 0?t=`<img src="data:${ko[Bo(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="${Et(e.path)}"><h2 class="fp">${Z(e.path)}</h2><div class="fb">${t}</div></section>`}function Ro(e,t){let o=Object.fromEntries(Object.entries(e).filter(([m])=>!_o.has(m)).map(([m,h])=>[m,m==="services"?Eo(h):h])),r=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",l=typeof e.description=="string"?e.description:"",v=t.filter(m=>m.path!=="kizen.json"&&m.path!=="plugin-report.html"),f=Pr(Io(v)),T=v.map(Do).join(`
|
|
174
|
+
`);return`<!DOCTYPE html>
|
|
175
|
+
<html lang="en">
|
|
176
|
+
<head>
|
|
177
|
+
<meta charset="UTF-8">
|
|
178
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
179
|
+
<title>${Z(r)} \u2014 Plugin Report</title>
|
|
180
|
+
<style>
|
|
181
|
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
182
|
+
:root{
|
|
183
|
+
--bg:#1e1e2e;--sb:#181825;--hd:#11111b;--tx:#cdd6f4;--mu:#6c7086;
|
|
184
|
+
--ac:#89b4fa;--gr:#a6e3a1;--bd:#313244;--cb:#181825;--sw:280px;
|
|
185
|
+
--fn:'Menlo','Consolas','Monaco',monospace;
|
|
186
|
+
}
|
|
187
|
+
html{font-size:14px}
|
|
188
|
+
body{background:var(--bg);color:var(--tx);font-family:var(--fn);display:flex;flex-direction:column;height:100vh}
|
|
189
|
+
header{background:var(--hd);border-bottom:1px solid var(--bd);padding:14px 20px;flex-shrink:0}
|
|
190
|
+
header h1{font-size:1.1rem;color:var(--ac)}
|
|
191
|
+
header p{color:var(--mu);font-size:.85rem;margin-top:3px}
|
|
192
|
+
.layout{display:flex;flex:1;overflow:hidden}
|
|
193
|
+
nav{width:var(--sw);background:var(--sb);border-right:1px solid var(--bd);overflow-y:auto;padding:12px 0;flex-shrink:0}
|
|
194
|
+
nav a.cfg{display:block;padding:6px 16px;color:var(--gr);text-decoration:none;font-size:.85rem}
|
|
195
|
+
nav a.cfg:hover,nav a.cfg.active{background:var(--bd)}
|
|
196
|
+
nav ul{list-style:none;padding-left:0}
|
|
197
|
+
.td>.dn{display:block;padding:4px 16px;color:var(--mu);font-size:.8rem}
|
|
198
|
+
.td ul{padding-left:14px}
|
|
199
|
+
.tf a{display:block;padding:3px 16px;color:var(--tx);text-decoration:none;font-size:.8rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
200
|
+
.tf a:hover,.tf a.active{background:var(--bd);color:var(--ac)}
|
|
201
|
+
main{flex:1;overflow-y:auto;padding:0 24px 40px}
|
|
202
|
+
section{padding:32px 0;border-bottom:1px solid var(--bd)}
|
|
203
|
+
h2.fp{font-size:.9rem;color:var(--ac);margin-bottom:12px;word-break:break-all}
|
|
204
|
+
#config h2.fp{color:var(--gr)}
|
|
205
|
+
pre{background:var(--cb);border:1px solid var(--bd);border-radius:6px;padding:14px;overflow-x:auto;font-size:.78rem;line-height:1.6;white-space:pre}
|
|
206
|
+
code{font-family:var(--fn)}
|
|
207
|
+
img{border:1px solid var(--bd);border-radius:4px}
|
|
208
|
+
.bin{color:var(--mu);font-style:italic;padding:12px 0}
|
|
209
|
+
::-webkit-scrollbar{width:6px;height:6px}
|
|
210
|
+
::-webkit-scrollbar-track{background:transparent}
|
|
211
|
+
::-webkit-scrollbar-thumb{background:var(--bd);border-radius:3px}
|
|
212
|
+
</style>
|
|
213
|
+
</head>
|
|
214
|
+
<body>
|
|
215
|
+
<header>
|
|
216
|
+
<h1>${Z(r)}${n?` <span style="color:var(--mu);font-size:.8em">v${Z(n)}</span>`:""}</h1>
|
|
217
|
+
${l?`<p>${Z(l)}</p>`:""}
|
|
218
|
+
</header>
|
|
219
|
+
<div class="layout">
|
|
220
|
+
<nav>
|
|
221
|
+
<a href="#config" class="cfg" data-id="config">kizen.json (config)</a>
|
|
222
|
+
${f}
|
|
223
|
+
</nav>
|
|
224
|
+
<main>
|
|
225
|
+
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Z(JSON.stringify(o,null,2))}</code></pre></div></section>
|
|
226
|
+
${T}
|
|
227
|
+
</main>
|
|
228
|
+
</div>
|
|
229
|
+
<script>
|
|
230
|
+
(function(){
|
|
231
|
+
var links=document.querySelectorAll('[data-id]');
|
|
232
|
+
function setActive(id){links.forEach(function(l){l.classList.toggle('active',l.getAttribute('data-id')===id);})}
|
|
233
|
+
links.forEach(function(l){l.addEventListener('click',function(){setActive(this.getAttribute('data-id'));});});
|
|
234
|
+
var obs=new IntersectionObserver(function(es){es.forEach(function(e){if(e.isIntersecting)setActive(e.target.id);});},{rootMargin:'-20% 0px -70% 0px'});
|
|
235
|
+
document.querySelectorAll('section[id]').forEach(function(s){obs.observe(s);});
|
|
236
|
+
})();
|
|
237
|
+
</script>
|
|
238
|
+
</body>
|
|
239
|
+
</html>`}var Sr=nt(fe,"examples");function Tr(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Sr}/<api_name>.html)`).action(async t=>{let o=process.cwd(),r;try{let T=await To(nt(o,"kizen.json"),"utf-8"),m=JSON.parse(T);r=Array.isArray(m)?m[0]:m}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let n=typeof r.api_name=="string"?r.api_name:"plugin",l=t.output??nt(Sr,`${n}.html`),v=await Me(o),f=Ro(r,v);await So(nt(l,".."),{recursive:!0}),await Po(l,f,"utf-8"),console.log(`Plugin report written to: ${l}`)})}var Ao=Fo(jo(Lo(import.meta.url)),"..","package.json"),$o=JSON.parse(No(Ao,"utf-8"));Se.name("appbuilder").description("Kizen plugin app builder").version($o.version);Yt(Se);zt(Se);Cr(Se);Tr(Se);Se.parse();
|
|
174
240
|
//# sourceMappingURL=index.js.map
|