@kizenapps/cli 1.15.0 → 1.16.0-f8f99f7

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 CHANGED
@@ -1,14 +1,128 @@
1
1
  #!/usr/bin/env node
2
- import*as uf from"http";var It="If you're behind a proxy, upgrade Node to 24.14+ or set NODE_USE_ENV_PROXY=1 on a Node version that supports it.",Oa=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],La=e=>e!==void 0&&e!=="",Ee="not-configured";function Zn({env:e,http:t}){return Ee==="applied"||(Oa.some(r=>La(e[r]))?e.NODE_USE_ENV_PROXY==="1"?Ee="already-set":typeof t.setGlobalProxyFromEnv!="function"?Ee="unavailable":(t.setGlobalProxyFromEnv(e),Ee="applied"):Ee="not-configured"),Ee}var Dt=()=>Ee;import{readFileSync as of}from"fs";import{dirname as sf,join as af}from"path";import{fileURLToPath as lf}from"url";import{Command as cf}from"commander";import{createElement as Pd}from"react";import{render as Ed}from"ink";import{PluginValidationError as Td}from"@kizenapps/packager";import{spawn as za}from"child_process";import{platform as Qn}from"process";function Ma(){return Qn==="darwin"?[{cmd:"pbcopy",args:[]}]:Qn==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var Ua=2e3;function Ha(e,{cmd:t,args:r}){return new Promise(o=>{let n;try{n=za(t,r,{stdio:["pipe","ignore","ignore"]})}catch{o(!1);return}let i=n,s=!1;function a(p){s||(s=!0,clearTimeout(l),o(p))}let l=setTimeout(()=>{i.kill(),a(!1)},Ua);l.unref(),i.on("error",()=>{a(!1)}),i.on("close",p=>{a(p===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function At(e){for(let t of Ma())if(await Ha(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as Sl,CONFIG_FILE_NAME as _l,MANIFEST_FILE_NAME as Pl,sanitizeToAPIName as El}from"@kizenapps/packager";import{posix as Va}from"path";var H=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Nt=e=>e instanceof Error&&e.code==="ENOENT",Bt=e=>{let t=Va.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};var Rt=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as Wa}from"crypto";import{mkdir as Ka,readFile as Ja,writeFile as qa}from"fs/promises";import{dirname as Ga,join as ro}from"path";var Z=["go","fmo","staging","integration","test1"];function it(e){return typeof e=="string"?e.trim():""}function st(e){return{apiKey:it(e.apiKey),userId:it(e.userId),businessId:it(e.businessId)}}var $r="appbuilder:",Me=".kizenapp/pushes.json",Ya=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Fr(e){return typeof e=="number"&&Number.isFinite(e)}function $t(e,t,r){return Math.min(Math.max(e,t),r)}function Xa(e){let t={...e};return delete t.custom_object,t}function no(e,t){return`${$r}${e}/${t}`}function oo(e){if(!e.startsWith($r))return null;let t=e.slice($r.length).split("/");if(t.length!==2)return null;let[r,o]=t;return!r||!o?null:{pluginApiName:r,blockApiName:o}}function io(e){let t={};for(let r of Rt){let o=e[r];Fr(o)&&(t[r]=o)}return t}function so(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var ao=e=>Object.entries(e).map(([t,r])=>({name:t,script:r}));function Za(e){return{api_name:e.api_name,name:e.name,type:e.type,...e.script!==""&&{script:e.script},...e.html!==""&&{html:e.html},...e.css!==""&&{css:e.css},event_scripts:ao(e.event_scripts)}}function Or(e){return e.length>0?{views:e.map(Za)}:{}}function lo(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:ao(e.event_scripts),...io(e),...so(e),...Or(t)}}function Qa(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function el(e){let t=0;for(let r of e){let o=r.layout;if(!H(o))continue;let{y:n,h:i}=o;!Fr(n)||!Fr(i)||(t=Math.max(t,n+i))}return t}function tl(e,t,r){let o=$t(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),n=$t(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:r,x:0,y:el(e),w:$t(o,2,12),h:$t(n,1,99)}}function co(e){return{name:no(e.pluginApiName,e.blockApiName),layout:tl(e.dashlets,e.content,e.layoutId),config:Qa({content:e.content,objectId:e.objectId})}}function uo(e,t){let r=e.config;return{config:{...Xa(H(r)?r:{}),content:t}}}function po(e){let t=e.config;return H(t)?t.content:void 0}function Ye(e){let t=e.config;if(!H(t)||t.chart_type!=="html")return!1;let r=t.content;return H(r)&&r.kind==="custom_code"}function fo(e){return e.dashlets.filter(Ye)}function Ft(e){let t=po(e);return H(t)&&typeof t.name=="string"?t.name:e.name}var Te=e=>typeof e=="string"?e:"";function mo(e){return Array.isArray(e)?e.filter(H).map(t=>({name:Te(t.name),script:Te(t.script)})):H(e)?Object.entries(e).map(([t,r])=>({name:t,script:Te(r)})):[]}function jr(e){if(Array.isArray(e))return e.map(jr);if(H(e)){let t={};for(let r of Object.keys(e).sort())t[r]=jr(e[r]);return t}return e}function ho(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function rl(e){return Array.isArray(e)?e.filter(H).map(t=>({api_name:Te(t.api_name),name:ho(t.name),type:Te(t.type),script:Te(t.script),html:Te(t.html),css:Te(t.css),event_scripts:mo(t.event_scripts)})):[]}function Lr(e){let t=H(e)?e:{},r=rl(t.views),o={name:ho(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:mo(t.event_scripts),...io(t),...so(t),...r.length>0&&{views:r}};return Wa("sha256").update(JSON.stringify(jr(o))).digest("hex")}function go(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&Ye(i))return{kind:"map",dashlet:i,entry:t}}let r=no(e.pluginApiName,e.blockApiName),o=e.dashlets.filter(i=>i.name===r&&Ye(i)),[n]=o;return o.length===1&&n?{kind:"name",dashlet:n}:o.length>1?{kind:"ambiguous",dashlets:o}:{kind:"none"}}function yo(e,t){return t?.dashletId!==e.id?!1:Lr(po(e))!==t.contentHash}function zr(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Mr(e,t){return e.find(r=>zr(r,t))}function bo(e,t){let r=e.findIndex(o=>zr(o,t));return r===-1?[...e,t]:e.map((o,n)=>n===r?t:o)}function wo(e,t){return e.filter(r=>!zr(r,t))}function nl(e){if(!H(e))return null;for(let r of Ya)if(typeof e[r]!="string")return null;let t=e;return{environment:t.environment,businessId:it(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var eo=e=>Date.parse(e.pushedAt)||0;function ol(e){let t=new Map;for(let r of e){let o=[r.environment,r.businessId,r.pluginApiName,r.blockApiName].join("\0"),n=t.get(o);(n===void 0||eo(r)>eo(n))&&t.set(o,r)}return[...t.values()]}var to=e=>e instanceof Error?e.message:String(e);async function xo(e){let t;try{t=await Ja(ro(e,Me),"utf8")}catch(o){if(Nt(o))return[];throw new Error(`Couldn't read ${Me}: ${to(o)}. Fix its permissions, or delete it to start a fresh push map.`)}let r;try{r=JSON.parse(t)}catch(o){throw new Error(`${Me} is not valid JSON (${to(o)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(r))throw new Error(`${Me} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return ol(r.map(nl).filter(o=>o!==null))}async function vo(e,t){let r=ro(e,Me);await Ka(Ga(r),{recursive:!0}),await qa(r,`${JSON.stringify(t,null,2)}
3
- `,"utf8")}var il={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},sl={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Ur(e){return il[e]}function ko(e){return sl[e]}function Co(e){let t=e.appBaseUrl.replace(/\/+$/,""),r=e.dashboardId;return e.surface==="homepage"?`${t}/home/${r}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${r}`:`${t}/custom-objects/${e.customObject.id}/charts/${r}`:`${t}/dashboard/${r}`}import{mkdir as ml,writeFile as hl}from"fs/promises";import{join as gl}from"path";import{PluginValidationError as yl,packagePlugin as bl,parseManifestFromFiles as wl,transformDeployablePlugin as xl,transformFiles as vl,validatePluginApp as kl}from"@kizenapps/packager";import{readdir as al,readFile as So}from"fs/promises";import{join as _o,relative as ll}from"path";var cl=new Set([".png",".svg"]),dl=new Set([".kzn"]),ul=new Set([".DS_Store"]),jt=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),pl=8e3;function fl(e){return e.subarray(0,pl).includes(0)}async function Po(e,t){let r=await al(e,{withFileTypes:!0}),o=[];for(let n of r)if(n.isDirectory()){if(jt.has(n.name))continue;o.push(...await Po(_o(e,n.name),t))}else n.isFile()&&(ul.has(n.name)||o.push(_o(e,n.name)));return o}async function Ot(e,{detectBinaryByContent:t=!1}={}){let r=await Po(e,e);return Promise.all(r.map(async o=>{let n=ll(e,o).split("\\").join("/"),i=n.lastIndexOf("."),s=i>=0?n.slice(i).toLowerCase():"";if(cl.has(s)){let l=await So(o);return{path:n,content:"",base64Image:l.toString("base64")}}let a=await So(o);return dl.has(s)||t&&fl(a)?{path:n,content:"",binaryData:a}:{path:n,content:a.toString("utf-8")}}))}var Cl=(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 Hr(e,t){t?.("reading-files");let r=await Ot(e);t?.("validating");let o=kl(r);if(o.some(l=>l.severity==="error"))throw new yl(o);t?.("minifying");let n=await vl(r);t?.("packaging");let i=wl(n),s=bl(n,i),a=Object.values(s).map(xl);return{files:r,deployable:a,issues:o}}async function Lt(e,t,r){await ml(t,{recursive:!0});let{files:o,deployable:n}=await Hr(e,r);r?.("writing-bundle");let i=n.map(p=>{let g=p.release_notes_directory?.replace(/\/$/,""),v=g?o.filter(k=>k.path.startsWith(g+"/")&&k.path.endsWith(".md")&&k.content).map(k=>({version:k.path.slice(k.path.lastIndexOf("/")+1,-3),notes:k.content})).sort((k,f)=>f.version.localeCompare(k.version,void 0,{numeric:!0})):[];return Cl(p,v)}),s=JSON.stringify(i,null,2),a=(p,g)=>p==="allReleaseNotes"?void 0:g,l=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await hl(gl(t,"bundle.json"),s,"utf-8"),{bundleSize:l}}var Io=["min_w","max_w","min_h","max_h"],Do=[["min_w","max_w"],["min_h","max_h"]],zt={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},Tl=Object.keys(zt),Ao=[...Rt,"host_chrome"],Il=["\0","{__ref:"],Vr="views",Wr=class extends Error{reason;available;field;constructor(t,r,o={}){super(r),this.name="BlockExportError",this.reason=t,this.available=o.available??[],this.field=o.field}};function Dl(e){let t=new Set(e.map(r=>r.pluginApiName)).size>1;return e.map(r=>t?`${r.pluginApiName}/${r.apiName}`:r.apiName).join(", ")}function Al(e,t){let r=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),o=r.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(r.length===0)return{ok:!1,reason:"no_blocks",available:o};if(t===void 0){let[s]=r;return r.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:o}}let n=r.filter(({block:s})=>s.api_name===t),[i]=n;return i?n.length>1?{ok:!1,reason:"ambiguous",available:n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:o}}var Eo=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,at=e=>Il.some(t=>e.includes(t));function Nl(e){let t=e,{name:r,script:o,styles:n,event_scripts:i}=t;if(typeof o!="string"||!o.trim())return"script";if(r!==void 0&&typeof r!="string")return"name";if(n!==void 0&&typeof n!="string")return"styles";if(i!==void 0){if(!H(i))return"event_scripts";let g=Object.entries(i).find(([v,k])=>typeof k!="string"||at(v)||at(k));if(g)return`event_scripts.${g[0]}`}let s=[["name",r],["script",o],["styles",n]].find(([,g])=>typeof g=="string"&&at(g));if(s)return s[0];let a=Io.find(g=>t[g]!==void 0&&!Eo(t[g]));if(a)return a;let l=Do.find(([g,v])=>{let k=t[g],f=t[v];return typeof k=="number"&&typeof f=="number"&&k>f});if(l)return l[0];let p=Tl.find(g=>{let v=t[g];if(v===void 0)return!1;if(typeof v!="number"||!Eo(v))return!0;let[k,f]=zt[g],c=t[k],h=t[f];return typeof c=="number"&&v<c||typeof h=="number"&&v>h});if(p)return p;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var Bl=["api_name","name","script","html","css"],To=e=>typeof e!="string"||at(e);function Rl(e){for(let t of e){let r=t,o=typeof r.api_name=="string"?r.api_name:String(r.api_name),n=Bl.find(a=>To(r[a]));if(n)return{view:o,field:n};let i=r.event_scripts;if(!H(i))return{view:o,field:"event_scripts"};let s=Object.entries(i).find(([a,l])=>at(a)||To(l));if(s)return{view:o,field:`event_scripts.${s[0]}`}}}var $l=({view:e,field:t})=>`views.${e}.${t}`,Fl=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,jl=(e,t)=>{if(t==="script")return`Block "${e}" has no script. Add a non-empty script.js to the block directory.`;if(t==="host_chrome")return`Block "${e}" has an invalid host_chrome: it must be true or false.`;let r=Do.find(([o])=>o===t);if(r)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${r[1]}.`;if(Io.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in zt){let[o,n]=zt[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${o} and ${n}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},Ol=({reason:e,available:t},r,o)=>{let n=Dl(t);return e==="no_blocks"?"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.":e==="not_found"?`No block with api_name "${r??""}". Available blocks: ${n}`:r===void 0?`This plugin has several blocks; pass the api_name of the one to ${o}: ${n}`:`More than one plugin has a block with api_name "${r}": ${n}`},Ll=e=>{try{let t=JSON.parse(e);return H(t)?t:void 0}catch{return}},No=e=>{let t=e.find(i=>i.path===Pl),r=t?JSON.parse(t.content):[],o=Array.isArray(r)?r:[r],n=new Map;for(let i of o)H(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&n.set(i.api_name,i.entry);return n},Bo=(e,t)=>{let r=Bt(e);return r===""?t:`${r}/${t}`},Ro=(e,t,r)=>{let o=`${Bo(t,r)}/`,n=new Set,i=[];for(let s of e){if(!s.path.startsWith(o)||s.path.endsWith(".DS_Store"))continue;let[a,l,...p]=s.path.slice(o.length).split("/");if(a&&(n.add(a),l===_l&&p.length===0)){let g=Ll(s.content);g&&i.push([a,g])}}return{directories:n,configs:i}},$o=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:El(t),zl=(e,t)=>{let r=new Map;for(let[o,n]of Ro(e,t,Sl).configs){let i=$o(n,o),s={};for(let a of Ao)n[a]!==void 0&&(s[a]=n[a]);r.set(i,s)}return r},Ml=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([o])=>!Ao.includes(o))),...t});function Ul(e,t){let r=No(t);return e.map(o=>{let n=r.get(o.api_name),i=n===void 0?new Map:zl(t,n);return{...o,artifacts:{...o.artifacts,custom_blocks:o.artifacts.custom_blocks.map(s=>Ml(s,i.get(s.api_name)))}}})}var Fo=(e,t)=>JSON.stringify([String(e),String(t)]),Hl=(e,t)=>{let{directories:r,configs:o}=Ro(e,t,Vr),n=new Map(o),i=new Set;for(let s of r){let a=n.get(s)??{};i.add(Fo($o(a,s),a.name||s))}return i},Vl=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),Wl="appbuilder/views-unmatched";function Kl(e,t){let r=No(t),o={},n=[];for(let i of e){let s=r.get(i.api_name),a=s===void 0?new Set:Hl(t,s),l=i.artifacts.routable_pages.filter(p=>a.has(Fo(p.api_name,p.name))).sort(Vl);l.length!==a.size&&s!==void 0&&n.push({rule:Wl,severity:"warning",message:`Found ${String(a.size)} ${Vr}/ components but matched ${String(l.length)} packaged views; the pushed block carries only the matched ones.`,path:Bo(s,Vr),pluginApiName:i.api_name}),o[i.api_name]=l}return{views:o,warnings:n}}function Jl(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function jo(e){return{...e.block,...Or(e.views)}}async function Kr(e){let{files:t,deployable:r,issues:o}=await Hr(e),n=Kl(r,t);return{deployable:Ul(r,t),views:n.views,warnings:[...o.filter(i=>i.severity==="warning"),...n.warnings]}}function Jr({deployable:e,views:t,warnings:r},o,n){let i=Al(e,o);if(!i.ok)return{ok:!1,reason:i.reason,message:Ol(i,o,n),available:i.available};let s=Nl(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:jl(i.block.api_name,s),available:[],field:s};let a=Jl(t,i.pluginApiName),l=Rl(a);return l!==void 0?{ok:!1,reason:"invalid_block",message:Fl(i.block.api_name,l),available:[],field:$l(l)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:r}}}async function Oo(e,t){let r=Jr(await Kr(e),t,"export");if(!r.ok)throw new Wr(r.reason,r.message,r);return r.value}var qr=(e,t,r)=>`${String(e)} ${e===1?t:r}`,Gr=e=>{let t=new Map;for(let r of e){let o=r.path??r.pluginApiName??"general",n=t.get(o)??[];n.push(r),t.set(o,n)}return t},ql=e=>{let t=e.filter(n=>n.severity==="error").length,r=e.length-t;if(t===0)return`\u26A0 ${qr(r,"validation warning","validation warnings")}`;let o=`\u2717 ${qr(t,"validation error","validation errors")}`;return r===0?o:`${o}, ${qr(r,"warning","warnings")}`};function xe(e){if(e.length===0)return"";let t=[...Gr(e)].map(([r,o])=>[r,...o.map(n=>` ${n.severity==="error"?"\u2717":"\u26A0"} ${n.message} (${n.rule})`)].join(`
4
- `));return[ql(e),...t].join(`
5
-
6
- `)}import{randomUUID as Nc}from"crypto";import{join as Bc}from"path";import{PluginValidationError as Rc}from"@kizenapps/packager";var Lo={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api",integration:"https://integration.kizen.dev/api",test1:"https://test1.kizen.dev/api"},zo={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com",integration:"https://v2.integration.kizen.dev",test1:"https://test1.kizen.dev"},Gl=["go","fmo"];function Yr(e){return Gl.includes(e)}import{mkdir as Yl,readFile as Xl,writeFile as Zl}from"fs/promises";import{join as Mo}from"path";async function he(e){try{let t=await Xl(Mo(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ie(e,t){await Yl(e,{recursive:!0}),await Zl(Mo(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{mkdir as Uo,readFile as Ql,readdir as ec,writeFile as Ho}from"fs/promises";import{homedir as tc}from"os";import{dirname as rc,join as Mt}from"path";var Ue=Mt(tc(),".kizenappbuilder"),ve=Mt(Ue,"credentials.json"),De="credentials";function Vo(e){return Z.includes(e)}function nc(e){return typeof e=="string"?e.trim():e}function oc(e){return Vo(e)?"explicit":e==null||e===""?"missing":"invalid"}function ic(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,r=nc(t.environment);return{credentials:{...st(t),environment:Vo(r)?r:"go"},environmentSource:oc(r)}}async function Ut(e){let t=await Ql(e,"utf-8");return ic(JSON.parse(t))}async function Ae(e){return(await Ut(e)).credentials}async function re(){try{return await Ae(ve)}catch{return null}}async function sc(e){await Uo(rc(ve),{recursive:!0,mode:448}),await Ho(ve,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Wo(e){return Mt(Ue,`${e}.json`)}async function Ne(){let e=[{name:De,path:ve,isDefault:!0}];try{let t=await ec(Ue);for(let r of t){if(!r.endsWith(".json"))continue;let o=r.slice(0,-5);o!==De&&e.push({name:o,path:Mt(Ue,r),isDefault:!1})}}catch{}return e}async function Ko(e,t){if(e===De){await sc(t);return}await Uo(Ue,{recursive:!0,mode:448}),await Ho(Wo(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function ke(e){try{return await Ae(Wo(e))}catch{return null}}async function Jo(){let e=await Ne(),t=await Promise.all(e.map(r=>Ut(r.path).then(()=>!0,()=>!1)));return e.filter((r,o)=>t[o]===!0)}import*as Xe from"fs";import*as qo from"path";var ac=[".kizenapp/",".copilot-docs/"];function ge(e){let t=qo.join(e,".gitignore"),r="";Xe.existsSync(t)&&(r=Xe.readFileSync(t,"utf8"));let o=new Set(r.split(`
7
- `).map(a=>a.trim())),n=ac.filter(a=>!o.has(a)&&!o.has(a.replace(/\/$/,"")));if(n.length===0)return;let i=n.join(`
2
+ import*as Kh from"http";var Xt="If you're behind a proxy, upgrade Node to 24.14+ or set NODE_USE_ENV_PROXY=1 on a Node version that supports it.",ll=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],dl=e=>e!==void 0&&e!=="",Re="not-configured";function jo({env:e,http:t}){return Re==="applied"||(ll.some(n=>dl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Re="already-set":typeof t.setGlobalProxyFromEnv!="function"?Re="unavailable":(t.setGlobalProxyFromEnv(e),Re="applied"):Re="not-configured"),Re}var Zt=()=>Re;import{readFileSync as Lh}from"fs";import{dirname as Mh,join as zh}from"path";import{fileURLToPath as Uh}from"url";import{Command as Hh}from"commander";var dr={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api",integration:"https://integration.kizen.dev/api",test1:"https://test1.kizen.dev/api"},ut=e=>new URL(dr[e]).origin,Lo={go:"https://go.kizen.com",fmo:"https://fmo.kizen.com",staging:"https://v2.staging.kizen.com",integration:"https://v2.integration.kizen.dev",test1:"https://test1.kizen.dev"},ul=["go","fmo"];function ur(e){return ul.includes(e)}import{mkdir as Mo,readFile as pl,readdir as fl,writeFile as zo}from"fs/promises";import{homedir as ml}from"os";import{dirname as hl,join as Qt}from"path";var W=["go","fmo","staging","integration","test1"];function kt(e){return typeof e=="string"?e.trim():""}function Ct(e){return{apiKey:kt(e.apiKey),userId:kt(e.userId),businessId:kt(e.businessId)}}var Se=Qt(ml(),".kizenappbuilder"),Oe=Qt(Se,"credentials.json"),Be="credentials",St=e=>W.includes(e),gl=e=>`Unknown --env "${e}". Use one of: ${W.join(", ")}.`,et=e=>St(e)?{environment:e}:{message:gl(e)};function yl(e){return typeof e=="string"?e.trim():e}function bl(e){return St(e)?"explicit":e==null||e===""?"missing":"invalid"}function wl(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=yl(t.environment);return{credentials:{...Ct(t),environment:St(n)?n:"go"},environmentSource:bl(n)}}async function en(e){let t=await pl(e,"utf-8");return wl(JSON.parse(t))}async function Fe(e){return(await en(e)).credentials}async function oe(){try{return await Fe(Oe)}catch{return null}}async function vl(e){await Mo(hl(Oe),{recursive:!0,mode:448}),await zo(Oe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Uo(e){return Qt(Se,`${e}.json`)}async function je(){let e=[{name:Be,path:Oe,isDefault:!0}];try{let t=await fl(Se);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Be&&e.push({name:r,path:Qt(Se,n),isDefault:!1})}}catch{}return e}async function Ho(e,t){if(e===Be){await vl(t);return}await Mo(Se,{recursive:!0,mode:448}),await zo(Uo(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Pe(e){try{return await Fe(Uo(e))}catch{return null}}async function Vo(){let e=await je(),t=await Promise.all(e.map(n=>en(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}import{posix as xl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tn=(e,t)=>e?.code===t,nn=e=>e instanceof Error&&tn(e,"ENOENT"),tt=async e=>{try{return await e}catch(t){if(tn(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,Le=e=>e instanceof Error?e.message:String(e),Pt=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},rn=e=>{let t=xl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as _l}from"child_process";import{createHash as Tl,randomBytes as Al}from"crypto";import{createServer as Il}from"http";import{platform as Wo}from"process";var kl=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Cl=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${kl.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Sl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Pl=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${Sl[e]}</svg>`,El=`
3
+ :root {
4
+ color-scheme: light dark;
5
+ --page-bg: #F4F9F7;
6
+ --card-bg: #FFFFFF;
7
+ --card-border: #EBEDEF;
8
+ --card-shadow: 0 18px 26px rgba(46, 55, 62, 0.05);
9
+ --text-primary: #343941;
10
+ --text-secondary: #4B525C;
11
+ --brand: #0C595C;
12
+ --success-accent: #3BAA7A;
13
+ --success-bg: #E6FDF1;
14
+ --success-text: #00704A;
15
+ --error-accent: #E9644E;
16
+ --error-bg: #FFF4F2;
17
+ --error-text: #9F3424;
18
+ }
19
+ @media (prefers-color-scheme: dark) {
20
+ :root {
21
+ --page-bg: #15181C;
22
+ --card-bg: #1F2328;
23
+ --card-border: #2E343B;
24
+ --card-shadow: 0 18px 26px rgba(0, 0, 0, 0.35);
25
+ --text-primary: #F1F3F5;
26
+ --text-secondary: #B8BEC6;
27
+ --brand: #FFFFFF;
28
+ --success-accent: #3BAA7A;
29
+ --success-bg: rgba(59, 170, 122, 0.16);
30
+ --success-text: #6FD3A4;
31
+ --error-accent: #E9644E;
32
+ --error-bg: rgba(233, 100, 78, 0.16);
33
+ --error-text: #F59A8A;
34
+ }
35
+ }
36
+ *, *::before, *::after { box-sizing: border-box; }
37
+ html, body { height: 100%; }
38
+ body {
39
+ margin: 0;
40
+ display: flex;
41
+ align-items: center;
42
+ justify-content: center;
43
+ min-height: 100vh;
44
+ padding: 30px 16px;
45
+ background: var(--page-bg);
46
+ color: var(--text-primary);
47
+ font-family: "Proxima Nova", "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
48
+ -webkit-font-smoothing: antialiased;
49
+ -moz-osx-font-smoothing: grayscale;
50
+ }
51
+ main {
52
+ width: 100%;
53
+ max-width: 420px;
54
+ display: flex;
55
+ flex-direction: column;
56
+ align-items: center;
57
+ gap: 20px;
58
+ }
59
+ .wordmark { display: block; width: 95px; height: 30px; color: var(--brand); }
60
+ .card {
61
+ width: 100%;
62
+ padding: 30px 20px;
63
+ background: var(--card-bg);
64
+ border: 1px solid var(--card-border);
65
+ border-radius: 8px;
66
+ box-shadow: var(--card-shadow);
67
+ text-align: center;
68
+ }
69
+ .status {
70
+ display: flex;
71
+ align-items: center;
72
+ justify-content: center;
73
+ width: 56px;
74
+ height: 56px;
75
+ margin: 0 auto 20px;
76
+ border-radius: 50%;
77
+ border: 1.5px solid var(--accent);
78
+ background: var(--tint);
79
+ color: var(--glyph);
80
+ }
81
+ .success { --accent: var(--success-accent); --tint: var(--success-bg); --glyph: var(--success-text); }
82
+ .error { --accent: var(--error-accent); --tint: var(--error-bg); --glyph: var(--error-text); }
83
+ h1 { margin: 0 0 10px; font-size: 22px; line-height: 1.3; font-weight: 600; }
84
+ p { margin: 0; font-size: 15px; line-height: 1.5; color: var(--text-secondary); }
85
+ `.trim().replace(/\n\s*/g,"");function Ko(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${El}</style></head><body><main>${Cl}<section class="card ${e}" data-status="${e}"><div class="status">${Pl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var on="127.0.0.1",pr="/callback",$l=`http://${on}${pr}`,Nl="read write offline_access",Dl="Kizen App Builder CLI",Rl=300*1e3,Me="go",Et=2e4,q=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},ye=e=>e===Me?"appbuilder login":`appbuilder login --env ${e}`,ze=(e,t,n={})=>new q("login_required",`${t} Run \`${ye(e)}\` to sign in${n.again===!0?" again":""}.`),Ol=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function fr(e,t,n,r){let o=AbortSignal.timeout(r);try{let i=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:o});return{res:i,body:Ol(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:Pt(i);throw new q("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Jo(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new q(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new q("server_error",`${e} failed with HTTP ${String(t)}`)}async function Go(e,t,n=Et){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new q("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await fr(t,r,{},n);if(!i.ok)throw o(`failed with HTTP ${String(i.status)}`);if(!O(s))throw o("didn't return valid JSON");if(s.issuer!==e)throw o(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function Yo(e,t,n=Et){let{res:r,body:o}=await fr(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Dl,redirect_uris:[$l],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Jo("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new q("server_error","App registration returned no client_id");return i}var Bl=e=>Tl("sha256").update(e,"ascii").digest("base64url"),mr=()=>Al(32).toString("base64url");function Xo(){let e=mr();return{verifier:e,challenge:Bl(e)}}function Zo(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",Nl),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function hr(e,t,n,r=Et){let{res:o,body:i}=await fr(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw Jo("The token request",o.status,i);let s=O(i)?ie(i.access_token):void 0,a=O(i)?ie(i.refresh_token):void 0;if(!O(i)||s===void 0||a===void 0)throw new q("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var qo=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Ko(n.kind,n.heading,n.text))},Fl={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},jl={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},Ll={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},Ml=e=>{try{return new URL(e??"/",`http://${on}`)}catch{return}};async function Qo(e){let t=e.timeoutMs??Rl,n,r=new Promise((h,v)=>{n={resolve:h,reject:v}});r.catch(()=>{});let o=!1,i,s=Il((h,v)=>{let p=Ml(h.url);if(o||h.method!=="GET"||p?.pathname!==pr){v.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let l=p.searchParams;if(l.get("state")!==e.state){qo(v,400,Ll);return}let w=l.get("error"),C=l.get("error_description"),E=l.get("code")??"",x=w!==null?new q(w,`Kizen denied the sign-in (${w}${C?`: ${C}`:""})`):E?void 0:new q("invalid_callback","The sign-in callback had no authorization code");qo(v,x?400:200,x?jl:Fl),c(x,E)}),a=()=>(i??=new Promise(h=>{clearTimeout(g),s.close(()=>{h()}),s.closeAllConnections()}),i);function c(h,v=""){o||(o=!0,h?n.reject(h):n.resolve({code:v}),a())}await new Promise((h,v)=>{s.once("error",v),s.listen(0,on,()=>{s.off("error",v),h()})});let g=setTimeout(()=>{c(new q("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),u=s.address();return{port:u.port,redirectUri:`http://${on}:${String(u.port)}${pr}`,result:r,close:a}}function ei(e){let[t,n]=Wo==="darwin"?["open",[e]]:Wo==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=_l(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var zl="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Ul="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Hl=e=>ze(e,"Kizen rejected the signed-in session.",{again:!0}).message,Vl="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Kl={authFailed:zl,forbidden:Ul},Wl=100,ql=new Set(["detail","non_field_errors"]),Z=class extends Error{kind;status;hint;constructor(t,n,r={}){super(n),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint}},_t=encodeURIComponent,Tt=(e,t)=>t===void 0?`/dashboards/${_t(e)}/dashlet`:`/dashboards/${_t(e)}/dashlet/${_t(t)}`;function gr(e,t,n){let r=o=>{n.push(t===""?o:`${t}: ${o}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let o=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");o.length>0&&r(o.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&gr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&ql.has(o)?"":t===""?o:`${t}.${o}`;gr(i,s,n)}}function Jl(e){if(typeof e!="object"||e===null)return;let t=[];return gr(e,"",t),t.length>0?t.join("; "):void 0}async function Gl(e){let t=await e.text();if(t==="")return{text:t,json:void 0};try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Yl(e,t,n,r,o){let i=Jl(r),s=`${e} ${t} failed with ${String(n)}${i===void 0?"":`: ${i}`}`;return n===401?new Z("auth_failed",s,{status:n,hint:o.authFailed}):n===403?new Z("forbidden",s,{status:n,hint:o.forbidden}):n===404?new Z("not_found",s,{status:n}):new Z("api_error",s,{status:n})}function ti(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(O(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new Z("api_error",`${e} ${t} returned an unexpected response shape`)}var sn=e=>O(e)?e:{};function ni(e){let t=sn(e);return{business:sn(t.business),team:sn(t.team)}}var Xl=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Zl(e,t){let n=Le(e),r=e instanceof q?Xl.get(e.code):void 0;return r===void 0?new Z("api_error",`Couldn't refresh the ${t} session: ${n}`):new Z(r,n)}function At(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??dr[n],o=e.bearer?{authFailed:Hl(n),forbidden:Vl}:Kl,i=u=>{throw Zl(u,n)},s=async()=>{if(!e.bearer){let{apiKey:v,userId:p,businessId:l}=e.credentials;return{headers:{"X-API-KEY":v,"X-USER-ID":p,"X-BUSINESS-ID":l}}}let{bearer:u}=e,h=await u.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${h}`},retry:async()=>({Authorization:`Bearer ${await u.refreshAccessToken(h).catch(i)}`})}},a=async(u,h,v)=>{let p=/^https?:\/\//.test(h)?h:`${r}${h}`,l=p.startsWith(r)?p.slice(r.length):p,w=async b=>{let f={...b,Accept:"application/json"},d={method:u,headers:f};v!==void 0&&(f["Content-Type"]="application/json",d.body=JSON.stringify(v));try{return await t(p,d)}catch(m){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${Pt(m)}${Zt()==="unavailable"?` ${Xt}`:""}`)}},{headers:C,retry:E}=await s(),x=await w(C);x.status===401&&E&&(await x.body?.cancel().catch(()=>{}),x=await w(await E()));let y,P;try{({text:y,json:P}=await Gl(x))}catch(b){throw new Z("network_error",`${u} ${l}: couldn't read the response: ${Pt(b)}. The request may have been applied; check Kizen before retrying.`,{status:x.status})}if(!x.ok)throw Yl(u,l,x.status,P,o);if(P===void 0&&y!=="")throw new Z("api_error",`${u} ${l} returned a response that is not JSON`,{status:x.status});return P},c=u=>{let h=new URL(r),v=new URL(u,h.origin);if(v.protocol=h.protocol,v.port=h.port,v.username="",v.password="",v.hash="",v.origin!==h.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${v.origin}${v.pathname}`);return v.toString()},g;return{async listDashboards(u,h){let v=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:u});h!==void 0&&v.set("custom_object_id",h);let p=`/dashboards/mine?${v.toString()}`;return ti("GET",p,await a("GET",p)).results},async listCustomObjects(){let u=[],h=new Set,v="/custom-objects?page_size=200";for(;v!==void 0&&!h.has(v)&&h.size<Wl;){h.add(v);let p=ti("GET",v,await a("GET",v));u.push(...p.results),v=typeof p.next=="string"&&p.next!==""?c(p.next):void 0}return u},async getCustomObject(u){let h=`/custom-objects/${_t(u)}`,v=await a("GET",h);if(!O(v)||typeof v.id!="string"||typeof v.fetch_url!="string")throw new Z("api_error",`GET ${h} returned an unexpected response shape`);return v},async getIdentity(){let u=await a("GET","/auth/bootstrap"),{business:h,team:v}=ni(u),p=ie(h.id),l=ie(v.user);if(p===void 0||l===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return g=u,{userId:l,businessId:p,businessName:ie(h.name),fullName:ie(v.full_name),email:ie(v.email)}},async getClientObjectId(){let u=g??await a("GET","/auth/bootstrap"),{business:h}=ni(u);return ie(sn(h.client_object).id)??null},async getDashboard(u){return await a("GET",`/dashboards/${_t(u)}`)},async createDashlet(u,h){return await a("POST",Tt(u),h)},async updateDashlet(u,h,v){return await a("PATCH",Tt(u,h),v)}}}import{randomBytes as ri}from"crypto";import{chmod as Ql,mkdir as ed,open as td,readdir as nd,readFile as yr,rename as oi,rm as ii,unlink as si}from"fs/promises";import{join as It}from"path";var rd="clients.json",od=10*6e4,id=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ai=e=>typeof e=="string"&&id.test(e),an=e=>O(e)&&ai(e.businessId)&&ai(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,Ee=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,pt=e=>{if(an(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function ci(e){let t;try{t=JSON.parse(e)}catch{return}return an(t)}var br=e=>typeof e=="string"?e:void 0;function sd(e,t){let n=an(e);return!O(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:br(e.businessName),fullName:br(e.fullName),email:br(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ue(e=Se){let t=It(e,"oauth"),n=x=>It(t,`${x}.json`),r=(x,y)=>It(t,`${x}.${pt(y)}.json`),o=It(t,rd),i=(x,y)=>{let P=`${x}.`;if(!y.startsWith(P)||!y.endsWith(".json"))return;let b=y.slice(P.length,-5).split(".");if(b.length!==2)return;let[f,d]=b;return an({businessId:f,userId:d})},s=async()=>await tt(nd(t))??[],a=async()=>{await ed(t,{recursive:!0,mode:448}),await Ql(t,448)},c=async(x,y)=>{await a();let P=`${x}.${ri(6).toString("hex")}.tmp`;try{let b=await td(P,"wx",384);try{await b.writeFile(JSON.stringify(y,null,2),"utf-8"),await b.sync()}finally{await b.close()}await oi(P,x)}catch(b){throw await ii(P,{force:!0}),b}},g=(x,y)=>ze(x,`The saved ${x} session at ${y} can't be read.`,{again:!0}),u=async x=>{try{let y=new RegExp(`^${x}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let P of await s()){let b=y.exec(P)?.[1];b!==void 0&&Date.now()-Number(b)>od&&await tt(si(It(t,P)))}}catch{}},h=async()=>{let x;try{x=JSON.parse(await tt(yr(o,"utf-8"))??"{}")}catch(y){if(y instanceof SyntaxError)return{};throw y}return O(x)?x:{}},v=async(x,y)=>{try{return await tt(yr(y,"utf-8"))}catch{throw g(x,y)}},p=async(x,y)=>{let P=r(x,y),b=await v(x,P);if(b===void 0)return null;try{let f=sd(JSON.parse(b),x);if(f!==null&&Ee(f,y))return f}catch{}throw g(x,P)},l=async x=>{let y=n(x),P=await v(x,y);if(P===void 0)return;let b=ci(P);if(b===void 0)throw g(x,y);return b},w=async x=>{let y=await l(x);return y===void 0?null:p(x,y)},C=async x=>{let y=n(x),P=`${y}.${String(Date.now())}-${ri(6).toString("hex")}.signout`;if(await tt(oi(y,P).then(()=>!0))===!0)try{return{account:ci(await yr(P,"utf-8"))}}catch{return{account:void 0}}finally{await ii(P,{force:!0})}},E=async(x,y)=>await tt(si(r(x,y)).then(()=>!0))??!1;return{dir:t,sessionPath:n,accountPath:r,readSession:w,readAccount:p,async listAccounts(x){let y;try{y=await l(x)}catch{}let P=(await s()).map(d=>i(x,d)).filter(d=>d!==void 0),b=await Promise.all(P.map(async d=>{let m;try{let k=await p(x,d);if(k===null)return;m=k}catch(k){if(!(k instanceof q&&k.code==="login_required"))throw k}return{account:d,session:m,current:y!==void 0&&Ee(y,d)}})),f=d=>(d.session?.businessName??d.account.businessId).toLowerCase();return b.filter(d=>d!==void 0).sort((d,m)=>f(d).localeCompare(f(m))||pt(d.account).localeCompare(pt(m.account)))},async writeSession(x){await c(r(x.environment,x),x)},async setCurrent(x,y){let{businessId:P,userId:b}=y;await c(n(x),{businessId:P,userId:b}),await u(x)},async deleteSession(x,y){return E(x,y)},async signOut(x){let y=await C(x),P=y!==void 0;return y?.account!==void 0&&(P=await E(x,y.account)),await u(x),P},async removeAccount(x,y){let P=!1,b;try{b=await l(x)}catch{}b!==void 0&&Ee(b,y)&&(P=await C(x)!==void 0);let f=await E(x,y);return await u(x),{removed:f,current:P}},async signOutAll(x){let y=await C(x),P=y!==void 0&&y.account===void 0,b=0;for(let f of await s()){let d=i(x,f);d!==void 0&&await E(x,d)&&(b+=1,P||=y?.account!==void 0&&Ee(y.account,d))}return await u(x),{signedIn:P,removed:b}},async listSessions(){return(await Promise.all(W.map(async y=>{try{return await w(y)===null?void 0:y}catch(P){if(P instanceof q&&P.code==="login_required")return y;throw P}}))).filter(y=>y!==void 0)},async readClientId(x){let y=(await h())[x];return O(y)?ie(y.clientId):void 0},async writeClientId(x,y){await c(o,{...await h(),[x]:{clientId:y}})},async forgetClientId(x){let y=await h();x in y&&await c(o,Object.fromEntries(Object.entries(y).filter(([P])=>P!==x)))}}}var ad=6e4,cn=class extends q{},li=(e,t)=>fetch(e,t),di=()=>Date.now(),ui=(e,t,n)=>({store:e,fetch:li,now:di,print:t,openBrowser:ei,startLoopbackServer:Qo,identify:n}),cd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(ze(e,`Kizen rejected the new ${e} sign-in.`))}),ln=e=>ze(e,`You're not signed in to ${e}.`),ld=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),pi=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),dd=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function ud(e,t,n,r){let{verifier:o,challenge:i}=Xo(),s=mr(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=Zo(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:g}=await a.result;return await hr(e.tokenEndpoint,{grant_type:"authorization_code",code:g,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function wr(e,t,n={}){let r=dd(e,n.interactive??!0),o=await Go(ut(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await Yo(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await ud(o,s,t,r)}catch(h){throw h instanceof q&&h.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new q("timeout",`${h.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ye(e)}\` again.`)):h}let c=await t.identify(cd(e,a.accessToken)),g={businessId:c.businessId,userId:c.userId},u=pi({environment:e,...g,...ld(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(u),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,g)===null)throw ln(e);return u}if(await t.store.setCurrent(e,g),await t.store.readSession(e)===null)throw ln(e);return u}async function fi(e,t,n){try{await n.identify(n.provider)}catch(o){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw o}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw ln(e);return r}function pd(e,t){let n,r=t.account,o=c=>c.expiresAt-t.now()>ad,i=async()=>{let c=t.account===void 0?await t.store.readSession(e):await t.store.readAccount(e,t.account);if(c===null)throw ln(e);if(r??={businessId:c.businessId,userId:c.userId},!Ee(c,r))throw new cn("login_required",`The ${e} sign-in changed while this command was running. Run it again.`);return c},s=async(c,g)=>{let u=await i();if(u.accessToken!==c&&o(u))return u.accessToken;let h=g??t.now()+(t.requestTimeoutMs??Et),v=async()=>{let E=await i();return{stored:E,rotated:E.refreshToken!==u.refreshToken}},p=h-t.now();if(p<=0)return u.accessToken;let l;try{l=await hr(u.tokenEndpoint,{grant_type:"refresh_token",refresh_token:u.refreshToken,client_id:u.clientId},t.fetch,p)}catch(E){if(E instanceof q&&(E.code==="invalid_grant"||E.code==="invalid_client")){let{stored:x,rotated:y}=await v();if(y)return o(x)||g!==void 0?x.accessToken:s(x.accessToken,h);if(await t.store.deleteSession(e,u)&&E.code==="invalid_client")try{await t.store.readClientId(u.issuer)===u.clientId&&await t.store.forgetClientId(u.issuer)}catch{}throw ze(e,`The ${e} session is no longer valid.`)}throw E}let w=pi(u,l,t.now()),C;try{({rotated:C}=await v())}catch(E){if(E instanceof cn){let x=await t.store.readAccount(e,u).catch(()=>null);x!==null&&x.refreshToken===u.refreshToken&&await t.store.writeSession(w).catch(()=>{})}throw E}return C||await t.store.writeSession(w),w.accessToken},a=c=>(n??=s(c).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let c=await i();return o(c)?c.accessToken:a(c.accessToken)},refreshAccessToken:a}}var dn=(e,t,n={})=>pd(e,{store:t,now:di,...n,fetch:n.fetch??li}),fd=`You're not signed in. Run \`${ye(Me)}\` (add \`--env <env>\` to sign in to an environment other than ${Me}).`;async function nt(e,t){if(e!==void 0){let{environment:o,message:i}=et(e);return o===void 0?{ok:!1,problem:"unknown_environment",message:i}:{ok:!0,environment:o}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:fd}:{ok:!0,environment:r}}var be=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var md=5e3,hd=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function hi(e=Ue(),t){let n=(i,s)=>dn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>At({bearer:i}).getIdentity();return{store:e,loginDeps:ui(e,i=>{r(`${i}
86
+ `)},o),identify:o,tokenProvider:n,isInteractive:()=>hd(process.stdin,process.stdout),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:md},processEnv:process.env,writeStdout:i=>{process.stdout.write(i)},writeStderr:r,setExitCode:i=>{process.exitCode=i}}}function gi(e){let{environment:t,message:n}=et(e);if(t===void 0)throw new Error(n);return t}async function yi(e,t){let n=await nt(e,()=>t.listSessions());if(!n.ok)throw new Error(n.message);return n.environment}var un=(e,t)=>e?`${e} (${t})`:t,bi=(e,t)=>{let n=[t.fullName,t.email&&`<${t.email}>`].filter(Boolean).join(" ");return`Environment: ${e}
87
+ User: ${n===""?t.userId:`${n} (${t.userId})`}
88
+ Business: ${un(t.businessName,t.businessId)}
89
+ `};function wi(e,t,{prefix:n="Error",oneLine:r=!1}={}){let o=Le(t),i=t instanceof Z&&t.hint!==void 0?`
90
+ ${t.hint}`:"";e.writeStderr(`${n}: ${r?o.replace(/\s+/g," ").trim():`${o}${i}`}
91
+ `),e.setExitCode(1)}var xr=e=>async(t,n)=>{try{await e(t,n)}catch(r){wi(n,r)}},vr=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
92
+ `),e.writeStdout(bi(t.environment,t))},rt="browser",_e=({account:e,session:t})=>`${un(t?.businessName,e.businessId)} ${t?.email??`user ${e.userId}`}${t===void 0?" (can't be read)":""}`,gd=e=>[...e.map(({account:t,session:n,current:r})=>({key:pt(t),label:un(n?.businessName,t.businessId),description:[n?.email??t.userId,n===void 0?"(can't be read)":"",r?"(current)":""].filter(Boolean).join(" ")})),{key:rt,label:"Sign in with the browser"}],yd=(e,t)=>e===rt?rt:t.find(({account:n})=>pt(n)===e),bd=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function vi(e,t,n){let r=e.filter(({account:a})=>a.businessId===t),o=r.length>0?r:e.filter(({session:a})=>a?.businessName?.toLowerCase()===t.toLowerCase()),i=n===void 0?o:o.filter(({account:a})=>a.userId===n),[s]=i;return i.length===1&&s!==void 0?{kind:"one",account:s}:i.length===0?{kind:"none",candidates:[...e]}:{kind:"several",candidates:i}}var mi=e=>e.map(t=>`
93
+ ${_e(t)}`).join(""),ft=({business:e,user:t})=>`--business ${be(e)}${t===void 0?"":` --user ${be(t)}`}`;function xi(e,t,n,r=vi(t,n.business,n.user)){if(r.kind==="one")return r.account;let o=ft(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${o}. Saved accounts:${mi(r.candidates)}`);let[i]=r.candidates;throw i!==void 0&&r.candidates.every(({account:a})=>a.businessId===i.account.businessId)?new Error(`${o} matches several saved ${e} users of the same business. Pass --user too, for example \`${ft({business:i.account.businessId,user:i.account.userId})}\`:${r.candidates.map(a=>`
94
+ --user ${be(a.account.userId)}: ${_e(a)}`).join("")}`):new Error(`${o} matches several saved ${e} accounts. Pass one of these business ids instead:${mi(r.candidates)}`)}function wd(e,t,n,r){if(n){r.writeStdout(`${JSON.stringify(t.map(({account:o,session:i,current:s})=>({businessId:o.businessId,userId:o.userId,businessName:i?.businessName??null,fullName:i?.fullName??null,email:i?.email??null,current:s,readable:i!==void 0})))}
95
+ `);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
96
+ `);return}for(let o of t)r.writeStdout(`${_e(o)}${o.current?" (current)":""}
97
+ `)}async function vd(e,t,n,r){if(t.business!==void 0){let o={business:t.business,user:t.user},i=vi(n,o.business,o.user);return i.kind==="none"?{kind:"not_saved",request:o}:xi(e,n,o,i)}return n.length===0?rt:r.pickAccount===void 0||!r.isInteractive()?(r.writeStderr(`Saved accounts for ${e} exist; pass --business <id> to switch without the browser, or --list to see them.
98
+ `),rt):yd(await r.pickAccount(`Sign in to ${e}`,gd(n)),n)}function xd(e,t,n){let r=t.kind==="expired"?`The saved sign-in for ${_e(t.account)} has expired and was removed.`:`There's no saved ${e} account for ${JSON.stringify(t.request.business)}${t.request.user===void 0?"":` with user ${JSON.stringify(t.request.user)}`}.`,o=t.kind==="expired"?un(t.account.session?.businessName&&JSON.stringify(t.account.session.businessName),t.account.account.businessId):JSON.stringify(t.request.business),i=t.kind==="expired"?t.account.session?.email??t.account.account.userId:t.request.user,s=`the business ${o}${i===void 0?"":`, signed in as ${i}`}`;return n?`${r}
99
+ A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
100
+ `:`${r}
101
+ Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
102
+ `}function kd(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>Ee(r,n),requested:_e(t.account),retry:`${ye(e)} ${ft({business:n.businessId,user:n.userId})}`}}return{accepts:n=>bd(n,t.request),requested:ft(t.request),retry:`${ye(e)} ${ft(t.request)}`}}var ki=xr(async(e,t)=>{let n=gi(e.env??Me);if(e.json===!0&&e.list!==!0)throw new Error("--json only applies with --list.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");if(e.list===!0&&e.business!==void 0)throw new Error("--list can't be combined with --business.");let r=await t.store.listAccounts(n);if(e.list===!0){wd(n,r,e.json===!0,t);return}let o=await vd(n,e,r,t);if(o===void 0){t.writeStderr(`Cancelled.
103
+ `),t.setExitCode(1);return}if(o!==rt&&!("kind"in o)){let w=o,{account:C}=w;t.writeStderr(`Switching to ${_e(w)} on ${n}.
104
+ `);let E=await fi(n,C,{store:t.store,provider:t.tokenProvider(n,{account:C}),identify:t.identify});if(E!==void 0){vr(t,E);return}o={kind:"expired",account:w}}if(o===rt){t.writeStderr(`Signing in to ${n}.
105
+ `),vr(t,await wr(n,t.loginDeps,{interactive:t.isInteractive()}));return}let i=t.isInteractive(),s=kd(n,o);t.writeStderr(xd(n,o,i));let a=await wr(n,t.loginDeps,{makeCurrent:s.accepts,interactive:i});if(s.accepts(a)){vr(t,a);return}let c=await t.store.readSession(n).catch(()=>null),g=c!==null&&Ee(c,a),u=_e({account:a,session:a,current:!1}),h=i?"You":"The user",v=g?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,p=g?"":`To use it, run \`${ye(n)} ${ft({business:a.businessId,user:a.userId})}\`. `,l=i?"To try again":"To have them try again";t.writeStderr(`${h} signed in as ${u}, not ${s.requested}. ${v}
106
+ ${p}${l}, run \`${s.retry}\`.
107
+ `),t.setExitCode(1)}),Ci=xr(async(e,t)=>{if(e.all===!0&&e.business!==void 0)throw new Error("--all can't be combined with --business.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");let n=await nt(e.env,()=>t.store.listSessions());if(!n.ok){if(n.problem!=="not_signed_in")throw new Error(n.message);if(e.business!==void 0)throw new Error("Pass --env <env> with --business to remove a saved account.");if(e.all===!0)throw new Error("Pass --env <env> with --all to remove every saved account.");t.writeStdout(`Not signed in.
108
+ `);return}let{environment:r}=n;if(e.business!==void 0){let i=await t.store.listAccounts(r);if(i.length===0){t.writeStdout(`No saved accounts for ${r}.
109
+ `);return}let s=xi(r,i,{business:e.business,user:e.user}),{removed:a,current:c}=await t.store.removeAccount(r,s.account);t.writeStdout(a||c?`Removed the saved ${r} account ${_e(s)} from this machine.${c?` You're no longer signed in to ${r}.`:""}
110
+ `:`No saved ${r} account ${_e(s)}.
111
+ `);return}if(e.all===!0){let{signedIn:i,removed:s}=await t.store.signOutAll(r);t.writeStdout(i||s>0?`Signed out of ${r}. Removed ${String(s)} saved ${s===1?"account":"accounts"} from this machine.
112
+ `:`No saved accounts for ${r}.
113
+ `);return}let o=await t.store.signOut(r);t.writeStdout(o?`Signed out of ${r}. The session was removed from this machine.
114
+ `:`Not signed in to ${r}.
115
+ `)}),Si=xr(async(e,t)=>{let n=await yi(e.env,t.store);t.writeStdout(bi(n,await t.identify(t.tokenProvider(n))))});function Cd(e){let t;try{t=new URL(e).origin}catch{throw new Error("CLAUDE_CODE_MCP_SERVER_URL is not a valid URL, so auth-header won't send a token.")}let n=W.find(r=>ut(r)===t);if(n===void 0)throw new Error(`No Kizen environment matches the MCP server ${t}, so auth-header won't send it a token.`);return{environment:n,origin:t}}async function Sd(e,t){let n=e===void 0?void 0:gi(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let o=Cd(r);if(n!==void 0&&n!==o.environment)throw new Error(`--env ${n} doesn't match the MCP server ${o.origin} (${o.environment}), so auth-header won't send it a token.`);return o.environment}return n??yi(void 0,t.store)}var Pi=async(e,t)=>{let n;try{let r=await Sd(e.env,t),{requestTimeoutMs:o}=t.authHeaderTimeouts,i=await t.tokenProvider(r,{requestTimeoutMs:o}).getAccessToken();n=`${JSON.stringify({Authorization:`Bearer ${i}`})}
116
+ `}catch(r){wi(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};import{render as Id}from"ink";import{useMemo as Pd,useState as Ed}from"react";import{Box as kr,Text as ot,useInput as _d}from"ink";var pn=(e,t,n)=>Math.min(Math.max(e,t),n);function fn(e,t,n,r={}){if(t<=0)return 0;let o=pn(Math.trunc(e)||0,0,t-1),i=c=>r.disabled?.[c]!==!0;if(n===0)return o;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let g=((o+s*c)%t+t)%t;if(i(g))return g}return o}let a=pn(o+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(i(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(i(c))return c;return o}function Ei(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let o=pn(Math.trunc(e)||0,0,t-1),i=pn(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as it,jsxs as Sr}from"react/jsx-runtime";var Td="\u2191/\u2193 to move, Enter to select, Esc to cancel",Cr=10,Ad=e=>{let t=fn(0,e.length,0);if(e[t]?.disabled!==!0)return t;let n=e.findIndex(r=>r.disabled!==!0);return n===-1?t:n},Te=({title:e,items:t,onSelect:n,onCancel:r,hint:o=Td})=>{let[i,s]=Ed(()=>Ad(t)),a=Pd(()=>t.map(p=>p.disabled===!0),[t]),c=fn(i,t.length,0);_d((p,l)=>{let w=C=>{s(fn(c,t.length,C,{disabled:a}))};if(l.upArrow||p==="k")w(-1);else if(l.downArrow||p==="j")w(1);else if(l.pageUp)w(-Cr);else if(l.pageDown)w(Cr);else if(l.return){let C=t[c];C!==void 0&&C.disabled!==!0&&n(C,c)}else l.escape&&r?.()});let{start:g,end:u}=Ei(c,t.length,Cr),h=g,v=t.length-u;return Sr(kr,{flexDirection:"column",gap:1,children:[it(ot,{bold:!0,children:e}),Sr(kr,{flexDirection:"column",children:[h>0&&it(ot,{dimColor:!0,children:` \u2191 ${String(h)} more`}),t.slice(g,u).map((p,l)=>{let C=g+l===c,E=p.disabled===!0,x=C&&!E;return Sr(kr,{gap:2,children:[it(ot,{...x&&{color:"cyan"},dimColor:E,children:C?"\u276F":" "}),it(ot,{bold:x,dimColor:E,...x&&{color:"cyan"},children:p.label}),p.description!==void 0&&it(ot,{dimColor:!0,children:p.description})]},p.key)}),v>0&&it(ot,{dimColor:!0,children:` \u2193 ${String(v)} more`})]}),it(ot,{dimColor:!0,children:o})]})};import{jsx as $d}from"react/jsx-runtime";var _i=async(e,t)=>{let n,r=Id($d(Te,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var Nd=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"]],run:ki},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Ci},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one)",run:Si},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",run:Pi}];function Ti(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of Nd){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of o)s.option(a,c);s.action(async a=>{await i(a,hi(void 0,_i))})}}import{createElement as cf}from"react";import{render as lf}from"ink";import{PluginValidationError as df}from"@kizenapps/packager";import{spawn as Dd}from"child_process";import{platform as Ai}from"process";function Rd(){return Ai==="darwin"?[{cmd:"pbcopy",args:[]}]:Ai==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var Od=2e3;function Bd(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=Dd(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(g){s||(s=!0,clearTimeout(c),r(g))}let c=setTimeout(()=>{i.kill(),a(!1)},Od);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",g=>{a(g===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function mn(e){for(let t of Rd())if(await Bd(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as gu,CONFIG_FILE_NAME as yu,MANIFEST_FILE_NAME as bu,sanitizeToAPIName as wu}from"@kizenapps/packager";var hn=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as Fd}from"crypto";import{mkdir as jd,readFile as Ld,writeFile as Md}from"fs/promises";import{dirname as zd,join as Ni}from"path";var Pr="appbuilder:",st=".kizenapp/pushes.json",Ud=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function Er(e){return typeof e=="number"&&Number.isFinite(e)}function gn(e,t,n){return Math.min(Math.max(e,t),n)}function Hd(e){let t={...e};return delete t.custom_object,t}function Di(e,t){return`${Pr}${e}/${t}`}function Ri(e){if(!e.startsWith(Pr))return null;let t=e.slice(Pr.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Oi(e){let t={};for(let n of hn){let r=e[n];Er(r)&&(t[n]=r)}return t}function Bi(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Fi=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function Vd(e){return{api_name:e.api_name,name:e.name,type:e.type,...e.script!==""&&{script:e.script},...e.html!==""&&{html:e.html},...e.css!==""&&{css:e.css},event_scripts:Fi(e.event_scripts)}}function Tr(e){return e.length>0?{views:e.map(Vd)}:{}}function ji(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Fi(e.event_scripts),...Oi(e),...Bi(e),...Tr(t)}}function Kd(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function Wd(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!Er(o)||!Er(i)||(t=Math.max(t,o+i))}return t}function qd(e,t,n){let r=gn(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=gn(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:Wd(e),w:gn(r,2,12),h:gn(o,1,99)}}function Li(e){return{name:Di(e.pluginApiName,e.blockApiName),layout:qd(e.dashlets,e.content,e.layoutId),config:Kd({content:e.content,objectId:e.objectId})}}function Mi(e,t){let n=e.config;return{config:{...Hd(O(n)?n:{}),content:t}}}function zi(e){let t=e.config;return O(t)?t.content:void 0}function mt(e){let t=e.config;if(!O(t)||t.chart_type!=="html")return!1;let n=t.content;return O(n)&&n.kind==="custom_code"}function Ui(e){return e.dashlets.filter(mt)}function yn(e){let t=zi(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var He=e=>typeof e=="string"?e:"";function Hi(e){return Array.isArray(e)?e.filter(O).map(t=>({name:He(t.name),script:He(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:He(n)})):[]}function _r(e){if(Array.isArray(e))return e.map(_r);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=_r(e[n]);return t}return e}function Vi(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Jd(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:He(t.api_name),name:Vi(t.name),type:He(t.type),script:He(t.script),html:He(t.html),css:He(t.css),event_scripts:Hi(t.event_scripts)})):[]}function Ar(e){let t=O(e)?e:{},n=Jd(t.views),r={name:Vi(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Hi(t.event_scripts),...Oi(t),...Bi(t),...n.length>0&&{views:n}};return Fd("sha256").update(JSON.stringify(_r(r))).digest("hex")}function Ki(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&mt(i))return{kind:"map",dashlet:i,entry:t}}let n=Di(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(i=>i.name===n&&mt(i)),[o]=r;return r.length===1&&o?{kind:"name",dashlet:o}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function Wi(e,t){return t?.dashletId!==e.id?!1:Ar(zi(e))!==t.contentHash}function Ir(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function $r(e,t){return e.find(n=>Ir(n,t))}function qi(e,t){let n=e.findIndex(r=>Ir(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Ji(e,t){return e.filter(n=>!Ir(n,t))}function Gd(e){if(!O(e))return null;for(let n of Ud)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:kt(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var Ii=e=>Date.parse(e.pushedAt)||0;function Yd(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),o=t.get(r);(o===void 0||Ii(n)>Ii(o))&&t.set(r,n)}return[...t.values()]}var $i=e=>e instanceof Error?e.message:String(e);async function Gi(e){let t;try{t=await Ld(Ni(e,st),"utf8")}catch(r){if(nn(r))return[];throw new Error(`Couldn't read ${st}: ${$i(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${st} is not valid JSON (${$i(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${st} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return Yd(n.map(Gd).filter(r=>r!==null))}async function Yi(e,t){let n=Ni(e,st);await jd(zd(n),{recursive:!0}),await Md(n,`${JSON.stringify(t,null,2)}
117
+ `,"utf8")}var Xd={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},Zd={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Nr(e){return Xd[e]}function Xi(e){return Zd[e]}function Zi(e){let t=e.appBaseUrl.replace(/\/+$/,""),n=e.dashboardId;return e.surface==="homepage"?`${t}/home/${n}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${n}`:`${t}/custom-objects/${e.customObject.id}/charts/${n}`:`${t}/dashboard/${n}`}import{mkdir as su,writeFile as au}from"fs/promises";import{join as cu}from"path";import{PluginValidationError as lu,packagePlugin as du,parseManifestFromFiles as uu,transformDeployablePlugin as pu,transformFiles as fu,validatePluginApp as mu}from"@kizenapps/packager";import{readdir as Qd,readFile as Qi}from"fs/promises";import{join as es,relative as eu}from"path";var tu=new Set([".png",".svg"]),nu=new Set([".kzn"]),ru=new Set([".DS_Store"]),bn=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),ou=8e3;function iu(e){return e.subarray(0,ou).includes(0)}async function ts(e,t){let n=await Qd(e,{withFileTypes:!0}),r=[];for(let o of n)if(o.isDirectory()){if(bn.has(o.name))continue;r.push(...await ts(es(e,o.name),t))}else o.isFile()&&(ru.has(o.name)||r.push(es(e,o.name)));return r}async function wn(e,{detectBinaryByContent:t=!1}={}){let n=await ts(e,e);return Promise.all(n.map(async r=>{let o=eu(e,r).split("\\").join("/"),i=o.lastIndexOf("."),s=i>=0?o.slice(i).toLowerCase():"";if(tu.has(s)){let c=await Qi(r);return{path:o,content:"",base64Image:c.toString("base64")}}let a=await Qi(r);return nu.has(s)||t&&iu(a)?{path:o,content:"",binaryData:a}:{path:o,content:a.toString("utf-8")}}))}var hu=(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 Dr(e,t){t?.("reading-files");let n=await wn(e);t?.("validating");let r=mu(n);if(r.some(c=>c.severity==="error"))throw new lu(r);t?.("minifying");let o=await fu(n);t?.("packaging");let i=uu(o),s=du(o,i),a=Object.values(s).map(pu);return{files:n,deployable:a,issues:r}}async function vn(e,t,n){await su(t,{recursive:!0});let{files:r,deployable:o}=await Dr(e,n);n?.("writing-bundle");let i=o.map(g=>{let u=g.release_notes_directory?.replace(/\/$/,""),h=u?r.filter(v=>v.path.startsWith(u+"/")&&v.path.endsWith(".md")&&v.content).map(v=>({version:v.path.slice(v.path.lastIndexOf("/")+1,-3),notes:v.content})).sort((v,p)=>p.version.localeCompare(v.version,void 0,{numeric:!0})):[];return hu(g,h)}),s=JSON.stringify(i,null,2),a=(g,u)=>g==="allReleaseNotes"?void 0:u,c=Buffer.byteLength(JSON.stringify(i,a,2),"utf-8");return await au(cu(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var os=["min_w","max_w","min_h","max_h"],is=[["min_w","max_w"],["min_h","max_h"]],xn={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},vu=Object.keys(xn),ss=[...hn,"host_chrome"],xu=["\0","{__ref:"],Rr="views",Or=class extends Error{reason;available;field;constructor(t,n,r={}){super(n),this.name="BlockExportError",this.reason=t,this.available=r.available??[],this.field=r.field}};function ku(e){let t=new Set(e.map(n=>n.pluginApiName)).size>1;return e.map(n=>t?`${n.pluginApiName}/${n.apiName}`:n.apiName).join(", ")}function Cu(e,t){let n=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),r=n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(n.length===0)return{ok:!1,reason:"no_blocks",available:r};if(t===void 0){let[s]=n;return n.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:r}}let o=n.filter(({block:s})=>s.api_name===t),[i]=o;return i?o.length>1?{ok:!1,reason:"ambiguous",available:o.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:r}}var ns=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,$t=e=>xu.some(t=>e.includes(t));function Su(e){let t=e,{name:n,script:r,styles:o,event_scripts:i}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(o!==void 0&&typeof o!="string")return"styles";if(i!==void 0){if(!O(i))return"event_scripts";let u=Object.entries(i).find(([h,v])=>typeof v!="string"||$t(h)||$t(v));if(u)return`event_scripts.${u[0]}`}let s=[["name",n],["script",r],["styles",o]].find(([,u])=>typeof u=="string"&&$t(u));if(s)return s[0];let a=os.find(u=>t[u]!==void 0&&!ns(t[u]));if(a)return a;let c=is.find(([u,h])=>{let v=t[u],p=t[h];return typeof v=="number"&&typeof p=="number"&&v>p});if(c)return c[0];let g=vu.find(u=>{let h=t[u];if(h===void 0)return!1;if(typeof h!="number"||!ns(h))return!0;let[v,p]=xn[u],l=t[v],w=t[p];return typeof l=="number"&&h<l||typeof w=="number"&&h>w});if(g)return g;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var Pu=["api_name","name","script","html","css"],rs=e=>typeof e!="string"||$t(e);function Eu(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),o=Pu.find(a=>rs(n[a]));if(o)return{view:r,field:o};let i=n.event_scripts;if(!O(i))return{view:r,field:"event_scripts"};let s=Object.entries(i).find(([a,c])=>$t(a)||rs(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var _u=({view:e,field:t})=>`views.${e}.${t}`,Tu=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,Au=(e,t)=>{if(t==="script")return`Block "${e}" has no script. Add a non-empty script.js to the block directory.`;if(t==="host_chrome")return`Block "${e}" has an invalid host_chrome: it must be true or false.`;let n=is.find(([r])=>r===t);if(n)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${n[1]}.`;if(os.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in xn){let[r,o]=xn[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${o}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},Iu=({reason:e,available:t},n,r)=>{let o=ku(t);return e==="no_blocks"?"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.":e==="not_found"?`No block with api_name "${n??""}". Available blocks: ${o}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${o}`:`More than one plugin has a block with api_name "${n}": ${o}`},$u=e=>{try{let t=JSON.parse(e);return O(t)?t:void 0}catch{return}},as=e=>{let t=e.find(i=>i.path===bu),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],o=new Map;for(let i of r)O(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&o.set(i.api_name,i.entry);return o},cs=(e,t)=>{let n=rn(e);return n===""?t:`${n}/${t}`},ls=(e,t,n)=>{let r=`${cs(t,n)}/`,o=new Set,i=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...g]=s.path.slice(r.length).split("/");if(a&&(o.add(a),c===yu&&g.length===0)){let u=$u(s.content);u&&i.push([a,u])}}return{directories:o,configs:i}},ds=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:wu(t),Nu=(e,t)=>{let n=new Map;for(let[r,o]of ls(e,t,gu).configs){let i=ds(o,r),s={};for(let a of ss)o[a]!==void 0&&(s[a]=o[a]);n.set(i,s)}return n},Du=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!ss.includes(r))),...t});function Ru(e,t){let n=as(t);return e.map(r=>{let o=n.get(r.api_name),i=o===void 0?new Map:Nu(t,o);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>Du(s,i.get(s.api_name)))}}})}var us=(e,t)=>JSON.stringify([String(e),String(t)]),Ou=(e,t)=>{let{directories:n,configs:r}=ls(e,t,Rr),o=new Map(r),i=new Set;for(let s of n){let a=o.get(s)??{};i.add(us(ds(a,s),a.name||s))}return i},Bu=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),Fu="appbuilder/views-unmatched";function ju(e,t){let n=as(t),r={},o=[];for(let i of e){let s=n.get(i.api_name),a=s===void 0?new Set:Ou(t,s),c=i.artifacts.routable_pages.filter(g=>a.has(us(g.api_name,g.name))).sort(Bu);c.length!==a.size&&s!==void 0&&o.push({rule:Fu,severity:"warning",message:`Found ${String(a.size)} ${Rr}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:cs(s,Rr),pluginApiName:i.api_name}),r[i.api_name]=c}return{views:r,warnings:o}}function Lu(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function ps(e){return{...e.block,...Tr(e.views)}}async function Br(e){let{files:t,deployable:n,issues:r}=await Dr(e),o=ju(n,t);return{deployable:Ru(n,t),views:o.views,warnings:[...r.filter(i=>i.severity==="warning"),...o.warnings]}}function Fr({deployable:e,views:t,warnings:n},r,o){let i=Cu(e,r);if(!i.ok)return{ok:!1,reason:i.reason,message:Iu(i,r,o),available:i.available};let s=Su(i.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:Au(i.block.api_name,s),available:[],field:s};let a=Lu(t,i.pluginApiName),c=Eu(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:Tu(i.block.api_name,c),available:[],field:_u(c)}:{ok:!0,value:{block:i.block,pluginApiName:i.pluginApiName,views:a,warnings:n}}}async function fs(e,t){let n=Fr(await Br(e),t,"export");if(!n.ok)throw new Or(n.reason,n.message,n);return n.value}var jr=(e,t,n)=>`${String(e)} ${e===1?t:n}`,Lr=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",o=t.get(r)??[];o.push(n),t.set(r,o)}return t},Mu=e=>{let t=e.filter(o=>o.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${jr(n,"validation warning","validation warnings")}`;let r=`\u2717 ${jr(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${jr(n,"warning","warnings")}`};function Ae(e){if(e.length===0)return"";let t=[...Lr(e)].map(([n,r])=>[n,...r.map(o=>` ${o.severity==="error"?"\u2717":"\u26A0"} ${o.message} (${o.rule})`)].join(`
118
+ `));return[Mu(e),...t].join(`
119
+
120
+ `)}import{randomUUID as gp}from"crypto";import{join as yp}from"path";import{PluginValidationError as bp}from"@kizenapps/packager";import{mkdir as zu,readFile as Uu,writeFile as Hu}from"fs/promises";import{join as ms}from"path";async function we(e){try{let t=await Uu(ms(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ve(e,t){await zu(e,{recursive:!0}),await Hu(ms(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import*as ht from"fs";import*as hs from"path";var Vu=[".kizenapp/",".copilot-docs/"];function ve(e){let t=hs.join(e,".gitignore"),n="";ht.existsSync(t)&&(n=ht.readFileSync(t,"utf8"));let r=new Set(n.split(`
121
+ `).map(a=>a.trim())),o=Vu.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(o.length===0)return;let i=o.join(`
8
122
  `)+`
9
- `,s=r===""||r.endsWith(`
123
+ `,s=n===""||n.endsWith(`
10
124
  `)?i:`
11
- `+i;Xe.writeFileSync(t,r+s)}var lc="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",cc="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",dc=100,uc=new Set(["detail","non_field_errors"]),ne=class extends Error{kind;status;hint;constructor(t,r,o={}){super(r),this.name="KizenApiError",this.kind=t,this.status=o.status,this.hint=o.hint}},lt=encodeURIComponent,ct=(e,t)=>t===void 0?`/dashboards/${lt(e)}/dashlet`:`/dashboards/${lt(e)}/dashlet/${lt(t)}`;function Xr(e,t,r){let o=n=>{r.push(t===""?n:`${t}: ${n}`)};if(typeof e=="string"){e.trim()!==""&&o(e);return}if(typeof e=="number"||typeof e=="boolean"){o(String(e));return}if(Array.isArray(e)){let n=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");n.length>0&&o(n.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&Xr(i,t,r);return}if(H(e))for(let[n,i]of Object.entries(e)){let s=t===""&&uc.has(n)?"":t===""?n:`${t}.${n}`;Xr(i,s,r)}}function pc(e){if(typeof e!="object"||e===null)return;let t=[];return Xr(e,"",t),t.length>0?t.join("; "):void 0}function Go(e){let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)}async function fc(e){let t=await e.text();if(t==="")return{text:t,json:void 0};try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function mc(e,t,r,o){let n=pc(o),i=`${e} ${t} failed with ${String(r)}${n===void 0?"":`: ${n}`}`;return r===401?new ne("auth_failed",i,{status:r,hint:lc}):r===403?new ne("forbidden",i,{status:r,hint:cc}):r===404?new ne("not_found",i,{status:r}):new ne("api_error",i,{status:r})}function Yo(e,t,r){if(Array.isArray(r))return{results:r,next:null};if(H(r)&&Array.isArray(r.results))return{results:r.results,next:r.next};throw new ne("api_error",`${e} ${t} returned an unexpected response shape`)}function Xo(e){let{credentials:t}=e,r=e.fetch??fetch,o=e.baseUrl??Lo[t.environment],n=async(s,a,l)=>{let p=/^https?:\/\//.test(a)?a:`${o}${a}`,g=p.startsWith(o)?p.slice(o.length):p,v={"X-API-KEY":t.apiKey,"X-USER-ID":t.userId,"X-BUSINESS-ID":t.businessId,Accept:"application/json"},k={method:s,headers:v};l!==void 0&&(v["Content-Type"]="application/json",k.body=JSON.stringify(l));let f;try{f=await r(p,k)}catch(x){throw new ne("network_error",`Couldn't reach Kizen at ${o}: ${Go(x)}${Dt()==="unavailable"?` ${It}`:""}`)}let c,h;try{({text:c,json:h}=await fc(f))}catch(x){throw new ne("network_error",`${s} ${g}: couldn't read the response: ${Go(x)}. The request may have been applied; check Kizen before retrying.`,{status:f.status})}if(!f.ok)throw mc(s,g,f.status,h);if(h===void 0&&c!=="")throw new ne("api_error",`${s} ${g} returned a response that is not JSON`,{status:f.status});return h},i=s=>{let a=new URL(o),l=new URL(s,a.origin);if(l.hostname!==a.hostname)throw new ne("api_error",`GET /custom-objects pagination pointed at an unexpected host ${l.hostname}`);return new URL(`${l.pathname}${l.search}`,a.origin).toString()};return{async listDashboards(s,a){let l=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:s});a!==void 0&&l.set("custom_object_id",a);let p=`/dashboards/mine?${l.toString()}`;return Yo("GET",p,await n("GET",p)).results},async listCustomObjects(){let s=[],a=new Set,l="/custom-objects?page_size=200";for(;l!==void 0&&!a.has(l)&&a.size<dc;){a.add(l);let p=Yo("GET",l,await n("GET",l));s.push(...p.results),l=typeof p.next=="string"&&p.next!==""?i(p.next):void 0}return s},async getCustomObject(s){let a=`/custom-objects/${lt(s)}`,l=await n("GET",a);if(!H(l)||typeof l.id!="string"||typeof l.fetch_url!="string")throw new ne("api_error",`GET ${a} returned an unexpected response shape`);return l},async getClientObjectId(){let s=await n("GET","/auth/bootstrap"),a=H(s)?s.business:void 0,l=H(a)?a.client_object:void 0,p=H(l)?l.id:void 0;return typeof p=="string"&&p!==""?p:null},async getDashboard(s){return await n("GET",`/dashboards/${lt(s)}`)},async createDashlet(s,a){return await n("POST",ct(s),a)},async updateDashlet(s,a,l){return await n("PATCH",ct(s,a),l)}}}import{join as qt}from"path";var Zo="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `appbuilder setup-claude --include-lib` in the plugin directory.\n\n- If it reports `updated` for `.claude/skills/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `.claude/skills/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file, or `updated` for `.claude/skills/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n\n`setup-claude` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `setup-claude` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` both accept `-c/--credentials <path>` and `--profile <name>` to pick the credential.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the same command with `--yes` in place of `--dry-run`. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `Claude files managed by appbuilder are out of date; run appbuilder setup-claude`, run `appbuilder setup-claude --include-lib`, re-read `.claude/skills/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, choice?, choices? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`.\n\n### `needs_choice`\n\n`choice` is `'profile'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`, where `args` is a string array. Ask the user using each option's `label`, then re-run the same command with the chosen option's `args` appended exactly. Never construct these flags by hand. The \"new\" option is `{ value: 'new', args: ['--dashboard', <id>, '--create'] }`.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `credentials_invalid`, tell the user to fix the credential file named in `message`, or to pass `--profile` or `-c`.\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var Qo=`# Designing a Kizen custom block
125
+ `+i;ht.writeFileSync(t,n+s)}var Ku="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function gs(e){return(e.credentials!==void 0||e.profile!==void 0)&&e.env!==void 0?{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."}:e.credentials!==void 0?{ok:!0,selection:{kind:"api-key",credentials:e.credentials}}:e.profile!==void 0?{ok:!0,selection:{kind:"api-key",profile:e.profile}}:{ok:!0,selection:e.env===void 0?{kind:"oauth"}:{kind:"oauth",env:e.env}}}var ys=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${be(e)} to use the API key.`}`,bs=e=>`${e} ${Ku}`;import{spawn as ip}from"child_process";import{join as _n}from"path";var ws="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `appbuilder setup-claude --include-lib` in the plugin directory.\n\n- If it reports `updated` for `.claude/skills/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `.claude/skills/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file, or `updated` for `.claude/skills/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n\n`setup-claude` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `setup-claude` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the same command with `--yes` in place of `--dry-run`. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `Claude files managed by appbuilder are out of date; run appbuilder setup-claude`, run `appbuilder setup-claude --include-lib`, re-read `.claude/skills/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, choice?, choices? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`, where `args` is a string array. Ask the user using each option's `label`, then re-run the same command with the chosen option's `args` appended exactly. Never construct these flags by hand. The \"new\" option is `{ value: 'new', args: ['--dashboard', <id>, '--create'] }`.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `credentials_invalid`, if `message` says they're not signed in, tell the user to run `appbuilder login` (add `--env <env>` for an environment other than `go`). Otherwise tell them to fix the credential file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var vs=`# Designing a Kizen custom block
12
126
 
13
127
  With host chrome (the default), a block must look like a native Kizen dashlet. Follow every rule here exactly. Where a rule says "use judgment", pick the option that looks most native. A block whose \`config.json\` sets \`"host_chrome": false\` follows section M for its card and outer box, and skips every rule marked "with host chrome".
14
128
 
@@ -357,7 +471,7 @@ render(
357
471
  color: var(--color-font-placeholder);
358
472
  }
359
473
  \`\`\`
360
- `;var ei=`# Copilot review instructions for this Kizen plugin
474
+ `;var xs=`# Copilot review instructions for this Kizen plugin
361
475
 
362
476
  This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
363
477
  that \`@kizenapps/packager\` finds by walking the directory tree under the
@@ -410,7 +524,7 @@ This file covers repo structure and general review. Two path-scoped files cover
410
524
  the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
411
525
  patterns and \`.github/instructions/version-discipline.instructions.md\` for
412
526
  manifest version bumps.
413
- `;var ti='---\napplyTo: "src/**/*.js,kizen.json"\n---\n\n# Security review rules for plugin scripts\n\nThe rules themselves live in the docs corpus that\n`.github/workflows/copilot-code-review.yml` fetches into `.copilot-docs/`, so\nthey cannot drift out of date here. Read them there rather than reviewing from\nmemory.\n\nWhen a change touches a service, `auth_credentials`, a `{{secret.KEY}}`\nreference, `base_config.secrets`, or dynamic code (`eval`, `new Function`, or a\nstring argument to `setTimeout` or `setInterval`), read\n`.copilot-docs/06-auth-secrets-services.md` together with the "Services, auth &\nsecrets" and "Release & publish" sections of `.copilot-docs/17-gotchas.md`, and\nreview the change against what they say.\n\nWhen a change uses `__dangerouslySkipProxy`, also read\n`.copilot-docs/11-output-ui-iframes-frames.md`.\n';var ri=`---
527
+ `;var ks='---\napplyTo: "src/**/*.js,kizen.json"\n---\n\n# Security review rules for plugin scripts\n\nThe rules themselves live in the docs corpus that\n`.github/workflows/copilot-code-review.yml` fetches into `.copilot-docs/`, so\nthey cannot drift out of date here. Read them there rather than reviewing from\nmemory.\n\nWhen a change touches a service, `auth_credentials`, a `{{secret.KEY}}`\nreference, `base_config.secrets`, or dynamic code (`eval`, `new Function`, or a\nstring argument to `setTimeout` or `setInterval`), read\n`.copilot-docs/06-auth-secrets-services.md` together with the "Services, auth &\nsecrets" and "Release & publish" sections of `.copilot-docs/17-gotchas.md`, and\nreview the change against what they say.\n\nWhen a change uses `__dangerouslySkipProxy`, also read\n`.copilot-docs/11-output-ui-iframes-frames.md`.\n';var Cs=`---
414
528
  applyTo: "kizen.json"
415
529
  ---
416
530
 
@@ -423,7 +537,7 @@ cannot drift out of date here.
423
537
  Check every \`kizen.json\` diff against the "How big a bump?" matrix in
424
538
  \`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
425
539
  \`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
426
- `;var ni=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
540
+ `;var Ss=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
427
541
  name: Copilot code review setup
428
542
 
429
543
  on:
@@ -462,7 +576,7 @@ jobs:
462
576
  echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
463
577
  test "$count" -ge 24
464
578
  du -sh .copilot-docs
465
- `;var oi=`const MAX_PAGE_SIZE = 1000;
579
+ `;var Ps=`const MAX_PAGE_SIZE = 1000;
466
580
  const DEFAULT_MAX_PAGES = 10;
467
581
 
468
582
  const fieldCache = new Map();
@@ -707,20 +821,22 @@ export const sumBy = (records, name, valueOf) =>
707
821
  total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
708
822
  0,
709
823
  );
710
- `;function Ht(){return[{path:".github/copilot-instructions.md",content:ei},{path:".github/instructions/security.instructions.md",content:ti},{path:".github/instructions/version-discipline.instructions.md",content:ri},{path:".github/workflows/copilot-code-review.yml",content:ni}]}var ii="lib/kizenData.js",Zr=(e="src")=>e===""?ii:`${e}/${ii}`;function Vt(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:Zo},{path:".claude/skills/kizen-custom-block/design.md",content:Qo},...[...new Set(e)].map(t=>({path:Zr(t),content:oi}))]}import{access as kc,mkdir as Cc,readFile as Sc,writeFile as _c}from"fs/promises";import{dirname as Pc,join as si}from"path";var Wt={readFile:async e=>{try{return await Sc(e,"utf-8")}catch(t){if(Nt(t))return;throw t}},writeFile:async(e,t)=>{await Cc(Pc(e),{recursive:!0}),await _c(e,t,"utf-8")},exists:async e=>{try{return await kc(e),!0}catch{return!1}}},Ec=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Qr(e,t,r=Wt){return Promise.all(t.map(async o=>({path:o.path,status:Ec(await r.readFile(si(e,o.path)),o.content)})))}async function Kt(e,t,r={},o=Wt){let n=await Qr(e,t,o);return r.dryRun===!0||await Promise.all(t.filter((i,s)=>n[s]?.status!=="unchanged").map(i=>o.writeFile(si(e,i.path),i.content))),n}var Jt=e=>`${e.status.padEnd(9)} ${e.path}`;var ai=".claude/skills/kizen-custom-block/SKILL.md",li="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",tn=Wt,Tc=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Bt(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Ic(e){let r=(Array.isArray(e)?e:[e]).map(o=>typeof o=="object"&&o!==null&&"entry"in o?Tc(o.entry):void 0).filter(o=>o!==void 0);return r.length>0?[...new Set(r)]:["src"]}var Dc=async(e,t)=>{try{let r=await t.readFile(qt(e,"kizen.json"));return r===void 0?["src"]:Ic(JSON.parse(r))}catch{return["src"]}};async function ci(e,t=tn,r={}){let o=await Dc(e,t),n=r.includeLib===!0?o:(await Promise.all(o.map(async i=>await t.exists(qt(e,Zr(i)))?i:void 0))).filter(i=>i!==void 0);return Vt(n)}async function di(e,t=tn){try{let r=await ci(e,t);return!r.some(n=>n.path===ai)||await t.readFile(qt(e,ai))===void 0?!1:(await Qr(e,r,t)).some(n=>n.status!=="unchanged")}catch{return!1}}var Ac={fs:tn,log:e=>{console.log(e)},error:e=>{console.error(e)},setExitCode:e=>{process.exitCode=e}},en=(e,t)=>`${String(e.filter(r=>r.status===t).length)} ${t}`;async function ui(e,t,r=Ac){if(!await r.fs.exists(qt(e,"kizen.json"))){r.error("Error: kizen.json not found. Run this command from a plugin directory."),r.setExitCode(1);return}let o=t.dryRun===!0,n;try{n=await Kt(e,await ci(e,r.fs,{includeLib:t.includeLib===!0}),{dryRun:o},r.fs)}catch(a){r.error(`Error: ${a instanceof Error?a.message:String(a)}`),r.setExitCode(1);return}for(let a of n)r.log(Jt(a));let i=`${en(n,"created")}, ${en(n,"updated")}, ${en(n,"unchanged")}`,s="these files are managed by appbuilder, so local edits to them are replaced";r.log(o?`Dry run: ${i}; nothing written (${s}).`:`Claude files: ${i} (${s}).`)}function Xt(e){return{cwd:e,loadCredentialsDetailed:Ut,listLoadableCredentialProfiles:Jo,loadConfig:he,packageBlocks:Kr,createClient:t=>Xo({credentials:t}),readPushMap:xo,writePushMap:vo,ensureGitignore:ge,isClaudeSkillStale:t=>di(t),randomUUID:Nc,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t}}}var $c=new Set(["owner","admin","edit"]),Fc="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",nn=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function W(e,t,r={}){return{ok:!1,code:e,message:t,...r}}var ue=e=>({ok:!0,value:e});function Ve(e){return e instanceof ne?W(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Rc?W("validation_failed",xe(e.issues),{issues:e.issues}):W("local_error",nn(e))}var jc=()=>Z.join(", ");async function Gt(e,t){let r;try{r=await t.loadCredentialsDetailed(e)}catch(i){return W("credentials_invalid",`Couldn't read credentials from ${e}: ${nn(i)}`)}if(r.environmentSource!=="explicit"){let i=r.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return W("credentials_invalid",`${e} ${i}. Set it to one of: ${jc()}. The CLI won't default to production.`)}let{credentials:o}=r,n=["apiKey","userId","businessId"].filter(i=>o[i].trim()==="");return n.length>0?W("credentials_invalid",`${e} is missing ${n.map(i=>`"${i}"`).join(", ")}.`):ue({credentials:o})}async function Zt(e,t){if(e.credentials!==void 0)return Gt(e.credentials,t);let r=await t.listLoadableCredentialProfiles(),o=r.map(a=>a.name);if(e.profile!==void 0){let a=r.find(l=>l.name===e.profile);return a?Gt(a.path,t):W("credentials_invalid",o.length===0?`No loadable credential profile named "${e.profile}". No profiles are loadable; create ${ve} or pass -c <path>.`:`No loadable credential profile named "${e.profile}". Loadable profiles: ${o.join(", ")}`)}let n=await t.loadConfig(Bc(t.cwd,".kizenapp"));if(n.credentialMode==="local")return W("credentials_invalid","This plugin is set to use local browser-only credentials the CLI can't read. Pass -c <path> or --profile <name>.");let i=n.activeCredentialProfile===void 0?void 0:r.find(a=>a.name===n.activeCredentialProfile);if(i)return Gt(i.path,t);let[s]=r;return r.length===1&&s?Gt(s.path,t):r.length===0?W("credentials_invalid",`No credentials found. Create ${ve} or pass -c <path>.`):W("needs_choice",`Several credential profiles are available; pass --profile <name>: ${o.join(", ")}`,{choice:"profile",choices:r.map(a=>({value:a.name,label:a.isDefault?`${a.name} (default)`:a.name,args:["--profile",a.name]}))})}function Oc(e,t){let r=new Set(t.map(o=>o.pluginApiName)).size>1;return t.map(({pluginApiName:o,apiName:n})=>{let i=e.find(a=>a.api_name===o)?.artifacts.custom_blocks.find(a=>a.api_name===n),s=r?`${o}/${n}`:n;return{value:n,label:`${i?.name??n} (${s})`,args:[n]}})}async function on(e,t){let r=await t.packageBlocks(t.cwd),o=Jr(r,e,"push");if(!o.ok){let{reason:p,message:g,field:v}=o;return p==="no_blocks"||p==="invalid_block"?W("invalid_block",g,v===void 0?{}:{field:v}):W("needs_choice",g,{choice:"block",choices:Oc(r.deployable,o.available)})}let{block:n,pluginApiName:i,views:s,warnings:a}=o.value,l=lo(n,s);return ue({block:n,pluginApiName:i,content:l,contentHash:Lr(l),warnings:a})}var mi=e=>e==null?null:$c.has(e.toLowerCase());function dt(e,t){return{id:e.id,name:e.name,type:t,dashletsCount:e.dashlets_count??null,employeeAccess:e.employee_access??null,hidden:e.hidden??!1,canEdit:mi(e.employee_access)}}var hi=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Lc="Contacts";async function sn(e){let[t,r]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),o=t.map(hi).sort((n,i)=>n.objectName.localeCompare(i.objectName));return r!==null&&r!==""&&!o.some(n=>n.id===r)&&o.push({id:r,objectName:Lc,fetchUrl:"client"}),o}async function zc(e,t,r){let{environment:o,businessId:n}=t;try{if(r.object!==void 0){let l=r.object,[p,g]=await Promise.all([e.getCustomObject(l).catch(()=>null),e.listDashboards("chart_group",l)]);return ue({ok:!0,environment:o,businessId:n,object:p?hi(p):null,surfaces:{chart_group:g.map(v=>dt(v,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),sn(e)]);return ue({ok:!0,environment:o,businessId:n,surfaces:{dashboard:i.map(l=>dt(l,"dashboard")),homepage:s.map(l=>dt(l,"homepage"))},customObjects:a})}catch(i){return Ve(i)}}var an=(e,t)=>t.dashboard===e.id;function Qt(e,t){return[...fo(e).filter(o=>an(e,o)).map(o=>{let n=oo(o.name);return{value:o.id,label:Ft(o),args:["--dashboard",e.id,"--dashlet",o.id],pushKey:n?o.name:null,isFromThisPlugin:n?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var ln=(e,t)=>go({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),gi=(e,t)=>ue({dashboard:e,surface:Ur(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Yt=(e,t,r)=>ue({dashboard:e,surface:Ur(e.type),action:"update",dashlet:t,resolvedBy:r});async function Mc(e){let[t,r]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),o=n=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:n,canEdit:mi(i.employee_access)});return W("needs_choice",`Choose where to push; pass --dashboard <id>. ${Fc}`,{choice:"dashboard",choices:[...t.map(o("dashboard")),...r.map(o("homepage"))]})}async function Uc(e,t,r){let o=await e.client.getDashboard(t);if(r.create)return gi(o,"flag");let n=()=>Qt(o,e.block);if(r.dashlet!==void 0){let s=r.dashlet,a=o.dashlets.find(l=>l.id===s&&an(o,l));return a?Ye(a)?Yt(o,a,"flag"):W("usage_error",`Dashlet ${s} is not a custom code block, so it can't be updated with a pushed block. Pass --create to add a new one.`):W("not_found",`Dashlet ${s} is not on dashboard "${o.name}" (${o.id}).`,{choice:"target",choices:n()})}let i=ln(e,o);return i.kind==="map"?Yt(o,i.dashlet,"push_map"):i.kind==="name"?Yt(o,i.dashlet,"name"):W("needs_choice",i.kind==="ambiguous"?`Dashboard "${o.name}" has ${String(i.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${o.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:n()})}async function Hc(e,t,r){let o;try{o=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof ne&&i.kind==="not_found")return W("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw i}if(r.create)return gi(o,"remembered");let n=o.dashlets.find(i=>i.id===t.dashletId&&an(o,i));return n&&Ye(n)?Yt(o,n,"remembered"):W("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${o.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:Qt(o,e.block)})}async function cn(e,t){if(t.dashlet!==void 0&&t.create)return W("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return W("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await Uc(e,t.dashboard,t):e.entry?await Hc(e,e.entry,t):await Mc(e)}catch(r){return Ve(r)}}async function Vc(e,t,r){let o=t.custom_object;if(o==null||o==="")return null;if(typeof o!="string"){if(typeof o!="object"||typeof o.id!="string")return null;let{id:n,fetch_url:i}=o;return typeof i=="string"?{id:n,fetchUrl:i}:{id:n}}if(r!=="chart_group")return{id:o};try{let n=await e.getCustomObject(o);return{id:o,fetchUrl:n.fetch_url}}catch{return{id:o}}}async function dn(e,t,r,o){let{credentials:n,block:i}=e,{dashboard:s,surface:a}=t,l=[],p,g;if(t.action==="update"){let{dashlet:k}=t;if(yo(k,e.entry)){let f=`"${Ft(k)}" (dashlet ${k.id}) was changed in Kizen since the last push.`;if(!r.force)return W("drift_detected",`${f} Pushing would overwrite those changes; pass --force to overwrite them.`);l.push(`${f} Overwriting it because of --force.`)}p={action:"update",method:"PATCH",path:ct(s.id,k.id),body:uo(k,i.content),dashletId:k.id},g=`Update "${Ft(k)}" (dashlet ${k.id})`}else p={action:"create",method:"POST",path:ct(s.id),body:co({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:o.randomUUID(),layoutId:o.randomUUID()}),dashletId:null},g=`Create a new block on "${s.name}"`;let v=Co({appBaseUrl:zo[n.environment],surface:a,dashboardId:s.id,customObject:await Vc(e.client,s,a)});return ue({...p,dashboard:{id:s.id,name:s.name,type:a},url:v,resolvedBy:t.resolvedBy,warnings:l,summary:{environment:n.environment,businessId:n.businessId,isProduction:Yr(n.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:g,dashletId:p.dashletId,blockName:i.block.name,blockApiName:i.block.api_name,pluginApiName:i.pluginApiName,scriptBytes:Buffer.byteLength(i.content.script,"utf8"),stylesBytes:Buffer.byteLength(i.content.styles,"utf8"),...i.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(i.content.views),"utf8")}}})}var un=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function pn(e,t,r){let o;try{if(t.action==="create"){let l=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof l!="string"||l==="")return W("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);o=l}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),o=t.dashletId}catch(a){return Ve(a)}let n=[...t.warnings],i={...un(e),dashboardId:t.dashboard.id,dashletId:o,contentHash:e.block.contentHash,pushedAt:r.now().toISOString()},s=!1;try{r.ensureGitignore(r.cwd),await r.writePushMap(r.cwd,bo(e.pushMap,i)),s=!0}catch(a){n.push(`The push succeeded, but ${Me} couldn't be written, so this target isn't remembered: ${nn(a)}`)}return ue({dashletId:o,remembered:s,warnings:n})}var Wc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function fn(e){return Wc.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function Kc(e,t){let r=un(e);if(!Mr(e.pushMap,r))return null;let o=wo(e.pushMap,r);return await t.writePushMap(t.cwd,o),o}async function mn(e,t){let{client:r,credentials:o,block:n}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await Kc({credentials:o,block:n,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:r,credentials:o,block:n,pushMap:i,entry:Mr(i,un({credentials:o,block:n}))},forgotten:s}}function hn(e,t){return e.dryRun?ue({kind:"dry-run",reason:"flag"}):e.yes?Yr(t)&&!e.allowProduction?W("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):ue({kind:"apply"}):ue({kind:"dry-run",reason:"no_yes"})}var Jc="Dry run only: pass --yes to write.",He=e=>e.map(t=>`Warning: ${t}`);function ut(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,`Surface: ${e.surface}`,`Dashboard: "${e.dashboardName}" (${e.dashboardId})`,`Action: ${e.actionLine}`,`Block: ${e.blockName} (${e.pluginApiName}/${e.blockApiName})`,`Size: script ${String(e.scriptBytes)} bytes, styles ${String(e.stylesBytes)} bytes${e.viewsBytes===void 0?"":`, views ${String(e.viewsBytes)} bytes`}`]}var qc=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`,Gc=e=>/^[\w./:@=-]+$/.test(e)?e:JSON.stringify(e);function Yc(e,t,r){let o=[`Error: ${e.message}`];if(e.hint!==void 0&&o.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){o.push("Choices:");for(let n of e.choices){let i=r(n,e.choice).map(Gc).join(" ");o.push(` ${n.label} \u2192 ${t} ${i}`)}}return`${o.join(`
824
+ `;function kn(){return[{path:".github/copilot-instructions.md",content:xs},{path:".github/instructions/security.instructions.md",content:ks},{path:".github/instructions/version-discipline.instructions.md",content:Cs},{path:".github/workflows/copilot-code-review.yml",content:Ss}]}var Es="lib/kizenData.js",Mr=(e="src")=>e===""?Es:`${e}/${Es}`;function Cn(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:ws},{path:".claude/skills/kizen-custom-block/design.md",content:vs},...[...new Set(e)].map(t=>({path:Mr(t),content:Ps}))]}import{access as Qu,mkdir as ep,readFile as tp,writeFile as np}from"fs/promises";import{dirname as rp,join as _s}from"path";var Sn={readFile:async e=>{try{return await tp(e,"utf-8")}catch(t){if(nn(t))return;throw t}},writeFile:async(e,t)=>{await ep(rp(e),{recursive:!0}),await np(e,t,"utf-8")},exists:async e=>{try{return await Qu(e),!0}catch{return!1}}},op=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function zr(e,t,n=Sn){return Promise.all(t.map(async r=>({path:r.path,status:op(await n.readFile(_s(e,r.path)),r.content)})))}async function Pn(e,t,n={},r=Sn){let o=await zr(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((i,s)=>o[s]?.status!=="unchanged").map(i=>r.writeFile(_s(e,i.path),i.content))),o}var En=e=>`${e.status.padEnd(9)} ${e.path}`;var Ts=".claude/skills/kizen-custom-block/SKILL.md",Is="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",Hr=Sn,sp=e=>{if(typeof e!="string"||e.trim()==="")return;let t=rn(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function ap(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?sp(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var cp=async(e,t)=>{try{let n=await t.readFile(_n(e,"kizen.json"));return n===void 0?["src"]:ap(JSON.parse(n))}catch{return["src"]}};async function $s(e,t=Hr,n={}){let r=await cp(e,t),o=n.includeLib===!0?r:(await Promise.all(r.map(async i=>await t.exists(_n(e,Mr(i)))?i:void 0))).filter(i=>i!==void 0);return Cn(o)}async function Ns(e,t=Hr){try{let n=await $s(e,t);return!n.some(o=>o.path===Ts)||await t.readFile(_n(e,Ts))===void 0?!1:(await zr(e,n,t)).some(o=>o.status!=="unchanged")}catch{return!1}}var lp="@kizenapps/cli",dp=6e4,up=(e,t)=>new Promise((n,r)=>{let o=ip(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:dp}),i="",s="";o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",a=>{i+=a}),o.stderr.on("data",a=>{s+=a}),o.on("error",r),o.on("close",a=>{n({code:a,stdout:i,stderr:s})})}),Ds=e=>({run:up,hasOAuthSession:async t=>await Ue().readSession(t)!==null,cliVersion:e,fs:Hr,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}}),Ur=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;function pp(e,t){let n=`kizen-${e}`,r=`${ut(e)}/api/mcp`,o=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${lp}@${t} auth-header`}),i=["mcp","add-json","--scope","user",n,o];return{environment:e,name:n,url:r,addArgs:i,addCommand:["claude",...i].map(be).join(" ")}}function fp(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.env===void 0?void 0:et(e.env).message}var mp=e=>/already\s+exists/i.test(`${e.stdout}
825
+ ${e.stderr}`),As=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function hp(e,t,n){let r=pp(e,n.cliVersion),{name:o}=r,i=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${o}: ${a}`),i&&(n.error(`The old ${o} registration was already removed, so Claude Code has no ${o} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&mp(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${As(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${As(a)}`);return}}catch(a){if(!i&&tn(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(Le(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${ye(e)}\` before using ${r.name}.`)}catch(a){n.log(Le(a))}}async function Rs(e,t,n){let r=fp(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}if(!await n.fs.exists(_n(e,"kizen.json"))){n.error("Error: kizen.json not found. Run this command from a plugin directory."),n.setExitCode(1);return}let o=t.dryRun===!0,i;try{i=await Pn(e,await $s(e,n.fs,{includeLib:t.includeLib===!0}),{dryRun:o},n.fs)}catch(c){n.error(`Error: ${Le(c)}`),n.setExitCode(1);return}for(let c of i)n.log(En(c));let s=`${Ur(i,"created")}, ${Ur(i,"updated")}, ${Ur(i,"unchanged")}`,a="these files are managed by appbuilder, so local edits to them are replaced";n.log(o?`Dry run: ${s}; nothing written (${a}).`:`Claude files: ${s} (${a}).`),t.mcp===!0&&await hp((t.env===void 0?void 0:et(t.env).environment)??Me,{dryRun:o,force:t.force===!0},n)}function wp(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),connect:async r=>{let o=dn(r,e,{...n&&{fetch:n}}),i=At({bearer:o,...n&&{fetch:n}});return{identity:await i.getIdentity(),client:i}}}}function Kr(e){return{cwd:e,loadCredentialsDetailed:en,listLoadableCredentialProfiles:Vo,loadConfig:we,packageBlocks:Br,createClient:t=>At({credentials:t}),readPushMap:Gi,writePushMap:Yi,ensureGitignore:ve,isClaudeSkillStale:t=>Ns(t),randomUUID:gp,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},oauth:wp(Ue())}}var vp=new Set(["owner","admin","edit"]),xp="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Wr=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function V(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var fe=e=>({ok:!0,value:e});function Ke(e){return e instanceof Z?V(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof bp?V("validation_failed",Ae(e.issues),{issues:e.issues}):V("local_error",Wr(e))}async function Fs(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return V("credentials_invalid",`Couldn't read credentials from ${e}: ${Wr(i)}`)}if(n.environmentSource!=="explicit"){let i=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return V("credentials_invalid",`${e} ${i}. Set it to one of: ${W.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,o=["apiKey","userId","businessId"].filter(i=>r[i].trim()==="");return o.length>0?V("credentials_invalid",`${e} is missing ${o.map(i=>`"${i}"`).join(", ")}.`):fe({credentials:r,client:t.createClient(r),notices:[]})}async function kp(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(o=>o.name===e);if(!r){let o=n.map(i=>i.name);return V("credentials_invalid",o.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${Oe} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return Fs(r.path,t)}async function Cp(e){let{activeCredentialProfile:t}=await e.loadConfig(yp(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[ys(t)]}async function Sp(e,t){let n=[],r=await nt(e,async()=>(n=await t.oauth.listSessions(),n));if(!r.ok)switch(r.problem){case"not_signed_in":return V("credentials_invalid",bs(r.message));case"several_sessions":return V("needs_choice",r.message,{choice:"environment",choices:n.map(s=>({value:s,label:s,args:["--env",s]}))});case"unknown_environment":return V("usage_error",r.message)}let{environment:o}=r,i;try{i=await t.oauth.connect(o)}catch(s){return Ke(s)}return fe({credentials:{environment:o,businessId:i.identity.businessId},client:i.client,notices:await Cp(t)})}async function An(e,t){let n=gs(e);if(!n.ok)return V("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?Sp(r.env,t):r.credentials===void 0?kp(r.profile,t):Fs(r.credentials,t)}function Pp(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:o})=>{let i=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===o),s=n?`${r}/${o}`:o;return{value:o,label:`${i?.name??o} (${s})`,args:[o]}})}async function qr(e,t){let n=await t.packageBlocks(t.cwd),r=Fr(n,e,"push");if(!r.ok){let{reason:g,message:u,field:h}=r;return g==="no_blocks"||g==="invalid_block"?V("invalid_block",u,h===void 0?{}:{field:h}):V("needs_choice",u,{choice:"block",choices:Pp(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=ji(o,s);return fe({block:o,pluginApiName:i,content:c,contentHash:Ar(c),warnings:a})}var js=e=>e==null?null:vp.has(e.toLowerCase());function Nt(e,t){return{id:e.id,name:e.name,type:t,dashletsCount:e.dashlets_count??null,employeeAccess:e.employee_access??null,hidden:e.hidden??!1,canEdit:js(e.employee_access)}}var Ls=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),Ep="Contacts";async function Jr(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Ls).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:Ep,fetchUrl:"client"}),r}async function _p(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[g,u]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return fe({ok:!0,environment:r,businessId:o,object:g?Ls(g):null,surfaces:{chart_group:u.map(h=>Nt(h,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Jr(e)]);return fe({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>Nt(c,"dashboard")),homepage:s.map(c=>Nt(c,"homepage"))},customObjects:a})}catch(i){return Ke(i)}}var Gr=(e,t)=>t.dashboard===e.id;function In(e,t){return[...Ui(e).filter(r=>Gr(e,r)).map(r=>{let o=Ri(r.name);return{value:r.id,label:yn(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:o?r.name:null,isFromThisPlugin:o?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var Yr=(e,t)=>Ki({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Ms=(e,t)=>fe({dashboard:e,surface:Nr(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Tn=(e,t,n)=>fe({dashboard:e,surface:Nr(e.type),action:"update",dashlet:t,resolvedBy:n});async function Tp(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=o=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:o,canEdit:js(i.employee_access)});return V("needs_choice",`Choose where to push; pass --dashboard <id>. ${xp}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function Ap(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Ms(r,"flag");let o=()=>In(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&Gr(r,c));return a?mt(a)?Tn(r,a,"flag"):V("usage_error",`Dashlet ${s} is not a custom code block, so it can't be updated with a pushed block. Pass --create to add a new one.`):V("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:o()})}let i=Yr(e,r);return i.kind==="map"?Tn(r,i.dashlet,"push_map"):i.kind==="name"?Tn(r,i.dashlet,"name"):V("needs_choice",i.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(i.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:o()})}async function Ip(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof Z&&i.kind==="not_found")return V("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw i}if(n.create)return Ms(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&Gr(r,i));return o&&mt(o)?Tn(r,o,"remembered"):V("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:In(r,e.block)})}async function Xr(e,t){if(t.dashlet!==void 0&&t.create)return V("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return V("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await Ap(e,t.dashboard,t):e.entry?await Ip(e,e.entry,t):await Tp(e)}catch(n){return Ke(n)}}async function $p(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:o,fetch_url:i}=r;return typeof i=="string"?{id:o,fetchUrl:i}:{id:o}}if(n!=="chart_group")return{id:r};try{let o=await e.getCustomObject(r);return{id:r,fetchUrl:o.fetch_url}}catch{return{id:r}}}async function Zr(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],g,u;if(t.action==="update"){let{dashlet:v}=t;if(Wi(v,e.entry)){let p=`"${yn(v)}" (dashlet ${v.id}) was changed in Kizen since the last push.`;if(!n.force)return V("drift_detected",`${p} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${p} Overwriting it because of --force.`)}g={action:"update",method:"PATCH",path:Tt(s.id,v.id),body:Mi(v,i.content),dashletId:v.id},u=`Update "${yn(v)}" (dashlet ${v.id})`}else g={action:"create",method:"POST",path:Tt(s.id),body:Li({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},u=`Create a new block on "${s.name}"`;let h=Zi({appBaseUrl:Lo[o.environment],surface:a,dashboardId:s.id,customObject:await $p(e.client,s,a)});return fe({...g,dashboard:{id:s.id,name:s.name,type:a},url:h,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:ur(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:u,dashletId:g.dashletId,blockName:i.block.name,blockApiName:i.block.api_name,pluginApiName:i.pluginApiName,scriptBytes:Buffer.byteLength(i.content.script,"utf8"),stylesBytes:Buffer.byteLength(i.content.styles,"utf8"),...i.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(i.content.views),"utf8")}}})}var Qr=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function eo(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return V("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Ke(a)}let o=[...t.warnings],i={...Qr(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,qi(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${st} couldn't be written, so this target isn't remembered: ${Wr(a)}`)}return fe({dashletId:r,remembered:s,warnings:o})}var Np=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function to(e){return Np.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function Dp(e,t){let n=Qr(e);if(!$r(e.pushMap,n))return null;let r=Ji(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function no(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await Dp({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:$r(i,Qr({credentials:r,block:o}))},forgotten:s}}function ro(e,t){return e.dryRun?fe({kind:"dry-run",reason:"flag"}):e.yes?ur(t)&&!e.allowProduction?V("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):fe({kind:"apply"}):fe({kind:"dry-run",reason:"no_yes"})}var Rp="Dry run only: pass --yes to write.",at=e=>e.map(t=>`Warning: ${t}`);function Dt(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,`Surface: ${e.surface}`,`Dashboard: "${e.dashboardName}" (${e.dashboardId})`,`Action: ${e.actionLine}`,`Block: ${e.blockName} (${e.pluginApiName}/${e.blockApiName})`,`Size: script ${String(e.scriptBytes)} bytes, styles ${String(e.stylesBytes)} bytes${e.viewsBytes===void 0?"":`, views ${String(e.viewsBytes)} bytes`}`]}var Op=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function Bp(e,t,n){let r=[`Error: ${e.message}`];if(e.hint!==void 0&&r.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){r.push("Choices:");for(let o of e.choices){let i=n(o,e.choice).map(be).join(" ");r.push(` ${o.label} \u2192 ${t} ${i}`)}}return`${r.join(`
711
826
  `)}
712
- `}function yi(e,t,r,o){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
713
- `):e.deps.writeStderr(Yc(t,r,o)),e.deps.setExitCode(1)}function pi(e,t,r,o=r){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
714
- `),e.deps.writeStderr(o)):e.deps.writeStdout(r)}var fi=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile===void 0?[]:["--profile",e.profile];async function Xc(e){try{return await e.isClaudeSkillStale(e.cwd)?[li]:[]}catch{return[]}}async function bi(e,t,r){let o={json:t.json===!0,deps:r},n="appbuilder block push",i=e===void 0?[]:[e],s=(l,p)=>p==="profile"?[...i,...l.args]:p==="block"?[...l.args,...fi(t)]:[...i,...fi(t),...l.args],a=l=>{yi(o,l,n,s)};try{let l=await Zt(t,r);if(!l.ok){a(l);return}let{credentials:p}=l.value,g=r.createClient(p),v=await on(e,r);if(!v.ok){a(v);return}let k=v.value;i=[k.block.api_name],k.warnings.length>0&&r.writeStderr(`${xe(k.warnings)}
715
- `);let{context:f,forgotten:c}=await mn({client:g,credentials:p,block:k,forget:t.forget===!0},r);c&&r.writeStderr(`Forgot the remembered target for ${k.block.api_name}.
716
- `);let h=await cn(f,t);if(!h.ok){a(h);return}let x=hn(t,p.environment);if(!x.ok){a(x);return}let I=await dn(f,h.value,t,r);if(!I.ok){a(I);return}let C=I.value,S={pluginApiName:k.pluginApiName,apiName:k.block.api_name,name:k.block.name},N={environment:p.environment,businessId:p.businessId,dashboard:C.dashboard},b=[...k.warnings.map(qc),...await Xc(r)],u=x.value;if(u.kind==="dry-run"){let _=[...b,...C.warnings],R={ok:!0,applied:!1,dryRun:!0,reason:u.reason,action:C.action,...N,dashletId:C.dashletId,url:C.url,resolvedBy:C.resolvedBy,block:S,method:C.method,path:C.path,body:C.body,warnings:_,...c?{forgotten:!0}:{}};pi(o,R,[...ut(C.summary),`URL: ${C.url}`,...He(_),"",`${C.method} ${C.path}`,JSON.stringify(C.body,null,2),""].join(`
717
- `),[...ut(C.summary),...He(_),""].join(`
718
- `)),u.reason==="no_yes"&&r.writeStderr(`${Jc}
719
- `);return}let d=await pn(f,C,r);if(!d.ok){a(d);return}let m=d.value,y=[...b,...m.warnings],w=fn(C.dashboard.id),E={ok:!0,applied:!0,dryRun:!1,action:C.action==="create"?"created":"updated",...N,dashletId:m.dashletId,url:C.url,...w?{refresh:w}:{},resolvedBy:C.resolvedBy,block:S,remembered:m.remembered,warnings:y,...c?{forgotten:!0}:{}};pi(o,E,[`\u2713 ${E.action==="created"?"Created":"Updated"} ${k.block.name} on "${C.dashboard.name}" (dashlet ${m.dashletId})`,...ut(C.summary),`URL: ${C.url}`,...w?[`Refresh an open tab: ${w.script}`]:[],...He(y),""].join(`
720
- `))}catch(l){a(Ve(l))}}var Zc=(e,t)=>e.padEnd(t);function rn(e,t){if(t.length===0)return[e," (none)"];let r=["NAME","ID","DASHLETS","ACCESS"],o=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),n=r.map((s,a)=>Math.max(s.length,...o.map(l=>(l[a]??"").length))),i=s=>` ${s.map((a,l)=>Zc(a,n[l]??0)).join(" ")}`.trimEnd();return[e,i(r),...o.map(i)]}function Qc(e){let t=[`Environment: ${e.environment}`,`Business: ${e.businessId}`,""];return"object"in e?t.push(e.object===null?"Custom object: not found in /custom-objects":`Custom object: ${e.object.objectName} (${e.object.id})`,"",...rn("Chart groups",e.surfaces.chart_group)):t.push(...rn("Dashboards",e.surfaces.dashboard),"",...rn("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(r=>` ${r.objectName} ${r.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
827
+ `}function zs(e,t,n,r){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
828
+ `):e.deps.writeStderr(Bp(t,n,r)),e.deps.setExitCode(1)}function Os(e,t,n,r=n){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
829
+ `),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var Bs=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:e.env===void 0?[]:["--env",e.env],Us=(e,t)=>{for(let n of t)e.writeStderr(`${n}
830
+ `)};async function Fp(e){try{return await e.isClaudeSkillStale(e.cwd)?[Is]:[]}catch{return[]}}async function Hs(e,t,n){let r={json:t.json===!0,deps:n},o="appbuilder block push",i=e===void 0?[]:[e],s=(c,g)=>g==="environment"?[...i,...c.args]:g==="block"?[...c.args,...Bs(t)]:[...i,...Bs(t),...c.args],a=c=>{zs(r,c,o,s)};try{let c=await An(t,n);if(!c.ok){a(c);return}let{credentials:g,client:u,notices:h}=c.value;Us(n,h);let v=await qr(e,n);if(!v.ok){a(v);return}let p=v.value;i=[p.block.api_name],p.warnings.length>0&&n.writeStderr(`${Ae(p.warnings)}
831
+ `);let{context:l,forgotten:w}=await no({client:u,credentials:g,block:p,forget:t.forget===!0},n);w&&n.writeStderr(`Forgot the remembered target for ${p.block.api_name}.
832
+ `);let C=await Xr(l,t);if(!C.ok){a(C);return}let E=ro(t,g.environment);if(!E.ok){a(E);return}let x=await Zr(l,C.value,t,n);if(!x.ok){a(x);return}let y=x.value,P={pluginApiName:p.pluginApiName,apiName:p.block.api_name,name:p.block.name},b={environment:g.environment,businessId:g.businessId,dashboard:y.dashboard},f=[...p.warnings.map(Op),...await Fp(n)],d=E.value;if(d.kind==="dry-run"){let R=[...f,...y.warnings],z={ok:!0,applied:!1,dryRun:!0,reason:d.reason,action:y.action,...b,dashletId:y.dashletId,url:y.url,resolvedBy:y.resolvedBy,block:P,method:y.method,path:y.path,body:y.body,warnings:R,...w?{forgotten:!0}:{}};Os(r,z,[...Dt(y.summary),`URL: ${y.url}`,...at(R),"",`${y.method} ${y.path}`,JSON.stringify(y.body,null,2),""].join(`
833
+ `),[...Dt(y.summary),...at(R),""].join(`
834
+ `)),d.reason==="no_yes"&&n.writeStderr(`${Rp}
835
+ `);return}let m=await eo(l,y,n);if(!m.ok){a(m);return}let k=m.value,S=[...f,...k.warnings],T=to(y.dashboard.id),_={ok:!0,applied:!0,dryRun:!1,action:y.action==="create"?"created":"updated",...b,dashletId:k.dashletId,url:y.url,...T?{refresh:T}:{},resolvedBy:y.resolvedBy,block:P,remembered:k.remembered,warnings:S,...w?{forgotten:!0}:{}};Os(r,_,[`\u2713 ${_.action==="created"?"Created":"Updated"} ${p.block.name} on "${y.dashboard.name}" (dashlet ${k.dashletId})`,...Dt(y.summary),`URL: ${y.url}`,...T?[`Refresh an open tab: ${T.script}`]:[],...at(S),""].join(`
836
+ `))}catch(c){a(Ke(c))}}var jp=(e,t)=>e.padEnd(t);function Vr(e,t){if(t.length===0)return[e," (none)"];let n=["NAME","ID","DASHLETS","ACCESS"],r=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),o=n.map((s,a)=>Math.max(s.length,...r.map(c=>(c[a]??"").length))),i=s=>` ${s.map((a,c)=>jp(a,o[c]??0)).join(" ")}`.trimEnd();return[e,i(n),...r.map(i)]}function Lp(e){let t=[`Environment: ${e.environment}`,`Business: ${e.businessId}`,""];return"object"in e?t.push(e.object===null?"Custom object: not found in /custom-objects":`Custom object: ${e.object.objectName} (${e.object.id})`,"",...Vr("Chart groups",e.surfaces.chart_group)):t.push(...Vr("Dashboards",e.surfaces.dashboard),"",...Vr("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(n=>` ${n.objectName} ${n.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
721
837
  `)}
722
- `}async function wi(e,t){let r={json:e.json===!0,deps:t},o="appbuilder block targets",n=e.object===void 0?[]:["--object",e.object],i=a=>[...a.args,...n],s=a=>{yi(r,a,o,i)};try{let a=await Zt(e,t);if(!a.ok){s(a);return}let{credentials:l}=a.value,p=await zc(t.createClient(l),l,e.object===void 0?{}:{object:e.object});if(!p.ok){s(p);return}t.writeStdout(r.json?`${JSON.stringify(p.value,null,2)}
723
- `:Qc(p.value))}catch(a){s(Ve(a))}}import{useEffect as Si,useState as rr}from"react";import{Box as se,Text as q,useApp as gd,useInput as Ti}from"ink";import"@kizenapps/packager";import{Box as nd,Text as od}from"ink";import{Box as ed,Text as td}from"ink";import{jsx as xi}from"react/jsx-runtime";var rd=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],vi=()=>xi(ed,{flexDirection:"column",children:rd.map((e,t)=>xi(td,{color:"cyan",children:e},t))});import{Fragment as id,jsx as gn,jsxs as sd}from"react/jsx-runtime";var K=({marginBottom:e=0})=>sd(id,{children:[gn(vi,{}),gn(nd,{flexDirection:"column",marginTop:1,marginBottom:e,children:gn(od,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useMemo as ad,useState as ld}from"react";import{Box as yn,Text as We,useInput as cd}from"ink";var er=(e,t,r)=>Math.min(Math.max(e,t),r);function tr(e,t,r,o={}){if(t<=0)return 0;let n=er(Math.trunc(e)||0,0,t-1),i=l=>o.disabled?.[l]!==!0;if(r===0)return n;let s=r>0?1:-1;if(Math.abs(r)===1){for(let l=1;l<=t;l++){let p=((n+s*l)%t+t)%t;if(i(p))return p}return n}let a=er(n+Math.trunc(r),0,t-1);for(let l=a;l>=0&&l<t;l+=s)if(i(l))return l;for(let l=a-s;l>=0&&l<t;l-=s)if(i(l))return l;return n}function ki(e,t,r=10){if(t<=0)return{start:0,end:0};let o=Math.max(1,Math.floor(r));if(t<=o)return{start:0,end:t};let n=er(Math.trunc(e)||0,0,t-1),i=er(n-Math.floor(o/2),0,t-o);return{start:i,end:i+o}}import{jsx as Ke,jsxs as wn}from"react/jsx-runtime";var dd="\u2191/\u2193 to move, Enter to select, Esc to cancel",bn=10,ud=e=>{let t=tr(0,e.length,0);if(e[t]?.disabled!==!0)return t;let r=e.findIndex(o=>o.disabled!==!0);return r===-1?t:r},Je=({title:e,items:t,onSelect:r,onCancel:o,hint:n=dd})=>{let[i,s]=ld(()=>ud(t)),a=ad(()=>t.map(f=>f.disabled===!0),[t]),l=tr(i,t.length,0);cd((f,c)=>{let h=x=>{s(tr(l,t.length,x,{disabled:a}))};if(c.upArrow||f==="k")h(-1);else if(c.downArrow||f==="j")h(1);else if(c.pageUp)h(-bn);else if(c.pageDown)h(bn);else if(c.return){let x=t[l];x!==void 0&&x.disabled!==!0&&r(x,l)}else c.escape&&o?.()});let{start:p,end:g}=ki(l,t.length,bn),v=p,k=t.length-g;return wn(yn,{flexDirection:"column",gap:1,children:[Ke(We,{bold:!0,children:e}),wn(yn,{flexDirection:"column",children:[v>0&&Ke(We,{dimColor:!0,children:` \u2191 ${String(v)} more`}),t.slice(p,g).map((f,c)=>{let x=p+c===l,I=f.disabled===!0,C=x&&!I;return wn(yn,{gap:2,children:[Ke(We,{...C&&{color:"cyan"},dimColor:I,children:x?"\u276F":" "}),Ke(We,{bold:C,dimColor:I,...C&&{color:"cyan"},children:f.label}),f.description!==void 0&&Ke(We,{dimColor:!0,children:f.description})]},f.key)}),k>0&&Ke(We,{dimColor:!0,children:` \u2193 ${String(k)} more`})]}),Ke(We,{dimColor:!0,children:n})]})};import{useEffect as pd,useState as fd}from"react";import{Text as md}from"ink";import{jsx as hd}from"react/jsx-runtime";var Ci=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ye=()=>{let[e,t]=fd(0);return pd(()=>{let r=setInterval(()=>{t(o=>(o+1)%Ci.length)},80);return()=>{clearInterval(r)}},[]),hd(md,{color:"cyan",children:Ci[e]??"\u280B"})};import{Fragment as _d,jsx as B,jsxs as J}from"react/jsx-runtime";var _i=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],yd={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},xn="\u2191/\u2193 to move, Enter to select, Esc to go back",bd="The block was edited in Kizen since your last push. Overwriting discards those edits.",nr=e=>e.args.includes("--create");function Pi(e,t){let r=e.filter(i=>i.value===t),o=e.filter(nr),n=e.filter(i=>i.value!==t&&!nr(i));return r.length>0?[...r,...n,...o]:[...o,...n]}function Ze(e,t){return(r,o)=>{let n=e[o];n!==void 0&&t(n)}}function wd(e,t){if(nr(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let r=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...r?{description:r}:{}}}function xd(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let r=[e.employeeAccess,e.hidden?"hidden":null].filter(o=>o!==null&&o!=="").join(" \xB7 ");return{key:e.id,label:t,...r===""?{}:{description:r}}}function vd(e,t,r){let o={...e,dashboard:t};return delete o.dashlet,delete o.create,nr(r)?{...o,create:!0}:{...o,dashlet:r.value}}function kd(e,t,r,o){let n=f=>{t.setExitCode(1),r({type:"error",view:f})},i=f=>{f().catch(c=>{n(Ve(c))})},s=async(f,c)=>{r({type:"applying",plan:c});let h=await pn(f,c,t);if(!h.ok){n(h);return}r({type:"done",plan:c,applied:h.value})},a=async(f,c,h)=>{r({type:"loading",label:"Preparing the push\u2026"});let x=await dn(f,c,h,t);if(!x.ok){if(x.code==="drift_detected"){r({type:"confirm",kind:"drift",message:x.message,target:c,options:h,context:f});return}n(x);return}if(h.dryRun){r({type:"done",plan:x.value,applied:null});return}if(h.yes){let I=hn(h,f.credentials.environment);if(I.ok&&I.value.kind==="apply"){await s(f,x.value);return}}r({type:"confirm",kind:"push",plan:x.value,options:h,context:f})},l=async(f,c,h)=>{r({type:"loading",label:"Resolving the target\u2026"});let x=await cn(f,c);if(x.ok){await a(f,x.value,c);return}let I=c.dashboard??f.entry?.dashboardId;if((x.code==="needs_choice"&&x.choice==="target"||x.code==="remembered_target_missing")&&x.choices&&x.choices.length>0&&I!==void 0){r({type:"target-select",dashboardId:I,title:"Choose a block to update, or create a new one",message:x.message,choices:Pi(x.choices,null),matchedId:null,back:h,options:c,context:f});return}n(x)},p=async(f,c,h)=>{let{context:x,forgotten:I}=await mn({client:t.createClient(c),credentials:c,block:h,forget:f.forget===!0},t);if(I&&o(C=>({...C,notices:[...C.notices,`Forgot the remembered target for ${h.block.api_name}.`]})),f.dashboard!==void 0||x.entry){await l(x,f,null);return}r({type:"surface-select",options:f,context:x})},g=async(f,c,h)=>{r({type:"packaging"});let x=await on(h,t);if(!x.ok){if(x.choice==="block"&&x.choices){r({type:"block-select",options:f,credentials:c,choices:x.choices});return}n(x);return}o(I=>({...I,warnings:x.value.warnings})),await p(f,c,x.value)},v=async f=>{r({type:"loading",label:"Loading credentials\u2026"});let c=await Zt(f,t);if(!c.ok){if(c.choice==="profile"&&c.choices){r({type:"profile-select",options:f,choices:c.choices});return}n(c);return}let{credentials:h}=c.value;o(x=>({...x,credentials:h})),await g(f,h,e)},k=async({options:f,context:c},h,x,I)=>{let C=yd[h];r({type:"loading",label:`Loading ${C}s\u2026`});let N=(await c.client.listDashboards(ko(h),x?.id)).map(d=>dt(d,h)),{environment:b,businessId:u}=c.credentials;if(N.length===0){n({message:`No ${C}s found${x?` on ${x.objectName}`:""} for business ${u} (${b}).`});return}r({type:"dashboard-select",surface:h,objectId:x?.id??null,title:x?`Choose a chart group on ${x.objectName}`:`Choose a ${C}`,rows:N,back:I,options:f,context:c})};return{start:f=>{i(()=>v(f))},pickProfile:(f,c)=>{i(()=>v({...f.options,profile:c.value}))},pickBlock:(f,c)=>{i(()=>g(f.options,f.credentials,c.value))},pickSurface:(f,c)=>{i(async()=>{if(c!=="chart_group"){await k(f,c,null,f);return}r({type:"loading",label:"Loading custom objects\u2026"});let h=await sn(f.context.client);if(h.length===0){n({message:"No custom objects found, so there are no chart groups to push to."});return}r({type:"object-select",objects:h,back:f,options:f.options,context:f.context})})},pickObject:(f,c)=>{i(()=>k(f,"chart_group",c,f))},pickDashboard:(f,c)=>{i(async()=>{let{context:h}=f,x={...f.options,dashboard:c.id};if(x.dashlet!==void 0||x.create){await l(h,x,f);return}r({type:"loading",label:`Loading "${c.name}"\u2026`});let I=await h.client.getDashboard(c.id),C=ln(h,I),S=C.kind==="map"||C.kind==="name"?C.dashlet.id:null;r({type:"target-select",dashboardId:I.id,title:`Choose what to push to on "${I.name}"`,message:null,choices:Pi(Qt(I,h.block),S),matchedId:S,back:f,options:x,context:h})})},pickTarget:(f,c)=>{i(()=>l(f.context,vd(f.options,f.dashboardId,c),f))},acceptDrift:f=>{i(()=>a(f.context,f.target,{...f.options,force:!0}))},acceptPush:f=>{i(()=>s(f.context,f.plan))},cancel:()=>{n({message:"Cancelled."})}}}var Ei=({prompt:e,strict:t,onAccept:r,onCancel:o})=>(Ti((n,i)=>{if(i.ctrl)return;let s=n.toLowerCase();s==="y"||!t&&i.return?r():(t||s==="n"||i.escape)&&o()}),B(q,{bold:!0,children:e})),Qe=({lines:e,color:t})=>B(se,{flexDirection:"column",children:e.map((r,o)=>B(q,{...t&&{color:t},children:r},`${String(o)}-${r}`))}),Ii=({plan:e})=>J(se,{flexDirection:"column",children:[B(Qe,{lines:ut(e.summary)}),J(q,{children:["URL: ",e.url]})]}),vn=({label:e})=>J(se,{gap:1,children:[B(ye,{}),B(q,{dimColor:!0,children:e})]}),Cd=({view:e})=>J(se,{flexDirection:"column",gap:1,children:[J(se,{gap:1,children:[B(q,{color:"red",children:"\u2717"}),B(q,{color:"red",children:e.issues&&e.issues.length>0?xe(e.issues):e.message})]}),e.hint!==void 0&&J(q,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&J(se,{flexDirection:"column",children:[B(q,{children:"Choices:"}),B(Qe,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Sd=({plan:e,applied:t})=>{let r=fn(e.dashboard.id);return t===null?J(se,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:"Dry run: nothing was written."}),B(Ii,{plan:e}),e.warnings.length>0&&B(Qe,{lines:He(e.warnings),color:"yellow"}),J(se,{flexDirection:"column",children:[J(q,{bold:!0,children:[e.method," ",e.path]}),B(q,{children:JSON.stringify(e.body,null,2)})]})]}):J(se,{flexDirection:"column",gap:1,children:[J(se,{gap:1,children:[B(q,{color:"green",children:"\u2713"}),J(q,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),J(se,{flexDirection:"column",children:[J(q,{children:["URL: ",e.url]}),r&&J(q,{dimColor:!0,children:["Refresh an open tab: ",r.script]})]}),t.warnings.length>0&&B(Qe,{lines:He(t.warnings),color:"yellow"})]})},Di=({apiName:e,options:t,deps:r})=>{let o=gd(),[n,i]=rr({type:"loading",label:"Loading credentials\u2026"}),[s,a]=rr({credentials:null,warnings:[],notices:[]}),[l]=rr(()=>kd(e,r,i,a)),[p]=rr(t);Si(()=>{l.start(p)},[l,p]),Si(()=>{(n.type==="done"||n.type==="error")&&o.exit()},[n,o]),Ti((v,k)=>{k.ctrl&&v==="c"&&n.type!=="done"&&n.type!=="error"&&(r.setExitCode(130),o.exit())});let g=v=>J(se,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[B(K,{}),s.credentials&&J(q,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.warnings.length>0&&B(q,{dimColor:!0,children:xe(s.warnings)}),s.notices.length>0&&B(Qe,{lines:s.notices}),v]});switch(n.type){case"loading":return g(B(vn,{label:n.label}));case"packaging":return g(B(vn,{label:"Packaging blocks\u2026"}));case"applying":return g(B(vn,{label:`Pushing ${n.plan.summary.blockName} to "${n.plan.dashboard.name}"\u2026`}));case"profile-select":return g(B(Je,{title:"Credential profile",items:n.choices.map(v=>({key:v.value,label:v.label})),onSelect:Ze(n.choices,v=>{l.pickProfile(n,v)}),onCancel:l.cancel},"profile"));case"block-select":return g(B(Je,{title:"Block to push",items:n.choices.map(v=>({key:v.value,label:v.label})),onSelect:Ze(n.choices,v=>{l.pickBlock(n,v)}),onCancel:l.cancel},"block"));case"surface-select":return g(B(Je,{title:"Where should the block go?",items:_i,onSelect:Ze(_i,v=>{l.pickSurface(n,v.key)}),onCancel:l.cancel},"surface"));case"object-select":return g(B(Je,{title:"Custom object",items:n.objects.map(v=>({key:v.id,label:v.objectName})),onSelect:Ze(n.objects,v=>{l.pickObject(n,v)}),onCancel:()=>{i(n.back)},hint:xn},"object"));case"dashboard-select":return g(B(Je,{title:n.title,items:n.rows.map(xd),onSelect:Ze(n.rows,v=>{l.pickDashboard(n,v)}),onCancel:()=>{i(n.back)},hint:xn},`dashboards-${n.surface}-${n.objectId??""}`));case"target-select":{let{back:v}=n;return g(J(_d,{children:[n.message!==null&&B(q,{color:"yellow",children:n.message}),B(Je,{title:n.title,items:n.choices.map(k=>wd(k,n.matchedId)),onSelect:Ze(n.choices,k=>{l.pickTarget(n,k)}),onCancel:v?()=>{i(v)}:l.cancel,...v&&{hint:xn}},`targets-${n.dashboardId}`)]}))}case"confirm":return n.kind==="drift"?g(J(se,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:bd}),B(q,{dimColor:!0,children:n.message}),B(Ei,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{l.acceptDrift(n)},onCancel:l.cancel},"drift")]})):g(J(se,{flexDirection:"column",gap:1,children:[B(Ii,{plan:n.plan}),n.plan.warnings.length>0&&B(Qe,{lines:He(n.plan.warnings),color:"yellow"}),n.plan.summary.isProduction&&B(q,{color:"red",bold:!0,children:"PRODUCTION"}),B(Ei,{prompt:n.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:n.plan.summary.isProduction,onAccept:()=>{l.acceptPush(n)},onCancel:l.cancel},"push")]}));case"done":return g(B(Sd,{plan:n.plan,applied:n.applied}));case"error":return g(B(Cd,{view:n.view}))}};var Ni=e=>`Error: ${e instanceof Error?e.message:String(e)}`,Id=e=>e instanceof Td?xe(e.issues):Ni(e),Ai=e=>{console.error(Ni(e)),process.exitCode=1};function Bi(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(r,o)=>{try{let n=await Oo(process.cwd(),r),{block:i,warnings:s}=n;s.length>0&&console.error(xe(s));let a=JSON.stringify(jo(n),null,2);console.log(a),o.copy&&console.error(await At(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(n){console.error(Id(n)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to a credentials JSON file").option("--profile <name>","stored credential profile to use").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").action(async(r,o)=>{try{if(!process.stdin.isTTY||!process.stdout.isTTY||o.json===!0){await bi(r,o,Xt(process.cwd()));return}let{waitUntilExit:n}=Ed(Pd(Di,{...r!==void 0&&{apiName:r},options:o,deps:Xt(process.cwd())}),{exitOnCtrlC:!1});await n()}catch(n){Ai(n)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to a credentials JSON file").option("--profile <name>","stored credential profile to use").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").action(async r=>{try{await wi(r,Xt(process.cwd()))}catch(o){Ai(o)}})}import{createElement as Bd}from"react";import{render as Rd}from"ink";import{useEffect as $i,useState as mt}from"react";import{Box as ht,Text as et,useApp as Dd}from"ink";import{PluginValidationError as Ad}from"@kizenapps/packager";function pt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as kn,Text as or}from"ink";import{jsx as Ri,jsxs as ft}from"react/jsx-runtime";var ir=({issues:e})=>{let t=e.filter(r=>r.severity==="error").length;return ft(kn,{flexDirection:"column",marginTop:1,children:[ft(or,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Gr(e)].map(([r,o])=>ft(kn,{flexDirection:"column",marginTop:1,children:[Ri(or,{bold:!0,children:r}),o.map((n,i)=>Ri(kn,{paddingLeft:2,children:ft(or,{color:n.severity==="error"?"red":"yellow",children:[n.severity==="error"?"\u2717":"\u26A0"," ",n.message," ",ft(or,{dimColor:!0,children:["(",n.rule,")"]})]})},`${n.rule}-${String(i)}`))]},r))]})};import{Fragment as Nd,jsx as Be,jsxs as qe}from"react/jsx-runtime";var Fi=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],sr={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",validating:"Validating plugin app",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},ji=({outputDir:e,pluginDir:t})=>{let r=Dd(),[o,n]=mt("creating-dir"),[i,s]=mt(!1),[a,l]=mt(null),[p,g]=mt(null),[v,k]=mt(null);$i(()=>{Lt(t,e,n).then(({bundleSize:h})=>{k(h),n("done")}).catch(h=>{h instanceof Ad?l(h.issues):g(h instanceof Error?h.message:String(h)),s(!0),process.exitCode=1})},[e,t]),$i(()=>{(o==="done"||i)&&r.exit()},[o,i,r]);let f=Fi.indexOf(o),c=o==="done";return qe(ht,{flexDirection:"column",paddingY:1,paddingX:2,children:[Be(K,{marginBottom:1}),qe(ht,{flexDirection:"column",gap:0,children:[Fi.map((h,x)=>{let I=o===h,C=c||f>x;return Be(ht,{gap:1,children:i&&x===f?qe(et,{color:"red",children:["\u2717 ",sr[h]]}):C?qe(et,{color:"green",children:["\u2713 ",sr[h]]}):I?qe(Nd,{children:[Be(ye,{}),Be(et,{children:sr[h]})]}):qe(et,{dimColor:!0,children:[" ",sr[h]]})},h)}),c&&v!==null&&Be(ht,{marginTop:1,gap:1,children:qe(et,{color:"green",children:["\u2713 bundle \u2014 ",pt(v)]})}),a!==null&&Be(ir,{issues:a}),p!==null&&Be(ht,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Be(et,{color:"red",children:p})})]})]})};function Oi(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),r=`${t}/.kizenapp`;ge(t);let{waitUntilExit:o}=Rd(Bd(ji,{outputDir:r,pluginDir:t}));await o()})}import{createElement as Eu}from"react";import{render as Tu}from"ink";import{useCallback as fr,useState as tt}from"react";import{Box as V,Text as D,useApp as xu,useInput as vu}from"ink";import{join as mr}from"path";import{access as gu,mkdir as lr,writeFile as Tn}from"fs/promises";import{dirname as yu,join as Ce}from"path";var Li=`{
838
+ `}async function Vs(e,t){let n={json:e.json===!0,deps:t},r="appbuilder block targets",o=e.object===void 0?[]:["--object",e.object],i=a=>[...a.args,...o],s=a=>{zs(n,a,r,i)};try{let a=await An(e,t);if(!a.ok){s(a);return}let{credentials:c,client:g,notices:u}=a.value;Us(t,u);let h=await _p(g,c,e.object===void 0?{}:{object:e.object});if(!h.ok){s(h);return}t.writeStdout(n.json?`${JSON.stringify(h.value,null,2)}
839
+ `:Lp(h.value))}catch(a){s(Ke(a))}}import{useEffect as Js,useState as $n}from"react";import{Box as ce,Text as Y,useApp as Xp,useInput as Zs}from"ink";import"@kizenapps/packager";import{Box as Hp,Text as Vp}from"ink";import{Box as Mp,Text as zp}from"ink";import{jsx as Ks}from"react/jsx-runtime";var Up=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],Ws=()=>Ks(Mp,{flexDirection:"column",children:Up.map((e,t)=>Ks(zp,{color:"cyan",children:e},t))});import{Fragment as Kp,jsx as oo,jsxs as Wp}from"react/jsx-runtime";var J=({marginBottom:e=0})=>Wp(Kp,{children:[oo(Ws,{}),oo(Hp,{flexDirection:"column",marginTop:1,marginBottom:e,children:oo(Vp,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as qp,useState as Jp}from"react";import{Text as Gp}from"ink";import{jsx as Yp}from"react/jsx-runtime";var qs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xe=()=>{let[e,t]=Jp(0);return qp(()=>{let n=setInterval(()=>{t(r=>(r+1)%qs.length)},80);return()=>{clearInterval(n)}},[]),Yp(Gp,{color:"cyan",children:qs[e]??"\u280B"})};import{Fragment as af,jsx as D,jsxs as G}from"react/jsx-runtime";var Gs=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Zp={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},io="\u2191/\u2193 to move, Enter to select, Esc to go back",Qp="The block was edited in Kizen since your last push. Overwriting discards those edits.",Nn=e=>e.args.includes("--create");function Ys(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Nn),o=e.filter(i=>i.value!==t&&!Nn(i));return n.length>0?[...n,...o,...r]:[...r,...o]}function gt(e,t){return(n,r)=>{let o=e[r];o!==void 0&&t(o)}}function ef(e,t){if(Nn(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function tf(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function nf(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Nn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function rf(e,t,n,r){let o=p=>{t.setExitCode(1),n({type:"error",view:p})},i=p=>{p().catch(l=>{o(Ke(l))})},s=async(p,l)=>{n({type:"applying",plan:l});let w=await eo(p,l,t);if(!w.ok){o(w);return}n({type:"done",plan:l,applied:w.value})},a=async(p,l,w)=>{n({type:"loading",label:"Preparing the push\u2026"});let C=await Zr(p,l,w,t);if(!C.ok){if(C.code==="drift_detected"){n({type:"confirm",kind:"drift",message:C.message,target:l,options:w,context:p});return}o(C);return}if(w.dryRun){n({type:"done",plan:C.value,applied:null});return}if(w.yes){let E=ro(w,p.credentials.environment);if(E.ok&&E.value.kind==="apply"){await s(p,C.value);return}}n({type:"confirm",kind:"push",plan:C.value,options:w,context:p})},c=async(p,l,w)=>{n({type:"loading",label:"Resolving the target\u2026"});let C=await Xr(p,l);if(C.ok){await a(p,C.value,l);return}let E=l.dashboard??p.entry?.dashboardId;if((C.code==="needs_choice"&&C.choice==="target"||C.code==="remembered_target_missing")&&C.choices&&C.choices.length>0&&E!==void 0){n({type:"target-select",dashboardId:E,title:"Choose a block to update, or create a new one",message:C.message,choices:Ys(C.choices,null),matchedId:null,back:w,options:l,context:p});return}o(C)},g=async(p,{credentials:l,client:w},C)=>{let{context:E,forgotten:x}=await no({client:w,credentials:l,block:C,forget:p.forget===!0},t);if(x&&r(y=>({...y,notices:[...y.notices,`Forgot the remembered target for ${C.block.api_name}.`]})),p.dashboard!==void 0||E.entry){await c(E,p,null);return}n({type:"surface-select",options:p,context:E})},u=async(p,l,w)=>{n({type:"packaging"});let C=await qr(w,t);if(!C.ok){if(C.choice==="block"&&C.choices){n({type:"block-select",options:p,resolved:l,choices:C.choices});return}o(C);return}r(E=>({...E,warnings:C.value.warnings})),await g(p,l,C.value)},h=async p=>{n({type:"loading",label:"Loading credentials\u2026"});let l=await An(p,t);if(!l.ok){if(l.choice==="environment"&&l.choices){n({type:"environment-select",options:p,choices:l.choices});return}o(l);return}r(w=>({...w,credentials:l.value.credentials,credentialNotices:l.value.notices})),await u(p,l.value,e)},v=async({options:p,context:l},w,C,E)=>{let x=Zp[w];n({type:"loading",label:`Loading ${x}s\u2026`});let P=(await l.client.listDashboards(Xi(w),C?.id)).map(d=>Nt(d,w)),{environment:b,businessId:f}=l.credentials;if(P.length===0){o({message:`No ${x}s found${C?` on ${C.objectName}`:""} for business ${f} (${b}).`});return}n({type:"dashboard-select",surface:w,objectId:C?.id??null,title:C?`Choose a chart group on ${C.objectName}`:`Choose a ${x}`,rows:P,back:E,options:p,context:l})};return{start:p=>{i(()=>h(p))},pickEnvironment:(p,l)=>{i(()=>h({...p.options,env:l.value}))},pickBlock:(p,l)=>{i(()=>u(p.options,p.resolved,l.value))},pickSurface:(p,l)=>{i(async()=>{if(l!=="chart_group"){await v(p,l,null,p);return}n({type:"loading",label:"Loading custom objects\u2026"});let w=await Jr(p.context.client);if(w.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:w,back:p,options:p.options,context:p.context})})},pickObject:(p,l)=>{i(()=>v(p,"chart_group",l,p))},pickDashboard:(p,l)=>{i(async()=>{let{context:w}=p,C={...p.options,dashboard:l.id};if(C.dashlet!==void 0||C.create){await c(w,C,p);return}n({type:"loading",label:`Loading "${l.name}"\u2026`});let E=await w.client.getDashboard(l.id),x=Yr(w,E),y=x.kind==="map"||x.kind==="name"?x.dashlet.id:null;n({type:"target-select",dashboardId:E.id,title:`Choose what to push to on "${E.name}"`,message:null,choices:Ys(In(E,w.block),y),matchedId:y,back:p,options:C,context:w})})},pickTarget:(p,l)=>{i(()=>c(p.context,nf(p.options,p.dashboardId,l),p))},acceptDrift:p=>{i(()=>a(p.context,p.target,{...p.options,force:!0}))},acceptPush:p=>{i(()=>s(p.context,p.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Xs=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Zs((o,i)=>{if(i.ctrl)return;let s=o.toLowerCase();s==="y"||!t&&i.return?n():(t||s==="n"||i.escape)&&r()}),D(Y,{bold:!0,children:e})),ct=({lines:e,color:t})=>D(ce,{flexDirection:"column",children:e.map((n,r)=>D(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),Qs=({plan:e})=>G(ce,{flexDirection:"column",children:[D(ct,{lines:Dt(e.summary)}),G(Y,{children:["URL: ",e.url]})]}),so=({label:e})=>G(ce,{gap:1,children:[D(xe,{}),D(Y,{dimColor:!0,children:e})]}),of=({view:e})=>G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"red",children:"\u2717"}),D(Y,{color:"red",children:e.issues&&e.issues.length>0?Ae(e.issues):e.message})]}),e.hint!==void 0&&G(Y,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&G(ce,{flexDirection:"column",children:[D(Y,{children:"Choices:"}),D(ct,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),sf=({plan:e,applied:t})=>{let n=to(e.dashboard.id);return t===null?G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:"Dry run: nothing was written."}),D(Qs,{plan:e}),e.warnings.length>0&&D(ct,{lines:at(e.warnings),color:"yellow"}),G(ce,{flexDirection:"column",children:[G(Y,{bold:!0,children:[e.method," ",e.path]}),D(Y,{children:JSON.stringify(e.body,null,2)})]})]}):G(ce,{flexDirection:"column",gap:1,children:[G(ce,{gap:1,children:[D(Y,{color:"green",children:"\u2713"}),G(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),G(ce,{flexDirection:"column",children:[G(Y,{children:["URL: ",e.url]}),n&&G(Y,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&D(ct,{lines:at(t.warnings),color:"yellow"})]})},ea=({apiName:e,options:t,deps:n})=>{let r=Xp(),[o,i]=$n({type:"loading",label:"Loading credentials\u2026"}),[s,a]=$n({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=$n(()=>rf(e,n,i,a)),[g]=$n(t);Js(()=>{c.start(g)},[c,g]),Js(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Zs((h,v)=>{v.ctrl&&h==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let u=h=>G(ce,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(J,{}),s.credentials&&G(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&D(ct,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&D(Y,{dimColor:!0,children:Ae(s.warnings)}),s.notices.length>0&&D(ct,{lines:s.notices}),h]});switch(o.type){case"loading":return u(D(so,{label:o.label}));case"packaging":return u(D(so,{label:"Packaging blocks\u2026"}));case"applying":return u(D(so,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return u(D(Te,{title:"Environment",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickEnvironment(o,h)}),onCancel:c.cancel},"environment"));case"block-select":return u(D(Te,{title:"Block to push",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:gt(o.choices,h=>{c.pickBlock(o,h)}),onCancel:c.cancel},"block"));case"surface-select":return u(D(Te,{title:"Where should the block go?",items:Gs,onSelect:gt(Gs,h=>{c.pickSurface(o,h.key)}),onCancel:c.cancel},"surface"));case"object-select":return u(D(Te,{title:"Custom object",items:o.objects.map(h=>({key:h.id,label:h.objectName})),onSelect:gt(o.objects,h=>{c.pickObject(o,h)}),onCancel:()=>{i(o.back)},hint:io},"object"));case"dashboard-select":return u(D(Te,{title:o.title,items:o.rows.map(tf),onSelect:gt(o.rows,h=>{c.pickDashboard(o,h)}),onCancel:()=>{i(o.back)},hint:io},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:h}=o;return u(G(af,{children:[o.message!==null&&D(Y,{color:"yellow",children:o.message}),D(Te,{title:o.title,items:o.choices.map(v=>ef(v,o.matchedId)),onSelect:gt(o.choices,v=>{c.pickTarget(o,v)}),onCancel:h?()=>{i(h)}:c.cancel,...h&&{hint:io}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?u(G(ce,{flexDirection:"column",gap:1,children:[D(Y,{color:"yellow",children:Qp}),D(Y,{dimColor:!0,children:o.message}),D(Xs,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):u(G(ce,{flexDirection:"column",gap:1,children:[D(Qs,{plan:o.plan}),o.plan.warnings.length>0&&D(ct,{lines:at(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&D(Y,{color:"red",bold:!0,children:"PRODUCTION"}),D(Xs,{prompt:o.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:o.plan.summary.isProduction,onAccept:()=>{c.acceptPush(o)},onCancel:c.cancel},"push")]}));case"done":return u(D(sf,{plan:o.plan,applied:o.applied}));case"error":return u(D(of,{view:o.view}))}};var na=e=>`Error: ${e instanceof Error?e.message:String(e)}`,uf=e=>e instanceof df?Ae(e.issues):na(e),ta=e=>{console.error(na(e)),process.exitCode=1};function ra(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(n,r)=>{try{let o=await fs(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(Ae(s));let a=JSON.stringify(ps(o),null,2);console.log(a),r.copy&&console.error(await mn(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(o){console.error(uf(o)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").option("--env <env>","environment of the `appbuilder login` session to use").action(async(n,r)=>{try{let o=Kr(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await Hs(n,r,o);return}let{waitUntilExit:i}=lf(cf(ea,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){ta(o)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").action(async n=>{try{await Vs(n,Kr(process.cwd()))}catch(r){ta(r)}})}import{createElement as hf}from"react";import{render as gf}from"ink";import{useEffect as ia,useState as Bt}from"react";import{Box as Ft,Text as yt,useApp as pf}from"ink";import{PluginValidationError as ff}from"@kizenapps/packager";function Rt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as ao,Text as Dn}from"ink";import{jsx as oa,jsxs as Ot}from"react/jsx-runtime";var Rn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Ot(ao,{flexDirection:"column",marginTop:1,children:[Ot(Dn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Lr(e)].map(([n,r])=>Ot(ao,{flexDirection:"column",marginTop:1,children:[oa(Dn,{bold:!0,children:n}),r.map((o,i)=>oa(ao,{paddingLeft:2,children:Ot(Dn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Ot(Dn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as mf,jsx as We,jsxs as lt}from"react/jsx-runtime";var sa=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],On={"creating-dir":"Creating .kizenapp directory","reading-files":"Reading plugin files",validating:"Validating plugin app",minifying:"Minifying scripts",packaging:"Packaging plugin","writing-bundle":"Writing bundle.json"},aa=({outputDir:e,pluginDir:t})=>{let n=pf(),[r,o]=Bt("creating-dir"),[i,s]=Bt(!1),[a,c]=Bt(null),[g,u]=Bt(null),[h,v]=Bt(null);ia(()=>{vn(t,e,o).then(({bundleSize:w})=>{v(w),o("done")}).catch(w=>{w instanceof ff?c(w.issues):u(w instanceof Error?w.message:String(w)),s(!0),process.exitCode=1})},[e,t]),ia(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let p=sa.indexOf(r),l=r==="done";return lt(Ft,{flexDirection:"column",paddingY:1,paddingX:2,children:[We(J,{marginBottom:1}),lt(Ft,{flexDirection:"column",gap:0,children:[sa.map((w,C)=>{let E=r===w,x=l||p>C;return We(Ft,{gap:1,children:i&&C===p?lt(yt,{color:"red",children:["\u2717 ",On[w]]}):x?lt(yt,{color:"green",children:["\u2713 ",On[w]]}):E?lt(mf,{children:[We(xe,{}),We(yt,{children:On[w]})]}):lt(yt,{dimColor:!0,children:[" ",On[w]]})},w)}),l&&h!==null&&We(Ft,{marginTop:1,gap:1,children:lt(yt,{color:"green",children:["\u2713 bundle \u2014 ",Rt(h)]})}),a!==null&&We(Rn,{issues:a}),g!==null&&We(Ft,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:We(yt,{color:"red",children:g})})]})]})};function ca(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;ve(t);let{waitUntilExit:r}=gf(hf(aa,{outputDir:n,pluginDir:t}));await r()})}import{createElement as cm}from"react";import{render as lm}from"ink";import{useCallback as Un,useState as bt}from"react";import{Box as K,Text as $,useApp as nm,useInput as rm}from"ink";import{join as Hn}from"path";import{access as Zf,mkdir as Fn,writeFile as mo}from"fs/promises";import{dirname as Qf,join as Ie}from"path";var la=`{
724
840
  "name": "Hello Frame",
725
841
  "api_name": "hello_frame",
726
842
  "title": "Hello Frame",
@@ -729,13 +845,13 @@ export const sumBy = (records, name, valueOf) =>
729
845
  "height": 320,
730
846
  "width": 280
731
847
  }
732
- `;var zi=`this.outputUI(\`
848
+ `;var da=`this.outputUI(\`
733
849
  <div class="hello-frame">
734
850
  <h2 class="hello-frame__title">Hello from a floating frame</h2>
735
851
  <p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
736
852
  </div>
737
853
  \`);
738
- `;var Mi=`.hello-frame {
854
+ `;var ua=`.hello-frame {
739
855
  padding: 16px;
740
856
  font-family: system-ui, sans-serif;
741
857
  }
@@ -749,18 +865,18 @@ export const sumBy = (records, name, valueOf) =>
749
865
  margin: 0;
750
866
  color: #555;
751
867
  }
752
- `;var Ui=`{
868
+ `;var pa=`{
753
869
  "name": "Hello Block",
754
870
  "api_name": "hello_block",
755
871
  "types": ["dashboards"]
756
872
  }
757
- `;var Hi=`this.outputUI(\`
873
+ `;var fa=`this.outputUI(\`
758
874
  <div class="hello-block">
759
875
  <h2 class="hello-block__title">Hello from a block</h2>
760
876
  <p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
761
877
  </div>
762
878
  \`);
763
- `;var Vi=`.hello-block {
879
+ `;var ma=`.hello-block {
764
880
  padding: 16px;
765
881
  font-family: system-ui, sans-serif;
766
882
  background: #f8fafc;
@@ -776,25 +892,25 @@ export const sumBy = (records, name, valueOf) =>
776
892
  margin: 0;
777
893
  color: #555;
778
894
  }
779
- `;var Wi=`{
895
+ `;var ha=`{
780
896
  "icon": "phone",
781
897
  "color": "#0ea5e9",
782
898
  "tooltip": "Hello adornment",
783
899
  "field_type": "phonenumber"
784
900
  }
785
- `;var Ki=`this.showToast('Hello from a data adornment.', { variant: 'success' });
786
- `;var Ji=`{
901
+ `;var ga=`this.showToast('Hello from a data adornment.', { variant: 'success' });
902
+ `;var ya=`{
787
903
  "name": "Hello Page",
788
904
  "api_name": "hello_page"
789
905
  }
790
- `;var qi=`this.outputUI(\`
906
+ `;var ba=`this.outputUI(\`
791
907
  <div class="hello-page">
792
908
  <p class="hello-page__loading">Loading\u2026</p>
793
909
  </div>
794
910
  \`);
795
911
 
796
912
  this.runEventScript('greet');
797
- `;var Gi=`.hello-page {
913
+ `;var wa=`.hello-page {
798
914
  padding: 24px;
799
915
  font-family: system-ui, sans-serif;
800
916
  }
@@ -832,7 +948,7 @@ this.runEventScript('greet');
832
948
  .hello-page__button:hover {
833
949
  background: #cbd5e1;
834
950
  }
835
- `;var Yi=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
951
+ `;var va=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
836
952
 
837
953
  const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
838
954
 
@@ -855,33 +971,33 @@ this.outputUI(\`
855
971
  </div>
856
972
  </div>
857
973
  \`);
858
- `;var Xi=`{
974
+ `;var xa=`{
859
975
  "api_name": "hello_toolbar_item",
860
976
  "label": "Hello Toolbar Item",
861
977
  "icon": "star",
862
978
  "color": "#0ea5e9"
863
979
  }
864
- `;var Zi=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
865
- `;var Qi=`{
980
+ `;var ka=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
981
+ `;var Ca=`{
866
982
  "api_name": "hello_object_settings_item",
867
983
  "label": "Hello Object Settings"
868
984
  }
869
- `;var es=`this.showToast('Hello from an object settings item.', { variant: 'success' });
870
- `;var ts=`{
985
+ `;var Sa=`this.showToast('Hello from an object settings item.', { variant: 'success' });
986
+ `;var Pa=`{
871
987
  "name": "Hello Action",
872
988
  "api_name": "hello_action",
873
989
  "hint_object_name": "client_client"
874
990
  }
875
- `;var rs=`this.showToast('Hello from a JS action.', { variant: 'success' });
876
- `;var oe=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],Cn={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},Qd={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":Li,"script.js":zi,"styles.css":Mi}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Ui,"script.js":Hi,"styles.css":Vi}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Wi,"script.js":Ki}},page:{directory:"pages",component:"helloPage",files:{"config.json":Ji,"script.js":qi,"styles.css":Gi,"eventScripts/greet.js":Yi}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":Xi,"script.js":Zi}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Qi,"script.js":es}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":ts,"script.js":rs}}};function eu(e,t="src"){let{directory:r,component:o,files:n}=Qd[e];return Object.entries(n).map(([i,s])=>({path:`${t}/${r}/${o}/${i}`,content:s}))}function ns(e,t="src"){return[...new Set(e)].flatMap(r=>eu(r,t))}import{deflateSync as tu}from"zlib";var _n=512,ru=150,nu=26,Pn=46,os=.6,ou=Pn*.55,iu=.55,su=.47;function au(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t}function lu(e){let t=au(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function cu(e,t,r){let o=(1-Math.abs(2*r-1))*t,n=e/60,i=o*(1-Math.abs(n%2-1)),s=r-o/2,[a,l,p]=n<1?[o,i,0]:n<2?[i,o,0]:n<3?[0,o,i]:n<4?[0,i,o]:n<5?[i,0,o]:[o,0,i];return[Math.round((a+s)*255),Math.round((l+s)*255),Math.round((p+s)*255)]}function gt(e,t,r,o,n){let i=Math.abs(e)-r+n,s=Math.abs(t)-o+n;return Math.hypot(Math.max(i,0),Math.max(s,0))+Math.min(Math.max(i,s),0)-n}function ar(e,t,r,o,n){return Math.hypot(e-r,t-o)-n}function du(e,t){let r=ru,o=Pn,n=o*os,i=ou,s=gt(e,t,r,r,nu),a=Math.min(ar(e,t,0,-r-n,o),gt(e,t+r+n/2,i,n/2+1,0)),l=Math.min(ar(e,t,r+n,0,o),gt(e-r-n/2,t,n/2+1,i,0));s=Math.min(s,a,l);let p=Math.min(ar(e,t,0,r-n,o),gt(e,t-r+n/2,i,n/2+1,0)),g=Math.min(ar(e,t,-r+n,0,o),gt(e+r-n/2,t,n/2+1,i,0));return Math.max(s,-p,-g)}function uu(e){let t=_n,r=new Uint8Array(t*t*4),[o,n,i]=cu(e.hue,iu,su),s=Pn*(1+os),a=(t-1)/2,l=s/2;for(let p=0;p<t;p+=1)for(let g=0;g<t;g+=1){let v=g-a,k=p-a;for(let x=0;x<e.quarterTurns;x+=1)[v,k]=[-k,v];let f=du(v+l,k-l),c=Math.min(1,Math.max(0,.5-f));if(c<=0)continue;let h=(p*t+g)*4;r[h]=o,r[h+1]=n,r[h+2]=i,r[h+3]=Math.round(c*255)}return r}var pu=new Uint32Array(256).map((e,t)=>{let r=t;for(let o=0;o<8;o+=1)r=r&1?3988292384^r>>>1:r>>>1;return r>>>0});function fu(e){let t=4294967295;for(let r of e)t=(pu[(t^r)&255]??0)^t>>>8;return(t^4294967295)>>>0}function Sn(e,t){let r=Buffer.from(e,"latin1"),o=Buffer.alloc(4);o.writeUInt32BE(t.length);let n=Buffer.alloc(4);return n.writeUInt32BE(fu(Buffer.concat([r,t]))),Buffer.concat([o,r,t,n])}var mu=Buffer.from([137,80,78,71,13,10,26,10]);function hu(e,t,r){if(r.length!==e*t*4)throw new Error(`encodePng: expected ${String(e*t*4)} bytes of RGBA for ${String(e)}x${String(t)}, got ${String(r.length)}`);let o=Buffer.alloc(13);o.writeUInt32BE(e,0),o.writeUInt32BE(t,4),o[8]=8,o[9]=6;let n=e*4,i=Buffer.alloc((n+1)*t);for(let s=0;s<t;s+=1)i.set(r.subarray(s*n,(s+1)*n),s*(n+1)+1);return Buffer.concat([mu,Sn("IHDR",o),Sn("IDAT",tu(i,{level:9})),Sn("IEND",new Uint8Array(0))])}function is(e){return hu(_n,_n,uu(lu(e)))}var bu="src/thumbnail.png",wu=["go","fmo"];async function cr(e){try{return await gu(e),!0}catch{return!1}}async function Re(e){return await cr(Ce(e,"kizen.json"))?"has-manifest":await cr(Ce(e,".kizenapp"))?"has-kizenapp":"ok"}async function ss(e,t){let r=Ce(e,t);if(!await cr(r))return r;for(let o=1;o<1e3;o++){let n=Ce(e,`${t}-${String(o)}`);if(!await cr(n))return n}throw new Error(`Could not find an available directory name for "${t}"`)}function In(e){let t=e.developerBusinessId.trim(),r=t!==""&&!wu.includes(e.developerEnvironment)?[e.developerEnvironment]:["prod"];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:r,config_template:{},base_config:{},...t?{developer_business_id:{[e.developerEnvironment]:t}}:{}}}async function En(e,t){let r=t.map(n=>({fullPath:Ce(e,...n.path.split("/")),content:n.content})),o=new Set(r.map(n=>yu(n.fullPath)));await Promise.all([...o].map(n=>lr(n,{recursive:!0}))),await Promise.all(r.map(n=>Tn(n.fullPath,n.content,"utf-8")))}async function dr(e){await lr(e.targetDir,{recursive:!0});let t=In(e);await Tn(Ce(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
877
- `,"utf-8"),await lr(Ce(e.targetDir,"src"),{recursive:!0}),await lr(Ce(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([En(e.targetDir,ns(e.artifacts??[])),En(e.targetDir,Ht()),En(e.targetDir,Vt(e.includeLib===!0?["src"]:[])),Tn(Ce(e.targetDir,...bu.split("/")),is(e.apiName))]),ge(e.targetDir)}var $e=["name","apiName","externalLink","description","developerBusinessId"],ur={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Dn=["name","apiName","description"],An=/^[a-z_][a-z0-9_]+$/,Nn="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function pr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function as(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function ls(e,t){let r=t.trim();if(Dn.includes(e)&&!r)return`${ur[e]} is required`;if(e==="apiName"&&!An.test(r))return`${ur[e]} ${Nn}`}function cs(e,t){return e==="description"?t:t.trim()}function ds(e,t){let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),oe.filter(o=>r.has(o))}import{jsx as T,jsxs as $}from"react/jsx-runtime";var Ge=({text:e})=>T(D,{dimColor:!0,children:e}),us=({parentDir:e,defaultBusinessId:t,defaultEnvironment:r,includeLib:o=!1})=>{let n=xu(),[i,s]=tt({type:"target-select",cursor:0}),[a,l]=tt("in-place"),[p,g]=tt(()=>as(t)),[v,k]=tt(()=>[...oe]),[f,c]=tt(""),[h,x]=tt(e),I=fr((b,u)=>{l(b),c(u.name),s({type:"field-entry",field:0,values:u})},[]),C=fr(async b=>{let u=await Re(b);if(u!=="ok"){s({type:"precheck-error",targetDir:b,reason:u});return}x(b),I("in-place",p)},[p,I]),S=fr(async(b,u)=>{try{let d=await ss(e,b.apiName);x(d),s({type:"confirm",values:b,artifacts:u})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),N=fr(async(b,u,d)=>{try{await dr({targetDir:u,name:b.name,apiName:b.apiName,externalLink:b.externalLink,description:b.description,developerBusinessId:b.developerBusinessId,developerEnvironment:r,artifacts:d,includeLib:o}),s({type:"done",targetDir:u})}catch(m){s({type:"error",message:m instanceof Error?m.message:String(m)})}},[r,o]);if(vu((b,u)=>{if(u.ctrl&&b==="c"){n.exit();return}if(i.type==="target-select"){u.upArrow?s({type:"target-select",cursor:0}):u.downArrow?s({type:"target-select",cursor:1}):u.return?i.cursor===0?C(e):I("sub-dir",p):u.escape&&n.exit();return}if(i.type==="precheck-error"){(u.return||u.escape)&&n.exit();return}if(i.type==="field-entry"){let{field:d,values:m}=i,y=$e[d];if(!y)return;if(u.escape){n.exit();return}if(u.backspace||u.delete){c(w=>w.slice(0,-1));return}if(u.upArrow&&d>0){let w={...m,[y]:f},E=d-1,_=$e[E];s({type:"field-entry",field:E,values:w}),g(w),c(_?w[_]:"");return}if(u.return||u.tab||u.downArrow){let w=ls(y,f);if(w!==void 0){s({type:"field-entry",field:d,values:m,fieldError:w});return}let E=cs(y,f),_={...m,[y]:E};g(_);let R=d+1;if(R>=$e.length)c(""),s({type:"artifact-select",values:_,cursor:0,selected:v});else{let M=$e[R],X=M?_[M]:"",ie=M==="apiName"&&!X?pr(_.name):X;s({type:"field-entry",field:R,values:_}),c(ie)}return}b&&!u.ctrl&&!u.meta&&c(w=>w+b);return}if(i.type==="artifact-select"){let{cursor:d,selected:m,values:y}=i;if(u.escape){let w=$e.length-1,E=$e[w];s({type:"field-entry",field:w,values:y}),c(E?y[E]:"");return}if(u.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(u.downArrow){s({...i,cursor:Math.min(oe.length-1,d+1)});return}if(b===" "){let w=oe[d];if(w){let E=ds(m,w);k(E),s({...i,selected:E})}return}if(b==="a"){k([...oe]),s({...i,selected:[...oe]});return}if(b==="n"){k([]),s({...i,selected:[]});return}u.return&&(a==="sub-dir"?(s({type:"resolving-target"}),S(y,m)):s({type:"confirm",values:y,artifacts:m}));return}if(i.type==="confirm"){if(u.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}u.return&&(s({type:"writing"}),N(i.values,h,i.artifacts));return}(i.type==="done"||i.type==="error")&&(u.return||u.escape)&&n.exit()}),i.type==="target-select"){let b=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Where should the new plugin live?"}),b.map((u,d)=>{let m=i.cursor===d;return $(V,{gap:2,children:[T(D,{...m&&{color:"cyan"},children:m?"\u276F":" "}),T(D,{bold:m,...m&&{color:"cyan"},children:u.label}),T(D,{dimColor:!0,children:u.desc})]},u.label)})]}),T(Ge,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:b,reason:u}=i;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),T(D,{color:"red",bold:!0,children:"Cannot create plugin"}),$(V,{flexDirection:"column",gap:0,children:[$(D,{children:[b," already contains ",T(D,{bold:!0,children:u==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),T(D,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),T(Ge,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:b,fieldError:u}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${h}`;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Plugin details"}),T(D,{dimColor:!0,children:d})]}),u!==void 0&&$(D,{color:"red",children:["Error: ",u]}),T(V,{flexDirection:"column",gap:0,children:$e.map((m,y)=>{let w=b===y,E=w?f:p[m],_=Dn.includes(m),R=`${ur[m]}${_?"":" (optional)"}`;return $(V,{gap:2,children:[T(V,{width:24,children:T(D,{bold:w,...w&&{color:"cyan"},children:R})}),T(D,{...w&&{color:"cyan"},children:">"}),T(D,{children:E}),w&&T(D,{color:"cyan",children:"\u2588"})]},m)})}),T(Ge,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:b,selected:u}=i;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Which artifacts should we scaffold?"}),T(D,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),T(V,{flexDirection:"column",gap:0,children:oe.map((d,m)=>{let y=b===m,w=u.includes(d);return $(V,{gap:1,children:[T(D,{...y&&{color:"cyan"},children:y?"\u276F":" "}),T(D,{...w&&{color:"green"},children:w?"\u25C9":"\u25EF"}),T(D,{bold:y,...y&&{color:"cyan"},children:Cn[d]})]},d)})}),T(Ge,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let b=In({targetDir:h,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:r});return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Ready to create"}),$(D,{dimColor:!0,children:["Target: ",h]})]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"kizen.json preview"}),T(D,{children:JSON.stringify(b,null,2)})]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?$(D,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(u=>$(D,{dimColor:!0,children:[" ",Cn[u]]},u))]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{dimColor:!0,children:"Also creates:"}),$(D,{dimColor:!0,children:[" ",mr(h,"src/")]}),$(D,{dimColor:!0,children:[" ",mr(h,"src/thumbnail.png")," (generated placeholder)"]}),$(D,{dimColor:!0,children:[" ",mr(h,"releaseNotes/")]}),$(D,{dimColor:!0,children:[" ",mr(h,".gitignore")," (adds .kizenapp/)"]})]}),T(Ge,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?T(V,{paddingY:1,paddingX:2,children:T(D,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?T(V,{paddingY:1,paddingX:2,children:T(D,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),$(D,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),$(V,{flexDirection:"column",gap:0,children:[T(D,{dimColor:!0,children:"Next steps:"}),$(D,{children:[" ","cd ",i.targetDir]}),$(D,{children:[" ","npx --yes @kizenapps/cli dev"]}),$(D,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),T(Ge,{text:"Enter or Esc to exit"})]}):$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[T(K,{}),T(D,{color:"red",bold:!0,children:"Failed to create plugin"}),T(D,{children:i.message}),T(Ge,{text:"Enter or Esc to exit"})]})};var ku="A hello-world Kizen plugin.",ps=e=>Object.entries(e).some(([t,r])=>t!=="includeLib"&&r!==void 0);function Cu(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...oe];if(e.trim()==="none")return[];let t=e.split(",").map(o=>o.trim()).filter(o=>o!==""),r=t.filter(o=>!oe.includes(o));if(r.length>0)throw new Error(`Unknown artifact type(s): ${r.join(", ")}. Valid types: ${oe.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function Su(e,t,r){let o=e.name?.trim()??"";if(o==="")throw new Error("--name is required for a non-interactive run.");let n=(e.apiName?.trim()??"")||pr(o);if(!An.test(n))throw new Error(`api_name "${n}" is invalid: ${Nn}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=Pu(e,t);return{targetDir:r,name:o,apiName:n,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?ku:i,developerBusinessId:s,developerEnvironment:a,artifacts:Cu(e.artifacts),includeLib:e.includeLib===!0}}function _u(e){return Z.includes(e)}function Pu(e,t){let r=e.environment?.trim();if(r!==void 0&&r!==""){if(!_u(r))throw new Error(`Unknown environment "${r}". Valid environments: ${Z.join(", ")}.`);return r}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when no credentials are saved, so the id is keyed to the environment that issued it.");return t.environment}async function fs(e,t,r,o){let n;try{n=Su(e,t,r)}catch(a){o.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
878
- `),o.setExitCode(1);return}let i=await o.precheckTargetDir(r);if(i!=="ok"){let a=i==="has-manifest"?"kizen.json":".kizenapp/";o.writeStderr(`Error: ${r} already contains ${a}. Refusing to overwrite an existing plugin.
879
- `),o.setExitCode(1);return}try{await o.createPlugin(n)}catch(a){o.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
880
- `),o.setExitCode(1);return}let s=n.artifacts&&n.artifacts.length>0?n.artifacts.join(", "):"none";o.writeStdout(`Created plugin ${n.apiName} at ${r}
881
- `),o.writeStdout(`Artifacts: ${s}
882
- `),o.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
883
- `),n.developerBusinessId.trim()===""&&o.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
884
- `)}function ms(e){e.command("create").description("Scaffold a new Kizen plugin project").option("-n, --name <name>","plugin display name (implies a non-interactive run)").option("-a, --api-name <name>","plugin api_name (inferred from --name when omitted)").option("-d, --description <text>","plugin description").option("-l, --external-link <url>","external link shown on the plugin listing").option("-b, --business-id <id>","developer business id (defaults to saved credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${Z.join(", ")} (defaults to saved credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${oe.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let r=process.cwd(),o=await re(),n=o?.businessId??"",i=o?.environment??"go";if(!process.stdin.isTTY||!process.stdout.isTTY||ps(t)){await fs(t,{businessId:n,environment:i},r,{precheckTargetDir:Re,createPlugin:dr,writeStdout:l=>{process.stdout.write(l)},writeStderr:l=>{process.stderr.write(l)},setExitCode:l=>{process.exitCode=l}});return}let{waitUntilExit:a}=Tu(Eu(us,{parentDir:r,defaultBusinessId:n,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as Js}from"react";import{render as qs}from"ink";import{useCallback as rt,useEffect as vr,useRef as Se,useState as ae}from"react";import{Box as ee,Text as F,useInput as Pp}from"ink";import{PluginValidationError as Ep}from"@kizenapps/packager";import{watch as Tp}from"fs";import{createServer as Ip}from"http";import{join as Vs}from"path";import{WebSocketServer as Dp}from"ws";import{createReadStream as Is,realpathSync as Ju}from"fs";import{access as qu,readdir as Gu,readFile as Yu,realpath as Xu,stat as Ds}from"fs/promises";import{dirname as Zu,extname as As,join as kt,resolve as Qu,sep as Un}from"path";import{fileURLToPath as ep}from"url";var Iu=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function hr(e){let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();Iu.has(n)||n.startsWith("access-control-")||(t[r]=o)}return t}var Bn=10*1024*1024,Du=6e4,Au=200,yt=class extends Error{bytesRead;limit;constructor(t,r){super(`Upstream response exceeded ${String(r)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=r}};async function Rn(e,t){let r=e.body;if(r===null)return Buffer.alloc(0);let o=[],n=0;for await(let i of r){if(n+=i.length,n>t)throw new yt(n,t);o.push(i)}return Buffer.concat(o)}async function hs(e){let t=hr(Object.fromEntries(e.headers)),r=await Rn(e,Bn);return{status:e.status,headers:t,body:r}}function gs(e={}){let{onChange:t,enabled:r=!0}=e;if(!r)return{async get(s,a){return{response:await hs(await a()),fromCache:!1}},clear(){}};let o=new Map,n=()=>{t?.(o.size)},i=s=>{o.delete(s)&&n()};return{get(s,a){let l=o.get(s);if(l!==void 0){if(Date.now()-l.insertedAt<Du)return l.promise.then(g=>({response:g,fromCache:!0}));i(s)}if(o.size>=Au){let g=o.keys().next().value;g!==void 0&&i(g)}let p=a().then(hs).catch(g=>{throw i(s),g});return o.set(s,{insertedAt:Date.now(),promise:p}),n(),p.then(g=>((g.status<200||g.status>=300)&&i(s),{response:g,fromCache:!1}))},clear(){o.clear(),n()}}}var $n={".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"};var Fn={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function bt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Fn.prod:process.env.PLUGIN_WIZARD_URL_DEV!==void 0&&process.env.PLUGIN_WIZARD_URL_DEV!==""?process.env.PLUGIN_WIZARD_URL_DEV:process.env.APPBUILDER_LOCAL_DEV!==void 0&&process.env.APPBUILDER_LOCAL_DEV!==""?Fn.localDev:Fn.dev}import{spawn as zn}from"child_process";import{writeFile as vs,rm as Ln,mkdtemp as $u,access as Fu}from"fs/promises";import{join as xt}from"path";import{tmpdir as ju}from"os";var ys=`awslambdaric
991
+ `;var Ea=`this.showToast('Hello from a JS action.', { variant: 'success' });
992
+ `;var se=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],co={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},Of={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":la,"script.js":da,"styles.css":ua}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":pa,"script.js":fa,"styles.css":ma}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":ha,"script.js":ga}},page:{directory:"pages",component:"helloPage",files:{"config.json":ya,"script.js":ba,"styles.css":wa,"eventScripts/greet.js":va}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":xa,"script.js":ka}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Ca,"script.js":Sa}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":Pa,"script.js":Ea}}};function Bf(e,t="src"){let{directory:n,component:r,files:o}=Of[e];return Object.entries(o).map(([i,s])=>({path:`${t}/${n}/${r}/${i}`,content:s}))}function _a(e,t="src"){return[...new Set(e)].flatMap(n=>Bf(n,t))}import{deflateSync as Ff}from"zlib";var uo=512,jf=150,Lf=26,po=46,Ta=.6,Mf=po*.55,zf=.55,Uf=.47;function Hf(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t}function Vf(e){let t=Hf(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function Kf(e,t,n){let r=(1-Math.abs(2*n-1))*t,o=e/60,i=r*(1-Math.abs(o%2-1)),s=n-r/2,[a,c,g]=o<1?[r,i,0]:o<2?[i,r,0]:o<3?[0,r,i]:o<4?[0,i,r]:o<5?[i,0,r]:[r,0,i];return[Math.round((a+s)*255),Math.round((c+s)*255),Math.round((g+s)*255)]}function jt(e,t,n,r,o){let i=Math.abs(e)-n+o,s=Math.abs(t)-r+o;return Math.hypot(Math.max(i,0),Math.max(s,0))+Math.min(Math.max(i,s),0)-o}function Bn(e,t,n,r,o){return Math.hypot(e-n,t-r)-o}function Wf(e,t){let n=jf,r=po,o=r*Ta,i=Mf,s=jt(e,t,n,n,Lf),a=Math.min(Bn(e,t,0,-n-o,r),jt(e,t+n+o/2,i,o/2+1,0)),c=Math.min(Bn(e,t,n+o,0,r),jt(e-n-o/2,t,o/2+1,i,0));s=Math.min(s,a,c);let g=Math.min(Bn(e,t,0,n-o,r),jt(e,t-n+o/2,i,o/2+1,0)),u=Math.min(Bn(e,t,-n+o,0,r),jt(e+n-o/2,t,o/2+1,i,0));return Math.max(s,-g,-u)}function qf(e){let t=uo,n=new Uint8Array(t*t*4),[r,o,i]=Kf(e.hue,zf,Uf),s=po*(1+Ta),a=(t-1)/2,c=s/2;for(let g=0;g<t;g+=1)for(let u=0;u<t;u+=1){let h=u-a,v=g-a;for(let C=0;C<e.quarterTurns;C+=1)[h,v]=[-v,h];let p=Wf(h+c,v-c),l=Math.min(1,Math.max(0,.5-p));if(l<=0)continue;let w=(g*t+u)*4;n[w]=r,n[w+1]=o,n[w+2]=i,n[w+3]=Math.round(l*255)}return n}var Jf=new Uint32Array(256).map((e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function Gf(e){let t=4294967295;for(let n of e)t=(Jf[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function lo(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let o=Buffer.alloc(4);return o.writeUInt32BE(Gf(Buffer.concat([n,t]))),Buffer.concat([r,n,t,o])}var Yf=Buffer.from([137,80,78,71,13,10,26,10]);function Xf(e,t,n){if(n.length!==e*t*4)throw new Error(`encodePng: expected ${String(e*t*4)} bytes of RGBA for ${String(e)}x${String(t)}, got ${String(n.length)}`);let r=Buffer.alloc(13);r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=8,r[9]=6;let o=e*4,i=Buffer.alloc((o+1)*t);for(let s=0;s<t;s+=1)i.set(n.subarray(s*o,(s+1)*o),s*(o+1)+1);return Buffer.concat([Yf,lo("IHDR",r),lo("IDAT",Ff(i,{level:9})),lo("IEND",new Uint8Array(0))])}function Aa(e){return Xf(uo,uo,qf(Vf(e)))}var em="src/thumbnail.png",tm=["go","fmo"];async function jn(e){try{return await Zf(e),!0}catch{return!1}}async function qe(e){return await jn(Ie(e,"kizen.json"))?"has-manifest":await jn(Ie(e,".kizenapp"))?"has-kizenapp":"ok"}async function Ia(e,t){let n=Ie(e,t);if(!await jn(n))return n;for(let r=1;r<1e3;r++){let o=Ie(e,`${t}-${String(r)}`);if(!await jn(o))return o}throw new Error(`Could not find an available directory name for "${t}"`)}function ho(e){let t=e.developerBusinessId.trim(),n=t!==""&&!tm.includes(e.developerEnvironment)?[e.developerEnvironment]:["prod"];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:n,config_template:{},base_config:{},...t?{developer_business_id:{[e.developerEnvironment]:t}}:{}}}async function fo(e,t){let n=t.map(o=>({fullPath:Ie(e,...o.path.split("/")),content:o.content})),r=new Set(n.map(o=>Qf(o.fullPath)));await Promise.all([...r].map(o=>Fn(o,{recursive:!0}))),await Promise.all(n.map(o=>mo(o.fullPath,o.content,"utf-8")))}async function Ln(e){await Fn(e.targetDir,{recursive:!0});let t=ho(e);await mo(Ie(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
993
+ `,"utf-8"),await Fn(Ie(e.targetDir,"src"),{recursive:!0}),await Fn(Ie(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([fo(e.targetDir,_a(e.artifacts??[])),fo(e.targetDir,kn()),fo(e.targetDir,Cn(e.includeLib===!0?["src"]:[])),mo(Ie(e.targetDir,...em.split("/")),Aa(e.apiName))]),ve(e.targetDir)}var Je=["name","apiName","externalLink","description","developerBusinessId"],Mn={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},go=["name","apiName","description"],yo=/^[a-z_][a-z0-9_]+$/,bo="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function zn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function $a(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function Na(e,t){let n=t.trim();if(go.includes(e)&&!n)return`${Mn[e]} is required`;if(e==="apiName"&&!yo.test(n))return`${Mn[e]} ${bo}`}function Da(e,t){return e==="description"?t:t.trim()}function Ra(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),se.filter(r=>n.has(r))}import{jsx as I,jsxs as B}from"react/jsx-runtime";var dt=({text:e})=>I($,{dimColor:!0,children:e}),Oa=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=nm(),[i,s]=bt({type:"target-select",cursor:0}),[a,c]=bt("in-place"),[g,u]=bt(()=>$a(t)),[h,v]=bt(()=>[...se]),[p,l]=bt(""),[w,C]=bt(e),E=Un((b,f)=>{c(b),l(f.name),s({type:"field-entry",field:0,values:f})},[]),x=Un(async b=>{let f=await qe(b);if(f!=="ok"){s({type:"precheck-error",targetDir:b,reason:f});return}C(b),E("in-place",g)},[g,E]),y=Un(async(b,f)=>{try{let d=await Ia(e,b.apiName);C(d),s({type:"confirm",values:b,artifacts:f})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),P=Un(async(b,f,d)=>{try{await Ln({targetDir:f,name:b.name,apiName:b.apiName,externalLink:b.externalLink,description:b.description,developerBusinessId:b.developerBusinessId,developerEnvironment:n,artifacts:d,includeLib:r}),s({type:"done",targetDir:f})}catch(m){s({type:"error",message:m instanceof Error?m.message:String(m)})}},[n,r]);if(rm((b,f)=>{if(f.ctrl&&b==="c"){o.exit();return}if(i.type==="target-select"){f.upArrow?s({type:"target-select",cursor:0}):f.downArrow?s({type:"target-select",cursor:1}):f.return?i.cursor===0?x(e):E("sub-dir",g):f.escape&&o.exit();return}if(i.type==="precheck-error"){(f.return||f.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:d,values:m}=i,k=Je[d];if(!k)return;if(f.escape){o.exit();return}if(f.backspace||f.delete){l(S=>S.slice(0,-1));return}if(f.upArrow&&d>0){let S={...m,[k]:p},T=d-1,_=Je[T];s({type:"field-entry",field:T,values:S}),u(S),l(_?S[_]:"");return}if(f.return||f.tab||f.downArrow){let S=Na(k,p);if(S!==void 0){s({type:"field-entry",field:d,values:m,fieldError:S});return}let T=Da(k,p),_={...m,[k]:T};u(_);let R=d+1;if(R>=Je.length)l(""),s({type:"artifact-select",values:_,cursor:0,selected:h});else{let z=Je[R],ee=z?_[z]:"",ae=z==="apiName"&&!ee?zn(_.name):ee;s({type:"field-entry",field:R,values:_}),l(ae)}return}b&&!f.ctrl&&!f.meta&&l(S=>S+b);return}if(i.type==="artifact-select"){let{cursor:d,selected:m,values:k}=i;if(f.escape){let S=Je.length-1,T=Je[S];s({type:"field-entry",field:S,values:k}),l(T?k[T]:"");return}if(f.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(f.downArrow){s({...i,cursor:Math.min(se.length-1,d+1)});return}if(b===" "){let S=se[d];if(S){let T=Ra(m,S);v(T),s({...i,selected:T})}return}if(b==="a"){v([...se]),s({...i,selected:[...se]});return}if(b==="n"){v([]),s({...i,selected:[]});return}f.return&&(a==="sub-dir"?(s({type:"resolving-target"}),y(k,m)):s({type:"confirm",values:k,artifacts:m}));return}if(i.type==="confirm"){if(f.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}f.return&&(s({type:"writing"}),P(i.values,w,i.artifacts));return}(i.type==="done"||i.type==="error")&&(f.return||f.escape)&&o.exit()}),i.type==="target-select"){let b=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Where should the new plugin live?"}),b.map((f,d)=>{let m=i.cursor===d;return B(K,{gap:2,children:[I($,{...m&&{color:"cyan"},children:m?"\u276F":" "}),I($,{bold:m,...m&&{color:"cyan"},children:f.label}),I($,{dimColor:!0,children:f.desc})]},f.label)})]}),I(dt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:b,reason:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Cannot create plugin"}),B(K,{flexDirection:"column",gap:0,children:[B($,{children:[b," already contains ",I($,{bold:!0,children:f==="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."})]}),I(dt,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:b,fieldError:f}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${w}`;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Plugin details"}),I($,{dimColor:!0,children:d})]}),f!==void 0&&B($,{color:"red",children:["Error: ",f]}),I(K,{flexDirection:"column",gap:0,children:Je.map((m,k)=>{let S=b===k,T=S?p:g[m],_=go.includes(m),R=`${Mn[m]}${_?"":" (optional)"}`;return B(K,{gap:2,children:[I(K,{width:24,children:I($,{bold:S,...S&&{color:"cyan"},children:R})}),I($,{...S&&{color:"cyan"},children:">"}),I($,{children:T}),S&&I($,{color:"cyan",children:"\u2588"})]},m)})}),I(dt,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:b,selected:f}=i;return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Which artifacts should we scaffold?"}),I($,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),I(K,{flexDirection:"column",gap:0,children:se.map((d,m)=>{let k=b===m,S=f.includes(d);return B(K,{gap:1,children:[I($,{...k&&{color:"cyan"},children:k?"\u276F":" "}),I($,{...S&&{color:"green"},children:S?"\u25C9":"\u25EF"}),I($,{bold:k,...k&&{color:"cyan"},children:co[d]})]},d)})}),I(dt,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let b=ho({targetDir:w,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:n});return B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Ready to create"}),B($,{dimColor:!0,children:["Target: ",w]})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"kizen.json preview"}),I($,{children:JSON.stringify(b,null,2)})]}),B(K,{flexDirection:"column",gap:0,children:[I($,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?B($,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(f=>B($,{dimColor:!0,children:[" ",co[f]]},f))]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Also creates:"}),B($,{dimColor:!0,children:[" ",Hn(w,"src/")]}),B($,{dimColor:!0,children:[" ",Hn(w,"src/thumbnail.png")," (generated placeholder)"]}),B($,{dimColor:!0,children:[" ",Hn(w,"releaseNotes/")]}),B($,{dimColor:!0,children:[" ",Hn(w,".gitignore")," (adds .kizenapp/)"]})]}),I(dt,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(K,{paddingY:1,paddingX:2,children:I($,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),B($,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(K,{flexDirection:"column",gap:0,children:[I($,{dimColor:!0,children:"Next steps:"}),B($,{children:[" ","cd ",i.targetDir]}),B($,{children:[" ","npx --yes @kizenapps/cli dev"]}),B($,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),I(dt,{text:"Enter or Esc to exit"})]}):B(K,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(J,{}),I($,{color:"red",bold:!0,children:"Failed to create plugin"}),I($,{children:i.message}),I(dt,{text:"Enter or Esc to exit"})]})};async function Ba(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let i=await e.loadGlobalCredentials();return{businessId:i?.businessId??"",environment:i?.environment??"go"}}let n=await nt(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var om="A hello-world Kizen plugin.",Fa=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function im(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...se];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!se.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${se.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function sm(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let o=(e.apiName?.trim()??"")||zn(r);if(!yo.test(o))throw new Error(`api_name "${o}" is invalid: ${bo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=am(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?om:i,developerBusinessId:s,developerEnvironment:a,artifacts:im(e.artifacts),includeLib:e.includeLib===!0}}function am(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!St(n))throw new Error(`Unknown environment "${n}". Valid environments: ${W.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function ja(e,t,n,r){let o;try{o=sm(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
994
+ `),r.setExitCode(1);return}let i=await r.precheckTargetDir(n);if(i!=="ok"){let a=i==="has-manifest"?"kizen.json":".kizenapp/";r.writeStderr(`Error: ${n} already contains ${a}. Refusing to overwrite an existing plugin.
995
+ `),r.setExitCode(1);return}try{await r.createPlugin(o)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
996
+ `),r.setExitCode(1);return}let s=o.artifacts&&o.artifacts.length>0?o.artifacts.join(", "):"none";r.writeStdout(`Created plugin ${o.apiName} at ${n}
997
+ `),r.writeStdout(`Artifacts: ${s}
998
+ `),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
999
+ `),o.developerBusinessId.trim()===""&&r.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
1000
+ `)}function La(e){e.command("create").description("Scaffold a new Kizen plugin project").option("-n, --name <name>","plugin display name (implies a non-interactive run)").option("-a, --api-name <name>","plugin api_name (inferred from --name when omitted)").option("-d, --description <text>","plugin description").option("-l, --external-link <url>","external link shown on the plugin listing").option("-b, --business-id <id>","developer business id (defaults to your sign-in session, else saved API-key credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${W.join(", ")} (defaults to your sign-in session, else saved API-key credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${se.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let n=process.cwd(),r=Ue(),{businessId:o,environment:i}=await Ba({listSessions:r.listSessions,readSession:r.readSession,loadGlobalCredentials:oe,...t.environment!==void 0&&{requestedEnvironment:t.environment}});if(!process.stdin.isTTY||!process.stdout.isTTY||Fa(t)){await ja(t,{businessId:o,environment:i},n,{precheckTargetDir:qe,createPlugin:Ln,writeStdout:c=>{process.stdout.write(c)},writeStderr:c=>{process.stderr.write(c)},setExitCode:c=>{process.exitCode=c}});return}let{waitUntilExit:a}=lm(cm(Oa,{parentDir:n,defaultBusinessId:o,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as bc}from"react";import{render as wc}from"ink";import{useCallback as wt,useEffect as Yn,useRef as $e,useState as le}from"react";import{Box as ne,Text as F,useInput as ah}from"ink";import{PluginValidationError as ch}from"@kizenapps/packager";import{watch as lh}from"fs";import{createServer as dh}from"http";import{join as hc}from"path";import{WebSocketServer as uh}from"ws";import{createReadStream as ec,realpathSync as Tm}from"fs";import{access as Am,readdir as Im,readFile as $m,realpath as Nm,stat as tc}from"fs/promises";import{dirname as Dm,extname as nc,join as Vt,resolve as Rm,sep as To}from"path";import{fileURLToPath as Om}from"url";var dm=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function Vn(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();dm.has(o)||o.startsWith("access-control-")||(t[n]=r)}return t}var wo=10*1024*1024,um=6e4,pm=200,Lt=class extends Error{bytesRead;limit;constructor(t,n){super(`Upstream response exceeded ${String(n)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=n}};async function vo(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],o=0;for await(let i of n){if(o+=i.length,o>t)throw new Lt(o,t);r.push(i)}return Buffer.concat(r)}async function Ma(e){let t=Vn(Object.fromEntries(e.headers)),n=await vo(e,wo);return{status:e.status,headers:t,body:n}}function za(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await Ma(await a()),fromCache:!1}},clear(){}};let r=new Map,o=()=>{t?.(r.size)},i=s=>{r.delete(s)&&o()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<um)return c.promise.then(u=>({response:u,fromCache:!0}));i(s)}if(r.size>=pm){let u=r.keys().next().value;u!==void 0&&i(u)}let g=a().then(Ma).catch(u=>{throw i(s),u});return r.set(s,{insertedAt:Date.now(),promise:g}),o(),g.then(u=>((u.status<200||u.status>=300)&&i(s),{response:u,fromCache:!1}))},clear(){r.clear(),o()}}}var xo={".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"};var ko={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function Mt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||ko.prod:process.env.PLUGIN_WIZARD_URL_DEV!==void 0&&process.env.PLUGIN_WIZARD_URL_DEV!==""?process.env.PLUGIN_WIZARD_URL_DEV:process.env.APPBUILDER_LOCAL_DEV!==void 0&&process.env.APPBUILDER_LOCAL_DEV!==""?ko.localDev:ko.dev}import{spawn as Eo}from"child_process";import{writeFile as Wa,rm as Po,mkdtemp as gm,access as ym}from"fs/promises";import{join as Ut}from"path";import{tmpdir as bm}from"os";var Ua=`awslambdaric
885
1001
  bcrypt
886
1002
  boto3
887
1003
  fpdf2
@@ -899,8 +1015,8 @@ pytz
899
1015
  requests
900
1016
  sqlalchemy>=2.0,<2.1
901
1017
  tzdata
902
- `;import{AUTOMATION_SCRIPT_RUNTIMES as Ou,isSupportedScriptRuntime as Lu,scriptRuntimeToApiName as Cs}from"@kizenapps/packager";function bs(e){return e.split(`
903
- `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function ws(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),r=t?.[1],o=t?.[2];return r!==void 0&&o!==void 0?`python${r}.${o}`:"python3"}function Bu(e){return e==null||e.trim()===""?null:e}function Ru(e){return e==null?null:typeof e=="string"?Bu(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function xs(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Ru(r)])):{}}var zu=`
1018
+ `;import{AUTOMATION_SCRIPT_RUNTIMES as wm,isSupportedScriptRuntime as vm,scriptRuntimeToApiName as Ja}from"@kizenapps/packager";function Ha(e){return e.split(`
1019
+ `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Va(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),n=t?.[1],r=t?.[2];return n!==void 0&&r!==void 0?`python${n}.${r}`:"python3"}function mm(e){return e==null||e.trim()===""?null:e}function hm(e){return e==null?null:typeof e=="string"?mm(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Ka(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,hm(n)])):{}}var xm=`
904
1020
  import sys, json, os, traceback
905
1021
 
906
1022
  # --- Inputs proxy (attribute access) ---
@@ -1060,29 +1176,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
1060
1176
  sys.stdout.write(json.dumps(result, ensure_ascii=False))
1061
1177
  sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
1062
1178
  sys.stdout.flush()
1063
- `.trim(),Mu=3e4,gr=xt(process.cwd(),".kizenapp","venv"),Uu=Ou.map(Cs),Ss=bs(ys);if(Ss.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var wt=null,vt=[3,10];function _s([e,t]){return e>vt[0]||e===vt[0]&&t>=vt[1]}function jn(e){return`${String(e[0])}.${String(e[1])}`}function Ps(e){return new Promise(t=>{let r=zn(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),o="";r.stdout.on("data",n=>{o+=n.toString("utf-8")}),r.on("error",()=>{t(null)}),r.on("close",n=>{let i=/(\d+)\.(\d+)/.exec(o);if(n!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Hu(e){let t=ws(e),r=t==="python3"?["python3"]:[t,"python3"],o=[];for(let n of r){let i=await Ps(n);if(!i){o.push(`${n}: not found`);continue}if(_s(i))return n;o.push(`${n}: ${jn(i)} (too old)`)}throw new Error(`No Python >= ${jn(vt)} found for runtime "${e}". The local runner needs Python ${jn(vt)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${o.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}function ks(e,t,r){return new Promise((o,n)=>{let i=zn(e,t,{stdio:["ignore","pipe","pipe"]}),s=(l,p)=>{let g=[],v="";return l.on("data",k=>{v+=k.toString("utf-8");let f=v.indexOf(`
1064
- `);for(;f>=0;){let c=v.slice(0,f).replace(/\r$/,"");v=v.slice(f+1),g.push(c),r?.(c,p),f=v.indexOf(`
1065
- `)}}),l.on("end",()=>{if(v.length>0){let k=v.replace(/\r$/,"");g.push(k),r?.(k,p)}}),g},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",n),i.on("close",l=>{if(l===0)o();else{let p=a.slice(-10).join(`
1066
- `).trim(),g=p.length>0?`: ${p}`:"";n(new Error(`${e} exited with code ${String(l)}${g}`))}})})}var On=null;function Vu(e,t){if(wt)return t&&On?.add(t),wt;let r=new Set;t&&r.add(t),On=r;let o=i=>{for(let s of r)s(i)},n=xt(gr,"bin","python");return wt=(async()=>{try{let i=!1;try{await Fu(n);let s=await Ps(n);i=s!==null&&_s(s)}catch{i=!1}if(!i){await Ln(gr,{recursive:!0,force:!0}).catch(()=>{});let s=await Hu(e);await ks(s,["-m","venv",gr])}return o({kind:"start"}),await ks(n,["-m","pip","install","--disable-pip-version-check",...Ss],(s,a)=>{o({kind:"log",line:s,stream:a})}),o({kind:"complete"}),n}catch(i){let s=i instanceof Error?i.message:String(i);throw o({kind:"error",message:s}),wt=null,await Ln(gr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{On=null}})(),wt}function Wu(e){let t="__KIZEN_RESULT_START__",r="__KIZEN_RESULT_END__",o=e.indexOf(t),n=e.indexOf(r);if(o===-1||n===-1)return{userStdout:e,result:null};let i=e.slice(0,o).trimEnd(),s=e.slice(o+t.length,n).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function Ku(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Es(e){let t=e.timeout??Mu;if(!Lu(e.scriptRuntime))return Ku(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Uu.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let o=await Vu(Cs(e.scriptRuntime),e.onInstallProgress),n=Date.now(),i;try{i=await $u(xt(ju(),"kizen-step-"));let s=xt(i,"wrapper.py"),a=xt(i,"script.py");await Promise.all([vs(s,zu,"utf-8"),vs(a,e.script,"utf-8")]);let l={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:p,stdout:g,stderr:v}=await new Promise(x=>{let I=[],C=[],S=!1,N=zn(o,[s],{env:l,cwd:i,stdio:["ignore","pipe","pipe"]}),b=setTimeout(()=>{N.kill("SIGKILL")},t);N.stdout.on("data",d=>{I.push(d)}),N.stderr.on("data",d=>{C.push(d)});let u=d=>{S||(S=!0,clearTimeout(b),x({exitCode:d??1,stdout:Buffer.concat(I).toString("utf-8"),stderr:Buffer.concat(C).toString("utf-8")}))};N.on("close",u),N.on("error",d=>{S||(S=!0,clearTimeout(b),x({exitCode:1,stdout:"",stderr:d.message}))})}),k=Date.now()-n,{userStdout:f,result:c}=Wu(g);if(c){let x={success:c.success,outputValues:c.outputValues,logs:c.logs,stdout:f,stderr:v,exitCode:p,durationMs:k};return c.error!==null&&(x.error=c.error),c.httpRequests&&(x.httpRequests=c.httpRequests),x}let h={success:!1,outputValues:{},logs:[],stdout:f,stderr:v,exitCode:p,durationMs:k};return p!==0&&(h.error=`Process exited with code ${String(p)}`),h}finally{i&&Ln(i,{recursive:!0,force:!0})}}var Ts=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);import{CRYPTO_ALG as Ns,CRYPTO_VERSION as Bs,DEFAULT_AUTOMATION_RUNTIME as tp,deserializeEnvelope as rp,encrypt as np,scriptRuntimeToApiName as op,serializeEnvelope as ip}from"@kizenapps/packager";function Mn(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",r=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${r}${t}`}var sp=2*1024*1024,ap=new Set([".DS_Store",".gitignore"]);function lp(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 js=["kizen.com","kizen.dev"];function cp(e){let t;try{t=new URL(e)}catch{return!1}let r=t.hostname.toLowerCase();return r==="localhost"||r==="127.0.0.1"||r==="[::1]"?!0:t.protocol!=="https:"?!1:js.some(o=>r===o||r.endsWith("."+o))}function dp(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let r=t.hostname.toLowerCase();return js.some(o=>r===o||r.endsWith("."+o))}function up(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 Rs(e,t){if(t.includes("\0"))return null;let r=t.replace(/^\/+/,""),o=Qu(e,r);if(o!==e&&!o.startsWith(e+Un))return null;try{let n=await Xu(o);return n!==e&&!n.startsWith(e+Un)?null:n}catch{return null}}function $s(e,t){let r=t===e?"":t.slice(e.length+1);return r===""?!1:r.split(Un).some(n=>jt.has(n))}function Os(){let e=ep(import.meta.url);return kt(Zu(e),"viewer")}function Fs(e,t,r){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let o=JSON.parse(r.toString("utf8"));return typeof o.status_code=="number"?o.status_code:void 0}catch{return}}async function Hn(e){try{return await qu(e),!0}catch{return!1}}function Ls(e,t,r,o,n,i,s,a,l,p,g){let v=gs({onChange:a,enabled:g}),k=Ju(p);return(f,c)=>{(async()=>{let h=f.url??"/";try{if(!lp(f.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!up(f.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${h}`),h==="/api/credentials"){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({credentials:o.current??null,activeProfile:n.current??null}));return}if(h==="/api/credential-profiles"&&f.method==="GET"){let u=await Ne();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:u,active:n.current}));return}if(h==="/api/credentials/switch"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let m=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}").profile,y=m===void 0||m===""?await re():await ke(m);if(y!==null){o.current=y,n.current=m??void 0;let w=n.current,E=await he(i);await Ie(i,{...E,credentialMode:"global",...w!==void 0&&{activeCredentialProfile:w}}),s({type:"credentials-updated",credentials:y,activeProfile:n.current??null})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:y!==null}));return}if(h==="/api/bundle"){let u=kt(process.cwd(),".kizenapp","bundle.json");try{let d=await Yu(u,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(d)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(h==="/api/last-path"&&f.method==="POST"){let u=[];for await(let m of f)u.push(m);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.path=="string"){l.current=d.path;let m=await he(i);await Ie(i,{...m,lastPath:d.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/encryption-target"&&f.method==="GET"){let d=(await he(i)).encryptionTarget==="dev"?"dev":"prod";c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({target:d}));return}if(h==="/api/encryption-target"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}"),m=d!==null&&typeof d=="object"?d:{};if(m.target!=="dev"&&m.target!=="prod"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let y=await he(i);await Ie(i,{...y,encryptionTarget:m.target}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/execute-step"&&f.method==="POST"){let u=[];for await(let w of f)u.push(w);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.script!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: script"}));return}let m={script:d.script,scriptRuntime:d.scriptRuntime??op(tp),inputs:xs(d.inputs),secrets:d.secrets??{},onInstallProgress:w=>{w.kind==="start"?s({type:"venv-install-start"}):w.kind==="log"?s({type:"venv-install-log",line:w.line,stream:w.stream}):w.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:w.message})}};typeof d.timeout=="number"&&d.timeout>0&&(m.timeout=Math.min(d.timeout,300*1e3));let y=await Es(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(y));return}if(h==="/api/proxy-cache/clear"){v.clear(),r({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(h==="/api/local/encrypt"&&f.method==="POST"){let u=[];for await(let m of f)u.push(m);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let m=np(d.value,d.publicKeyPem),y=ip(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(y))}catch(m){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:m.message}))}return}if(h==="/api/local/validate"&&f.method==="POST"){let u=[];for await(let _ of f)u.push(_);let d=JSON.parse(Buffer.concat(u).toString("utf-8")||"{}");if(typeof d.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: value"}));return}let m,y;try{m=rp(d.value)}catch(_){y=_.message}if(y!==void 0||m===void 0){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:!1,checks:[],error:y}));return}let w=_=>Buffer.from(_,"base64").length,E=[{label:"Version",expected:String(Bs),actual:String(m.v),pass:m.v===Bs},{label:"Algorithm",expected:Ns,actual:m.alg,pass:m.alg===Ns},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(w(m.k))} bytes`,pass:w(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(w(m.iv))} bytes`,pass:w(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(w(m.tag))} bytes`,pass:w(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(w(m.ct))} bytes`,pass:w(m.ct)>=1}];c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:E.every(_=>_.pass),checks:E}));return}if(h.startsWith("/api/wizard")){let u=f.headers["x-encryption-target"],m=(Array.isArray(u)?u[0]:u)==="dev"?"dev":"prod",y=bt(m);if(!cp(y)){c.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:`Encryption API host is not allowed: ${y}`}));return}let w=h.slice(11)||"/",E=`${y}${w}`,_=f.method??"GET",R=[];for await(let Oe of f)R.push(Oe);let{host:M,"x-encryption-target":X,...ie}=f.headers,pe=R.length>0?Buffer.concat(R):void 0,fe=pe&&pe.length>0?pe:void 0,ce;try{ce=await fetch(E,{method:_,headers:ie,...fe!==void 0&&{body:fe}})}catch(Oe){let Er=Oe.code==="ECONNREFUSED"?`plugin-wizard is not running at ${y}`:`Failed to reach plugin-wizard: ${Oe.message}`;c.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:Er}));return}let le=hr(Object.fromEntries(ce.headers)),nt=await ce.arrayBuffer();c.writeHead(ce.status,le),c.end(Buffer.from(nt));return}if(h.startsWith("/api/proxy")){let u=f.headers["x-proxy-target"];if(typeof u!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!dp(u)){c.writeHead(400),c.end("Invalid proxy target");return}let d=h.slice(10)||"/",m=`${u}${d}`,y=f.method??"GET",w=[];for await(let ce of f)w.push(ce);let{host:E,"x-proxy-target":_,...R}=f.headers;if(y==="GET"){let ce=`GET::${m}`,{response:le,fromCache:nt}=await v.get(ce,()=>fetch(m,{method:"GET",headers:R}));r({kind:"request",method:"GET",status:le.status,upstreamStatus:Fs(d,le.headers,le.body),fromCache:nt,url:d}),c.writeHead(le.status,le.headers),c.end(le.body);return}let M=w.length>0?Buffer.concat(w):void 0,X=M&&M.length>0?M:void 0,ie=await fetch(m,{method:y,headers:R,...X!==void 0&&{body:X}}),pe=hr(Object.fromEntries(ie.headers)),fe=await Rn(ie,Bn);r({kind:"request",method:y,status:ie.status,upstreamStatus:Fs(d,pe,fe),fromCache:!1,url:d}),c.writeHead(ie.status,pe),c.end(fe);return}if(h.startsWith("/api/source/tree")&&f.method==="GET"){let d=new URL(h,"http://localhost").searchParams.get("path")??"",m=await Rs(k,d);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if($s(k,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let y=await Gu(m,{withFileTypes:!0}),w=await Promise.all(y.filter(_=>_.isDirectory()?!jt.has(_.name):_.isFile()?!ap.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",M={name:_.name,kind:R};if(R==="file")try{let X=await Ds(kt(m,_.name));M.size=X.size}catch{}return M}));w.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let E=m===k?"":m.slice(k.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:E,entries:w}))}catch(y){let w=y instanceof Error?y.message:String(y);t(`source/tree failed (${d}): ${w}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(h.startsWith("/api/source/file")&&f.method==="GET"){let d=new URL(h,"http://localhost").searchParams.get("path")??"";if(d===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let m=await Rs(k,d);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if($s(k,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let y=await Ds(m);if(!y.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(y.size>sp){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:y.size}));return}let w=As(m).toLowerCase(),E=$n[w],_=Ts.has(w),R=E??(_?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":R,"Content-Length":String(y.size)}),Is(m).pipe(c)}catch(y){let w=y instanceof Error?y.message:String(y);t(`source/file failed (${d}): ${w}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let C=kt(e,h==="/"?"/index.html":h),S=await Hn(C)?C:kt(e,"index.html"),N=As(S),b=$n[N]??"application/octet-stream";c.writeHead(200,{"Content-Type":b}),Is(S).pipe(c)}catch(x){if(h.startsWith("/api/proxy")){let I=h.slice(10)||"/",C=f.method??"GET";x instanceof yt?r({kind:"info",message:`${C} ${I} \u2192 502 (response exceeded ${String(x.limit)} bytes)`}):r({kind:"request",method:C,status:502,fromCache:!1,url:I})}else r({kind:"info",message:`Error handling ${h}: ${x instanceof Error?x.message:String(x)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as pp}from"chrome-launcher";import{createRequire as fp}from"module";import{mkdirSync as mp}from"fs";import{readFile as hp}from"fs/promises";import{dirname as gp,join as yp}from"path";import{fileURLToPath as bp}from"url";var zs=fp(import.meta.url)("chrome-remote-interface"),wp=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Us=["kizen.dev","kizen.com"];function Ms(e){try{let{hostname:t}=new URL(e);return Us.some(r=>t===r||t.endsWith("."+r))}catch{return!1}}async function xp(e){try{let t=yp(gp(bp(import.meta.url)),"viewer","icon.png"),r=await hp(t);await e.Browser.setDockTile({image:r.toString("base64")})}catch{}}async function Hs(e){mp(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,r=await pp({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),o=r.port,n=null,i=null,s=null,a=null,l=0,p=!1,g=S=>{e.debugLog?.(S)},v=S=>{e.verbose&&e.debugLog?.(S)},k=()=>{i!==null&&(clearInterval(i),i=null)},f=S=>S==="chrome://new-tab-page/"||S==="chrome://newtab/",c=async S=>{k(),s=null,await xp(S),await S.Fetch.enable({patterns:Us.flatMap(b=>[{urlPattern:`*://${b}/*`,requestStage:"Response"},{urlPattern:`*://*.${b}/*`,requestStage:"Response"}])}),S.on("Fetch.requestPaused",b=>{(async()=>{let u=b,{requestId:d,request:m,responseHeaders:y,responseStatusCode:w}=u,E=m.url;v(`Fetch ${String(w??"?")} ${E}`);let _=[],R=!1;for(let M of y??[])if(!wp.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&Ms(E)){let X=M.value.split(`
1067
- `).map(ie=>/SameSite=/i.test(ie)?ie.replace(/SameSite=\w+/i,"SameSite=None"):ie+"; SameSite=None; Secure").join(`
1068
- `);_.push({name:M.name,value:X}),R=!0}else _.push(M);R&&v(` rewrote Set-Cookie SameSite on ${E}`);try{let{body:M,base64Encoded:X}=await S.Fetch.getResponseBody({requestId:d});await S.Fetch.fulfillRequest({requestId:d,responseCode:w??200,responseHeaders:_,body:M,...X&&{base64Encoded:!0}})}catch(M){v(` fulfillRequest failed (${M.message}), falling through`);try{await S.Fetch.continueRequest({requestId:d})}catch(X){v(` continueRequest also failed (${X.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:b}=await S.Network.getAllCookies(),u=0;for(let d of b){if(!Ms(`https://${d.domain??""}`)||d.sameSite==="None")continue;let m=d.domain??"",y=m.startsWith(".")?m.slice(1):m;await S.Network.setCookie({url:`https://${y}`,name:d.name,value:d.value,domain:m,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),u++}u>0&&v(`cookie-patch cycle: updated ${String(u)} cookie(s) to SameSite=None`)}catch(b){v(`cookie-patch cycle failed: ${b.message}`)}})()},2e3),await S.Target.setDiscoverTargets({discover:!0});let N=b=>{if(b.type==="page"){if(f(b.url)){g(`closed stray new-tab-page target ${b.targetId}`),s!==null&&S.Target.activateTarget({targetId:s}).catch(()=>{}),S.Target.closeTarget({targetId:b.targetId}).catch(()=>{});return}s===null&&(s=b.targetId,g(`captured main target ${b.targetId} (${b.url})`))}};S.on("Target.targetCreated",b=>{let{targetInfo:u}=b;v(`target +${u.type} ${u.targetId} ${u.url}`),N(u)}),S.on("Target.targetInfoChanged",b=>{let{targetInfo:u}=b;v(`target ~${u.type} ${u.targetId} ${u.url}`),N(u)}),S.on("disconnect",()=>{p||n!==S||(g("CDP disconnected"),n=null,k(),h())})},h=()=>{if(p||a!==null)return;let S=Math.min(1e3*2**l,1e4),N=l+1;l++,g(`CDP reconnect scheduled in ${String(S)}ms (attempt #${String(N)})`),a=setTimeout(()=>{a=null,(async()=>{let b;try{b=await zs({port:o})}catch{g(`CDP reconnect attempt #${String(N)} failed`),h();return}if(p){try{await b.close()}catch{}return}n=b;try{await c(b),g(`CDP reconnected after ${String(N)} attempt(s)`),l=0}catch{n===b&&(n=null);try{await b.close()}catch{}g(`CDP reconnect attempt #${String(N)} failed during setup`),h()}})()},S)},x=30,I=300;for(let S=0;S<x;S++){await new Promise(N=>setTimeout(N,I)),g(`CDP connect attempt ${String(S+1)}/${String(x)}`);try{let N=await zs({port:o});n=N,e.path&&N.send("Page.navigate",{url:`${t}${e.path}`});try{await c(N),g("CDP connected")}catch{n===N&&(n=null);try{await N.close()}catch{}g("CDP setup failed after connect")}break}catch{if(S===x-1){let N=`CDP unavailable after ${String(x)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return g(N),e.onWarn?.(N),{kill:()=>{r.kill()}}}}}return n?{kill:()=>{if(g("CDP kill requested \u2014 tearing down"),p=!0,a!==null&&(clearTimeout(a),a=null),k(),n!==null){try{n.close()}catch{}n=null}r.kill()}}:{kill:()=>{r.kill()}}}import{useCallback as vp,useState as kp}from"react";function yr(e){let[t,r]=kp([]),o=vp(n=>{r(i=>[...i,`${new Date().toLocaleTimeString()}: ${n}`].slice(-e))},[e]);return[t,o]}import{useCallback as br,useEffect as Vn,useState as wr}from"react";import{Box as Y,Text as L,useInput as Cp}from"ink";import{jsx as A,jsxs as Q}from"react/jsx-runtime";var Fe=["apiKey","userId","businessId"],Sp={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Ct=({text:e})=>A(L,{dimColor:!0,children:e}),xr=({initialMode:e,showProfileManager:t,onComplete:r,onCancel:o})=>{let[n,i]=wr(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=wr(""),[l,p]=wr(null),[g,v]=wr(void 0),k=br(b=>{if(b==="local"){r({mode:"local",credentials:null});return}i({type:"profile-loading"})},[r]),f=br(async b=>{if(b===null){i({type:"profile-loading"});let m=await Ne();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}v(b.isDefault?void 0:b.name),i({type:"loading"});let u=b.isDefault?await re():await ke(b.name),d=u?Math.max(0,Z.indexOf(u.environment)):0;i({type:"creds-entry",field:0,values:u??{},envCursor:d})},[]),c=br(async(b,u)=>{let d=Z[u]??"go",m={...st(b),environment:d};i({type:"saving"});try{await Ko(g??De,m),r({mode:"global",credentials:m,...g!==void 0&&{profileName:g}})}catch(y){p(y instanceof Error?y.message:String(y)),i({type:"creds-entry",field:0,values:b,envCursor:u})}},[r,g]);Cp((b,u)=>{if(u.ctrl&&b==="c"&&process.exit(0),u.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),h();return}o?.();return}if(n.type==="mode-select"){if(u.upArrow)i({type:"mode-select",cursor:0});else if(u.downArrow)i({type:"mode-select",cursor:1});else if(u.return){let d=n.cursor===0?"global":"local";k(d)}return}if(n.type==="profile-select"){let{profiles:d,cursor:m}=n,y=d.length,w=d.length+1;if(u.upArrow)i({...n,cursor:(m-1+w)%w});else if(u.downArrow)i({...n,cursor:(m+1)%w});else if(u.return)if(m===y)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let E=d[m]??d[0];E&&f(E)}return}if(n.type==="name-entry"){let{nameBuffer:d,existingProfiles:m}=n;if(u.backspace||u.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:m});else if(u.return){let y=d.trim();if(!y){i({...n,nameError:"Name cannot be empty"});return}if(y===De){i({...n,nameError:`"${De}" is reserved`});return}if(m.some(w=>w.name===y)){i({...n,nameError:`Profile "${y}" already exists`});return}v(y),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else b&&!u.ctrl&&!u.meta&&i({type:"name-entry",nameBuffer:d+b,existingProfiles:m});return}if(n.type==="creds-entry"){let{field:d,values:m,envCursor:y}=n;if(d===Fe.length){u.leftArrow?i({...n,envCursor:(y-1+Z.length)%Z.length}):u.rightArrow?i({...n,envCursor:(y+1)%Z.length}):u.upArrow?(i({...n,field:d-1}),a(m[Fe[d-1]]??"")):u.return&&c(m,y);return}let E=Fe[d];if(!E)return;if(u.backspace||u.delete)a(_=>_.slice(0,-1));else if(u.upArrow&&d>0){let _={...m,[E]:s},R=d-1;i({...n,field:R,values:_}),a(_[Fe[R]]??"")}else if(u.return||u.tab||u.downArrow){let _={...m,[E]:s},R=d+1;i({...n,field:R,values:_}),R<Fe.length?a(_[Fe[R]]??""):a("")}else b&&!u.ctrl&&!u.meta&&a(_=>_+b)}});let h=br(async()=>{let b=await Ne();i({type:"profile-select",profiles:b,cursor:0})},[]);if(Vn(()=>{n.type==="profile-loading"&&h()},[n.type,h]),Vn(()=>{e==="global"&&!t&&(async()=>{let b=await re(),u=b?Math.max(0,Z.indexOf(b.environment)):0;i({type:"creds-entry",field:0,values:b??{},envCursor:u})})()},[]),Vn(()=>{n.type==="creds-entry"&&n.field===0&&a(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let b=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return A(Y,{paddingY:1,paddingX:2,children:A(L,{dimColor:!0,children:b})})}if(n.type==="done")return null;if(n.type==="mode-select")return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{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((u,d)=>{let m=n.cursor===d;return Q(Y,{gap:2,children:[A(L,{...m&&{color:"cyan"},children:m?"\u276F":" "}),A(L,{bold:m,...m&&{color:"cyan"},children:u.label}),A(L,{dimColor:!0,children:u.desc})]},u.mode)})]}),A(Ct,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:b,cursor:u}=n,d=b.length;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{bold:!0,children:"Credential profiles"}),b.map((m,y)=>{let w=u===y;return Q(Y,{gap:2,children:[A(L,{...w&&{color:"cyan"},children:w?"\u276F":" "}),A(L,{bold:w,...w&&{color:"cyan"},children:m.isDefault?"Default":m.name}),A(L,{dimColor:!0,children:m.path})]},m.name)}),Q(Y,{gap:2,children:[A(L,{...u===d&&{color:"cyan"},children:u===d?"\u276F":" "}),A(L,{bold:u===d,...u===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),A(Ct,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:b,nameError:u}=n;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),A(Y,{flexDirection:"column",gap:0,children:A(L,{bold:!0,children:"New credential profile"})}),u&&Q(L,{color:"red",children:["Error: ",u]}),Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:!0,color:"cyan",children:"Profile name"})}),A(L,{color:"cyan",children:">"}),A(L,{children:b}),A(L,{color:"cyan",children:"\u2588"})]}),A(Ct,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:x,values:I,envCursor:C}=n,S=x===Fe.length,N=g??De;return Q(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),Q(Y,{flexDirection:"column",gap:0,children:[A(L,{bold:!0,children:g!==void 0?`Profile: ${g}`:"Global credentials"}),Q(L,{dimColor:!0,children:["Saved to:"," ",g!==void 0?`~/.kizenappbuilder/${g}.json`:ve]})]}),l&&Q(L,{color:"red",children:["Error: ",l]}),Q(Y,{flexDirection:"column",gap:0,children:[Fe.map((b,u)=>{let d=x===u,m=d?s:I[b]??"";return Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:d,...d&&{color:"cyan"},children:Sp[b]})}),A(L,{...d&&{color:"cyan"},children:">"}),A(L,{children:m}),d&&A(L,{color:"cyan",children:"\u2588"})]},b)}),Q(Y,{gap:2,children:[A(Y,{width:12,children:A(L,{bold:S,...S&&{color:"cyan"},children:"Environment"})}),A(L,{...S&&{color:"cyan"},children:">"}),A(Y,{gap:1,children:Z.map((b,u)=>{let d=u===C;return S?A(L,{bold:d,...d&&{color:"cyan"},children:d?`[${b}]`:b},b):A(L,{dimColor:!d,bold:d,children:b},b)})})]})]}),S?A(Ct,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):A(Ct,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Q(L,{dimColor:!0,children:["Profile: ",N]})]})};import{jsx as j,jsxs as G}from"react/jsx-runtime";var Ap=[".kizenapp",".git"],Ws=({port:e,pluginDir:t,outputDir:r,credentials:o,credentialMode:n,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:l=!1,autoViewer:p=!0,cacheEnabled:g=!0})=>{let v=Se(o),k=Se(i),f=Se(s),[c,h]=ae("main"),[x,I]=ae(n),[C,S]=ae("starting"),[N,b]=ae(null),[u,d]=yr(50),[m,y]=yr(50),[w,E]=yr(50),[_,R]=ae([]),[M,X]=ae("pending"),[ie,pe]=ae(null),[fe,ce]=ae(null),[le,nt]=ae(null),[Oe,Er]=ae(null),[Tr,Ir]=ae(0),[qn,Aa]=ae(0),[Na,Ba]=ae(0),[Dr,Ra]=ae(0),Ar=Se(!1),Gn=Se(!1),_t=Se(null),ot=Se(null),_e=Se(new Set),Pt=Se([]),de=rt(P=>{let U=JSON.stringify(P);if(_e.current.size===0){Pt.current=[...Pt.current,U].slice(-50);return}let Pe=!1;for(let me of _e.current)if(me.readyState===1)try{me.send(U)}catch{_e.current.delete(me),Pe=!0}Pe&&Ir(_e.current.size)},[]),Et=d,Nr=rt(()=>{_t.current?.kill(),_t.current=null,Hs({port:e,userDataDir:Vs(r,".chrome"),broadcast:de,onWarn:P=>{d(`\u26A0 ${P}`)},...f.current!==void 0&&{path:f.current},...a&&{debugLog:E},...l&&{verbose:!0}}).then(P=>{_t.current=P})},[e,r,de,a,l,E,d]);vr(()=>{let P=()=>{_t.current?.kill()};return process.on("exit",P),()=>{process.off("exit",P)}},[]),Pp((P,U)=>{(P==="q"||U.ctrl&&P==="c")&&process.exit(0),P==="c"&&h("editing"),P==="v"&&Nr()},{isActive:c==="main"}),vr(()=>{C!=="running"||Gn.current||!p||(Gn.current=!0,Nr())},[C,p,Nr]);let $a=rt(P=>{v.current=P.credentials,k.current=P.profileName,h("main"),I(P.mode);let U=P.profileName;Ie(r,{credentialMode:P.mode,...U!==void 0&&{activeCredentialProfile:U}}),de({type:"credentials-updated",credentials:P.credentials})},[r,de]),Yn=rt(P=>{R(U=>[...U,`${new Date().toLocaleTimeString()}: ${Mn(P)}`].slice(-50)),P.kind==="request"&&(P.fromCache?Ba(U=>U+1):Ra(U=>U+1)),de({type:"proxy-log",entry:P})},[de]),Le=rt(P=>{y(P),de({type:"log",message:P})},[y,de]),Br=rt(()=>{Ar.current||(Ar.current=!0,X("building"),pe(null),ce(null),Le("Build started"),Lt(t,r).then(({bundleSize:P})=>{Le(`Build finished \u2014 bundle: ${pt(P)}`),X("done"),nt(new Date),Er(P),Le("Notifying viewers to reload"),de({type:"rebuild"})}).catch(P=>{P instanceof Ep?(ce(P.issues),pe(null)):(pe(P instanceof Error?P.message:String(P)),ce(null)),X("error")}).finally(()=>{Ar.current=!1}))},[t,r,Le,de]);if(vr(()=>{Br();let P=Tp(t,{recursive:!0},(U,Pe)=>{if(!Pe)return;let me=Pe.replace(/\\/g,"/");Ap.some(Tt=>me.startsWith(Tt))||(Le(`File change detected: ${Pe}`),ot.current!==null&&clearTimeout(ot.current),ot.current=setTimeout(Br,150))});return P.on("error",U=>{Le(`File watcher error \u2014 rebuilds have stopped: ${U.message}`)}),()=>{P.close(),ot.current!==null&&clearTimeout(ot.current)}},[t,Br,Le]),vr(()=>{let P=Os();Hn(Vs(P,"index.html")).then(U=>{if(!U){b("Viewer not built. Run 'pnpm build:viewer' first."),S("error");return}let Pe=Ls(P,Et,Yn,v,k,r,de,Aa,f,t,g),me=Ip(Pe),Tt=new Dp({server:me});return Tt.on("connection",ze=>{for(let ja of Pt.current)ze.readyState===1&&ze.send(ja);Pt.current=[],Et("Viewer connected for live reload"),_e.current.add(ze),Ir(_e.current.size),ze.on("close",()=>{_e.current.delete(ze),Ir(_e.current.size)})}),me.listen(e,"127.0.0.1",()=>{S("running"),Et(`Server started on 127.0.0.1:${String(e)}`)}),me.on("error",ze=>{b(ze.message),S("error")}),()=>{Tt.close(),me.close()}})},[e,Et,Yn,de,r,t,g]),c==="editing")return j(xr,{...x!==void 0&&{initialMode:x},showProfileManager:x==="global",onComplete:$a,onCancel:()=>{h("main")}});let Rr=le!==null?Math.round((Date.now()-le.getTime())/1e3):null,Fa=Rr===null?"":Rr<5?" (just now)":` (${String(Rr)}s ago)`,Xn=fe?.filter(P=>P.severity==="error").length??0;return G(ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(K,{marginBottom:1}),G(ee,{flexDirection:"column",children:[G(ee,{gap:2,marginBottom:0,children:[j(F,{bold:!0,dimColor:!0,children:"App Build"}),M==="pending"&&j(F,{dimColor:!0,children:"waiting\u2026"}),M==="building"&&G(ee,{gap:1,children:[j(ye,{}),j(F,{children:"Building plugin package\u2026"})]}),M==="done"&&G(ee,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),le!==null&&G(F,{dimColor:!0,children:["at ",le.toLocaleTimeString(),Fa]}),Oe!==null&&G(F,{dimColor:!0,children:["\xB7 bundle: ",pt(Oe)]})]}),M==="error"&&(fe!==null?G(F,{color:"red",children:["\u2717 ",Xn," validation ",Xn===1?"error":"errors"]}):G(F,{color:"red",children:["\u2717 ",ie??"unknown error"]}))]}),fe!==null&&j(ir,{issues:fe}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),C==="running"&&G(ee,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),G(F,{dimColor:!0,children:["\u25CF ",Tr," viewer",Tr!==1?"s":""]})]}),C==="error"&&G(F,{color:"red",children:["\u2717 ",N??"Server error"]})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:u.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:g?`\u25CF ${String(qn)} key${qn!==1?"s":""} in the network cache \xB7 ${String(Na)} hit \xB7 ${String(Dr)} miss`:`\u25CF network cache disabled \xB7 ${String(Dr)} request${Dr!==1?"s":""}`})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:_.length===0?j(F,{dimColor:!0,children:" No requests yet."}):_.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),a&&G(ee,{marginTop:1,flexDirection:"column",children:[G(ee,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),G(F,{dimColor:!0,children:["\u25CF ",w.length," event(s)"]})]}),j(ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:w.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):w.slice(-8).map((P,U)=>j(F,{dimColor:!0,wrap:"truncate",children:P},U))})]}),G(ee,{marginTop:1,gap:1,children:[j(F,{dimColor:!0,children:"["}),j(F,{children:"q"}),j(F,{dimColor:!0,children:"] quit ["}),j(F,{children:"c"}),j(F,{dimColor:!0,children:"] credentials ["}),j(F,{children:"v"}),G(F,{dimColor:!0,children:["] ",Tr===0?"open viewer":"relaunch viewer"]})]})]})};async function Ks(e){return new Promise(t=>{let r=null,o=i=>{r?.(),t(i)},{unmount:n}=qs(Js(xr,{...e!==void 0&&{initialMode:e},onComplete:o}),{exitOnCtrlC:!1});r=n})}function Gs(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)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let r=parseInt(t.port,10),o=process.cwd(),n=`${o}/.kizenapp`;ge(o);let i=null,s,a,{lastPath:l}=await he(n);if(t.credentials)i=await Ae(t.credentials);else{let c=await he(n);if(c.credentialMode==="local")s="local";else if(c.credentialMode==="global"){if(s="global",a=c.activeCredentialProfile,a?(i=await ke(a),i||(i=await re(),a=void 0)):i=await re(),!i){let h=await Ks("global");i=h.credentials,a=h.profileName}}else{let h=await Ks();i=h.credentials,s=h.mode,a=h.profileName;let x=h.profileName;await Ie(n,{credentialMode:h.mode,...x!==void 0&&{activeCredentialProfile:x}})}}let p=t.verbose===!0,g=p||t.debug===!0,v=t.viewer!==!1,k=t.cache!==!1,{waitUntilExit:f}=qs(Js(Ws,{port:r,pluginDir:o,outputDir:n,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...l!==void 0&&{lastPath:l},debug:g,verbose:p,autoViewer:v,cacheEnabled:k}),{exitOnCtrlC:!1});await f()})}import{createElement as Vp}from"react";import{render as Wp}from"ink";import{useCallback as Cr,useEffect as Qs,useState as Sr}from"react";import{Box as be,Text as z,useApp as Op,useInput as Lp}from"ink";import{encrypt as Np,serializeEnvelope as Bp}from"@kizenapps/packager";function Rp(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Ys(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function Xs(e,t,r){try{return await fetch(`${e}${t}`,r)}catch(o){throw new Error(Rp(o)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${o.message}${Dt()==="unavailable"?` ${It}`:""}`)}}async function Zs(e){let t=await e.text();if(t==="")return{};try{let r=JSON.parse(t);return typeof r=="object"&&r!==null?r:{}}catch{return{}}}async function $p(e,t,r){let o=bt(e.stage),n=await Xs(o,"/get-public-key",{method:"POST",headers:Ys(t),body:JSON.stringify({api_name:r})}),i=await Zs(n);if(!n.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(n.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function Fp(e,t){let r=Np(t,e),o=Bp(r);if(typeof o.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return o.value}async function jp(e,t,r,o){let n=bt(e.stage),i=await Xs(n,"/encrypt",{method:"POST",headers:Ys(t),body:JSON.stringify({api_name:r,value:o})}),s=await Zs(i);if(!i.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function kr(e,t,r,o,n){if(e.isRemote)return n?.("encrypting"),jp(e,t,r,o);n?.("fetching-key");let i=await $p(e,t,r);return n?.("encrypting"),Fp(i,o)}import{Fragment as _r,jsx as O,jsxs as te}from"react/jsx-runtime";var Wn=({text:e})=>O(z,{dimColor:!0,children:e}),ea=({ctx:e,stageDefaulted:t,credentialsPath:r,initialApiName:o,defaultApiName:n,initialValue:i,onDone:s})=>{let a=Op(),[l,p]=Sr({type:"loading"}),[g,v]=Sr(null),[k,f]=Sr(o??""),[c,h]=Sr(i??""),x=Cr(d=>{process.exitCode=1,p({type:"error",message:d instanceof Error?d.message:String(d)})},[]),I=Cr(async(d,m,y)=>{try{let w=await kr(e,d,m,y,R=>{p(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),E=JSON.stringify({encrypted:!0,value:w},null,2);s?.(w);let _=await At(E);p({type:"done",envelope:E,copied:_})}catch(w){x(w)}},[e,x,s]),C=Cr((d,m,y)=>{if(m.trim()===""){p({type:"api-name-entry",buffer:n??""});return}if(y===""){p({type:"value-entry",buffer:""});return}I(d,m.trim(),y)},[n,I]),S=Cr(async d=>{try{p({type:"loading"});let m=d.isDefault?await re():await ke(d.name);if(m===null)throw new Error(`Could not load credential profile: ${d.name}`);v(m),C(m,k,c)}catch(m){x(m)}},[k,c,C,x]);Qs(()=>{(async()=>{try{if(r!==void 0){let y;try{y=await Ae(r)}catch(w){throw new Error(`Could not load credentials from ${r}: ${w instanceof Error?w.message:String(w)}`)}v(y),C(y,k,c);return}let d=await Ne();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[m]=d;if(d.length===1&&m!==void 0){let y=m.isDefault?await re():await ke(m.name);if(y===null)throw new Error(`Could not load credential profile: ${m.name}`);v(y),C(y,k,c);return}p({type:"profile-select",profiles:d,cursor:0})}catch(d){x(d)}})()},[]),Qs(()=>{(l.type==="done"||l.type==="error")&&a.exit()},[l,a]),Lp((d,m)=>{if(m.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(l.type==="profile-select"){let{profiles:y,cursor:w}=l;if(m.upArrow)p({...l,cursor:(w-1+y.length)%y.length});else if(m.downArrow)p({...l,cursor:(w+1)%y.length});else if(m.return){let E=y[w];E!==void 0&&S(E)}return}if(l.type==="api-name-entry"){let{buffer:y}=l;if(m.backspace||m.delete)p({type:"api-name-entry",buffer:y.slice(0,-1)});else if(m.return){let w=y.trim();if(w===""){p({type:"api-name-entry",buffer:y,error:"api_name cannot be empty"});return}f(w),g?C(g,w,c):x(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&p({type:"api-name-entry",buffer:y+d});return}if(l.type==="value-entry"){let{buffer:y}=l;if(m.backspace||m.delete)p({type:"value-entry",buffer:y.slice(0,-1)});else if(m.return){if(y===""){p({type:"value-entry",buffer:y,error:"secret cannot be empty"});return}h(y),g?C(g,k,y):x(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&p({type:"value-entry",buffer:y+d});return}});let N=e.isRemote?"remote Kizen API":"on-machine",b=t===!0?`${e.stage} (default)`:e.stage,u=d=>te(be,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[O(K,{}),te(z,{dimColor:!0,children:["Mode: ",N," Stage: ",b]}),d]});if(l.type==="loading")return u(te(be,{gap:1,children:[O(ye,{}),O(z,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(l.type==="profile-select"){let{profiles:d,cursor:m}=l;return u(te(_r,{children:[O(z,{bold:!0,children:"Credential profile"}),O(be,{flexDirection:"column",children:d.map((y,w)=>{let E=m===w;return te(be,{gap:2,children:[O(z,{...E&&{color:"cyan"},children:E?"\u276F":" "}),O(z,{bold:E,...E&&{color:"cyan"},children:y.isDefault?"Default":y.name}),O(z,{dimColor:!0,children:y.path})]},y.name)})}),O(Wn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return l.type==="api-name-entry"?u(te(_r,{children:[O(z,{bold:!0,children:"Plugin api_name"}),l.error!==void 0&&te(z,{color:"red",children:["Error: ",l.error]}),te(be,{gap:1,children:[O(z,{color:"cyan",children:">"}),O(z,{children:l.buffer}),O(z,{color:"cyan",children:"\u2588"})]}),O(Wn,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):l.type==="value-entry"?u(te(_r,{children:[O(z,{bold:!0,children:"Secret value"}),l.error!==void 0&&te(z,{color:"red",children:["Error: ",l.error]}),te(be,{gap:1,children:[O(z,{color:"cyan",children:">"}),O(z,{children:"\u2022".repeat(l.buffer.length)}),O(z,{color:"cyan",children:"\u2588"})]}),O(Wn,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):l.type==="fetching-key"?u(te(be,{gap:1,children:[O(ye,{}),te(z,{children:["Fetching ",e.stage," public key for ",O(z,{bold:!0,children:k}),"\u2026"]})]})):l.type==="encrypting"?u(te(be,{gap:1,children:[O(ye,{}),O(z,{children:"Encrypting\u2026"})]})):l.type==="error"?u(te(be,{gap:1,children:[O(z,{color:"red",children:"\u2717"}),O(z,{color:"red",children:l.message})]})):u(te(_r,{children:[te(be,{gap:1,children:[O(z,{color:"green",children:"\u2713"}),O(z,{bold:!0,children:"Encrypted secret ready"})]}),l.copied?O(z,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):O(z,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),O(z,{children:l.envelope})]}))};import{readFile as zp,writeFile as Mp}from"fs/promises";import{join as Up}from"path";function ta(e){return{encrypted:!0,value:e}}function ra(e){return JSON.stringify(ta(e))}async function Kn(e,t){await Mp(e,`${JSON.stringify(ta(t),null,2)}
1069
- `,"utf-8")}var Hp="prod";function na(e){return e==="dev"||e==="prod"}function oa(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function ia(e){return{stage:e==="dev"||e==="prod"?e:Hp,wasDefaulted:e===void 0}}function sa(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1070
- `}async function aa(e=process.cwd()){try{let t=await zp(Up(e,"kizen.json"),"utf-8"),r=JSON.parse(t),o=Array.isArray(r)?r[0]:r,n=typeof o.api_name=="string"&&o.api_name!==""?o.api_name:void 0;return{...n!==void 0&&{apiName:n}}}catch{}return{}}function la(e){return e.replace(/[\r\n]+$/,"")}async function ca(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function da(e,t,r,o,n){let i=t.credentials!==void 0?await n.loadCredentialsFromFile(t.credentials):await n.loadGlobalCredentials();if(i===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??r.apiName;if(s===void 0||s.trim()==="")throw new Error("api_name is required in non-interactive mode. Pass --api-name or run inside a plugin directory.");o&&n.writeStderr(sa(e.stage));let a=t.value;if(a===void 0){if(n.stdinIsTTY())throw new Error('No secret provided and stdin is a terminal. Pass --value, or pipe the secret in (e.g. `printf %s "$SECRET" | npx --yes @kizenapps/cli encrypt \u2026`).');n.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
1071
- `),a=la(await n.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let l=await n.encryptSecret(e,i,s.trim(),a);if(n.writeStdout(`${ra(l)}
1072
- `),t.out!==void 0)try{await n.writeEnvelopeFile(t.out,l),n.writeStderr(`Wrote encrypted envelope to ${t.out}
1073
- `)}catch(p){n.writeStderr(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}
1074
- `),n.setExitCode(1)}}function ua(e){e.command("encrypt").description("Encrypt a secret for a plugin against its encryption keys").option("--remote","encrypt via the plugin-wizard's remote API instead of on-machine").option("-c, --credentials <path>","path to a credentials JSON file").option("-a, --api-name <name>","plugin api_name the secret belongs to").option("-v, --value <value>","plaintext secret value to encrypt").option("-s, --stage <stage>","which encryption API to use: dev or prod (default: prod)").option("-o, --out <path>","also write the encrypted envelope to a file").action(async t=>{t.stage!==void 0&&!na(t.stage)&&(console.error(oa(t.stage)),process.exit(1));let o=t.apiName===void 0?await aa():{},{stage:n,wasDefaulted:i}=ia(t.stage),s={isRemote:t.remote===!0,stage:n};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await da(s,t,o,i,{loadCredentialsFromFile:Ae,loadGlobalCredentials:re,encryptSecret:kr,readStdin:ca,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:p=>{process.stdout.write(p)},writeStderr:p=>{process.stderr.write(p)},writeEnvelopeFile:Kn,setExitCode:p=>{process.exitCode=p}})}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}return}let a,{waitUntilExit:l}=Wp(Vp(ea,{ctx:s,stageDefaulted:i,onDone:p=>{a=p},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...o.apiName!==void 0&&{defaultApiName:o.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await l(),a!==void 0&&t.out!==void 0)try{await Kn(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1075
- `)}catch(p){console.error(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}`),process.exitCode=1}})}var Kp=new Set(["phone","envelope","pen-nib","calendar-days","paperclip","file","clipboard","pen","tag","book","print","pen-to-square","folder","folder-open","thumbtack","globe","city","briefcase","compass","address-book","business-time","computer-classic","pen-fancy","badge-check","mug-saucer","landmark","chart-simple","envelopes","diagram-venn","calendar","pencil","phone-volume","copy","table","building","network-wired","address-card","tags","registered","signature","phone-office","projector","sitemap","marker","badge","wallet","copyright","bullseye","calculator","certificate","percent","eraser","file-spreadsheet","glasses","industry","vault","user-tie-hair-long","user-tie-hair","user-hair-mullet","trademark","timeline-arrow","timeline","table-tree","table-rows","table-pivot","table-layout","table-columns","stapler","square-poll-vertical","square-poll-horizontal","square-phone-flip","square-phone","square-pen","square-kanban","square-envelope","socks","slot-machine","signature-slash","signature-lock","shredder","scissors","scanner-image","scale-unbalanced-flip","scale-unbalanced","scale-balanced","router","rectangle-pro","print-slash","print-magnifying-glass","presentation-screen","podium","phone-slash","phone-intercom","phone-flip","person-chalkboard","pen-nib-slash","pen-clip","paste","paperclip-vertical","notebook","note-sticky","money-check-pen","money-check-dollar-pen","magnifying-glass-chart","magnifying-glass-arrow-right","list-tree","list-timeline","list-radio","list-dropdown","list-check","laptop-file","lamp-desk","keynote","industry-windows","inboxes","inbox-full","house-laptop","highlighter","folders","folder-xmark","folder-tree","folder-plus","folder-minus","folder-arrow-up","folder-arrow-down","floppy-disk-circle-xmark","floppy-disk-circle-arrow-right","floppy-disk","file-user","file-lines","file-circle-plus","file-circle-info","file-chart-pie","file-chart-column","fax","envelope-open","envelope-dot","envelope-circle-check","coffee-pot","cloud-word","clipboard-question","chart-user","chart-tree-map","chart-simple-horizontal","chart-pyramid","chart-pie-simple","chart-pie","chart-line-up","chart-line-down","chart-line","cake-candles","cabinet-filing","bullhorn","briefcase-blank","briefcase-arrow-right","brain-arrow-curved-right","boxes-packing","box-archive","book-section","bars-staggered","bars-progress","badge-percent","badge-dollar","arrows-to-eye","arrows-to-dot","arrows-spin","sparkles","megaphone","block-question","lightbulb-slash","comments-dollar","comments","bullseye-pointer","lightbulb","user-group-crown","user-crown","signal-stream-slash","signal-stream","rectangle-ad","ranking-star","person-rays","people-group","messages-dollar","message-dollar","magnifying-glass-location","magnifying-glass-dollar","lightbulb-on","lightbulb-exclamation","lightbulb-dollar","lightbulb-cfl-on","lightbulb-cfl","hundred-points","group-arrows-rotate","gift-card","filter-circle-dollar","envelopes-bulk","envelope-open-text","envelope-open-dollar","comment-dollar","chart-mixed","bullseye-arrow","star","heart","camera-retro","truck-fast","bell","cart-shopping","gift","barcode","bookmark","camera","thumbs-up","thumbs-down","key","truck","balloons","handshake","shop","shirt","bag-shopping","moped","cart-plus","credit-card","store","cash-register","booth-curtain","trophy","receipt","truck-container","truck-clock","truck-bolt","trophy-star","store-slash","store-lock","star-exclamation","shop-slash","shop-lock","rectangle-barcode","person-booth","nfc-trash","nfc-symbol","nfc-slash","nfc-signal","nfc-pen","nfc-magnifying-glass","nfc-lock","nfc","money-check-dollar","money-check","mobile-signal-out","mobile-signal","hexagon-vertical-nft-slanted","hexagon-vertical-nft","hexagon-image","hand-holding-box","gifts","gem","credit-card-front","credit-card-blank","cart-xmark","cart-shopping-fast","cart-minus","cart-circle-xmark","cart-circle-plus","cart-circle-exclamation","cart-circle-check","cart-circle-arrow-up","cart-circle-arrow-down","cart-arrow-up","cart-arrow-down","box-open-full","basket-shopping-simple","basket-shopping","barcode-scan","barcode-read","balloon","bags-shopping","bars","browser","chart-bar","cog","database","calendar-alt","play","kizen-k","add","book-alt","form-entity","arrows-to-circle","question-circle","chevron-down","chevron-up","window-restore","forward"]),Jp=[...Kp].sort(),qp=new Set(["kizen-k","form-entity"]),pa=[...Jp,...[...qp].sort()];function fa(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of pa)console.log(t)})}import{mkdir as rf,writeFile as Sa,readFile as nf}from"fs/promises";import{join as Pr}from"path";var Gp=new Set(["developer_business_id"]);function Yp(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let r=t;if(typeof r.auth_credentials!="object"||r.auth_credentials===null)return r;let o=Object.fromEntries(Object.keys(r.auth_credentials).map(n=>[n,"*****"]));return{...r,auth_credentials:o}}):e}function ha(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let r of e){let o=r.path.split("/"),n=t;o.forEach((i,s)=>{n.children.has(i)||n.children.set(i,{name:i,children:new Map,isFile:s===o.length-1,filePath:o.slice(0,s+1).join("/")});let a=n.children.get(i);a&&(n=a)})}return t}function ga(e){return[...e.children.values()].sort((t,r)=>t.isFile!==r.isFile?t.isFile?1:-1:t.name.localeCompare(r.name))}function Jn(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function we(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ya(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var Xp={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function Zp(e){return Xp[ya(e)]??""}function ma(e){let t=[...e.matchAll(/`+/g)].reduce((r,o)=>Math.max(r,o[0].length),0);return"`".repeat(Math.max(3,t+1))}function ba(e,t=""){let r=ga(e);return r.map((o,n)=>{let i=n===r.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";return o.isFile?`${t}${s}${o.name}`:`${t}${s}${o.name}/
1076
- ${ba(o,t+a)}`}).join(`
1077
- `)}var Qp=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function wa(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!Qp.test(t.path))}function xa(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Gp.has(t)).map(([t,r])=>[t,t==="services"?Yp(r):r]))}var ef={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function va(e){return`<ul>${ga(e).map(o=>o.isFile?`<li class="tf"><a href="#${Jn(o.filePath)}" data-id="${Jn(o.filePath)}">${we(o.name)}</a></li>`:`<li class="td"><span class="dn">${we(o.name)}/</span>${va(o)}</li>`).join("")}</ul>`}function tf(e){let t;return e.base64Image!==void 0?t=`<img src="data:${ef[ya(e.path)]??"image/png"};base64,${e.base64Image}" alt="${we(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>${we(e.content)}</code></pre>`,`<section id="${Jn(e.path)}"><h2 class="fp">${we(e.path)}</h2><div class="fb">${t}</div></section>`}function ka(e,t){let r=xa(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=wa(t),a=[];a.push(`# ${o}${n?` v${n}`:""}`),i&&a.push("",i);let l=JSON.stringify(r,null,2),p=ma(l);a.push("","## Configuration (`kizen.json`)","",`${p}json`,l,p),a.push("","## File Tree","","```",ba(ha(s)),"```"),a.push("","## Files");for(let g of s)if(a.push("",`### \`${g.path}\``,""),g.base64Image!==void 0)a.push(`[Image file: ${g.path}]`);else if(g.binaryData!==void 0)a.push(`[Binary file: ${String(g.binaryData.length)} bytes]`);else{let v=ma(g.content);a.push(`${v}${Zp(g.path)}`,g.content,v)}return a.join(`
1179
+ `.trim(),km=3e4,Kn=Ut(process.cwd(),".kizenapp","venv"),Cm=wm.map(Ja),Ga=Ha(Ua);if(Ga.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var zt=null,Ht=[3,10];function Ya([e,t]){return e>Ht[0]||e===Ht[0]&&t>=Ht[1]}function Co(e){return`${String(e[0])}.${String(e[1])}`}function Xa(e){return new Promise(t=>{let n=Eo(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",o=>{r+=o.toString("utf-8")}),n.on("error",()=>{t(null)}),n.on("close",o=>{let i=/(\d+)\.(\d+)/.exec(r);if(o!==0||!i){t(null);return}t([Number(i[1]),Number(i[2])])})})}async function Sm(e){let t=Va(e),n=t==="python3"?["python3"]:[t,"python3"],r=[];for(let o of n){let i=await Xa(o);if(!i){r.push(`${o}: not found`);continue}if(Ya(i))return o;r.push(`${o}: ${Co(i)} (too old)`)}throw new Error(`No Python >= ${Co(Ht)} found for runtime "${e}". The local runner needs Python ${Co(Ht)}+ to install the bundled packages (e.g. psycopg 3.3), matching the remote code-runner (3.12 / 3.13). Tried ${r.join(", ")}. Install Python 3.12 or 3.13 and retry.`)}function qa(e,t,n){return new Promise((r,o)=>{let i=Eo(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,g)=>{let u=[],h="";return c.on("data",v=>{h+=v.toString("utf-8");let p=h.indexOf(`
1180
+ `);for(;p>=0;){let l=h.slice(0,p).replace(/\r$/,"");h=h.slice(p+1),u.push(l),n?.(l,g),p=h.indexOf(`
1181
+ `)}}),c.on("end",()=>{if(h.length>0){let v=h.replace(/\r$/,"");u.push(v),n?.(v,g)}}),u},a=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",o),i.on("close",c=>{if(c===0)r();else{let g=a.slice(-10).join(`
1182
+ `).trim(),u=g.length>0?`: ${g}`:"";o(new Error(`${e} exited with code ${String(c)}${u}`))}})})}var So=null;function Pm(e,t){if(zt)return t&&So?.add(t),zt;let n=new Set;t&&n.add(t),So=n;let r=i=>{for(let s of n)s(i)},o=Ut(Kn,"bin","python");return zt=(async()=>{try{let i=!1;try{await ym(o);let s=await Xa(o);i=s!==null&&Ya(s)}catch{i=!1}if(!i){await Po(Kn,{recursive:!0,force:!0}).catch(()=>{});let s=await Sm(e);await qa(s,["-m","venv",Kn])}return r({kind:"start"}),await qa(o,["-m","pip","install","--disable-pip-version-check",...Ga],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),o}catch(i){let s=i instanceof Error?i.message:String(i);throw r({kind:"error",message:s}),zt=null,await Po(Kn,{recursive:!0,force:!0}).catch(()=>{}),i}finally{So=null}})(),zt}function Em(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1)return{userStdout:e,result:null};let i=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,o).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function _m(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Za(e){let t=e.timeout??km;if(!vm(e.scriptRuntime))return _m(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${Cm.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await Pm(Ja(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await gm(Ut(bm(),"kizen-step-"));let s=Ut(i,"wrapper.py"),a=Ut(i,"script.py");await Promise.all([Wa(s,xm,"utf-8"),Wa(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:g,stdout:u,stderr:h}=await new Promise(C=>{let E=[],x=[],y=!1,P=Eo(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),b=setTimeout(()=>{P.kill("SIGKILL")},t);P.stdout.on("data",d=>{E.push(d)}),P.stderr.on("data",d=>{x.push(d)});let f=d=>{y||(y=!0,clearTimeout(b),C({exitCode:d??1,stdout:Buffer.concat(E).toString("utf-8"),stderr:Buffer.concat(x).toString("utf-8")}))};P.on("close",f),P.on("error",d=>{y||(y=!0,clearTimeout(b),C({exitCode:1,stdout:"",stderr:d.message}))})}),v=Date.now()-o,{userStdout:p,result:l}=Em(u);if(l){let C={success:l.success,outputValues:l.outputValues,logs:l.logs,stdout:p,stderr:h,exitCode:g,durationMs:v};return l.error!==null&&(C.error=l.error),l.httpRequests&&(C.httpRequests=l.httpRequests),C}let w={success:!1,outputValues:{},logs:[],stdout:p,stderr:h,exitCode:g,durationMs:v};return g!==0&&(w.error=`Process exited with code ${String(g)}`),w}finally{i&&Po(i,{recursive:!0,force:!0})}}var Qa=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".json",".md",".mdx",".yml",".yaml",".toml",".css",".scss",".html",".htm",".xml",".svg",".txt",".sh",".py",".env",".gitignore",".prettierrc",".eslintrc"]);import{CRYPTO_ALG as rc,CRYPTO_VERSION as oc,DEFAULT_AUTOMATION_RUNTIME as Bm,deserializeEnvelope as Fm,encrypt as jm,scriptRuntimeToApiName as Lm,serializeEnvelope as Mm}from"@kizenapps/packager";function _o(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",n=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${n}${t}`}var zm=2*1024*1024,Um=new Set([".DS_Store",".gitignore"]);function Hm(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 cc=["kizen.com","kizen.dev"];function Vm(e){let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="[::1]"?!0:t.protocol!=="https:"?!1:cc.some(r=>n===r||n.endsWith("."+r))}function Km(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return cc.some(r=>n===r||n.endsWith("."+r))}function Wm(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 ic(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=Rm(e,n);if(r!==e&&!r.startsWith(e+To))return null;try{let o=await Nm(r);return o!==e&&!o.startsWith(e+To)?null:o}catch{return null}}function sc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(To).some(o=>bn.has(o))}function lc(){let e=Om(import.meta.url);return Vt(Dm(e),"viewer")}function ac(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function Ao(e){try{return await Am(e),!0}catch{return!1}}function dc(e,t,n,r,o,i,s,a,c,g,u){let h=za({onChange:a,enabled:u}),v=Tm(g);return(p,l)=>{(async()=>{let w=p.url??"/";try{if(!Hm(p.headers.host)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if((p.method==="POST"||p.method==="PATCH"||p.method==="DELETE")&&!Wm(p.headers.origin)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${w}`),w==="/api/credentials"){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({credentials:r.current??null,activeProfile:o.current??null}));return}if(w==="/api/credential-profiles"&&p.method==="GET"){let f=await je();l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({profiles:f,active:o.current}));return}if(w==="/api/credentials/switch"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let m=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}").profile,k=m===void 0||m===""?await oe():await Pe(m);if(k!==null){r.current=k,o.current=m??void 0;let S=o.current,T=await we(i);await Ve(i,{...T,credentialMode:"global",...S!==void 0&&{activeCredentialProfile:S}}),s({type:"credentials-updated",credentials:k,activeProfile:o.current??null})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({ok:k!==null}));return}if(w==="/api/bundle"){let f=Vt(process.cwd(),".kizenapp","bundle.json");try{let d=await $m(f,"utf-8");l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(d)}catch{l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end("{}")}return}if(w==="/api/last-path"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.path=="string"){c.current=d.path;let m=await we(i);await Ve(i,{...m,lastPath:d.path})}l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/encryption-target"&&p.method==="GET"){let d=(await we(i)).encryptionTarget==="dev"?"dev":"prod";l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({target:d}));return}if(w==="/api/encryption-target"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}"),m=d!==null&&typeof d=="object"?d:{};if(m.target!=="dev"&&m.target!=="prod"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let k=await we(i);await Ve(i,{...k,encryptionTarget:m.target}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/execute-step"&&p.method==="POST"){let f=[];for await(let S of p)f.push(S);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.script!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: script"}));return}let m={script:d.script,scriptRuntime:d.scriptRuntime??Lm(Bm),inputs:Ka(d.inputs),secrets:d.secrets??{},onInstallProgress:S=>{S.kind==="start"?s({type:"venv-install-start"}):S.kind==="log"?s({type:"venv-install-log",line:S.line,stream:S.stream}):S.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:S.message})}};typeof d.timeout=="number"&&d.timeout>0&&(m.timeout=Math.min(d.timeout,300*1e3));let k=await Za(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k));return}if(w==="/api/proxy-cache/clear"){h.clear(),n({kind:"info",message:"Proxy cache cleared"}),l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end('{"ok":true}');return}if(w==="/api/local/encrypt"&&p.method==="POST"){let f=[];for await(let m of p)f.push(m);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let m=jm(d.value,d.publicKeyPem),k=Mm(m);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify(k))}catch(m){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:m.message}))}return}if(w==="/api/local/validate"&&p.method==="POST"){let f=[];for await(let _ of p)f.push(_);let d=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof d.value!="string"){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing required field: value"}));return}let m,k;try{m=Fm(d.value)}catch(_){k=_.message}if(k!==void 0||m===void 0){l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:!1,checks:[],error:k}));return}let S=_=>Buffer.from(_,"base64").length,T=[{label:"Version",expected:String(oc),actual:String(m.v),pass:m.v===oc},{label:"Algorithm",expected:rc,actual:m.alg,pass:m.alg===rc},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(S(m.k))} bytes`,pass:S(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(S(m.iv))} bytes`,pass:S(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(S(m.tag))} bytes`,pass:S(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(S(m.ct))} bytes`,pass:S(m.ct)>=1}];l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({valid:T.every(_=>_.pass),checks:T}));return}if(w.startsWith("/api/wizard")){let f=p.headers["x-encryption-target"],m=(Array.isArray(f)?f[0]:f)==="dev"?"dev":"prod",k=Mt(m);if(!Vm(k)){l.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:`Encryption API host is not allowed: ${k}`}));return}let S=w.slice(11)||"/",T=`${k}${S}`,_=p.method??"GET",R=[];for await(let Xe of p)R.push(Xe);let{host:z,"x-encryption-target":ee,...ae}=p.headers,me=R.length>0?Buffer.concat(R):void 0,he=me&&me.length>0?me:void 0,ue;try{ue=await fetch(T,{method:_,headers:ae,...he!==void 0&&{body:he}})}catch(Xe){let nr=Xe.code==="ECONNREFUSED"?`plugin-wizard is not running at ${k}`:`Failed to reach plugin-wizard: ${Xe.message}`;l.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:nr}));return}let de=Vn(Object.fromEntries(ue.headers)),vt=await ue.arrayBuffer();l.writeHead(ue.status,de),l.end(Buffer.from(vt));return}if(w.startsWith("/api/proxy")){let f=p.headers["x-proxy-target"];if(typeof f!="string"){l.writeHead(400),l.end("Missing x-proxy-target header");return}if(!Km(f)){l.writeHead(400),l.end("Invalid proxy target");return}let d=w.slice(10)||"/",m=`${f}${d}`,k=p.method??"GET",S=[];for await(let ue of p)S.push(ue);let{host:T,"x-proxy-target":_,...R}=p.headers;if(k==="GET"){let ue=`GET::${m}`,{response:de,fromCache:vt}=await h.get(ue,()=>fetch(m,{method:"GET",headers:R}));n({kind:"request",method:"GET",status:de.status,upstreamStatus:ac(d,de.headers,de.body),fromCache:vt,url:d}),l.writeHead(de.status,de.headers),l.end(de.body);return}let z=S.length>0?Buffer.concat(S):void 0,ee=z&&z.length>0?z:void 0,ae=await fetch(m,{method:k,headers:R,...ee!==void 0&&{body:ee}}),me=Vn(Object.fromEntries(ae.headers)),he=await vo(ae,wo);n({kind:"request",method:k,status:ae.status,upstreamStatus:ac(d,me,he),fromCache:!1,url:d}),l.writeHead(ae.status,me),l.end(he);return}if(w.startsWith("/api/source/tree")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"",m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await Im(m,{withFileTypes:!0}),S=await Promise.all(k.filter(_=>_.isDirectory()?!bn.has(_.name):_.isFile()?!Um.has(_.name):!1).map(async _=>{let R=_.isDirectory()?"dir":"file",z={name:_.name,kind:R};if(R==="file")try{let ee=await tc(Vt(m,_.name));z.size=ee.size}catch{}return z}));S.sort((_,R)=>_.kind!==R.kind?_.kind==="dir"?-1:1:_.name.localeCompare(R.name));let T=m===v?"":m.slice(v.length+1);l.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({path:T,entries:S}))}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/tree failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}if(w.startsWith("/api/source/file")&&p.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"";if(d===""){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Missing path"}));return}let m=await ic(v,d);if(m===null){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Invalid path"}));return}if(sc(v,m)){l.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Path is excluded"}));return}try{let k=await tc(m);if(!k.isFile()){l.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not a file"}));return}if(k.size>zm){l.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"File too large",size:k.size}));return}let S=nc(m).toLowerCase(),T=xo[S],_=Qa.has(S),R=T??(_?"text/plain; charset=utf-8":"application/octet-stream");l.writeHead(200,{"Content-Type":R,"Content-Length":String(k.size)}),ec(m).pipe(l)}catch(k){let S=k instanceof Error?k.message:String(k);t(`source/file failed (${d}): ${S}`),l.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),l.end(JSON.stringify({error:"Not found"}))}return}let x=Vt(e,w==="/"?"/index.html":w),y=await Ao(x)?x:Vt(e,"index.html"),P=nc(y),b=xo[P]??"application/octet-stream";l.writeHead(200,{"Content-Type":b}),ec(y).pipe(l)}catch(C){if(w.startsWith("/api/proxy")){let E=w.slice(10)||"/",x=p.method??"GET";C instanceof Lt?n({kind:"info",message:`${x} ${E} \u2192 502 (response exceeded ${String(C.limit)} bytes)`}):n({kind:"request",method:x,status:502,fromCache:!1,url:E})}else n({kind:"info",message:`Error handling ${w}: ${C instanceof Error?C.message:String(C)}`});l.headersSent||(l.writeHead(502),l.end("Bad Gateway"))}})()}}import{launch as qm}from"chrome-launcher";import{createRequire as Jm}from"module";import{mkdirSync as Gm}from"fs";import{readFile as Ym}from"fs/promises";import{dirname as Xm,join as Zm}from"path";import{fileURLToPath as Qm}from"url";var uc=Jm(import.meta.url)("chrome-remote-interface"),eh=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),fc=["kizen.dev","kizen.com"];function pc(e){try{let{hostname:t}=new URL(e);return fc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function th(e){try{let t=Zm(Xm(Qm(import.meta.url)),"viewer","icon.png"),n=await Ym(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function mc(e){Gm(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await qm({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,o=null,i=null,s=null,a=null,c=0,g=!1,u=y=>{e.debugLog?.(y)},h=y=>{e.verbose&&e.debugLog?.(y)},v=()=>{i!==null&&(clearInterval(i),i=null)},p=y=>y==="chrome://new-tab-page/"||y==="chrome://newtab/",l=async y=>{v(),s=null,await th(y),await y.Fetch.enable({patterns:fc.flatMap(b=>[{urlPattern:`*://${b}/*`,requestStage:"Response"},{urlPattern:`*://*.${b}/*`,requestStage:"Response"}])}),y.on("Fetch.requestPaused",b=>{(async()=>{let f=b,{requestId:d,request:m,responseHeaders:k,responseStatusCode:S}=f,T=m.url;h(`Fetch ${String(S??"?")} ${T}`);let _=[],R=!1;for(let z of k??[])if(!eh.has(z.name.toLowerCase()))if(z.name.toLowerCase()==="set-cookie"&&pc(T)){let ee=z.value.split(`
1183
+ `).map(ae=>/SameSite=/i.test(ae)?ae.replace(/SameSite=\w+/i,"SameSite=None"):ae+"; SameSite=None; Secure").join(`
1184
+ `);_.push({name:z.name,value:ee}),R=!0}else _.push(z);R&&h(` rewrote Set-Cookie SameSite on ${T}`);try{let{body:z,base64Encoded:ee}=await y.Fetch.getResponseBody({requestId:d});await y.Fetch.fulfillRequest({requestId:d,responseCode:S??200,responseHeaders:_,body:z,...ee&&{base64Encoded:!0}})}catch(z){h(` fulfillRequest failed (${z.message}), falling through`);try{await y.Fetch.continueRequest({requestId:d})}catch(ee){h(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:b}=await y.Network.getAllCookies(),f=0;for(let d of b){if(!pc(`https://${d.domain??""}`)||d.sameSite==="None")continue;let m=d.domain??"",k=m.startsWith(".")?m.slice(1):m;await y.Network.setCookie({url:`https://${k}`,name:d.name,value:d.value,domain:m,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),f++}f>0&&h(`cookie-patch cycle: updated ${String(f)} cookie(s) to SameSite=None`)}catch(b){h(`cookie-patch cycle failed: ${b.message}`)}})()},2e3),await y.Target.setDiscoverTargets({discover:!0});let P=b=>{if(b.type==="page"){if(p(b.url)){u(`closed stray new-tab-page target ${b.targetId}`),s!==null&&y.Target.activateTarget({targetId:s}).catch(()=>{}),y.Target.closeTarget({targetId:b.targetId}).catch(()=>{});return}s===null&&(s=b.targetId,u(`captured main target ${b.targetId} (${b.url})`))}};y.on("Target.targetCreated",b=>{let{targetInfo:f}=b;h(`target +${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("Target.targetInfoChanged",b=>{let{targetInfo:f}=b;h(`target ~${f.type} ${f.targetId} ${f.url}`),P(f)}),y.on("disconnect",()=>{g||o!==y||(u("CDP disconnected"),o=null,v(),w())})},w=()=>{if(g||a!==null)return;let y=Math.min(1e3*2**c,1e4),P=c+1;c++,u(`CDP reconnect scheduled in ${String(y)}ms (attempt #${String(P)})`),a=setTimeout(()=>{a=null,(async()=>{let b;try{b=await uc({port:r})}catch{u(`CDP reconnect attempt #${String(P)} failed`),w();return}if(g){try{await b.close()}catch{}return}o=b;try{await l(b),u(`CDP reconnected after ${String(P)} attempt(s)`),c=0}catch{o===b&&(o=null);try{await b.close()}catch{}u(`CDP reconnect attempt #${String(P)} failed during setup`),w()}})()},y)},C=30,E=300;for(let y=0;y<C;y++){await new Promise(P=>setTimeout(P,E)),u(`CDP connect attempt ${String(y+1)}/${String(C)}`);try{let P=await uc({port:r});o=P,e.path&&P.send("Page.navigate",{url:`${t}${e.path}`});try{await l(P),u("CDP connected")}catch{o===P&&(o=null);try{await P.close()}catch{}u("CDP setup failed after connect")}break}catch{if(y===C-1){let P=`CDP unavailable after ${String(C)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return u(P),e.onWarn?.(P),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(u("CDP kill requested \u2014 tearing down"),g=!0,a!==null&&(clearTimeout(a),a=null),v(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as nh,useState as rh}from"react";function Wn(e){let[t,n]=rh([]),r=nh(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as qn,useEffect as Io,useState as Jn}from"react";import{Box as Q,Text as M,useInput as oh}from"ink";import{jsx as N,jsxs as te}from"react/jsx-runtime";var Ge=["apiKey","userId","businessId"],ih={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},Kt=({text:e})=>N(M,{dimColor:!0,children:e}),Gn=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=Jn(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=Jn(""),[c,g]=Jn(null),[u,h]=Jn(void 0),v=qn(b=>{if(b==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),p=qn(async b=>{if(b===null){i({type:"profile-loading"});let m=await je();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}h(b.isDefault?void 0:b.name),i({type:"loading"});let f=b.isDefault?await oe():await Pe(b.name),d=f?Math.max(0,W.indexOf(f.environment)):0;i({type:"creds-entry",field:0,values:f??{},envCursor:d})},[]),l=qn(async(b,f)=>{let d=W[f]??"go",m={...Ct(b),environment:d};i({type:"saving"});try{await Ho(u??Be,m),n({mode:"global",credentials:m,...u!==void 0&&{profileName:u}})}catch(k){g(k instanceof Error?k.message:String(k)),i({type:"creds-entry",field:0,values:b,envCursor:f})}},[n,u]);oh((b,f)=>{if(f.ctrl&&b==="c"&&process.exit(0),f.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),w();return}r?.();return}if(o.type==="mode-select"){if(f.upArrow)i({type:"mode-select",cursor:0});else if(f.downArrow)i({type:"mode-select",cursor:1});else if(f.return){let d=o.cursor===0?"global":"local";v(d)}return}if(o.type==="profile-select"){let{profiles:d,cursor:m}=o,k=d.length,S=d.length+1;if(f.upArrow)i({...o,cursor:(m-1+S)%S});else if(f.downArrow)i({...o,cursor:(m+1)%S});else if(f.return)if(m===k)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let T=d[m]??d[0];T&&p(T)}return}if(o.type==="name-entry"){let{nameBuffer:d,existingProfiles:m}=o;if(f.backspace||f.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:m});else if(f.return){let k=d.trim();if(!k){i({...o,nameError:"Name cannot be empty"});return}if(k===Be){i({...o,nameError:`"${Be}" is reserved`});return}if(m.some(S=>S.name===k)){i({...o,nameError:`Profile "${k}" already exists`});return}h(k),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else b&&!f.ctrl&&!f.meta&&i({type:"name-entry",nameBuffer:d+b,existingProfiles:m});return}if(o.type==="creds-entry"){let{field:d,values:m,envCursor:k}=o;if(d===Ge.length){f.leftArrow?i({...o,envCursor:(k-1+W.length)%W.length}):f.rightArrow?i({...o,envCursor:(k+1)%W.length}):f.upArrow?(i({...o,field:d-1}),a(m[Ge[d-1]]??"")):f.return&&l(m,k);return}let T=Ge[d];if(!T)return;if(f.backspace||f.delete)a(_=>_.slice(0,-1));else if(f.upArrow&&d>0){let _={...m,[T]:s},R=d-1;i({...o,field:R,values:_}),a(_[Ge[R]]??"")}else if(f.return||f.tab||f.downArrow){let _={...m,[T]:s},R=d+1;i({...o,field:R,values:_}),R<Ge.length?a(_[Ge[R]]??""):a("")}else b&&!f.ctrl&&!f.meta&&a(_=>_+b)}});let w=qn(async()=>{let b=await je();i({type:"profile-select",profiles:b,cursor:0})},[]);if(Io(()=>{o.type==="profile-loading"&&w()},[o.type,w]),Io(()=>{e==="global"&&!t&&(async()=>{let b=await oe(),f=b?Math.max(0,W.indexOf(b.environment)):0;i({type:"creds-entry",field:0,values:b??{},envCursor:f})})()},[]),Io(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let b=o.type==="saving"?"Saving credentials\u2026":o.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return N(Q,{paddingY:1,paddingX:2,children:N(M,{dimColor:!0,children:b})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{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((f,d)=>{let m=o.cursor===d;return te(Q,{gap:2,children:[N(M,{...m&&{color:"cyan"},children:m?"\u276F":" "}),N(M,{bold:m,...m&&{color:"cyan"},children:f.label}),N(M,{dimColor:!0,children:f.desc})]},f.mode)})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:b,cursor:f}=o,d=b.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:"Credential profiles"}),b.map((m,k)=>{let S=f===k;return te(Q,{gap:2,children:[N(M,{...S&&{color:"cyan"},children:S?"\u276F":" "}),N(M,{bold:S,...S&&{color:"cyan"},children:m.isDefault?"Default":m.name}),N(M,{dimColor:!0,children:m.path})]},m.name)}),te(Q,{gap:2,children:[N(M,{...f===d&&{color:"cyan"},children:f===d?"\u276F":" "}),N(M,{bold:f===d,...f===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),N(Kt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:b,nameError:f}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),N(Q,{flexDirection:"column",gap:0,children:N(M,{bold:!0,children:"New credential profile"})}),f&&te(M,{color:"red",children:["Error: ",f]}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:!0,color:"cyan",children:"Profile name"})}),N(M,{color:"cyan",children:">"}),N(M,{children:b}),N(M,{color:"cyan",children:"\u2588"})]}),N(Kt,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:C,values:E,envCursor:x}=o,y=C===Ge.length,P=u??Be;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[N(J,{}),te(Q,{flexDirection:"column",gap:0,children:[N(M,{bold:!0,children:u!==void 0?`Profile: ${u}`:"Global credentials"}),te(M,{dimColor:!0,children:["Saved to:"," ",u!==void 0?`~/.kizenappbuilder/${u}.json`:Oe]})]}),c&&te(M,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Ge.map((b,f)=>{let d=C===f,m=d?s:E[b]??"";return te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:d,...d&&{color:"cyan"},children:ih[b]})}),N(M,{...d&&{color:"cyan"},children:">"}),N(M,{children:m}),d&&N(M,{color:"cyan",children:"\u2588"})]},b)}),te(Q,{gap:2,children:[N(Q,{width:12,children:N(M,{bold:y,...y&&{color:"cyan"},children:"Environment"})}),N(M,{...y&&{color:"cyan"},children:">"}),N(Q,{gap:1,children:W.map((b,f)=>{let d=f===x;return y?N(M,{bold:d,...d&&{color:"cyan"},children:d?`[${b}]`:b},b):N(M,{dimColor:!d,bold:d,children:b},b)})})]})]}),y?N(Kt,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):N(Kt,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(M,{dimColor:!0,children:["Profile: ",P]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var ph=[".kizenapp",".git"],gc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:g=!0,cacheEnabled:u=!0})=>{let h=$e(r),v=$e(i),p=$e(s),[l,w]=le("main"),[C,E]=le(o),[x,y]=le("starting"),[P,b]=le(null),[f,d]=Wn(50),[m,k]=Wn(50),[S,T]=Wn(50),[_,R]=le([]),[z,ee]=le("pending"),[ae,me]=le(null),[he,ue]=le(null),[de,vt]=le(null),[Xe,nr]=le(null),[rr,or]=le(0),[Ro,nl]=le(0),[rl,ol]=le(0),[ir,il]=le(0),sr=$e(!1),Oo=$e(!1),qt=$e(null),xt=$e(null),Ne=$e(new Set),Jt=$e([]),pe=wt(A=>{let H=JSON.stringify(A);if(Ne.current.size===0){Jt.current=[...Jt.current,H].slice(-50);return}let De=!1;for(let ge of Ne.current)if(ge.readyState===1)try{ge.send(H)}catch{Ne.current.delete(ge),De=!0}De&&or(Ne.current.size)},[]),Gt=d,ar=wt(()=>{qt.current?.kill(),qt.current=null,mc({port:e,userDataDir:hc(n,".chrome"),broadcast:pe,onWarn:A=>{d(`\u26A0 ${A}`)},...p.current!==void 0&&{path:p.current},...a&&{debugLog:T},...c&&{verbose:!0}}).then(A=>{qt.current=A})},[e,n,pe,a,c,T,d]);Yn(()=>{let A=()=>{qt.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),ah((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&w("editing"),A==="v"&&ar()},{isActive:l==="main"}),Yn(()=>{x!=="running"||Oo.current||!g||(Oo.current=!0,ar())},[x,g,ar]);let sl=wt(A=>{h.current=A.credentials,v.current=A.profileName,w("main"),E(A.mode);let H=A.profileName;Ve(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),pe({type:"credentials-updated",credentials:A.credentials})},[n,pe]),Bo=wt(A=>{R(H=>[...H,`${new Date().toLocaleTimeString()}: ${_o(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?ol(H=>H+1):il(H=>H+1)),pe({type:"proxy-log",entry:A})},[pe]),Ze=wt(A=>{k(A),pe({type:"log",message:A})},[k,pe]),cr=wt(()=>{sr.current||(sr.current=!0,ee("building"),me(null),ue(null),Ze("Build started"),vn(t,n).then(({bundleSize:A})=>{Ze(`Build finished \u2014 bundle: ${Rt(A)}`),ee("done"),vt(new Date),nr(A),Ze("Notifying viewers to reload"),pe({type:"rebuild"})}).catch(A=>{A instanceof ch?(ue(A.issues),me(null)):(me(A instanceof Error?A.message:String(A)),ue(null)),ee("error")}).finally(()=>{sr.current=!1}))},[t,n,Ze,pe]);if(Yn(()=>{cr();let A=lh(t,{recursive:!0},(H,De)=>{if(!De)return;let ge=De.replace(/\\/g,"/");ph.some(Yt=>ge.startsWith(Yt))||(Ze(`File change detected: ${De}`),xt.current!==null&&clearTimeout(xt.current),xt.current=setTimeout(cr,150))});return A.on("error",H=>{Ze(`File watcher error \u2014 rebuilds have stopped: ${H.message}`)}),()=>{A.close(),xt.current!==null&&clearTimeout(xt.current)}},[t,cr,Ze]),Yn(()=>{let A=lc();Ao(hc(A,"index.html")).then(H=>{if(!H){b("Viewer not built. Run 'pnpm build:viewer' first."),y("error");return}let De=dc(A,Gt,Bo,h,v,n,pe,nl,p,t,u),ge=dh(De),Yt=new uh({server:ge});return Yt.on("connection",Qe=>{for(let cl of Jt.current)Qe.readyState===1&&Qe.send(cl);Jt.current=[],Gt("Viewer connected for live reload"),Ne.current.add(Qe),or(Ne.current.size),Qe.on("close",()=>{Ne.current.delete(Qe),or(Ne.current.size)})}),ge.listen(e,"127.0.0.1",()=>{y("running"),Gt(`Server started on 127.0.0.1:${String(e)}`)}),ge.on("error",Qe=>{b(Qe.message),y("error")}),()=>{Yt.close(),ge.close()}})},[e,Gt,Bo,pe,n,t,u]),l==="editing")return j(Gn,{...C!==void 0&&{initialMode:C},showProfileManager:C==="global",onComplete:sl,onCancel:()=>{w("main")}});let lr=de!==null?Math.round((Date.now()-de.getTime())/1e3):null,al=lr===null?"":lr<5?" (just now)":` (${String(lr)}s ago)`,Fo=he?.filter(A=>A.severity==="error").length??0;return X(ne,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(J,{marginBottom:1}),X(ne,{flexDirection:"column",children:[X(ne,{gap:2,marginBottom:0,children:[j(F,{bold:!0,dimColor:!0,children:"App Build"}),z==="pending"&&j(F,{dimColor:!0,children:"waiting\u2026"}),z==="building"&&X(ne,{gap:1,children:[j(xe,{}),j(F,{children:"Building plugin package\u2026"})]}),z==="done"&&X(ne,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),de!==null&&X(F,{dimColor:!0,children:["at ",de.toLocaleTimeString(),al]}),Xe!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Rt(Xe)]})]}),z==="error"&&(he!==null?X(F,{color:"red",children:["\u2717 ",Fo," validation ",Fo===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ae??"unknown error"]}))]}),he!==null&&j(Rn,{issues:he}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),x==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),x==="running"&&X(ne,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),X(F,{dimColor:!0,children:["\u25CF ",rr," viewer",rr!==1?"s":""]})]}),x==="error"&&X(F,{color:"red",children:["\u2717 ",P??"Server error"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:u?`\u25CF ${String(Ro)} key${Ro!==1?"s":""} in the network cache \xB7 ${String(rl)} hit \xB7 ${String(ir)} miss`:`\u25CF network cache disabled \xB7 ${String(ir)} request${ir!==1?"s":""}`})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:_.length===0?j(F,{dimColor:!0,children:" No requests yet."}):_.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),a&&X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),X(F,{dimColor:!0,children:["\u25CF ",S.length," event(s)"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:S.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):S.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,gap:1,children:[j(F,{dimColor:!0,children:"["}),j(F,{children:"q"}),j(F,{dimColor:!0,children:"] quit ["}),j(F,{children:"c"}),j(F,{dimColor:!0,children:"] credentials ["}),j(F,{children:"v"}),X(F,{dimColor:!0,children:["] ",rr===0?"open viewer":"relaunch viewer"]})]})]})};async function yc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=wc(bc(Gn,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function vc(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 an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").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)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let n=parseInt(t.port,10),r=process.cwd(),o=`${r}/.kizenapp`;ve(r);let i=null,s,a,{lastPath:c}=await we(o);if(t.credentials)i=await Fe(t.credentials);else{let l=await we(o);if(l.credentialMode==="local")s="local";else if(l.credentialMode==="global"){if(s="global",a=l.activeCredentialProfile,a?(i=await Pe(a),i||(i=await oe(),a=void 0)):i=await oe(),!i){let w=await yc("global");i=w.credentials,a=w.profileName}}else{let w=await yc();i=w.credentials,s=w.mode,a=w.profileName;let C=w.profileName;await Ve(o,{credentialMode:w.mode,...C!==void 0&&{activeCredentialProfile:C}})}}let g=t.verbose===!0,u=g||t.debug===!0,h=t.viewer!==!1,v=t.cache!==!1,{waitUntilExit:p}=wc(bc(gc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:u,verbose:g,autoViewer:h,cacheEnabled:v}),{exitOnCtrlC:!1});await p()})}import{createElement as Ph}from"react";import{render as Eh}from"ink";import{useCallback as Zn,useEffect as Sc,useState as Qn}from"react";import{Box as ke,Text as U,useApp as wh,useInput as vh}from"ink";import{encrypt as fh,serializeEnvelope as mh}from"@kizenapps/packager";function hh(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function xc(e){return{"Content-Type":"application/json","x-api-key":e.apiKey,"x-user-id":e.userId,"x-business-id":e.businessId,"x-auth-environment":e.environment}}async function kc(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(hh(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${Zt()==="unavailable"?` ${Xt}`:""}`)}}async function Cc(e){let t=await e.text();if(t==="")return{};try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function gh(e,t,n){let r=Mt(e.stage),o=await kc(r,"/get-public-key",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n})}),i=await Cc(o);if(!o.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(o.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function yh(e,t){let n=fh(t,e),r=mh(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function bh(e,t,n,r){let o=Mt(e.stage),i=await kc(o,"/encrypt",{method:"POST",headers:xc(t),body:JSON.stringify({api_name:n,value:r})}),s=await Cc(i);if(!i.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function Xn(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),bh(e,t,n,r);o?.("fetching-key");let i=await gh(e,t,n);return o?.("encrypting"),yh(i,r)}import{Fragment as er,jsx as L,jsxs as re}from"react/jsx-runtime";var $o=({text:e})=>L(U,{dimColor:!0,children:e}),Pc=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=wh(),[c,g]=Qn({type:"loading"}),[u,h]=Qn(null),[v,p]=Qn(r??""),[l,w]=Qn(i??""),C=Zn(d=>{process.exitCode=1,g({type:"error",message:d instanceof Error?d.message:String(d)})},[]),E=Zn(async(d,m,k)=>{try{let S=await Xn(e,d,m,k,R=>{g(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),T=JSON.stringify({encrypted:!0,value:S},null,2);s?.(S);let _=await mn(T);g({type:"done",envelope:T,copied:_})}catch(S){C(S)}},[e,C,s]),x=Zn((d,m,k)=>{if(m.trim()===""){g({type:"api-name-entry",buffer:o??""});return}if(k===""){g({type:"value-entry",buffer:""});return}E(d,m.trim(),k)},[o,E]),y=Zn(async d=>{try{g({type:"loading"});let m=d.isDefault?await oe():await Pe(d.name);if(m===null)throw new Error(`Could not load credential profile: ${d.name}`);h(m),x(m,v,l)}catch(m){C(m)}},[v,l,x,C]);Sc(()=>{(async()=>{try{if(n!==void 0){let k;try{k=await Fe(n)}catch(S){throw new Error(`Could not load credentials from ${n}: ${S instanceof Error?S.message:String(S)}`)}h(k),x(k,v,l);return}let d=await je();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[m]=d;if(d.length===1&&m!==void 0){let k=m.isDefault?await oe():await Pe(m.name);if(k===null)throw new Error(`Could not load credential profile: ${m.name}`);h(k),x(k,v,l);return}g({type:"profile-select",profiles:d,cursor:0})}catch(d){C(d)}})()},[]),Sc(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),vh((d,m)=>{if(m.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:k,cursor:S}=c;if(m.upArrow)g({...c,cursor:(S-1+k.length)%k.length});else if(m.downArrow)g({...c,cursor:(S+1)%k.length});else if(m.return){let T=k[S];T!==void 0&&y(T)}return}if(c.type==="api-name-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"api-name-entry",buffer:k.slice(0,-1)});else if(m.return){let S=k.trim();if(S===""){g({type:"api-name-entry",buffer:k,error:"api_name cannot be empty"});return}p(S),u?x(u,S,l):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"api-name-entry",buffer:k+d});return}if(c.type==="value-entry"){let{buffer:k}=c;if(m.backspace||m.delete)g({type:"value-entry",buffer:k.slice(0,-1)});else if(m.return){if(k===""){g({type:"value-entry",buffer:k,error:"secret cannot be empty"});return}w(k),u?x(u,v,k):C(new Error("Internal error: credentials were not loaded"))}else d&&!m.ctrl&&!m.meta&&g({type:"value-entry",buffer:k+d});return}});let P=e.isRemote?"remote Kizen API":"on-machine",b=t===!0?`${e.stage} (default)`:e.stage,f=d=>re(ke,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(J,{}),re(U,{dimColor:!0,children:["Mode: ",P," Stage: ",b]}),d]});if(c.type==="loading")return f(re(ke,{gap:1,children:[L(xe,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:d,cursor:m}=c;return f(re(er,{children:[L(U,{bold:!0,children:"Credential profile"}),L(ke,{flexDirection:"column",children:d.map((k,S)=>{let T=m===S;return re(ke,{gap:2,children:[L(U,{...T&&{color:"cyan"},children:T?"\u276F":" "}),L(U,{bold:T,...T&&{color:"cyan"},children:k.isDefault?"Default":k.name}),L(U,{dimColor:!0,children:k.path})]},k.name)})}),L($o,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:c.buffer}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?f(re(er,{children:[L(U,{bold:!0,children:"Secret value"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(ke,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:"\u2022".repeat(c.buffer.length)}),L(U,{color:"cyan",children:"\u2588"})]}),L($o,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?f(re(ke,{gap:1,children:[L(xe,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:v}),"\u2026"]})]})):c.type==="encrypting"?f(re(ke,{gap:1,children:[L(xe,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?f(re(ke,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):f(re(er,{children:[re(ke,{gap:1,children:[L(U,{color:"green",children:"\u2713"}),L(U,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?L(U,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):L(U,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),L(U,{children:c.envelope})]}))};import{readFile as xh,writeFile as kh}from"fs/promises";import{join as Ch}from"path";function Ec(e){return{encrypted:!0,value:e}}function _c(e){return JSON.stringify(Ec(e))}async function No(e,t){await kh(e,`${JSON.stringify(Ec(t),null,2)}
1185
+ `,"utf-8")}var Sh="prod";function Tc(e){return e==="dev"||e==="prod"}function Ac(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function Ic(e){return{stage:e==="dev"||e==="prod"?e:Sh,wasDefaulted:e===void 0}}function $c(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1186
+ `}async function Nc(e=process.cwd()){try{let t=await xh(Ch(e,"kizen.json"),"utf-8"),n=JSON.parse(t),r=Array.isArray(n)?n[0]:n,o=typeof r.api_name=="string"&&r.api_name!==""?r.api_name:void 0;return{...o!==void 0&&{apiName:o}}}catch{}return{}}function Dc(e){return e.replace(/[\r\n]+$/,"")}async function Rc(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function Oc(e,t,n,r,o){let i=t.credentials!==void 0?await o.loadCredentialsFromFile(t.credentials):await o.loadGlobalCredentials();if(i===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??n.apiName;if(s===void 0||s.trim()==="")throw new Error("api_name is required in non-interactive mode. Pass --api-name or run inside a plugin directory.");r&&o.writeStderr($c(e.stage));let a=t.value;if(a===void 0){if(o.stdinIsTTY())throw new Error('No secret provided and stdin is a terminal. Pass --value, or pipe the secret in (e.g. `printf %s "$SECRET" | npx --yes @kizenapps/cli encrypt \u2026`).');o.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
1187
+ `),a=Dc(await o.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let c=await o.encryptSecret(e,i,s.trim(),a);if(o.writeStdout(`${_c(c)}
1188
+ `),t.out!==void 0)try{await o.writeEnvelopeFile(t.out,c),o.writeStderr(`Wrote encrypted envelope to ${t.out}
1189
+ `)}catch(g){o.writeStderr(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}
1190
+ `),o.setExitCode(1)}}function Bc(e){e.command("encrypt").description("Encrypt a secret for a plugin against its encryption keys").option("--remote","encrypt via the plugin-wizard's remote API instead of on-machine").option("-c, --credentials <path>","path to an API-key credentials JSON file (encrypt still uses API keys until plugin-wizard accepts sign-in sessions)").option("-a, --api-name <name>","plugin api_name the secret belongs to").option("-v, --value <value>","plaintext secret value to encrypt").option("-s, --stage <stage>","which encryption API to use: dev or prod (default: prod)").option("-o, --out <path>","also write the encrypted envelope to a file").action(async t=>{t.stage!==void 0&&!Tc(t.stage)&&(console.error(Ac(t.stage)),process.exit(1));let r=t.apiName===void 0?await Nc():{},{stage:o,wasDefaulted:i}=Ic(t.stage),s={isRemote:t.remote===!0,stage:o};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await Oc(s,t,r,i,{loadCredentialsFromFile:Fe,loadGlobalCredentials:oe,encryptSecret:Xn,readStdin:Rc,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:g=>{process.stdout.write(g)},writeStderr:g=>{process.stderr.write(g)},writeEnvelopeFile:No,setExitCode:g=>{process.exitCode=g}})}catch(g){console.error(`Error: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}return}let a,{waitUntilExit:c}=Eh(Ph(Pc,{ctx:s,stageDefaulted:i,onDone:g=>{a=g},...t.credentials!==void 0&&{credentialsPath:t.credentials},...t.apiName!==void 0&&{initialApiName:t.apiName},...r.apiName!==void 0&&{defaultApiName:r.apiName},...t.value!==void 0&&{initialValue:t.value}}),{exitOnCtrlC:!1});if(await c(),a!==void 0&&t.out!==void 0)try{await No(t.out,a),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1191
+ `)}catch(g){console.error(`Error writing ${t.out}: ${g instanceof Error?g.message:String(g)}`),process.exitCode=1}})}var _h=new Set(["phone","envelope","pen-nib","calendar-days","paperclip","file","clipboard","pen","tag","book","print","pen-to-square","folder","folder-open","thumbtack","globe","city","briefcase","compass","address-book","business-time","computer-classic","pen-fancy","badge-check","mug-saucer","landmark","chart-simple","envelopes","diagram-venn","calendar","pencil","phone-volume","copy","table","building","network-wired","address-card","tags","registered","signature","phone-office","projector","sitemap","marker","badge","wallet","copyright","bullseye","calculator","certificate","percent","eraser","file-spreadsheet","glasses","industry","vault","user-tie-hair-long","user-tie-hair","user-hair-mullet","trademark","timeline-arrow","timeline","table-tree","table-rows","table-pivot","table-layout","table-columns","stapler","square-poll-vertical","square-poll-horizontal","square-phone-flip","square-phone","square-pen","square-kanban","square-envelope","socks","slot-machine","signature-slash","signature-lock","shredder","scissors","scanner-image","scale-unbalanced-flip","scale-unbalanced","scale-balanced","router","rectangle-pro","print-slash","print-magnifying-glass","presentation-screen","podium","phone-slash","phone-intercom","phone-flip","person-chalkboard","pen-nib-slash","pen-clip","paste","paperclip-vertical","notebook","note-sticky","money-check-pen","money-check-dollar-pen","magnifying-glass-chart","magnifying-glass-arrow-right","list-tree","list-timeline","list-radio","list-dropdown","list-check","laptop-file","lamp-desk","keynote","industry-windows","inboxes","inbox-full","house-laptop","highlighter","folders","folder-xmark","folder-tree","folder-plus","folder-minus","folder-arrow-up","folder-arrow-down","floppy-disk-circle-xmark","floppy-disk-circle-arrow-right","floppy-disk","file-user","file-lines","file-circle-plus","file-circle-info","file-chart-pie","file-chart-column","fax","envelope-open","envelope-dot","envelope-circle-check","coffee-pot","cloud-word","clipboard-question","chart-user","chart-tree-map","chart-simple-horizontal","chart-pyramid","chart-pie-simple","chart-pie","chart-line-up","chart-line-down","chart-line","cake-candles","cabinet-filing","bullhorn","briefcase-blank","briefcase-arrow-right","brain-arrow-curved-right","boxes-packing","box-archive","book-section","bars-staggered","bars-progress","badge-percent","badge-dollar","arrows-to-eye","arrows-to-dot","arrows-spin","sparkles","megaphone","block-question","lightbulb-slash","comments-dollar","comments","bullseye-pointer","lightbulb","user-group-crown","user-crown","signal-stream-slash","signal-stream","rectangle-ad","ranking-star","person-rays","people-group","messages-dollar","message-dollar","magnifying-glass-location","magnifying-glass-dollar","lightbulb-on","lightbulb-exclamation","lightbulb-dollar","lightbulb-cfl-on","lightbulb-cfl","hundred-points","group-arrows-rotate","gift-card","filter-circle-dollar","envelopes-bulk","envelope-open-text","envelope-open-dollar","comment-dollar","chart-mixed","bullseye-arrow","star","heart","camera-retro","truck-fast","bell","cart-shopping","gift","barcode","bookmark","camera","thumbs-up","thumbs-down","key","truck","balloons","handshake","shop","shirt","bag-shopping","moped","cart-plus","credit-card","store","cash-register","booth-curtain","trophy","receipt","truck-container","truck-clock","truck-bolt","trophy-star","store-slash","store-lock","star-exclamation","shop-slash","shop-lock","rectangle-barcode","person-booth","nfc-trash","nfc-symbol","nfc-slash","nfc-signal","nfc-pen","nfc-magnifying-glass","nfc-lock","nfc","money-check-dollar","money-check","mobile-signal-out","mobile-signal","hexagon-vertical-nft-slanted","hexagon-vertical-nft","hexagon-image","hand-holding-box","gifts","gem","credit-card-front","credit-card-blank","cart-xmark","cart-shopping-fast","cart-minus","cart-circle-xmark","cart-circle-plus","cart-circle-exclamation","cart-circle-check","cart-circle-arrow-up","cart-circle-arrow-down","cart-arrow-up","cart-arrow-down","box-open-full","basket-shopping-simple","basket-shopping","barcode-scan","barcode-read","balloon","bags-shopping","bars","browser","chart-bar","cog","database","calendar-alt","play","kizen-k","add","book-alt","form-entity","arrows-to-circle","question-circle","chevron-down","chevron-up","window-restore","forward"]),Th=[..._h].sort(),Ah=new Set(["kizen-k","form-entity"]),Fc=[...Th,...[...Ah].sort()];function jc(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of Fc)console.log(t)})}import{mkdir as Fh,writeFile as Gc,readFile as jh}from"fs/promises";import{join as tr}from"path";var Ih=new Set(["developer_business_id"]);function $h(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let n=t;if(typeof n.auth_credentials!="object"||n.auth_credentials===null)return n;let r=Object.fromEntries(Object.keys(n.auth_credentials).map(o=>[o,"*****"]));return{...n,auth_credentials:r}}):e}function Mc(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let n of e){let r=n.path.split("/"),o=t;r.forEach((i,s)=>{o.children.has(i)||o.children.set(i,{name:i,children:new Map,isFile:s===r.length-1,filePath:r.slice(0,s+1).join("/")});let a=o.children.get(i);a&&(o=a)})}return t}function zc(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function Do(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Uc(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var Nh={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".css":"css",".scss":"scss",".html":"html",".htm":"html",".md":"markdown",".mdx":"markdown",".py":"python",".sh":"bash",".yml":"yaml",".yaml":"yaml",".xml":"xml",".toml":"toml"};function Dh(e){return Nh[Uc(e)]??""}function Lc(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function Hc(e,t=""){let n=zc(e);return n.map((r,o)=>{let i=o===n.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=i?" ":"\u2502 ";return r.isFile?`${t}${s}${r.name}`:`${t}${s}${r.name}/
1192
+ ${Hc(r,t+a)}`}).join(`
1193
+ `)}var Rh=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function Vc(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!Rh.test(t.path))}function Kc(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Ih.has(t)).map(([t,n])=>[t,t==="services"?$h(n):n]))}var Oh={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Wc(e){return`<ul>${zc(e).map(r=>r.isFile?`<li class="tf"><a href="#${Do(r.filePath)}" data-id="${Do(r.filePath)}">${Ce(r.name)}</a></li>`:`<li class="td"><span class="dn">${Ce(r.name)}/</span>${Wc(r)}</li>`).join("")}</ul>`}function Bh(e){let t;return e.base64Image!==void 0?t=`<img src="data:${Oh[Uc(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Ce(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>${Ce(e.content)}</code></pre>`,`<section id="${Do(e.path)}"><h2 class="fp">${Ce(e.path)}</h2><div class="fb">${t}</div></section>`}function qc(e,t){let n=Kc(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Vc(t),a=[];a.push(`# ${r}${o?` v${o}`:""}`),i&&a.push("",i);let c=JSON.stringify(n,null,2),g=Lc(c);a.push("","## Configuration (`kizen.json`)","",`${g}json`,c,g),a.push("","## File Tree","","```",Hc(Mc(s)),"```"),a.push("","## Files");for(let u of s)if(a.push("",`### \`${u.path}\``,""),u.base64Image!==void 0)a.push(`[Image file: ${u.path}]`);else if(u.binaryData!==void 0)a.push(`[Binary file: ${String(u.binaryData.length)} bytes]`);else{let h=Lc(u.content);a.push(`${h}${Dh(u.path)}`,u.content,h)}return a.join(`
1078
1194
  `)+`
1079
- `}function Ca(e,t){let r=xa(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=wa(t),a=va(ha(s)),l=s.map(tf).join(`
1195
+ `}function Jc(e,t){let n=Kc(e),r=typeof e.name=="string"?e.name:"Plugin",o=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Vc(t),a=Wc(Mc(s)),c=s.map(Bh).join(`
1080
1196
  `);return`<!DOCTYPE html>
1081
1197
  <html lang="en">
1082
1198
  <head>
1083
1199
  <meta charset="UTF-8">
1084
1200
  <meta name="viewport" content="width=device-width,initial-scale=1">
1085
- <title>${we(o)} \u2014 Plugin Report</title>
1201
+ <title>${Ce(r)} \u2014 Plugin Report</title>
1086
1202
  <style>
1087
1203
  *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
1088
1204
  :root{
@@ -1119,8 +1235,8 @@ img{border:1px solid var(--bd);border-radius:4px}
1119
1235
  </head>
1120
1236
  <body>
1121
1237
  <header>
1122
- <h1>${we(o)}${n?` <span style="color:var(--mu);font-size:.8em">v${we(n)}</span>`:""}</h1>
1123
- ${i?`<p>${we(i)}</p>`:""}
1238
+ <h1>${Ce(r)}${o?` <span style="color:var(--mu);font-size:.8em">v${Ce(o)}</span>`:""}</h1>
1239
+ ${i?`<p>${Ce(i)}</p>`:""}
1124
1240
  </header>
1125
1241
  <div class="layout">
1126
1242
  <nav>
@@ -1128,8 +1244,8 @@ img{border:1px solid var(--bd);border-radius:4px}
1128
1244
  ${a}
1129
1245
  </nav>
1130
1246
  <main>
1131
- <section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${we(JSON.stringify(r,null,2))}</code></pre></div></section>
1132
- ${l}
1247
+ <section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Ce(JSON.stringify(n,null,2))}</code></pre></div></section>
1248
+ ${c}
1133
1249
  </main>
1134
1250
  </div>
1135
1251
  <script>
@@ -1142,9 +1258,9 @@ ${l}
1142
1258
  })();
1143
1259
  </script>
1144
1260
  </body>
1145
- </html>`}var _a=Pr(Ue,"examples");function Pa(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${_a}/<api_name>.html)`).action(async t=>{let r=process.cwd(),o;try{let l=await nf(Pr(r,"kizen.json"),"utf-8"),p=JSON.parse(l);o=Array.isArray(p)?p[0]:p}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let n=typeof o.api_name=="string"?o.api_name:"plugin",i=t.output??Pr(_a,`${n}.html`),s=i.replace(/\.html$/,".md"),a=await Ot(r,{detectBinaryByContent:!0});await rf(Pr(i,".."),{recursive:!0}),await Promise.all([Sa(i,Ca(o,a),"utf-8"),Sa(s,ka(o,a),"utf-8")]),console.log(`Plugin report written to:
1261
+ </html>`}var Yc=tr(Se,"examples");function Xc(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${Yc}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await jh(tr(n,"kizen.json"),"utf-8"),g=JSON.parse(c);r=Array.isArray(g)?g[0]:g}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let o=typeof r.api_name=="string"?r.api_name:"plugin",i=t.output??tr(Yc,`${o}.html`),s=i.replace(/\.html$/,".md"),a=await wn(n,{detectBinaryByContent:!0});await Fh(tr(i,".."),{recursive:!0}),await Promise.all([Gc(i,Jc(r,a),"utf-8"),Gc(s,qc(r,a),"utf-8")]),console.log(`Plugin report written to:
1146
1262
  ${i}
1147
- ${s}`)})}function Ea(e){e.command("setup-claude").description("Install or refresh the Claude Code skill for building custom blocks").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").action(async t=>{await ui(process.cwd(),t)})}async function Ta(e,t={}){if(await Re(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let r=t.dryRun===!0,o=await Kt(e,Ht(),{dryRun:r});return r||ge(e),{files:o}}function Ia(e){e.command("setup-copilot").description("Add or refresh the Copilot code-review setup in an existing plugin repo").option("--dry-run","report what would change without writing anything").action(async t=>{let r=process.cwd();if(await Re(r)!=="has-manifest"){console.error(`No kizen.json found in ${r} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let o=t.dryRun===!0;try{let n=await Ta(r,{dryRun:o});for(let i of n.files)console.log(Jt(i));if(o){console.log(`
1263
+ ${s}`)})}function Zc(e,t){e.command("setup-claude").description("Install or refresh the Claude Code skill for building custom blocks").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").option("--mcp","also register the Kizen MCP server in Claude Code (user scope)").option("--env <env>","environment of the MCP server to register (with --mcp; default: go)").option("--force","replace an existing Kizen MCP server registration (with --mcp)").action(async n=>{await Rs(process.cwd(),n,Ds(t))})}async function Qc(e,t={}){if(await qe(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Pn(e,kn(),{dryRun:n});return n||ve(e),{files:r}}function el(e){e.command("setup-copilot").description("Add or refresh the Copilot code-review setup in an existing plugin repo").option("--dry-run","report what would change without writing anything").action(async t=>{let n=process.cwd();if(await qe(n)!=="has-manifest"){console.error(`No kizen.json found in ${n} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let r=t.dryRun===!0;try{let o=await Qc(n,{dryRun:r});for(let i of o.files)console.log(En(i));if(r){console.log(`
1148
1264
  Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
1149
- Ensured .gitignore ignores .kizenapp/ and .copilot-docs/.`),console.log("The code review workflow only takes effect once it is on the repository default branch \u2014 merge it before expecting reviews to cite .copilot-docs/.")}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}})}function df(){let e=af(sf(lf(import.meta.url)),"..","package.json");return JSON.parse(of(e,"utf-8")).version}function Da(){let e=new cf;return e.name("appbuilder").description("Kizen plugin app builder").version(df()),ms(e),Ea(e),Ia(e),Oi(e),Gs(e),ua(e),Pa(e),fa(e),Bi(e),e}Zn({env:process.env,http:uf});Da().parse();
1265
+ Ensured .gitignore ignores .kizenapp/ and .copilot-docs/.`),console.log("The code review workflow only takes effect once it is on the repository default branch \u2014 merge it before expecting reviews to cite .copilot-docs/.")}catch(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1}})}function Vh(){let e=zh(Mh(Uh(import.meta.url)),"..","package.json");return JSON.parse(Lh(e,"utf-8")).version}function tl(){let e=new Hh,t=Vh();return e.name("appbuilder").description("Kizen plugin app builder").version(t),La(e),Zc(e,t),el(e),ca(e),vc(e),Bc(e),Xc(e),jc(e),ra(e),Ti(e),e}jo({env:process.env,http:Kh});tl().parse();
1150
1266
  //# sourceMappingURL=index.js.map