@kizenapps/cli 1.13.0 → 1.14.0-8ac42d6

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,14 @@
1
1
  #!/usr/bin/env node
2
- import*as Sp from"http";var Nt="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.",ma=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],Ln=e=>e!==void 0&&e!=="",Pe="not-configured";function Hn({env:e,http:t}){return Pe==="applied"||(ma.some(r=>Ln(e[r]))?Ln(e.NODE_USE_ENV_PROXY)?Pe="already-set":typeof t.setGlobalProxyFromEnv!="function"?Pe="unavailable":(t.setGlobalProxyFromEnv(e),Pe="applied"):Pe="not-configured"),Pe}var Dt=()=>Pe;import{readFileSync as bp}from"fs";import{dirname as wp,join as xp}from"path";import{fileURLToPath as vp}from"url";import{Command as kp}from"commander";import{createElement as Uc}from"react";import{render as Vc}from"ink";import{PluginValidationError as Wc}from"@kizenapps/packager";import{spawn as ha}from"child_process";import{platform as Un}from"process";function ga(){return Un==="darwin"?[{cmd:"pbcopy",args:[]}]:Un==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var ya=2e3;function ba(e,{cmd:t,args:r}){return new Promise(o=>{let n;try{n=ha(t,r,{stdio:["pipe","ignore","ignore"]})}catch{o(!1);return}let i=n,s=!1;function l(p){s||(s=!0,clearTimeout(a),o(p))}let a=setTimeout(()=>{i.kill(),l(!1)},ya);a.unref(),i.on("error",()=>{l(!1)}),i.on("close",p=>{l(p===0)}),i.stdin.on("error",()=>{l(!1)});try{i.stdin.end(e)}catch{l(!1)}})}async function Rt(e){for(let t of ga())if(await ba(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as ja,CONFIG_FILE_NAME as Fa,MANIFEST_FILE_NAME as Oa,sanitizeToAPIName as za}from"@kizenapps/packager";import{mkdir as Pa,writeFile as Ea}from"fs/promises";import{join as Ta}from"path";import{PluginValidationError as Ia,packagePlugin as Aa,parseManifestFromFiles as Na,transformDeployablePlugin as Da,transformFiles as Ra,validatePluginApp as Ba}from"@kizenapps/packager";import{readdir as wa,readFile as Vn}from"fs/promises";import{join as Wn,relative as xa}from"path";var va=new Set([".png",".svg"]),ka=new Set([".kzn"]),Ca=new Set([".DS_Store"]),Bt=new Set(["node_modules",".git",".kizenapp",".github",".claude","__pycache__"]),Sa=8e3;function _a(e){return e.subarray(0,Sa).includes(0)}async function Kn(e,t){let r=await wa(e,{withFileTypes:!0}),o=[];for(let n of r)if(n.isDirectory()){if(Bt.has(n.name))continue;o.push(...await Kn(Wn(e,n.name),t))}else n.isFile()&&(Ca.has(n.name)||o.push(Wn(e,n.name)));return o}async function $t(e,{detectBinaryByContent:t=!1}={}){let r=await Kn(e,e);return Promise.all(r.map(async o=>{let n=xa(e,o).split("\\").join("/"),i=n.lastIndexOf("."),s=i>=0?n.slice(i).toLowerCase():"";if(va.has(s)){let a=await Vn(o);return{path:n,content:"",base64Image:a.toString("base64")}}let l=await Vn(o);return ka.has(s)||t&&_a(l)?{path:n,content:"",binaryData:l}:{path:n,content:l.toString("utf-8")}}))}var $a=(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 Tr(e,t){t?.("reading-files");let r=await $t(e);t?.("validating");let o=Ba(r);if(o.some(a=>a.severity==="error"))throw new Ia(o);t?.("minifying");let n=await Ra(r);t?.("packaging");let i=Na(n),s=Aa(n,i),l=Object.values(s).map(Da);return{files:r,deployable:l,issues:o}}async function jt(e,t,r){await Pa(t,{recursive:!0});let{files:o,deployable:n}=await Tr(e,r);r?.("writing-bundle");let i=n.map(p=>{let h=p.release_notes_directory?.replace(/\/$/,""),w=h?o.filter(x=>x.path.startsWith(h+"/")&&x.path.endsWith(".md")&&x.content).map(x=>({version:x.path.slice(x.path.lastIndexOf("/")+1,-3),notes:x.content})).sort((x,d)=>d.version.localeCompare(x.version,void 0,{numeric:!0})):[];return $a(p,w)}),s=JSON.stringify(i,null,2),l=(p,h)=>p==="allReleaseNotes"?void 0:h,a=Buffer.byteLength(JSON.stringify(i,l,2),"utf-8");return await Ea(Ta(t,"bundle.json"),s,"utf-8"),{bundleSize:a}}var Ar=["min_w","max_w","min_h","max_h"],qn=[["min_w","max_w"],["min_h","max_h"]],Ft={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},Gn=Object.keys(Ft),Ma=[...Ar,...Gn],Yn=[...Ma,"host_chrome"],La=["\0","{__ref:"],qe=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 Nr(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 Dr(e,t){let r=e.flatMap(s=>s.artifacts.custom_blocks.map(l=>({block:l,pluginApiName:s.api_name}))),o=r.map(({block:s,pluginApiName:l})=>({pluginApiName:l,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:l})=>({pluginApiName:l,apiName:s.api_name}))}:{ok:!0,...i}:{ok:!1,reason:"not_found",available:o}}var Rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Ir=e=>La.some(t=>e.includes(t));function Br(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(!Rr(i))return"event_scripts";let h=Object.entries(i).find(([w,x])=>typeof x!="string"||Ir(w)||Ir(x));if(h)return`event_scripts.${h[0]}`}let s=[["name",r],["script",o],["styles",n]].find(([,h])=>typeof h=="string"&&Ir(h));if(s)return s[0];let l=Ar.find(h=>t[h]!==void 0&&!Jn(t[h]));if(l)return l;let a=qn.find(([h,w])=>{let x=t[h],d=t[w];return typeof x=="number"&&typeof d=="number"&&x>d});if(a)return a[0];let p=Gn.find(h=>{let w=t[h];if(w===void 0)return!1;if(typeof w!="number"||!Jn(w))return!0;let[x,d]=Ft[h],c=t[x],y=t[d];return typeof c=="number"&&w<c||typeof y=="number"&&w>y});if(p)return p;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var $r=(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=qn.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(Ar.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in Ft){let[o,n]=Ft[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:".`},Ha=(e,t)=>{let{reason:r,available:o}=e,n=Nr(o);return r==="no_blocks"?new qe(r,"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.",{available:o}):r==="not_found"?new qe(r,`No block with api_name "${t??""}". Available blocks: ${n}`,{available:o}):new qe(r,t===void 0?`This plugin has several blocks; pass the api_name of the one to export: ${n}`:`More than one plugin has a block with api_name "${t}": ${n}`,{available:o})},Ua=e=>{try{let t=JSON.parse(e);return Rr(t)?t:void 0}catch{return}},Va=e=>{let t=e.find(i=>i.path===Oa),r=t?JSON.parse(t.content):[],o=Array.isArray(r)?r:[r],n=new Map;for(let i of o)Rr(i)&&typeof i.api_name=="string"&&typeof i.entry=="string"&&n.set(i.api_name,i.entry);return n},Wa=(e,t)=>{let r=`${t.replace(/\/+$/,"")}/${ja}/`,o=new Map;for(let n of e){if(!n.path.startsWith(r))continue;let[i,s,...l]=n.path.slice(r.length).split("/");if(!i||s!==Fa||l.length>0)continue;let a=Ua(n.content);if(!a)continue;let p=typeof a.api_name=="string"&&a.api_name!==""?a.api_name:za(i),h={};for(let w of Yn)a[w]!==void 0&&(h[w]=a[w]);o.set(p,h)}return o},Ka=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([o])=>!Yn.includes(o))),...t});function Ja(e,t){let r=Va(t);return e.map(o=>{let n=r.get(o.api_name),i=n===void 0?new Map:Wa(t,n);return{...o,artifacts:{...o.artifacts,custom_blocks:o.artifacts.custom_blocks.map(s=>Ka(s,i.get(s.api_name)))}}})}async function jr(e){let{files:t,deployable:r,issues:o}=await Tr(e);return{deployable:Ja(r,t),warnings:o.filter(n=>n.severity==="warning")}}async function Xn(e,t){let{deployable:r,warnings:o}=await jr(e),n=Dr(r,t);if(!n.ok)throw Ha(n,t);let i=Br(n.block);if(i!==void 0)throw new qe("invalid_block",$r(n.block.api_name,i),{field:i});return{block:n.block,pluginApiName:n.pluginApiName,warnings:o}}var Fr=(e,t,r)=>`${String(e)} ${e===1?t:r}`,qa=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},Ga=e=>{let t=e.filter(n=>n.severity==="error").length,r=e.length-t;if(t===0)return`\u26A0 ${Fr(r,"validation warning","validation warnings")}`;let o=`\u2717 ${Fr(t,"validation error","validation errors")}`;return r===0?o:`${o}, ${Fr(r,"warning","warnings")}`};function me(e){if(e.length===0)return"";let t=[...qa(e)].map(([r,o])=>[r,...o.map(n=>` ${n.severity==="error"?"\u2717":"\u26A0"} ${n.message} (${n.rule})`)].join(`
3
- `));return[Ga(e),...t].join(`
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(`
4
5
 
5
- `)}import{randomUUID as Gl}from"crypto";import{join as Yl}from"path";import{PluginValidationError as Go}from"@kizenapps/packager";var Zn={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"},Qn={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"},Ya=["go","fmo"];function Or(e){return Ya.includes(e)}import{mkdir as Xa,readFile as Za,writeFile as Qa}from"fs/promises";import{join as eo}from"path";async function he(e){try{let t=await Za(eo(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function Ee(e,t){await Xa(e,{recursive:!0}),await Qa(eo(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}import{mkdir as to,readFile as ro,readdir as el,writeFile as no}from"fs/promises";import{homedir as tl}from"os";import{dirname as rl,join as Ot}from"path";var X=["go","fmo","staging","integration","test1"];function Ge(e){return typeof e=="string"?e.trim():""}function at(e){return{apiKey:Ge(e.apiKey),userId:Ge(e.userId),businessId:Ge(e.businessId)}}var ze=Ot(tl(),".kizenappbuilder"),xe=Ot(ze,"credentials.json"),Te="credentials";function oo(e){return X.includes(e)}function io(e){return typeof e=="string"?e.trim():e}function so(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,r=io(t.environment);return{...at(t),environment:oo(r)?r:"go"}}async function Ie(e){let t=await ro(e,"utf-8");return so(JSON.parse(t))}function nl(e){let t=io(e.environment);return t==null||t===""?"missing":oo(t)?"explicit":"invalid"}async function zr(e){let t=await ro(e,"utf-8"),r=JSON.parse(t);return{credentials:so(r),environmentSource:nl(r)}}async function te(){try{return await Ie(xe)}catch{return null}}async function ol(e){await to(rl(xe),{recursive:!0,mode:448}),await no(xe,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function ao(e){return Ot(ze,`${e}.json`)}async function Ae(){let e=[{name:Te,path:xe,isDefault:!0}];try{let t=await el(ze);for(let r of t){if(!r.endsWith(".json"))continue;let o=r.slice(0,-5);o!==Te&&e.push({name:o,path:Ot(ze,r),isDefault:!1})}}catch{}return e}async function lo(e,t){if(e===Te){await ol(t);return}await to(ze,{recursive:!0,mode:448}),await no(ao(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function ve(e){try{return await Ie(ao(e))}catch{return null}}async function co(){let e=await Ae(),t=await Promise.all(e.map(r=>zr(r.path).then(()=>!0,()=>!1)));return e.filter((r,o)=>t[o]===!0)}import*as Ye from"fs";import*as uo from"path";function Ne(e){let t=uo.join(e,".gitignore"),r=".kizenapp/",o="";if(Ye.existsSync(t)){o=Ye.readFileSync(t,"utf8");let i=o.split(`
6
- `).map(s=>s.trim());if(i.includes(r)||i.includes(".kizenapp"))return}let n=o.endsWith(`
7
- `)?r+`
8
- `:`
9
- `+r+`
10
- `;Ye.writeFileSync(t,o+n)}var il="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",sl="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",al=100,ll=new Set(["detail","non_field_errors"]),re=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}},Xe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Mr(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&&Mr(i,t,r);return}if(Xe(e))for(let[n,i]of Object.entries(e)){let s=t===""&&ll.has(n)?"":t===""?n:`${t}.${n}`;Mr(i,s,r)}}function cl(e){if(typeof e!="object"||e===null)return;let t=[];return Mr(e,"",t),t.length>0?t.join("; "):void 0}function po(e){let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)}async function dl(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 ul(e,t,r,o){let n=cl(o),i=`${e} ${t} failed with ${String(r)}${n===void 0?"":`: ${n}`}`;return r===401?new re("auth_failed",i,{status:r,hint:il}):r===403?new re("forbidden",i,{status:r,hint:sl}):r===404?new re("not_found",i,{status:r}):new re("api_error",i,{status:r})}function fo(e,t,r){if(Array.isArray(r))return{results:r,next:null};if(Xe(r)&&Array.isArray(r.results))return{results:r.results,next:r.next};throw new re("api_error",`${e} ${t} returned an unexpected response shape`)}function mo(e){let{credentials:t}=e,r=e.fetch??fetch,o=e.baseUrl??Zn[t.environment],n=async(l,a,p)=>{let h=/^https?:\/\//.test(a)?a:`${o}${a}`,w=h.startsWith(o)?h.slice(o.length):h,x={"X-API-KEY":t.apiKey,"X-USER-ID":t.userId,"X-BUSINESS-ID":t.businessId,Accept:"application/json"},d={method:l,headers:x};p!==void 0&&(x["Content-Type"]="application/json",d.body=JSON.stringify(p));let c;try{c=await r(h,d)}catch(P){throw new re("network_error",`Couldn't reach Kizen at ${o}: ${po(P)}${Dt()==="unavailable"?` ${Nt}`:""}`)}let y,v;try{({text:y,json:v}=await dl(c))}catch(P){throw new re("network_error",`${l} ${w}: couldn't read the response: ${po(P)}. The request may have been applied; check Kizen before retrying.`,{status:c.status})}if(!c.ok)throw ul(l,w,c.status,v);if(v===void 0&&y!=="")throw new re("api_error",`${l} ${w} returned a response that is not JSON`,{status:c.status});return v},i=encodeURIComponent,s=l=>{let a=new URL(o),p=new URL(l,a.origin);if(p.hostname!==a.hostname)throw new re("api_error",`GET /custom-objects pagination pointed at an unexpected host ${p.hostname}`);return new URL(`${p.pathname}${p.search}`,a.origin).toString()};return{async listDashboards(l,a){let p=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:l});a!==void 0&&p.set("custom_object_id",a);let h=`/dashboards/mine?${p.toString()}`;return fo("GET",h,await n("GET",h)).results},async listCustomObjects(){let l=[],a=new Set,p="/custom-objects?page_size=200";for(;p!==void 0&&!a.has(p)&&a.size<al;){a.add(p);let h=fo("GET",p,await n("GET",p));l.push(...h.results),p=typeof h.next=="string"&&h.next!==""?s(h.next):void 0}return l},async getCustomObject(l){let a=`/custom-objects/${i(l)}`,p=await n("GET",a);if(!Xe(p)||typeof p.id!="string"||typeof p.fetch_url!="string")throw new re("api_error",`GET ${a} returned an unexpected response shape`);return p},async getClientObjectId(){let l=await n("GET","/auth/bootstrap"),a=Xe(l)?l.business:void 0,p=Xe(a)?a.client_object:void 0,h=Xe(p)?p.id:void 0;return typeof h=="string"&&h!==""?h:null},async getDashboard(l){return await n("GET",`/dashboards/${i(l)}`)},async createDashlet(l,a){return await n("POST",`/dashboards/${i(l)}/dashlet`,a)},async updateDashlet(l,a,p){return await n("PATCH",`/dashboards/${i(l)}/dashlet/${i(a)}`,p)}}}import{createHash as pl}from"crypto";import{mkdir as fl,readFile as ml,writeFile as hl}from"fs/promises";import{dirname as gl,join as yo}from"path";var Lr="appbuilder:",Me=".kizenapp/pushes.json",yl=["min_w","max_w","min_h","max_h","default_w","default_h"],bl=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e){return typeof e=="number"&&Number.isFinite(e)}function zt(e,t,r){return Math.min(Math.max(e,t),r)}function wl(e){let t={...e};return delete t.custom_object,t}function bo(e,t){return`${Lr}${e}/${t}`}function wo(e){if(!e.startsWith(Lr))return null;let t=e.slice(Lr.length).split("/");if(t.length!==2)return null;let[r,o]=t;return!r||!o?null:{pluginApiName:r,blockApiName:o}}function xo(e){let t={};for(let r of yl){let o=e[r];Hr(o)&&(t[r]=o)}return t}function vo(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}function ko(e){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Object.entries(e.event_scripts).map(([t,r])=>({name:t,script:r})),...xo(e),...vo(e)}}function xl(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function vl(e){let t=0;for(let r of e){let o=r.layout;if(!de(o))continue;let{y:n,h:i}=o;!Hr(n)||!Hr(i)||(t=Math.max(t,n+i))}return t}function kl(e,t,r){let o=zt(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),n=zt(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:r,x:0,y:vl(e),w:zt(o,2,12),h:zt(n,1,99)}}function Co(e){return{name:bo(e.pluginApiName,e.blockApiName),layout:kl(e.dashlets,e.content,e.layoutId),config:xl({content:e.content,objectId:e.objectId})}}function So(e,t){let r=e.config;return{config:{...wl(de(r)?r:{}),content:t}}}function _o(e){let t=e.config;return de(t)?t.content:void 0}function Ze(e){let t=e.config;if(!de(t)||t.chart_type!=="html")return!1;let r=t.content;return de(r)&&r.kind==="custom_code"}function Po(e){return e.dashlets.filter(Ze)}function Mt(e){let t=_o(e);return de(t)&&typeof t.name=="string"?t.name:e.name}function Cl(e){let t=r=>typeof r=="string"?r:"";return Array.isArray(e)?e.filter(de).map(r=>({name:t(r.name),script:t(r.script)})):de(e)?Object.entries(e).map(([r,o])=>({name:r,script:t(o)})):[]}function Ur(e){if(Array.isArray(e))return e.map(Ur);if(de(e)){let t={};for(let r of Object.keys(e).sort())t[r]=Ur(e[r]);return t}return e}function Sl(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Vr(e){let t=de(e)?e:{},r={name:Sl(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Cl(t.event_scripts),...xo(t),...vo(t)};return pl("sha256").update(JSON.stringify(Ur(r))).digest("hex")}function Lt(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&Ze(i))return{kind:"map",dashlet:i,entry:t}}let r=bo(e.pluginApiName,e.blockApiName),o=e.dashlets.filter(i=>i.name===r&&Ze(i)),[n]=o;return o.length===1&&n?{kind:"name",dashlet:n}:o.length>1?{kind:"ambiguous",dashlets:o}:{kind:"none"}}function Eo(e,t){return t?.dashletId!==e.id?!1:Vr(_o(e))!==t.contentHash}function Wr(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function lt(e,t){return e.find(r=>Wr(r,t))}function To(e,t){let r=e.findIndex(o=>Wr(o,t));return r===-1?[...e,t]:e.map((o,n)=>n===r?t:o)}function ct(e,t){return e.filter(r=>!Wr(r,t))}function _l(e){if(!de(e))return null;for(let r of bl)if(typeof e[r]!="string")return null;let t=e;return{environment:t.environment,businessId:Ge(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var ho=e=>Date.parse(e.pushedAt)||0;function Pl(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||ho(r)>ho(n))&&t.set(o,r)}return[...t.values()]}var El=e=>e instanceof Error&&e.code==="ENOENT",go=e=>e instanceof Error?e.message:String(e);async function Io(e){let t;try{t=await ml(yo(e,Me),"utf8")}catch(o){if(El(o))return[];throw new Error(`Couldn't read ${Me}: ${go(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 (${go(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 Pl(r.map(_l).filter(o=>o!==null))}async function Ao(e,t){let r=yo(e,Me);await fl(gl(r),{recursive:!0}),await hl(r,`${JSON.stringify(t,null,2)}
11
- `,"utf8")}var Tl={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},Il={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function No(e){return Tl[e]}function Do(e){return Il[e]}function Ro(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{access as Fl,mkdir as Ol,readFile as zl,writeFile as Ml}from"fs/promises";import{dirname as Ll,join as dt,posix as Hl}from"path";var Bo="---\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` 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. Navigate the tab to `url` instead. Then run `localStorage.getItem('kizen-flag-custom-code-blocks')` in that tab with `javascript_tool`. If it isn't `'true'`, tell the user once per conversation that setting that localStorage key to `'true'` in the Kizen tab enables in-place refresh. Never set it yourself.\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, with one exception: the read-only `localStorage.getItem('kizen-flag-custom-code-blocks')` check above.\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`, 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 $o=`# Designing a Kizen custom block
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(`
8
+ `)+`
9
+ `,s=r===""||r.endsWith(`
10
+ `)?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
12
12
 
13
13
  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
14
 
@@ -357,144 +357,112 @@ render(
357
357
  color: var(--color-font-placeholder);
358
358
  }
359
359
  \`\`\`
360
- `;var jo='# Copilot review instructions for this Kizen plugin\n\nThis repo is a Kizen plugin app: a `kizen.json` manifest plus the artifacts\nthat `@kizenapps/packager` finds by walking the directory tree under the\nmanifest\'s `entry` (default `src/`). No manifest key lists artifacts. The\ndirectory layout decides what gets packaged.\n\n## Component directories\n\nUnder `entry`, the packager treats these directory names as component types:\n\n- `floatingFrames`\n- `blocks`\n- `dataAdornments`\n- `pages`\n- `views`\n- `toolbarItems`\n- `objectSettingsItems`\n- `actions`\n- `routeScripts`\n- `automationSteps`\n- `calendarSources`\n\nEvery directory under a component type needs a `config.json`. `views/` is the\none exception.\n\n## `api_name` rules\n\n- An `api_name` must match `/^[a-z_][a-z0-9_]+$/`: lowercase letters, digits\n and underscores, starting with a letter or underscore, at least 2 characters.\n- Set `api_name` explicitly in each artifact\'s `config.json`. The fallback\n lowercases and strips the directory name (`myFrame` becomes `myframe`), and\n that result can collide with another artifact\'s explicit `api_name`.\n- Data adornments have no `api_name` field. Flag one that adds it as dead\n configuration.\n- Sibling components in the same directory need unique `api_name`s. `pages/`\n and `views/` go further and share one namespace, so a page and a view with\n the same `api_name` collide even though they live in different directories.\n\n## A green build does not mean a correct artifact\n\nThe packager coerces malformed artifact config instead of rejecting it: an\ninvalid `field_type` on a data adornment becomes `phonenumber`, and an invalid\n`minimized_style` on a floating frame becomes `circle`. It also says nothing\nabout a missing required field. Publishing is the real gate. The publish step\ncreates each artifact with no defaulting, so a field the packager never emitted\nis absent and the publish request 400s. Review each\n`config.json` as if the build will not catch mistakes in it, because for these\ncases it does not.\n\nPublishing an app requires these fields per artifact type. An artifact missing\none builds clean and fails to publish:\n\n| Artifact | Required fields |\n| --- | --- |\n| Floating frame | `api_name`, `name`, `title` |\n| Block | `api_name`, `name` |\n| Data adornment | `field_type` (one of `phonenumber`, `date`, `datetime`) |\n| Routable page | `api_name`, `name` |\n| Toolbar item | `api_name`, `label`, and a non-blank `script.js` |\n| Object settings item | `api_name`, `label`, and a non-blank `script.js` |\n| JS action | `api_name`, `name`, `hint_object_name` (non-blank) |\n\nA floating frame whose `default_position` ends in `-fixed` must set\n`minimized_style: "circle"` or omit `minimized_style`. Any other value fails\nthe build with `structure/fixed-frame-minimized-style`.\n\n## Publishing\n\nPublishing an app requires exactly one `thumbnail.png`, and it must sit inside\nthe `entry` directory (`src/thumbnail.png` by default). The packager never sees\na thumbnail at the repo root, and publishing then fails with "Thumbnail is\nrequired for publishing".\n\n## Scope\n\nThis file covers repo structure and general review. Two path-scoped files\ncover the rest: `.github/instructions/security.instructions.md` for\nsecurity-sensitive patterns and\n`.github/instructions/version-discipline.instructions.md` for manifest version\nbumps.\n';var Fo=`---
361
- applyTo: "src/**/*.js,kizen.json"
362
- ---
363
-
364
- # Security review rules for plugin scripts
365
-
366
- These rules mirror the \`security/*\` validation rules in \`@kizenapps/packager\`.
367
- Flag violations the way the packager would, and also flag the patterns listed
368
- here that its static scan cannot detect.
369
-
370
- ## \`__dangerouslySkipProxy\`
371
-
372
- The packager lets \`__dangerouslySkipProxy\` through with the build WARNING
373
- \`security/dangerously-skip-proxy\`. Flag every occurrence for human review
374
- anyway, because the request leaves the browser directly instead of passing
375
- through the Kizen proxy.
376
-
377
- ## Plaintext credentials
378
-
379
- In \`kizen.json\`, a service's \`auth_credentials.token\`,
380
- \`auth_credentials.password\` and \`auth_credentials.client_secret\` must each be
381
- one of:
382
-
383
- - an encrypted envelope (\`{ "encrypted": true, "value": "..." }\`) that
384
- \`appbuilder encrypt\` produced
385
- - a \`{{secret.KEY}}\` reference, with \`KEY\` declared in \`base_config.secrets\`
386
- - a reference through \`auth_credentials.integration_secret_api_name\`
387
-
388
- A raw literal in any of those three fields is the build ERROR
389
- \`security/plaintext-credential\`. Treat a credential that reaches a commit in
390
- plaintext as compromised and rotate it; deleting the line does not undo the
391
- exposure.
392
-
393
- \`client_id\` is excluded from this rule on purpose. Public client ids are not
394
- sensitive, so do not flag them.
395
-
396
- ## Undeclared secret references
397
-
398
- A \`{{secret.KEY}}\` reference whose \`KEY\` is missing from \`base_config.secrets\`
399
- is the build ERROR \`security/undeclared-secret-reference\`, because nothing
400
- would supply the value at install time.
401
-
402
- ## Dynamic code execution
403
-
404
- \`eval(...)\`, \`new Function(...)\` or \`Function(...)\`, and a string argument to
405
- \`setTimeout\` or \`setInterval\` are the build ERROR \`security/dynamic-code\`.
406
-
407
- This rule catches direct, literal usage only. The packager's scan is
408
- parser-based, so a call built through a computed property or a reassigned
409
- reference gets past it. Obfuscated dynamic code stays a human-review concern.
410
-
411
- ## Secret logging and exfiltration
412
-
413
- The packager has no static check for a secret that gets logged, sent to an
414
- unexpected endpoint, or otherwise exfiltrated. Review for this by hand: look
415
- for credentials or decrypted secret values flowing into \`console.log\`, error
416
- messages, analytics calls, or outbound requests to anything other than the
417
- service they belong to.
418
-
419
- ## Handling secrets in this repo
420
-
421
- Encrypt secrets locally with \`appbuilder encrypt\` before committing them. Do
422
- not commit a plaintext secret value in any form; a comment, a script fixture,
423
- and a commit you intend to rewrite later all count.
424
- `;var Oo=`---
360
+ `;var ei=`# Copilot review instructions for this Kizen plugin
361
+
362
+ This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
363
+ that \`@kizenapps/packager\` finds by walking the directory tree under the
364
+ manifest's \`entry\` (default \`src/\`). No manifest key lists artifacts. The
365
+ directory layout decides what gets packaged.
366
+
367
+ ## The full Kizen plugin documentation is available at \`.copilot-docs/\`
368
+
369
+ Before this review started, the complete Kizen plugin developer documentation
370
+ was fetched into \`.copilot-docs/\` by \`.github/workflows/copilot-code-review.yml\`.
371
+ It is not committed to this repo \u2014 it is cloned from \`kizen/app-engine\` at review
372
+ time, so it is always current. It is the authoritative reference for every plugin
373
+ API, manifest field and runtime contract. Deliberately, no plugin rules are
374
+ copied into this repo: read them from \`.copilot-docs/\` instead.
375
+
376
+ Use it. Start from:
377
+
378
+ - \`.copilot-docs/17-gotchas.md\` \u2014 the consolidated list of traps and silent
379
+ failure modes, grouped by topic. Scan the sections relevant to the changed
380
+ files.
381
+ - \`.copilot-docs/method-index.md\` \u2014 A\u2013Z lookup from any method, manifest field,
382
+ endpoint or identifier to the doc that owns it.
383
+ - \`.copilot-docs/03-manifest-reference.md\` \u2014 every \`kizen.json\` and \`config.json\`
384
+ field, the component directory names, \`api_name\` rules, and the build/publish
385
+ validation rules.
386
+ - The other numbered docs (\`.copilot-docs/04-worker-runtime-api.md\`,
387
+ \`.copilot-docs/07-automation-steps.md\`, \`.copilot-docs/08-actions.md\`, and so
388
+ on) for complete contracts.
389
+
390
+ **Many Kizen plugin APIs fail silently when misused** \u2014 the call succeeds,
391
+ nothing throws, and the behavior is quietly wrong. These defects are not
392
+ detectable from the calling code alone, and they are the single most valuable
393
+ thing to catch in review. When a changed file calls a \`this.*\` worker method,
394
+ look that method up in \`method-index.md\` and read its contract before concluding
395
+ the call is correct.
396
+
397
+ The same applies to artifact config: check each \`config.json\` against
398
+ \`03-manifest-reference.md\`, and each automation step against
399
+ \`07-automation-steps.md\`.
400
+
401
+ When a review comment is based on the documentation, name the file it came from.
402
+
403
+ If \`.copilot-docs/\` is not present, the setup workflow did not run \u2014 it only
404
+ takes effect once it is on the repository's default branch \u2014 so say that in
405
+ the review instead of guessing at the rules from memory.
406
+
407
+ ## Scope
408
+
409
+ This file covers repo structure and general review. Two path-scoped files cover
410
+ the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
411
+ patterns and \`.github/instructions/version-discipline.instructions.md\` for
412
+ 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=`---
425
414
  applyTo: "kizen.json"
426
415
  ---
427
416
 
428
417
  # Version-bump discipline for \`kizen.json\`
429
418
 
430
- ## What a wrong bump breaks
431
-
432
- A business that installs this plugin accumulates its own stored state
433
- (automation runs, config values, references to entities) shaped by what was
434
- published at the time. Publishing is additive: it never rewrites a business's
435
- stored rows, and the plugin author has no way to migrate that state for them.
436
- A change is breaking when it invalidates an assumption the business's existing
437
- data already depends on.
438
-
439
- A MINOR or PATCH republish applies at once to a business's running automations
440
- and installed artifacts. Only a new MAJOR version waits for the business to
441
- upgrade explicitly. A change that needed MAJOR but shipped as MINOR or PATCH
442
- therefore breaks the business with no upgrade gate in between.
443
-
444
- Two kinds of change get MAJOR because they fail without an error:
445
-
446
- - Renaming a config field, changing its type, or adding a required key. A
447
- template reference like \`{{config.key}}\` for a key that no longer exists
448
- resolves to a literal \`null\`, and the artifact renders wrong or does
449
- nothing.
450
- - Removing or renaming a JS action. A business's automation and UI
451
- associations key on the action's \`api_name\` as a plain string, with no
452
- foreign key. After a rename or removal those associations stop firing.
453
-
454
- Review every \`kizen.json\` diff against the table below before approving the
455
- version bump in the same PR.
456
-
457
- ## Bump matrix
458
-
459
- | Resource | Change | Required bump |
460
- | --- | --- | --- |
461
- | Plugin | change \`api_name\` | **HARD-BLOCK**: identity can never change |
462
- | Service | add | MINOR |
463
- | Service | remove | MAJOR |
464
- | Service | change auth type or \`auth_level\` | MAJOR |
465
- | Service | change \`auth_credentials\` (client id/secret, scopes, authorize/token URLs) | MAJOR |
466
- | Service | change base URL or other non-auth field | PATCH |
467
- | Service | rename \`api_name\` | MAJOR |
468
- | Secret | add | MINOR |
469
- | Secret | remove | MINOR |
470
- | Secret | rename key | MAJOR |
471
- | Secret | re-encrypt value only | PATCH |
472
- | Automation step | add | MINOR |
473
- | Automation step | remove entire step | MAJOR |
474
- | Automation step | remove an input or output | MAJOR |
475
- | Automation step | change input/output \`data_type\` | MAJOR |
476
- | Automation step | add required input | MAJOR |
477
- | Automation step | add optional input | MINOR |
478
- | Automation step | change python runtime | PATCH |
479
- | Automation step | edit script body only | PATCH |
480
- | Artifact (frame, block, adornment, page, route script, toolbar/object-settings item, calendar source) | add | MINOR |
481
- | Artifact | remove | MINOR |
482
- | Artifact | rename \`api_name\` | MINOR |
483
- | Artifact | edit script or behavior | PATCH |
484
- | JS action | add | MINOR |
485
- | JS action | remove | MAJOR |
486
- | JS action | rename \`api_name\` | MAJOR |
487
- | JS action | change \`hint_object_name\` or script | PATCH |
488
- | Config field | add optional (with default) | MINOR |
489
- | Config field | add required (no default) | MAJOR |
490
- | Config field | remove | MINOR |
491
- | Config field | rename | MAJOR |
492
- | Config field | change type | MAJOR |
493
- | Config field | change default or label | PATCH |
494
- | \`required_entitlement\` | add gating | MINOR |
495
- | \`required_entitlement\` | change or remove | PATCH |
496
- | Manifest metadata (\`name\`, \`description\`, \`entry\`, \`release_branches\`, \`release_environments\`, \`published\`, \`developer_business_id\`) | any change | PATCH |
497
- `;var zo=`const MAX_PAGE_SIZE = 1000;
419
+ The bump matrix lives in the docs corpus that
420
+ \`.github/workflows/copilot-code-review.yml\` fetches into \`.copilot-docs/\`, so it
421
+ cannot drift out of date here.
422
+
423
+ Check every \`kizen.json\` diff against the "How big a bump?" matrix in
424
+ \`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
425
+ \`.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.
427
+ name: Copilot code review setup
428
+
429
+ on:
430
+ workflow_dispatch:
431
+
432
+ jobs:
433
+ copilot-setup-steps:
434
+ runs-on: ubuntu-latest
435
+ timeout-minutes: 10
436
+ permissions:
437
+ contents: read
438
+ steps:
439
+ - name: Check out this plugin repo
440
+ uses: actions/checkout@v4
441
+
442
+ - name: Fetch the Kizen plugin docs corpus into .copilot-docs/
443
+ run: |
444
+ set -euo pipefail
445
+ git clone --depth 1 --filter=blob:none --sparse \\
446
+ https://github.com/kizen/app-engine.git .docs-src
447
+ git -C .docs-src sparse-checkout set --no-cone '/docs/**/*.md' '!/docs/site/**'
448
+ mv .docs-src/docs .copilot-docs
449
+ rm -rf .docs-src
450
+
451
+ - name: Verify the corpus landed
452
+ run: |
453
+ set -euo pipefail
454
+ test -f .copilot-docs/17-gotchas.md
455
+ test -f .copilot-docs/method-index.md
456
+
457
+ numbered=$(find .copilot-docs -maxdepth 1 -name '[0-9][0-9]-*.md' | wc -l | tr -d ' ')
458
+ test "$numbered" -ge 18
459
+ test -f .copilot-docs/examples/kitchen_sink.md
460
+
461
+ count=$(find .copilot-docs -name '*.md' | wc -l | tr -d ' ')
462
+ echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
463
+ test "$count" -ge 24
464
+ du -sh .copilot-docs
465
+ `;var oi=`const MAX_PAGE_SIZE = 1000;
498
466
  const DEFAULT_MAX_PAGES = 10;
499
467
 
500
468
  const fieldCache = new Map();
@@ -739,21 +707,20 @@ export const sumBy = (records, name, valueOf) =>
739
707
  total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
740
708
  0,
741
709
  );
742
- `;function Lo(){return[{path:".github/copilot-instructions.md",content:jo},{path:".github/instructions/security.instructions.md",content:Fo},{path:".github/instructions/version-discipline.instructions.md",content:Oo}]}var Mo="lib/kizenData.js",jl=(e="src")=>e===""?Mo:`${e}/${Mo}`;function Le(e=["src"]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:Bo},{path:".claude/skills/kizen-custom-block/design.md",content:$o},...[...new Set(e)].map(t=>({path:jl(t),content:zo}))]}var Ho=".claude/skills/kizen-custom-block/SKILL.md",Uo="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",Ul=e=>e instanceof Error&&"code"in e&&e.code==="ENOENT",ut={readFile:async e=>{try{return await zl(e,"utf-8")}catch(t){if(Ul(t))return;throw t}},writeFile:async(e,t)=>{await Ol(Ll(e),{recursive:!0}),await Ml(e,t,"utf-8")},exists:async e=>{try{return await Fl(e),!0}catch{return!1}}},Vl=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Hl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t==="."?"":t};function Wl(e){let r=(Array.isArray(e)?e:[e]).map(o=>typeof o=="object"&&o!==null&&"entry"in o?Vl(o.entry):void 0).filter(o=>o!==void 0);return r.length>0?[...new Set(r)]:["src"]}async function Vo(e,t=ut){try{let r=await t.readFile(dt(e,"kizen.json"));return Le(r===void 0?void 0:Wl(JSON.parse(r)))}catch{return Le()}}var Kl=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Wo(e,t=ut,r=Le()){return Promise.all(r.map(async o=>({path:o.path,status:Kl(await t.readFile(dt(e,o.path)),o.content)})))}async function Jl(e,t={},r=ut,o=Le()){let n=await Wo(e,r,o);return t.dryRun===!0||await Promise.all(o.filter((i,s)=>n[s]?.status!=="unchanged").map(i=>r.writeFile(dt(e,i.path),i.content))),n}async function Ko(e,t=ut,r){try{let o=r??await Vo(e,t);return!o.some(i=>i.path===Ho)||await t.readFile(dt(e,Ho))===void 0?!1:(await Wo(e,t,o)).some(i=>i.status!=="unchanged")}catch{return!1}}var ql={fs:ut,log:e=>{console.log(e)},error:e=>{console.error(e)},setExitCode:e=>{process.exitCode=e}},Kr=(e,t)=>`${String(e.filter(r=>r.status===t).length)} ${t}`;async function Jo(e,t,r=ql,o){if(!await r.fs.exists(dt(e,"kizen.json"))){r.error("Error: kizen.json not found. Run this command from a plugin directory."),r.setExitCode(1);return}let n=t.dryRun===!0,i;try{i=await Jl(e,{dryRun:n},r.fs,o??await Vo(e,r.fs))}catch(a){r.error(`Error: ${a instanceof Error?a.message:String(a)}`),r.setExitCode(1);return}for(let a of i)r.log(`${a.status.padEnd(9)} ${a.path}`);let s=`${Kr(i,"created")}, ${Kr(i,"updated")}, ${Kr(i,"unchanged")}`,l="these files are managed by appbuilder, so local edits to them are replaced";r.log(n?`Dry run: ${s}; nothing written (${l}).`:`Claude files: ${s} (${l}).`)}function Ut(e){return{cwd:e,loadCredentialsDetailed:zr,listLoadableCredentialProfiles:co,loadConfig:he,packageBlocks:jr,createClient:t=>mo({credentials:t}),readPushMap:Io,writePushMap:Ao,ensureGitignore:Ne,isClaudeSkillStale:t=>Ko(t),randomUUID:Gl,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t}}}var Xl=new Set(["owner","admin","edit"]),Zl="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Yr=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function L(e,t,r={}){return{ok:!1,code:e,message:t,...r}}var ge=e=>({ok:!0,value:e});function He(e){return e instanceof re?L(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Go?L("validation_failed",me(e.issues),{issues:e.issues}):L("local_error",Yr(e))}var Ql=()=>X.join(", ");async function Ht(e,t){let r;try{r=await t.loadCredentialsDetailed(e.path)}catch(i){return L("credentials_invalid",`Couldn't read credentials from ${e.path}: ${Yr(i)}`)}if(r.environmentSource!=="explicit"){let i=r.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return L("credentials_invalid",`${e.path} ${i}. Set it to one of: ${Ql()}. The CLI won't default to production.`)}let{credentials:o}=r,n=["apiKey","userId","businessId"].filter(i=>o[i].trim()==="");return n.length>0?L("credentials_invalid",`${e.path} is missing ${n.map(i=>`"${i}"`).join(", ")}.`):ge({credentials:o,source:e})}var Jr=e=>({kind:"profile",name:e.name,path:e.path});async function Vt(e,t){if(e.credentials!==void 0)return Ht({kind:"file",path:e.credentials},t);let r=await t.listLoadableCredentialProfiles(),o=r.map(l=>l.name);if(e.profile!==void 0){let l=r.find(a=>a.name===e.profile);return l?Ht(Jr(l),t):L("credentials_invalid",o.length===0?`No loadable credential profile named "${e.profile}". No profiles are loadable; create ${xe} or pass -c <path>.`:`No loadable credential profile named "${e.profile}". Loadable profiles: ${o.join(", ")}`)}let n=await t.loadConfig(Yl(t.cwd,".kizenapp"));if(n.credentialMode==="local")return L("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(l=>l.name===n.activeCredentialProfile);if(i)return Ht(Jr(i),t);let[s]=r;return r.length===1&&s?Ht(Jr(s),t):r.length===0?L("credentials_invalid",`No credentials found. Create ${xe} or pass -c <path>.`):L("needs_choice",`Several credential profiles are available; pass --profile <name>: ${o.join(", ")}`,{choice:"profile",choices:r.map(l=>({value:l.name,label:l.isDefault?`${l.name} (default)`:l.name,args:["--profile",l.name]}))})}function ec(e,t){let r=new Set(t.map(o=>o.pluginApiName)).size>1;return t.map(({pluginApiName:o,apiName:n})=>{let i=e.find(l=>l.api_name===o)?.artifacts.custom_blocks.find(l=>l.api_name===n),s=r?`${o}/${n}`:n;return{value:n,label:`${i?.name??n} (${s})`,args:[n]}})}function tc(e,t){let r=Nr(e.available);return e.reason==="no_blocks"?"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.":e.reason==="not_found"?`No block with api_name "${t??""}". Available blocks: ${r}`:t===void 0?`This plugin has several blocks; pass the api_name of the one to push: ${r}`:`More than one plugin has a block with api_name "${t}": ${r}`}async function Xr(e,t){let r;try{r=await t.packageBlocks(t.cwd)}catch(s){if(s instanceof Go)return L("validation_failed",me(s.issues),{issues:s.issues});throw s}let o=Dr(r.deployable,e);if(!o.ok){let s=tc(o,e);return o.reason==="no_blocks"?L("invalid_block",s):L("needs_choice",s,{choice:"block",choices:ec(r.deployable,o.available)})}let n=Br(o.block);if(n!==void 0)return L("invalid_block",$r(o.block.api_name,n),{field:n});let i=ko(o.block);return ge({block:o.block,pluginApiName:o.pluginApiName,content:i,contentHash:Vr(i),warnings:r.warnings})}var Yo=e=>e==null?null:Xl.has(e.toLowerCase());function pt(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:Yo(e.employee_access)}}var Xo=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),rc="Contacts";async function Zr(e){let[t,r]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),o=t.map(Xo).sort((n,i)=>n.objectName.localeCompare(i.objectName));return r!==null&&r!==""&&!o.some(n=>n.id===r)&&o.push({id:r,objectName:rc,fetchUrl:"client"}),o}async function nc(e,t,r){let{environment:o,businessId:n}=t;try{if(r.object!==void 0){let a=r.object,[p,h]=await Promise.all([e.getCustomObject(a).catch(()=>null),e.listDashboards("chart_group",a)]);return ge({ok:!0,environment:o,businessId:n,object:p?Xo(p):null,surfaces:{chart_group:h.map(w=>pt(w,"chart_group"))}})}let[i,s,l]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Zr(e)]);return ge({ok:!0,environment:o,businessId:n,surfaces:{dashboard:i.map(a=>pt(a,"dashboard")),homepage:s.map(a=>pt(a,"homepage"))},customObjects:l})}catch(i){return He(i)}}var Qr=(e,t)=>t.dashboard===e.id;function Wt(e,t){return[...Po(e).filter(o=>Qr(e,o)).map(o=>{let n=wo(o.name);return{value:o.id,label:Mt(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"]}]}function Qe(e,t,r,o){return ge({dashboard:e,surface:No(e.type),action:t,dashlet:r,resolvedBy:o})}async function oc(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:Yo(i.employee_access)});return L("needs_choice",`Choose where to push; pass --dashboard <id>. ${Zl}`,{choice:"dashboard",choices:[...t.map(o("dashboard")),...r.map(o("homepage"))]})}async function ic(e,t,r){let o=await e.client.getDashboard(t);if(r.create)return Qe(o,"create",void 0,"flag");let n=()=>Wt(o,e.block);if(r.dashlet!==void 0){let s=r.dashlet,l=o.dashlets.find(a=>a.id===s&&Qr(o,a));return l?Ze(l)?Qe(o,"update",l,"flag"):L("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.`):L("not_found",`Dashlet ${s} is not on dashboard "${o.name}" (${o.id}).`,{choice:"target",choices:n()})}let i=Lt({dashboardId:o.id,dashlets:o.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry});return i.kind==="map"?Qe(o,"update",i.dashlet,"push_map"):i.kind==="name"?Qe(o,"update",i.dashlet,"name"):L("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 sc(e,t,r){let o;try{o=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof re&&i.kind==="not_found")return L("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 Qe(o,"create",void 0,"remembered");let n=o.dashlets.find(i=>i.id===t.dashletId&&Qr(o,i));return n&&Ze(n)?Qe(o,"update",n,"remembered"):L("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:Wt(o,e.block)})}async function en(e,t){if(t.dashlet!==void 0&&t.create)return L("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return L("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await ic(e,t.dashboard,t):e.entry?await sc(e,e.entry,t):await oc(e)}catch(r){return He(r)}}async function ac(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}}}var qr=encodeURIComponent;async function tn(e,t,r,o){let{credentials:n,block:i}=e,{dashboard:s,surface:l,dashlet:a}=t,p=[],h,w,x;if(t.action==="update"){if(!a)return L("usage_error","An update needs a dashlet to update.");if(Eo(a,e.entry)){let y=`"${Mt(a)}" (dashlet ${a.id}) was changed in Kizen since the last push.`;if(!r.force)return L("drift_detected",`${y} Pushing would overwrite those changes; pass --force to overwrite them.`);p.push(`${y} Overwriting it because of --force.`)}h=So(a,i.content),w=`/dashboards/${qr(s.id)}/dashlet/${qr(a.id)}`,x=`Update "${Mt(a)}" (dashlet ${a.id})`}else h=Co({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:o.randomUUID(),layoutId:o.randomUUID()}),w=`/dashboards/${qr(s.id)}/dashlet`,x=`Create a new block on "${s.name}"`;let d=t.action==="update"&&a?a.id:null,c=Ro({appBaseUrl:Qn[n.environment],surface:l,dashboardId:s.id,customObject:await ac(e.client,s,l)});return ge({action:t.action,method:t.action==="update"?"PATCH":"POST",path:w,body:h,dashboard:{id:s.id,name:s.name,type:l},dashletId:d,url:c,resolvedBy:t.resolvedBy,warnings:p,summary:{environment:n.environment,businessId:n.businessId,isProduction:Or(n.environment),surface:l,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:x,dashletId:d,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")}})}var et=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function rn(e,t,r){let o;try{if(t.action==="create"){let a=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof a!="string"||a==="")return L("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);o=a}else{if(t.dashletId===null)return L("usage_error","An update needs a dashlet to update.");await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),o=t.dashletId}}catch(l){return He(l)}let n=[...t.warnings],i={...et(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,To(e.pushMap,i)),s=!0}catch(l){n.push(`The push succeeded, but ${Me} couldn't be written, so this target isn't remembered: ${Yr(l)}`)}return ge({dashletId:o,remembered:s,warnings:n})}var lc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nn(e){return lc.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function on(e,t){let r=et(e);return lt(e.pushMap,r)?(await t.writePushMap(t.cwd,ct(e.pushMap,r)),!0):!1}function sn(e,t){return e.dryRun?ge({kind:"dry-run",reason:"flag"}):e.yes?Or(t)&&!e.allowProduction?L("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):ge({kind:"apply"}):ge({kind:"dry-run",reason:"no_yes"})}var cc="Dry run only: pass --yes to write.";function ft(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`]}var dc=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`,uc=e=>/^[\w./:@=-]+$/.test(e)?e:JSON.stringify(e);function pc(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(uc).join(" ");o.push(` ${n.label} \u2192 ${t} ${i}`)}}return`${o.join(`
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(`
743
711
  `)}
744
- `}function Zo(e,t,r,o){e.json?e.deps.writeStdout(`${JSON.stringify(t,null,2)}
745
- `):e.deps.writeStderr(pc(t,r,o)),e.deps.setExitCode(1)}var qo=e=>e.credentials!==void 0?["-c",e.credentials]:e.profile===void 0?[]:["--profile",e.profile];async function fc(e){try{return await e.isClaudeSkillStale(e.cwd)?[Uo]:[]}catch{return[]}}async function Qo(e,t,r){let o={json:t.json===!0,deps:r},n="appbuilder block push",i=e===void 0?[]:[e],s=(a,p)=>p==="profile"?[...i,...a.args]:p==="block"?[...a.args,...qo(t)]:[...i,...qo(t),...a.args],l=a=>{Zo(o,a,n,s)};try{let a=await Vt(t,r);if(!a.ok){l(a);return}let{credentials:p}=a.value,h=r.createClient(p),w=await Xr(e,r);if(!w.ok){l(w);return}let x=w.value;i=[x.block.api_name],x.warnings.length>0&&r.writeStderr(`${me(x.warnings)}
746
- `);let d={client:h,credentials:p,block:x,pushMap:[],entry:void 0};d.pushMap=await r.readPushMap(r.cwd);let c=!1;t.forget&&(c=await on(d,r),c&&(d.pushMap=ct(d.pushMap,et(d)),r.writeStderr(`Forgot the remembered target for ${x.block.api_name}.
747
- `))),d.entry=lt(d.pushMap,et(d));let y=await en(d,t);if(!y.ok){l(y);return}let v=sn(t,p.environment);if(!v.ok){l(v);return}let P=await tn(d,y.value,t,r);if(!P.ok){l(P);return}let C=P.value,_={pluginApiName:x.pluginApiName,apiName:x.block.api_name,name:x.block.name},S={environment:p.environment,businessId:p.businessId,dashboard:C.dashboard},g=[...x.warnings.map(dc),...await fc(r)],f=v.value;if(f.kind==="dry-run"){let R=[...g,...C.warnings],M={ok:!0,applied:!1,dryRun:!0,reason:f.reason,action:C.action,...S,dashletId:C.dashletId,url:C.url,resolvedBy:C.resolvedBy,block:_,method:C.method,path:C.path,body:C.body,warnings:R,...c?{forgotten:!0}:{}};o.json?(r.writeStdout(`${JSON.stringify(M,null,2)}
748
- `),r.writeStderr([...ft(C.summary),...R.map(W=>`Warning: ${W}`),""].join(`
749
- `))):r.writeStdout([...ft(C.summary),`URL: ${C.url}`,...R.map(W=>`Warning: ${W}`),"",`${C.method} ${C.path}`,JSON.stringify(C.body,null,2),""].join(`
750
- `)),f.reason==="no_yes"&&r.writeStderr(`${cc}
751
- `);return}let u=await rn(d,C,r);if(!u.ok){l(u);return}let m=u.value,b=[...g,...m.warnings],k=nn(C.dashboard.id),I={ok:!0,applied:!0,dryRun:!1,action:C.action==="create"?"created":"updated",...S,dashletId:m.dashletId,url:C.url,...k?{refresh:k}:{},resolvedBy:C.resolvedBy,block:_,remembered:m.remembered,warnings:b,...c?{forgotten:!0}:{}},E=[`\u2713 ${I.action==="created"?"Created":"Updated"} ${x.block.name} on "${C.dashboard.name}" (dashlet ${m.dashletId})`,...ft(C.summary),`URL: ${C.url}`,...k?[`Refresh an open tab: ${k.script}`]:[],...b.map(R=>`Warning: ${R}`),""].join(`
752
- `);o.json?(r.writeStdout(`${JSON.stringify(I,null,2)}
753
- `),r.writeStderr(E)):r.writeStdout(E)}catch(a){l(He(a))}}var mc=(e,t)=>e.padEnd(t);function Gr(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,l)=>Math.max(s.length,...o.map(a=>(a[l]??"").length))),i=s=>` ${s.map((l,a)=>mc(l,n[a]??0)).join(" ")}`.trimEnd();return[e,i(r),...o.map(i)]}function hc(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})`,"",...Gr("Chart groups",e.surfaces.chart_group)):t.push(...Gr("Dashboards",e.surfaces.dashboard),"",...Gr("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(`
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(`
754
721
  `)}
755
- `}async function ei(e,t){let r={json:e.json===!0,deps:t},o="appbuilder block targets",n=e.object===void 0?[]:["--object",e.object],i=l=>[...l.args,...n],s=l=>{Zo(r,l,o,i)};try{let l=await Vt(e,t);if(!l.ok){s(l);return}let{credentials:a}=l.value,p=await nc(t.createClient(a),a,e.object===void 0?{}:{object:e.object});if(!p.ok){s(p);return}t.writeStdout(r.json?`${JSON.stringify(p.value,null,2)}
756
- `:hc(p.value))}catch(l){s(He(l))}}import{useEffect as ii,useState as qt}from"react";import{Box as oe,Text as q,useApp as Rc,useInput as ci}from"ink";import"@kizenapps/packager";import{Box as wc,Text as xc}from"ink";import{Box as gc,Text as yc}from"ink";import{jsx as ti}from"react/jsx-runtime";var bc=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],ri=()=>ti(gc,{flexDirection:"column",children:bc.map((e,t)=>ti(yc,{color:"cyan",children:e},t))});import{Fragment as vc,jsx as an,jsxs as kc}from"react/jsx-runtime";var K=({marginBottom:e=0})=>kc(vc,{children:[an(ri,{}),an(wc,{flexDirection:"column",marginTop:1,marginBottom:e,children:an(xc,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useMemo as Cc,useState as Sc}from"react";import{Box as ln,Text as Ue,useInput as _c}from"ink";var Kt=(e,t,r)=>Math.min(Math.max(e,t),r);function Jt(e,t,r,o={}){if(t<=0)return 0;let n=Kt(Math.trunc(e)||0,0,t-1),i=a=>o.disabled?.[a]!==!0;if(r===0)return n;let s=r>0?1:-1;if(Math.abs(r)===1){for(let a=1;a<=t;a++){let p=((n+s*a)%t+t)%t;if(i(p))return p}return n}let l=Kt(n+Math.trunc(r),0,t-1);for(let a=l;a>=0&&a<t;a+=s)if(i(a))return a;for(let a=l-s;a>=0&&a<t;a-=s)if(i(a))return a;return n}function ni(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=Kt(Math.trunc(e)||0,0,t-1),i=Kt(n-Math.floor(o/2),0,t-o);return{start:i,end:i+o}}import{jsx as Ve,jsxs as cn}from"react/jsx-runtime";var Pc="\u2191/\u2193 to move, Enter to select, Esc to cancel",Ec=10,Tc=(e,t)=>{let r=Jt(t,e.length,0);if(e[r]?.disabled!==!0)return r;let o=e.findIndex(n=>n.disabled!==!0);return o===-1?r:o},We=({title:e,items:t,onSelect:r,onCancel:o,hint:n=Pc,initialIndex:i=0,windowSize:s=Ec,isActive:l=!0})=>{let[a,p]=Sc(()=>Tc(t,i)),h=Cc(()=>t.map(P=>P.disabled===!0),[t]),w=Jt(a,t.length,0),x=Math.max(1,Math.floor(s));_c((P,C)=>{let _=S=>{p(Jt(w,t.length,S,{disabled:h}))};if(C.upArrow||P==="k")_(-1);else if(C.downArrow||P==="j")_(1);else if(C.pageUp)_(-x);else if(C.pageDown)_(x);else if(C.return){let S=t[w];S!==void 0&&S.disabled!==!0&&r(S,w)}else C.escape&&o?.()},{isActive:l});let{start:d,end:c}=ni(w,t.length,x),y=d,v=t.length-c;return cn(ln,{flexDirection:"column",gap:1,children:[Ve(Ue,{bold:!0,children:e}),cn(ln,{flexDirection:"column",children:[y>0&&Ve(Ue,{dimColor:!0,children:` \u2191 ${String(y)} more`}),t.slice(d,c).map((P,C)=>{let S=d+C===w,g=P.disabled===!0,f=S&&!g;return cn(ln,{gap:2,children:[Ve(Ue,{...f&&{color:"cyan"},dimColor:g,children:S?"\u276F":" "}),Ve(Ue,{bold:f,dimColor:g,...f&&{color:"cyan"},children:P.label}),P.description!==void 0&&Ve(Ue,{dimColor:!0,children:P.description})]},P.key)}),v>0&&Ve(Ue,{dimColor:!0,children:` \u2193 ${String(v)} more`})]}),Ve(Ue,{dimColor:!0,children:n})]})};import{useEffect as Ic,useState as Ac}from"react";import{Text as Nc}from"ink";import{jsx as Dc}from"react/jsx-runtime";var oi=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ye=()=>{let[e,t]=Ac(0);return Ic(()=>{let r=setInterval(()=>{t(o=>(o+1)%oi.length)},80);return()=>{clearInterval(r)}},[]),Dc(Nc,{color:"cyan",children:oi[e]??"\u280B"})};import{Fragment as Hc,jsx as B,jsxs as J}from"react/jsx-runtime";var si=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Bc={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},$c="The block was edited in Kizen since your last push. Overwriting discards those edits.",Gt=e=>e.args.includes("--create");function ai(e,t){let r=e.filter(i=>i.value===t),o=e.filter(Gt),n=e.filter(i=>i.value!==t&&!Gt(i));return r.length>0?[...r,...n,...o]:[...o,...n]}function jc(e,t){if(Gt(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 Fc(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 Oc(e,t,r){let o={...e,dashboard:t};return delete o.dashlet,delete o.create,Gt(r)?{...o,create:!0}:{...o,dashlet:r.value}}function zc(e,t,r,o){let n=d=>{t.setExitCode(1),r({type:"error",view:d})},i=d=>{d().catch(c=>{n(He(c))})},s=async(d,c)=>{r({type:"applying",plan:c});let y=await rn(d,c,t);if(!y.ok){n(y);return}r({type:"done",plan:c,applied:y.value})},l=async(d,c,y)=>{r({type:"loading",label:"Preparing the push\u2026"});let v=await tn(d,c,y,t);if(!v.ok){if(v.code==="drift_detected"){r({type:"confirm",kind:"drift",message:v.message,target:c,options:y,context:d});return}n(v);return}if(y.dryRun){r({type:"done",plan:v.value,applied:null});return}if(y.yes){let P=sn(y,d.credentials.environment);if(P.ok&&P.value.kind==="apply"){await s(d,v.value);return}}r({type:"confirm",kind:"push",plan:v.value,options:y,context:d})},a=async(d,c,y)=>{r({type:"loading",label:"Resolving the target\u2026"});let v=await en(d,c);if(v.ok){await l(d,v.value,c);return}let P=c.dashboard??d.entry?.dashboardId;if((v.code==="needs_choice"&&v.choice==="target"||v.code==="remembered_target_missing")&&v.choices&&v.choices.length>0&&P!==void 0){r({type:"target-select",dashboardId:P,title:"Choose a block to update, or create a new one",message:v.message,choices:ai(v.choices,null),matchedId:null,back:y,options:c,context:d});return}n(v)},p=async(d,c,y)=>{let v=et({credentials:c,block:y}),P=await t.readPushMap(t.cwd);d.forget&&await on({credentials:c,block:y,pushMap:P},t)&&(P=ct(P,v),o(_=>({..._,notices:[..._.notices,`Forgot the remembered target for ${y.block.api_name}.`]})));let C={client:t.createClient(c),credentials:c,block:y,pushMap:P,entry:lt(P,v)};if(d.dashboard!==void 0||C.entry){await a(C,d,null);return}r({type:"surface-select",options:d,context:C})},h=async(d,c,y)=>{r({type:"packaging"});let v=await Xr(y,t);if(!v.ok){if(v.choice==="block"&&v.choices){r({type:"block-select",options:d,credentials:c,choices:v.choices});return}n(v);return}o(P=>({...P,warnings:v.value.warnings})),await p(d,c,v.value)},w=async d=>{r({type:"loading",label:"Loading credentials\u2026"});let c=await Vt(d,t);if(!c.ok){if(c.choice==="profile"&&c.choices){r({type:"profile-select",options:d,choices:c.choices});return}n(c);return}let{credentials:y}=c.value;o(v=>({...v,credentials:y})),await h(d,y,e)},x=async({options:d,context:c},y,v,P)=>{let C=Bc[y];r({type:"loading",label:`Loading ${C}s\u2026`});let S=(await c.client.listDashboards(Do(y),v?.id)).map(u=>pt(u,y)),{environment:g,businessId:f}=c.credentials;if(S.length===0){n({message:`No ${C}s found${v?` on ${v.objectName}`:""} for business ${f} (${g}).`});return}r({type:"dashboard-select",surface:y,objectId:v?.id??null,title:v?`Choose a chart group on ${v.objectName}`:`Choose a ${C}`,rows:S,back:P,options:d,context:c})};return{start:d=>{i(()=>w(d))},pickProfile:(d,c)=>{i(()=>w({...d.options,profile:c.value}))},pickBlock:(d,c)=>{i(()=>h(d.options,d.credentials,c.value))},pickSurface:(d,c)=>{i(async()=>{if(c!=="chart_group"){await x(d,c,null,d);return}r({type:"loading",label:"Loading custom objects\u2026"});let y=await Zr(d.context.client);if(y.length===0){n({message:"No custom objects found, so there are no chart groups to push to."});return}r({type:"object-select",objects:y,back:d,options:d.options,context:d.context})})},pickObject:(d,c)=>{i(()=>x(d,"chart_group",c,d))},pickDashboard:(d,c)=>{i(async()=>{let{context:y}=d,v={...d.options,dashboard:c.id};if(v.dashlet!==void 0||v.create){await a(y,v,d);return}r({type:"loading",label:`Loading "${c.name}"\u2026`});let P=await y.client.getDashboard(c.id),C=Lt({dashboardId:P.id,dashlets:P.dashlets,pluginApiName:y.block.pluginApiName,blockApiName:y.block.block.api_name,entry:y.entry}),_=C.kind==="map"||C.kind==="name"?C.dashlet.id:null;r({type:"target-select",dashboardId:P.id,title:`Choose what to push to on "${P.name}"`,message:null,choices:ai(Wt(P,y.block),_),matchedId:_,back:d,options:v,context:y})})},pickTarget:(d,c)=>{i(()=>a(d.context,Oc(d.options,d.dashboardId,c),d))},acceptDrift:d=>{i(()=>l(d.context,d.target,{...d.options,force:!0}))},acceptPush:d=>{i(()=>s(d.context,d.plan))},cancel:()=>{n({message:"Cancelled."})}}}var li=({prompt:e,strict:t,onAccept:r,onCancel:o})=>(ci((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})),tt=({lines:e,color:t})=>B(oe,{flexDirection:"column",children:e.map((r,o)=>B(q,{...t&&{color:t},children:r},`${String(o)}-${r}`))}),di=({plan:e})=>J(oe,{flexDirection:"column",children:[B(tt,{lines:ft(e.summary)}),J(q,{children:["URL: ",e.url]})]}),dn=({label:e})=>J(oe,{gap:1,children:[B(ye,{}),B(q,{dimColor:!0,children:e})]}),Mc=({view:e})=>J(oe,{flexDirection:"column",gap:1,children:[J(oe,{gap:1,children:[B(q,{color:"red",children:"\u2717"}),B(q,{color:"red",children:e.issues&&e.issues.length>0?me(e.issues):e.message})]}),e.hint!==void 0&&J(q,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&J(oe,{flexDirection:"column",children:[B(q,{children:"Choices:"}),B(tt,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Lc=({plan:e,applied:t})=>{let r=nn(e.dashboard.id);return t===null?J(oe,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:"Dry run: nothing was written."}),B(di,{plan:e}),e.warnings.length>0&&B(tt,{lines:e.warnings.map(o=>`Warning: ${o}`),color:"yellow"}),J(oe,{flexDirection:"column",children:[J(q,{bold:!0,children:[e.method," ",e.path]}),B(q,{children:JSON.stringify(e.body,null,2)})]})]}):J(oe,{flexDirection:"column",gap:1,children:[J(oe,{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(oe,{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(tt,{lines:t.warnings.map(o=>`Warning: ${o}`),color:"yellow"})]})},ui=({apiName:e,options:t,deps:r})=>{let o=Rc(),[n,i]=qt({type:"loading",label:"Loading credentials\u2026"}),[s,l]=qt({credentials:null,warnings:[],notices:[]}),[a]=qt(()=>zc(e,r,i,l)),[p]=qt(t);ii(()=>{a.start(p)},[a,p]),ii(()=>{(n.type==="done"||n.type==="error")&&o.exit()},[n,o]),ci((w,x)=>{x.ctrl&&w==="c"&&n.type!=="done"&&n.type!=="error"&&(r.setExitCode(130),o.exit())});let h=w=>J(oe,{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:me(s.warnings)}),s.notices.length>0&&B(tt,{lines:s.notices}),w]});switch(n.type){case"loading":return h(B(dn,{label:n.label}));case"packaging":return h(B(dn,{label:"Packaging blocks\u2026"}));case"applying":return h(B(dn,{label:`Pushing ${n.plan.summary.blockName} to "${n.plan.dashboard.name}"\u2026`}));case"profile-select":return h(B(We,{title:"Credential profile",items:n.choices.map(w=>({key:w.value,label:w.label})),onSelect:(w,x)=>{let d=n.choices[x];d&&a.pickProfile(n,d)},onCancel:a.cancel},"profile"));case"block-select":return h(B(We,{title:"Block to push",items:n.choices.map(w=>({key:w.value,label:w.label})),onSelect:(w,x)=>{let d=n.choices[x];d&&a.pickBlock(n,d)},onCancel:a.cancel},"block"));case"surface-select":return h(B(We,{title:"Where should the block go?",items:si,onSelect:(w,x)=>{let d=si[x];d&&a.pickSurface(n,d.key)},onCancel:a.cancel},"surface"));case"object-select":return h(B(We,{title:"Custom object",items:n.objects.map(w=>({key:w.id,label:w.objectName})),onSelect:(w,x)=>{let d=n.objects[x];d&&a.pickObject(n,d)},onCancel:()=>{i(n.back)},hint:"\u2191/\u2193 to move, Enter to select, Esc to go back"},"object"));case"dashboard-select":return h(B(We,{title:n.title,items:n.rows.map(Fc),onSelect:(w,x)=>{let d=n.rows[x];d&&a.pickDashboard(n,d)},onCancel:()=>{i(n.back)},hint:"\u2191/\u2193 to move, Enter to select, Esc to go back"},`dashboards-${n.surface}-${n.objectId??""}`));case"target-select":{let{back:w}=n;return h(J(Hc,{children:[n.message!==null&&B(q,{color:"yellow",children:n.message}),B(We,{title:n.title,items:n.choices.map(x=>jc(x,n.matchedId)),onSelect:(x,d)=>{let c=n.choices[d];c&&a.pickTarget(n,c)},onCancel:w?()=>{i(w)}:a.cancel,...w&&{hint:"\u2191/\u2193 to move, Enter to select, Esc to go back"}},`targets-${n.dashboardId}`)]}))}case"confirm":return n.kind==="drift"?h(J(oe,{flexDirection:"column",gap:1,children:[B(q,{color:"yellow",children:$c}),B(q,{dimColor:!0,children:n.message}),B(li,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{a.acceptDrift(n)},onCancel:a.cancel},"drift")]})):h(J(oe,{flexDirection:"column",gap:1,children:[B(di,{plan:n.plan}),n.plan.warnings.length>0&&B(tt,{lines:n.plan.warnings.map(w=>`Warning: ${w}`),color:"yellow"}),n.plan.summary.isProduction&&B(q,{color:"red",bold:!0,children:"PRODUCTION"}),B(li,{prompt:n.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:n.plan.summary.isProduction,onAccept:()=>{a.acceptPush(n)},onCancel:a.cancel},"push")]}));case"done":return h(B(Lc,{plan:n.plan,applied:n.applied}));case"error":return h(B(Mc,{view:n.view}))}};var Kc=e=>e instanceof Wc?me(e.issues):`Error: ${e instanceof Error?e.message:String(e)}`;function pi(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{block:n,warnings:i}=await Xn(process.cwd(),r);i.length>0&&console.error(me(i));let s=JSON.stringify(n,null,2);console.log(s),o.copy&&console.error(await Rt(s)?`Copied block "${n.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(n){console.error(Kc(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 Qo(r,o,Ut(process.cwd()));return}let{waitUntilExit:n}=Vc(Uc(ui,{...r!==void 0&&{apiName:r},options:o,deps:Ut(process.cwd())}),{exitOnCtrlC:!1});await n()}catch(n){console.error(`Error: ${n instanceof Error?n.message:String(n)}`),process.exitCode=1}}),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 ei(r,Ut(process.cwd()))}catch(o){console.error(`Error: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1}})}import{createElement as Xc}from"react";import{render as Zc}from"ink";import{useEffect as mi,useState as gt}from"react";import{Box as yt,Text as rt,useApp as qc}from"ink";import{PluginValidationError as Gc}from"@kizenapps/packager";function mt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as un,Text as Yt}from"ink";import{jsx as fi,jsxs as ht}from"react/jsx-runtime";var Jc=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},Xt=({issues:e})=>{let t=e.filter(r=>r.severity==="error").length;return ht(un,{flexDirection:"column",marginTop:1,children:[ht(Yt,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Jc(e)].map(([r,o])=>ht(un,{flexDirection:"column",marginTop:1,children:[fi(Yt,{bold:!0,children:r}),o.map((n,i)=>fi(un,{paddingLeft:2,children:ht(Yt,{color:n.severity==="error"?"red":"yellow",children:[n.severity==="error"?"\u2717":"\u26A0"," ",n.message," ",ht(Yt,{dimColor:!0,children:["(",n.rule,")"]})]})},`${n.rule}-${String(i)}`))]},r))]})};import{Fragment as Yc,jsx as De,jsxs as Ke}from"react/jsx-runtime";var hi=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],Zt={"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"},gi=({outputDir:e,pluginDir:t})=>{let r=qc(),[o,n]=gt("creating-dir"),[i,s]=gt(!1),[l,a]=gt(null),[p,h]=gt(null),[w,x]=gt(null);mi(()=>{jt(t,e,n).then(({bundleSize:y})=>{x(y),n("done")}).catch(y=>{y instanceof Gc?a(y.issues):h(y instanceof Error?y.message:String(y)),s(!0),process.exitCode=1})},[e,t]),mi(()=>{(o==="done"||i)&&r.exit()},[o,i,r]);let d=hi.indexOf(o),c=o==="done";return Ke(yt,{flexDirection:"column",paddingY:1,paddingX:2,children:[De(K,{marginBottom:1}),Ke(yt,{flexDirection:"column",gap:0,children:[hi.map((y,v)=>{let P=o===y,C=c||d>v;return De(yt,{gap:1,children:i&&v===d?Ke(rt,{color:"red",children:["\u2717 ",Zt[y]]}):C?Ke(rt,{color:"green",children:["\u2713 ",Zt[y]]}):P?Ke(Yc,{children:[De(ye,{}),De(rt,{children:Zt[y]})]}):Ke(rt,{dimColor:!0,children:[" ",Zt[y]]})},y)}),c&&w!==null&&De(yt,{marginTop:1,gap:1,children:Ke(rt,{color:"green",children:["\u2713 bundle \u2014 ",mt(w)]})}),l!==null&&De(Xt,{issues:l}),p!==null&&De(yt,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:De(rt,{color:"red",children:p})})]})]})};function yi(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),r=`${t}/.kizenapp`;Ne(t);let{waitUntilExit:o}=Zc(Xc(gi,{outputDir:r,pluginDir:t}));await o()})}import{createElement as Wd}from"react";import{render as Kd}from"ink";import{useCallback as sr,useState as nt}from"react";import{Box as V,Text as N,useApp as Od,useInput as zd}from"ink";import{join as ar}from"path";import{access as Bd,mkdir as er,writeFile as yn}from"fs/promises";import{dirname as $d,join as ke}from"path";var bi=`{
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=`{
757
724
  "name": "Hello Frame",
758
725
  "api_name": "hello_frame",
759
726
  "title": "Hello Frame",
@@ -762,13 +729,13 @@ export const sumBy = (records, name, valueOf) =>
762
729
  "height": 320,
763
730
  "width": 280
764
731
  }
765
- `;var wi=`this.outputUI(\`
732
+ `;var zi=`this.outputUI(\`
766
733
  <div class="hello-frame">
767
734
  <h2 class="hello-frame__title">Hello from a floating frame</h2>
768
735
  <p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
769
736
  </div>
770
737
  \`);
771
- `;var xi=`.hello-frame {
738
+ `;var Mi=`.hello-frame {
772
739
  padding: 16px;
773
740
  font-family: system-ui, sans-serif;
774
741
  }
@@ -782,18 +749,18 @@ export const sumBy = (records, name, valueOf) =>
782
749
  margin: 0;
783
750
  color: #555;
784
751
  }
785
- `;var vi=`{
752
+ `;var Ui=`{
786
753
  "name": "Hello Block",
787
754
  "api_name": "hello_block",
788
755
  "types": ["dashboards"]
789
756
  }
790
- `;var ki=`this.outputUI(\`
757
+ `;var Hi=`this.outputUI(\`
791
758
  <div class="hello-block">
792
759
  <h2 class="hello-block__title">Hello from a block</h2>
793
760
  <p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
794
761
  </div>
795
762
  \`);
796
- `;var Ci=`.hello-block {
763
+ `;var Vi=`.hello-block {
797
764
  padding: 16px;
798
765
  font-family: system-ui, sans-serif;
799
766
  background: #f8fafc;
@@ -809,25 +776,25 @@ export const sumBy = (records, name, valueOf) =>
809
776
  margin: 0;
810
777
  color: #555;
811
778
  }
812
- `;var Si=`{
779
+ `;var Wi=`{
813
780
  "icon": "phone",
814
781
  "color": "#0ea5e9",
815
782
  "tooltip": "Hello adornment",
816
783
  "field_type": "phonenumber"
817
784
  }
818
- `;var _i=`this.showToast('Hello from a data adornment.', { variant: 'success' });
819
- `;var Pi=`{
785
+ `;var Ki=`this.showToast('Hello from a data adornment.', { variant: 'success' });
786
+ `;var Ji=`{
820
787
  "name": "Hello Page",
821
788
  "api_name": "hello_page"
822
789
  }
823
- `;var Ei=`this.outputUI(\`
790
+ `;var qi=`this.outputUI(\`
824
791
  <div class="hello-page">
825
792
  <p class="hello-page__loading">Loading\u2026</p>
826
793
  </div>
827
794
  \`);
828
795
 
829
796
  this.runEventScript('greet');
830
- `;var Ti=`.hello-page {
797
+ `;var Gi=`.hello-page {
831
798
  padding: 24px;
832
799
  font-family: system-ui, sans-serif;
833
800
  }
@@ -865,7 +832,7 @@ this.runEventScript('greet');
865
832
  .hello-page__button:hover {
866
833
  background: #cbd5e1;
867
834
  }
868
- `;var Ii=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
835
+ `;var Yi=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
869
836
 
870
837
  const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
871
838
 
@@ -888,33 +855,33 @@ this.outputUI(\`
888
855
  </div>
889
856
  </div>
890
857
  \`);
891
- `;var Ai=`{
858
+ `;var Xi=`{
892
859
  "api_name": "hello_toolbar_item",
893
860
  "label": "Hello Toolbar Item",
894
861
  "icon": "star",
895
862
  "color": "#0ea5e9"
896
863
  }
897
- `;var Ni=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
898
- `;var Di=`{
864
+ `;var Zi=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
865
+ `;var Qi=`{
899
866
  "api_name": "hello_object_settings_item",
900
867
  "label": "Hello Object Settings"
901
868
  }
902
- `;var Ri=`this.showToast('Hello from an object settings item.', { variant: 'success' });
903
- `;var Bi=`{
869
+ `;var es=`this.showToast('Hello from an object settings item.', { variant: 'success' });
870
+ `;var ts=`{
904
871
  "name": "Hello Action",
905
872
  "api_name": "hello_action",
906
873
  "hint_object_name": "client_client"
907
874
  }
908
- `;var $i=`this.showToast('Hello from a JS action.', { variant: 'success' });
909
- `;var ne=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],pn={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},yd={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":bi,"script.js":wi,"styles.css":xi}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":vi,"script.js":ki,"styles.css":Ci}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Si,"script.js":_i}},page:{directory:"pages",component:"helloPage",files:{"config.json":Pi,"script.js":Ei,"styles.css":Ti,"eventScripts/greet.js":Ii}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":Ai,"script.js":Ni}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Di,"script.js":Ri}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":Bi,"script.js":$i}}};function bd(e,t="src"){let{directory:r,component:o,files:n}=yd[e];return Object.entries(n).map(([i,s])=>({path:`${t}/${r}/${o}/${i}`,content:s}))}function ji(e,t="src"){return[...new Set(e)].flatMap(r=>bd(r,t))}import{deflateSync as wd}from"zlib";var mn=512,xd=150,vd=26,hn=46,Fi=.6,kd=hn*.55,Cd=.55,Sd=.47;function _d(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 Pd(e){let t=_d(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function Ed(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,[l,a,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((l+s)*255),Math.round((a+s)*255),Math.round((p+s)*255)]}function bt(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 Qt(e,t,r,o,n){return Math.hypot(e-r,t-o)-n}function Td(e,t){let r=xd,o=hn,n=o*Fi,i=kd,s=bt(e,t,r,r,vd),l=Math.min(Qt(e,t,0,-r-n,o),bt(e,t+r+n/2,i,n/2+1,0)),a=Math.min(Qt(e,t,r+n,0,o),bt(e-r-n/2,t,n/2+1,i,0));s=Math.min(s,l,a);let p=Math.min(Qt(e,t,0,r-n,o),bt(e,t-r+n/2,i,n/2+1,0)),h=Math.min(Qt(e,t,-r+n,0,o),bt(e+r-n/2,t,n/2+1,i,0));return Math.max(s,-p,-h)}function Id(e){let t=mn,r=new Uint8Array(t*t*4),[o,n,i]=Ed(e.hue,Cd,Sd),s=hn*(1+Fi),l=(t-1)/2,a=s/2;for(let p=0;p<t;p+=1)for(let h=0;h<t;h+=1){let w=h-l,x=p-l;for(let v=0;v<e.quarterTurns;v+=1)[w,x]=[-x,w];let d=Td(w+a,x-a),c=Math.min(1,Math.max(0,.5-d));if(c<=0)continue;let y=(p*t+h)*4;r[y]=o,r[y+1]=n,r[y+2]=i,r[y+3]=Math.round(c*255)}return r}var Ad=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 Nd(e){let t=4294967295;for(let r of e)t=(Ad[(t^r)&255]??0)^t>>>8;return(t^4294967295)>>>0}function fn(e,t){let r=Buffer.from(e,"latin1"),o=Buffer.alloc(4);o.writeUInt32BE(t.length);let n=Buffer.alloc(4);return n.writeUInt32BE(Nd(Buffer.concat([r,t]))),Buffer.concat([o,r,t,n])}var Dd=Buffer.from([137,80,78,71,13,10,26,10]);function Rd(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([Dd,fn("IHDR",o),fn("IDAT",wd(i,{level:9})),fn("IEND",new Uint8Array(0))])}function Oi(e){return Rd(mn,mn,Id(Pd(e)))}var jd="src/thumbnail.png",Fd=["go","fmo"];async function tr(e){try{return await Bd(e),!0}catch{return!1}}async function rr(e){return await tr(ke(e,"kizen.json"))?"has-manifest":await tr(ke(e,".kizenapp"))?"has-kizenapp":"ok"}async function zi(e,t){let r=ke(e,t);if(!await tr(r))return r;for(let o=1;o<1e3;o++){let n=ke(e,`${t}-${String(o)}`);if(!await tr(n))return n}throw new Error(`Could not find an available directory name for "${t}"`)}function bn(e){let t=e.developerBusinessId.trim(),r=t!==""&&!Fd.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 gn(e,t){let r=t.map(n=>({fullPath:ke(e,...n.path.split("/")),content:n.content})),o=new Set(r.map(n=>$d(n.fullPath)));await Promise.all([...o].map(n=>er(n,{recursive:!0}))),await Promise.all(r.map(n=>yn(n.fullPath,n.content,"utf-8")))}async function nr(e){await er(e.targetDir,{recursive:!0});let t=bn(e);await yn(ke(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
910
- `,"utf-8"),await er(ke(e.targetDir,"src"),{recursive:!0}),await er(ke(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([gn(e.targetDir,ji(e.artifacts??[])),gn(e.targetDir,Lo()),gn(e.targetDir,Le()),yn(ke(e.targetDir,...jd.split("/")),Oi(e.apiName))]),Ne(e.targetDir)}var Re=["name","apiName","externalLink","description","developerBusinessId"],or={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},wn=["name","apiName","description"],xn=/^[a-z_][a-z0-9_]+$/,vn="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function ir(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function Mi(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function Li(e,t){let r=t.trim();if(wn.includes(e)&&!r)return`${or[e]} is required`;if(e==="apiName"&&!xn.test(r))return`${or[e]} ${vn}`}function Hi(e,t){return e==="description"?t:t.trim()}function Ui(e,t){let r=new Set(e);return r.has(t)?r.delete(t):r.add(t),ne.filter(o=>r.has(o))}import{jsx as A,jsxs as $}from"react/jsx-runtime";var Je=({text:e})=>A(N,{dimColor:!0,children:e}),Vi=({parentDir:e,defaultBusinessId:t,defaultEnvironment:r})=>{let o=Od(),[n,i]=nt({type:"target-select",cursor:0}),[s,l]=nt("in-place"),[a,p]=nt(()=>Mi(t)),[h,w]=nt(()=>[...ne]),[x,d]=nt(""),[c,y]=nt(e),v=sr((S,g)=>{l(S),d(g.name),i({type:"field-entry",field:0,values:g})},[]),P=sr(async S=>{let g=await rr(S);if(g!=="ok"){i({type:"precheck-error",targetDir:S,reason:g});return}y(S),v("in-place",a)},[a,v]),C=sr(async(S,g)=>{try{let f=await zi(e,S.apiName);y(f),i({type:"confirm",values:S,artifacts:g})}catch(f){i({type:"error",message:f instanceof Error?f.message:String(f)})}},[e]),_=sr(async(S,g,f)=>{try{await nr({targetDir:g,name:S.name,apiName:S.apiName,externalLink:S.externalLink,description:S.description,developerBusinessId:S.developerBusinessId,developerEnvironment:r,artifacts:f}),i({type:"done",targetDir:g})}catch(u){i({type:"error",message:u instanceof Error?u.message:String(u)})}},[r]);if(zd((S,g)=>{if(g.ctrl&&S==="c"){o.exit();return}if(n.type==="target-select"){g.upArrow?i({type:"target-select",cursor:0}):g.downArrow?i({type:"target-select",cursor:1}):g.return?n.cursor===0?P(e):v("sub-dir",a):g.escape&&o.exit();return}if(n.type==="precheck-error"){(g.return||g.escape)&&o.exit();return}if(n.type==="field-entry"){let{field:f,values:u}=n,m=Re[f];if(!m)return;if(g.escape){o.exit();return}if(g.backspace||g.delete){d(b=>b.slice(0,-1));return}if(g.upArrow&&f>0){let b={...u,[m]:x},k=f-1,I=Re[k];i({type:"field-entry",field:k,values:b}),p(b),d(I?b[I]:"");return}if(g.return||g.tab||g.downArrow){let b=Li(m,x);if(b!==void 0){i({type:"field-entry",field:f,values:u,fieldError:b});return}let k=Hi(m,x),I={...u,[m]:k};p(I);let E=f+1;if(E>=Re.length)d(""),i({type:"artifact-select",values:I,cursor:0,selected:h});else{let R=Re[E],M=R?I[R]:"",W=R==="apiName"&&!M?ir(I.name):M;i({type:"field-entry",field:E,values:I}),d(W)}return}S&&!g.ctrl&&!g.meta&&d(b=>b+S);return}if(n.type==="artifact-select"){let{cursor:f,selected:u,values:m}=n;if(g.escape){let b=Re.length-1,k=Re[b];i({type:"field-entry",field:b,values:m}),d(k?m[k]:"");return}if(g.upArrow){i({...n,cursor:Math.max(0,f-1)});return}if(g.downArrow){i({...n,cursor:Math.min(ne.length-1,f+1)});return}if(S===" "){let b=ne[f];if(b){let k=Ui(u,b);w(k),i({...n,selected:k})}return}if(S==="a"){w([...ne]),i({...n,selected:[...ne]});return}if(S==="n"){w([]),i({...n,selected:[]});return}g.return&&(s==="sub-dir"?(i({type:"resolving-target"}),C(m,u)):i({type:"confirm",values:m,artifacts:u}));return}if(n.type==="confirm"){if(g.escape){i({type:"artifact-select",values:n.values,cursor:0,selected:n.artifacts});return}g.return&&(i({type:"writing"}),_(n.values,c,n.artifacts));return}(n.type==="done"||n.type==="error")&&(g.return||g.escape)&&o.exit()}),n.type==="target-select"){let S=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"Where should the new plugin live?"}),S.map((g,f)=>{let u=n.cursor===f;return $(V,{gap:2,children:[A(N,{...u&&{color:"cyan"},children:u?"\u276F":" "}),A(N,{bold:u,...u&&{color:"cyan"},children:g.label}),A(N,{dimColor:!0,children:g.desc})]},g.label)})]}),A(Je,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="precheck-error"){let{targetDir:S,reason:g}=n;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),A(N,{color:"red",bold:!0,children:"Cannot create plugin"}),$(V,{flexDirection:"column",gap:0,children:[$(N,{children:[S," already contains ",A(N,{bold:!0,children:g==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),A(N,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),A(Je,{text:"Enter or Esc to exit"})]})}if(n.type==="field-entry"){let{field:S,fieldError:g}=n,f=s==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${c}`;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"Plugin details"}),A(N,{dimColor:!0,children:f})]}),g!==void 0&&$(N,{color:"red",children:["Error: ",g]}),A(V,{flexDirection:"column",gap:0,children:Re.map((u,m)=>{let b=S===m,k=b?x:a[u],I=wn.includes(u),E=`${or[u]}${I?"":" (optional)"}`;return $(V,{gap:2,children:[A(V,{width:24,children:A(N,{bold:b,...b&&{color:"cyan"},children:E})}),A(N,{...b&&{color:"cyan"},children:">"}),A(N,{children:k}),b&&A(N,{color:"cyan",children:"\u2588"})]},u)})}),A(Je,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(n.type==="artifact-select"){let{cursor:S,selected:g}=n;return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"Which artifacts should we scaffold?"}),A(N,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),A(V,{flexDirection:"column",gap:0,children:ne.map((f,u)=>{let m=S===u,b=g.includes(f);return $(V,{gap:1,children:[A(N,{...m&&{color:"cyan"},children:m?"\u276F":" "}),A(N,{...b&&{color:"green"},children:b?"\u25C9":"\u25EF"}),A(N,{bold:m,...m&&{color:"cyan"},children:pn[f]})]},f)})}),A(Je,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(n.type==="confirm"){let S=bn({targetDir:c,name:n.values.name,apiName:n.values.apiName,externalLink:n.values.externalLink,description:n.values.description,developerBusinessId:n.values.developerBusinessId,developerEnvironment:r});return $(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"Ready to create"}),$(N,{dimColor:!0,children:["Target: ",c]})]}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"kizen.json preview"}),A(N,{children:JSON.stringify(S,null,2)})]}),$(V,{flexDirection:"column",gap:0,children:[A(N,{bold:!0,children:"Artifacts"}),n.artifacts.length===0?$(N,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):n.artifacts.map(g=>$(N,{dimColor:!0,children:[" ",pn[g]]},g))]}),$(V,{flexDirection:"column",gap:0,children:[A(N,{dimColor:!0,children:"Also creates:"}),$(N,{dimColor:!0,children:[" ",ar(c,"src/")]}),$(N,{dimColor:!0,children:[" ",ar(c,"src/thumbnail.png")," (generated placeholder)"]}),$(N,{dimColor:!0,children:[" ",ar(c,"releaseNotes/")]}),$(N,{dimColor:!0,children:[" ",ar(c,".gitignore")," (adds .kizenapp/)"]})]}),A(Je,{text:"Enter to create \xB7 Esc to go back"})]})}return n.type==="resolving-target"?A(V,{paddingY:1,paddingX:2,children:A(N,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):n.type==="writing"?A(V,{paddingY:1,paddingX:2,children:A(N,{dimColor:!0,children:"Creating plugin\u2026"})}):n.type==="done"?$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),$(N,{color:"green",bold:!0,children:["Plugin created at ",n.targetDir]}),$(V,{flexDirection:"column",gap:0,children:[A(N,{dimColor:!0,children:"Next steps:"}),$(N,{children:[" ","cd ",n.targetDir]}),$(N,{children:[" ","npx --yes @kizenapps/cli dev"]}),$(N,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),A(Je,{text:"Enter or Esc to exit"})]}):$(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[A(K,{}),A(N,{color:"red",bold:!0,children:"Failed to create plugin"}),A(N,{children:n.message}),A(Je,{text:"Enter or Esc to exit"})]})};var Md="A hello-world Kizen plugin.";function Ld(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...ne];if(e.trim()==="none")return[];let t=e.split(",").map(o=>o.trim()).filter(o=>o!==""),r=t.filter(o=>!ne.includes(o));if(r.length>0)throw new Error(`Unknown artifact type(s): ${r.join(", ")}. Valid types: ${ne.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function Hd(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()??"")||ir(o);if(!xn.test(n))throw new Error(`api_name "${n}" is invalid: ${vn}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,l=Vd(e,t);return{targetDir:r,name:o,apiName:n,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?Md:i,developerBusinessId:s,developerEnvironment:l,artifacts:Ld(e.artifacts)}}function Ud(e){return X.includes(e)}function Vd(e,t){let r=e.environment?.trim();if(r!==void 0&&r!==""){if(!Ud(r))throw new Error(`Unknown environment "${r}". Valid environments: ${X.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 Wi(e,t,r,o){let n;try{n=Hd(e,t,r)}catch(l){o.writeStderr(`Error: ${l instanceof Error?l.message:String(l)}
911
- `),o.setExitCode(1);return}let i=await o.precheckTargetDir(r);if(i!=="ok"){let l=i==="has-manifest"?"kizen.json":".kizenapp/";o.writeStderr(`Error: ${r} already contains ${l}. Refusing to overwrite an existing plugin.
912
- `),o.setExitCode(1);return}try{await o.createPlugin(n)}catch(l){o.writeStderr(`Error: ${l instanceof Error?l.message:String(l)}
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)}
913
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}
914
881
  `),o.writeStdout(`Artifacts: ${s}
915
882
  `),o.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
916
883
  `),n.developerBusinessId.trim()===""&&o.writeStderr(`Warning: no developer_business_id configured, so this plugin cannot be preview-published yet.
917
- `)}function Ki(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: ${X.join(", ")} (defaults to saved credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${ne.join(", ")}`).action(async t=>{let r=process.cwd(),o=await te(),n=o?.businessId??"",i=o?.environment??"go",s=Object.values(t).some(p=>p!==void 0);if(!process.stdin.isTTY||!process.stdout.isTTY||s){await Wi(t,{businessId:n,environment:i},r,{precheckTargetDir:rr,createPlugin:nr,writeStdout:p=>{process.stdout.write(p)},writeStderr:p=>{process.stderr.write(p)},setExitCode:p=>{process.exitCode=p}});return}let{waitUntilExit:a}=Kd(Wd(Vi,{parentDir:r,defaultBusinessId:n,defaultEnvironment:i}),{exitOnCtrlC:!1});await a()})}import{createElement as _s}from"react";import{render as Ps}from"ink";import{useCallback as ot,useEffect as mr,useRef as Ce,useState as ie}from"react";import{Box as Q,Text as j,useInput as Mu}from"ink";import{PluginValidationError as Lu}from"@kizenapps/packager";import{watch as Hu}from"fs";import{createServer as Uu}from"http";import{join as ks}from"path";import{WebSocketServer as Vu}from"ws";import{createReadStream as as,realpathSync as cu}from"fs";import{access as du,readdir as uu,readFile as pu,realpath as fu,stat as ls}from"fs/promises";import{dirname as mu,extname as cs,join as St,resolve as hu,sep as Nn}from"path";import{fileURLToPath as gu}from"url";var Jd=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function lr(e){let t={};for(let[r,o]of Object.entries(e)){let n=r.toLowerCase();Jd.has(n)||n.startsWith("access-control-")||(t[r]=o)}return t}var kn=10*1024*1024,qd=6e4,Gd=200,wt=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 Cn(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 wt(n,t);o.push(i)}return Buffer.concat(o)}async function Ji(e){let t=lr(Object.fromEntries(e.headers)),r=await Cn(e,kn);return{status:e.status,headers:t,body:r}}function qi(e={}){let{onChange:t,enabled:r=!0}=e;if(!r)return{async get(s,l){return{response:await Ji(await l()),fromCache:!1}},clear(){}};let o=new Map,n=()=>{t?.(o.size)},i=s=>{o.delete(s)&&n()};return{get(s,l){let a=o.get(s);if(a!==void 0){if(Date.now()-a.insertedAt<qd)return a.promise.then(h=>({response:h,fromCache:!0}));i(s)}if(o.size>=Gd){let h=o.keys().next().value;h!==void 0&&i(h)}let p=l().then(Ji).catch(h=>{throw i(s),h});return o.set(s,{insertedAt:Date.now(),promise:p}),n(),p.then(h=>((h.status<200||h.status>=300)&&i(s),{response:h,fromCache:!1}))},clear(){o.clear(),n()}}}var Sn={".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 _n={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function xt(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||_n.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!==""?_n.localDev:_n.dev}import{spawn as In}from"child_process";import{writeFile as Qi,rm as Tn,mkdtemp as Qd,access as eu}from"fs/promises";import{join as kt}from"path";import{tmpdir as tu}from"os";var Gi=`awslambdaric
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
918
885
  bcrypt
919
886
  boto3
920
887
  fpdf2
@@ -932,8 +899,8 @@ pytz
932
899
  requests
933
900
  sqlalchemy>=2.0,<2.1
934
901
  tzdata
935
- `;function Yi(e){return e.split(`
936
- `).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function Xi(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 Xd(e){return e==null||e.trim()===""?null:e}function Zd(e){return e==null?null:typeof e=="string"?Xd(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function Zi(e){return e?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,Zd(r)])):{}}var ru=`
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=`
937
904
  import sys, json, os, traceback
938
905
 
939
906
  # --- Inputs proxy (attribute access) ---
@@ -1093,23 +1060,23 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
1093
1060
  sys.stdout.write(json.dumps(result, ensure_ascii=False))
1094
1061
  sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
1095
1062
  sys.stdout.flush()
1096
- `.trim(),nu=3e4,cr=kt(process.cwd(),".kizenapp","venv"),ts=["python-3-12","python-3-13"];function ou(e){return ts.includes(e)}var rs=Yi(Gi);if(rs.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var vt=null,Ct=[3,10];function ns([e,t]){return e>Ct[0]||e===Ct[0]&&t>=Ct[1]}function Pn(e){return`${String(e[0])}.${String(e[1])}`}function os(e){return new Promise(t=>{let r=In(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 iu(e){let t=Xi(e),r=t==="python3"?["python3"]:[t,"python3"],o=[];for(let n of r){let i=await os(n);if(!i){o.push(`${n}: not found`);continue}if(ns(i))return n;o.push(`${n}: ${Pn(i)} (too old)`)}throw new Error(`No Python >= ${Pn(Ct)} found for runtime "${e}". The local runner needs Python ${Pn(Ct)}+ 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 es(e,t,r){return new Promise((o,n)=>{let i=In(e,t,{stdio:["ignore","pipe","pipe"]}),s=(a,p)=>{let h=[],w="";return a.on("data",x=>{w+=x.toString("utf-8");let d=w.indexOf(`
1097
- `);for(;d>=0;){let c=w.slice(0,d).replace(/\r$/,"");w=w.slice(d+1),h.push(c),r?.(c,p),d=w.indexOf(`
1098
- `)}}),a.on("end",()=>{if(w.length>0){let x=w.replace(/\r$/,"");h.push(x),r?.(x,p)}}),h},l=s(i.stderr,"stderr");s(i.stdout,"stdout"),i.on("error",n),i.on("close",a=>{if(a===0)o();else{let p=l.slice(-10).join(`
1099
- `).trim(),h=p.length>0?`: ${p}`:"";n(new Error(`${e} exited with code ${String(a)}${h}`))}})})}var En=null;function su(e,t){if(vt)return t&&En?.add(t),vt;let r=new Set;t&&r.add(t),En=r;let o=i=>{for(let s of r)s(i)},n=kt(cr,"bin","python");return vt=(async()=>{try{let i=!1;try{await eu(n);let s=await os(n);i=s!==null&&ns(s)}catch{i=!1}if(!i){await Tn(cr,{recursive:!0,force:!0}).catch(()=>{});let s=await iu(e);await es(s,["-m","venv",cr])}return o({kind:"start"}),await es(n,["-m","pip","install","--disable-pip-version-check",...rs],(s,l)=>{o({kind:"log",line:s,stream:l})}),o({kind:"complete"}),n}catch(i){let s=i instanceof Error?i.message:String(i);throw o({kind:"error",message:s}),vt=null,await Tn(cr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{En=null}})(),vt}function au(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 l=JSON.parse(s);return{userStdout:i,result:l}}catch{return{userStdout:e,result:null}}}function lu(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function is(e){let t=e.timeout??nu;if(!ou(e.scriptRuntime))return lu(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${ts.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await su(e.scriptRuntime,e.onInstallProgress),o=Date.now(),n;try{n=await Qd(kt(tu(),"kizen-step-"));let i=kt(n,"wrapper.py"),s=kt(n,"script.py");await Promise.all([Qi(i,ru,"utf-8"),Qi(s,e.script,"utf-8")]);let l={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:s},{exitCode:a,stdout:p,stderr:h}=await new Promise(y=>{let v=[],P=[],C=!1,_=In(r,[i],{env:l,cwd:n,stdio:["ignore","pipe","pipe"]}),S=setTimeout(()=>{_.kill("SIGKILL")},t);_.stdout.on("data",f=>{v.push(f)}),_.stderr.on("data",f=>{P.push(f)});let g=f=>{C||(C=!0,clearTimeout(S),y({exitCode:f??1,stdout:Buffer.concat(v).toString("utf-8"),stderr:Buffer.concat(P).toString("utf-8")}))};_.on("close",g),_.on("error",f=>{C||(C=!0,clearTimeout(S),y({exitCode:1,stdout:"",stderr:f.message}))})}),w=Date.now()-o,{userStdout:x,result:d}=au(p);if(d){let y={success:d.success,outputValues:d.outputValues,logs:d.logs,stdout:x,stderr:h,exitCode:a,durationMs:w};return d.error!==null&&(y.error=d.error),d.httpRequests&&(y.httpRequests=d.httpRequests),y}let c={success:!1,outputValues:{},logs:[],stdout:x,stderr:h,exitCode:a,durationMs:w};return a!==0&&(c.error=`Process exited with code ${String(a)}`),c}finally{n&&Tn(n,{recursive:!0,force:!0})}}var ss=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 ds,CRYPTO_VERSION as us,deserializeEnvelope as yu,encrypt as bu,serializeEnvelope as wu}from"@kizenapps/packager";function An(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 xu=2*1024*1024,vu=new Set([".DS_Store",".gitignore"]);function ku(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 hs=["kizen.com","kizen.dev"];function Cu(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:hs.some(o=>r===o||r.endsWith("."+o))}function Su(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let r=t.hostname.toLowerCase();return hs.some(o=>r===o||r.endsWith("."+o))}function _u(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 ps(e,t){if(t.includes("\0"))return null;let r=t.replace(/^\/+/,""),o=hu(e,r);if(o!==e&&!o.startsWith(e+Nn))return null;try{let n=await fu(o);return n!==e&&!n.startsWith(e+Nn)?null:n}catch{return null}}function fs(e,t){let r=t===e?"":t.slice(e.length+1);return r===""?!1:r.split(Nn).some(n=>Bt.has(n))}function gs(){let e=gu(import.meta.url);return St(mu(e),"viewer")}function ms(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 Dn(e){try{return await du(e),!0}catch{return!1}}function ys(e,t,r,o,n,i,s,l,a,p,h){let w=qi({onChange:l,enabled:h}),x=cu(p);return(d,c)=>{(async()=>{let y=d.url??"/";try{if(!ku(d.headers.host)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if((d.method==="POST"||d.method==="PATCH"||d.method==="DELETE")&&!_u(d.headers.origin)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${y}`),y==="/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(y==="/api/credential-profiles"&&d.method==="GET"){let f=await Ae();c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({profiles:f,active:n.current}));return}if(y==="/api/credentials/switch"&&d.method==="POST"){let f=[];for await(let k of d)f.push(k);let m=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}").profile,b=m===void 0||m===""?await te():await ve(m);if(b!==null){o.current=b,n.current=m??void 0;let k=n.current,I=await he(i);await Ee(i,{...I,credentialMode:"global",...k!==void 0&&{activeCredentialProfile:k}}),s({type:"credentials-updated",credentials:b,activeProfile:n.current??null})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({ok:b!==null}));return}if(y==="/api/bundle"){let f=St(process.cwd(),".kizenapp","bundle.json");try{let u=await pu(f,"utf-8");c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(u)}catch{c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end("{}")}return}if(y==="/api/last-path"&&d.method==="POST"){let f=[];for await(let m of d)f.push(m);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.path=="string"){a.current=u.path;let m=await he(i);await Ee(i,{...m,lastPath:u.path})}c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(y==="/api/encryption-target"&&d.method==="GET"){let u=(await he(i)).encryptionTarget==="dev"?"dev":"prod";c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({target:u}));return}if(y==="/api/encryption-target"&&d.method==="POST"){let f=[];for await(let k of d)f.push(k);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}"),m=u!==null&&typeof u=="object"?u:{};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 b=await he(i);await Ee(i,{...b,encryptionTarget:m.target}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(y==="/api/execute-step"&&d.method==="POST"){let f=[];for await(let k of d)f.push(k);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.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:u.script,scriptRuntime:u.scriptRuntime??"python-3-13",inputs:Zi(u.inputs),secrets:u.secrets??{},onInstallProgress:k=>{k.kind==="start"?s({type:"venv-install-start"}):k.kind==="log"?s({type:"venv-install-log",line:k.line,stream:k.stream}):k.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:k.message})}};typeof u.timeout=="number"&&u.timeout>0&&(m.timeout=Math.min(u.timeout,300*1e3));let b=await is(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(b));return}if(y==="/api/proxy-cache/clear"){w.clear(),r({kind:"info",message:"Proxy cache cleared"}),c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end('{"ok":true}');return}if(y==="/api/local/encrypt"&&d.method==="POST"){let f=[];for await(let m of d)f.push(m);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.publicKeyPem!="string"||typeof u.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=bu(u.value,u.publicKeyPem),b=wu(m);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify(b))}catch(m){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:m.message}))}return}if(y==="/api/local/validate"&&d.method==="POST"){let f=[];for await(let E of d)f.push(E);let u=JSON.parse(Buffer.concat(f).toString("utf-8")||"{}");if(typeof u.value!="string"){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing required field: value"}));return}let m,b;try{m=yu(u.value)}catch(E){b=E.message}if(b!==void 0||m===void 0){c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:!1,checks:[],error:b}));return}let k=E=>Buffer.from(E,"base64").length,I=[{label:"Version",expected:String(us),actual:String(m.v),pass:m.v===us},{label:"Algorithm",expected:ds,actual:m.alg,pass:m.alg===ds},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(k(m.k))} bytes`,pass:k(m.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(k(m.iv))} bytes`,pass:k(m.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(k(m.tag))} bytes`,pass:k(m.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(k(m.ct))} bytes`,pass:k(m.ct)>=1}];c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({valid:I.every(E=>E.pass),checks:I}));return}if(y.startsWith("/api/wizard")){let f=d.headers["x-encryption-target"],m=(Array.isArray(f)?f[0]:f)==="dev"?"dev":"prod",b=xt(m);if(!Cu(b)){c.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:`Encryption API host is not allowed: ${b}`}));return}let k=y.slice(11)||"/",I=`${b}${k}`,E=d.method??"GET",R=[];for await(let je of d)R.push(je);let{host:M,"x-encryption-target":W,...ae}=d.headers,ue=R.length>0?Buffer.concat(R):void 0,pe=ue&&ue.length>0?ue:void 0,le;try{le=await fetch(I,{method:E,headers:ae,...pe!==void 0&&{body:pe}})}catch(je){let xr=je.code==="ECONNREFUSED"?`plugin-wizard is not running at ${b}`:`Failed to reach plugin-wizard: ${je.message}`;c.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:xr}));return}let se=lr(Object.fromEntries(le.headers)),it=await le.arrayBuffer();c.writeHead(le.status,se),c.end(Buffer.from(it));return}if(y.startsWith("/api/proxy")){let f=d.headers["x-proxy-target"];if(typeof f!="string"){c.writeHead(400),c.end("Missing x-proxy-target header");return}if(!Su(f)){c.writeHead(400),c.end("Invalid proxy target");return}let u=y.slice(10)||"/",m=`${f}${u}`,b=d.method??"GET",k=[];for await(let le of d)k.push(le);let{host:I,"x-proxy-target":E,...R}=d.headers;if(b==="GET"){let le=`GET::${m}`,{response:se,fromCache:it}=await w.get(le,()=>fetch(m,{method:"GET",headers:R}));r({kind:"request",method:"GET",status:se.status,upstreamStatus:ms(u,se.headers,se.body),fromCache:it,url:u}),c.writeHead(se.status,se.headers),c.end(se.body);return}let M=k.length>0?Buffer.concat(k):void 0,W=M&&M.length>0?M:void 0,ae=await fetch(m,{method:b,headers:R,...W!==void 0&&{body:W}}),ue=lr(Object.fromEntries(ae.headers)),pe=await Cn(ae,kn);r({kind:"request",method:b,status:ae.status,upstreamStatus:ms(u,ue,pe),fromCache:!1,url:u}),c.writeHead(ae.status,ue),c.end(pe);return}if(y.startsWith("/api/source/tree")&&d.method==="GET"){let u=new URL(y,"http://localhost").searchParams.get("path")??"",m=await ps(x,u);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(fs(x,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await uu(m,{withFileTypes:!0}),k=await Promise.all(b.filter(E=>E.isDirectory()?!Bt.has(E.name):E.isFile()?!vu.has(E.name):!1).map(async E=>{let R=E.isDirectory()?"dir":"file",M={name:E.name,kind:R};if(R==="file")try{let W=await ls(St(m,E.name));M.size=W.size}catch{}return M}));k.sort((E,R)=>E.kind!==R.kind?E.kind==="dir"?-1:1:E.name.localeCompare(R.name));let I=m===x?"":m.slice(x.length+1);c.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({path:I,entries:k}))}catch(b){let k=b instanceof Error?b.message:String(b);t(`source/tree failed (${u}): ${k}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}if(y.startsWith("/api/source/file")&&d.method==="GET"){let u=new URL(y,"http://localhost").searchParams.get("path")??"";if(u===""){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Missing path"}));return}let m=await ps(x,u);if(m===null){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Invalid path"}));return}if(fs(x,m)){c.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await ls(m);if(!b.isFile()){c.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not a file"}));return}if(b.size>xu){c.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"File too large",size:b.size}));return}let k=cs(m).toLowerCase(),I=Sn[k],E=ss.has(k),R=I??(E?"text/plain; charset=utf-8":"application/octet-stream");c.writeHead(200,{"Content-Type":R,"Content-Length":String(b.size)}),as(m).pipe(c)}catch(b){let k=b instanceof Error?b.message:String(b);t(`source/file failed (${u}): ${k}`),c.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),c.end(JSON.stringify({error:"Not found"}))}return}let C=St(e,y==="/"?"/index.html":y),_=await Dn(C)?C:St(e,"index.html"),S=cs(_),g=Sn[S]??"application/octet-stream";c.writeHead(200,{"Content-Type":g}),as(_).pipe(c)}catch(v){if(y.startsWith("/api/proxy")){let P=y.slice(10)||"/",C=d.method??"GET";v instanceof wt?r({kind:"info",message:`${C} ${P} \u2192 502 (response exceeded ${String(v.limit)} bytes)`}):r({kind:"request",method:C,status:502,fromCache:!1,url:P})}else r({kind:"info",message:`Error handling ${y}: ${v instanceof Error?v.message:String(v)}`});c.headersSent||(c.writeHead(502),c.end("Bad Gateway"))}})()}}import{launch as Pu}from"chrome-launcher";import{createRequire as Eu}from"module";import{mkdirSync as Tu}from"fs";import{readFile as Iu}from"fs/promises";import{dirname as Au,join as Nu}from"path";import{fileURLToPath as Du}from"url";var bs=Eu(import.meta.url)("chrome-remote-interface"),Ru=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),xs=["kizen.dev","kizen.com"];function ws(e){try{let{hostname:t}=new URL(e);return xs.some(r=>t===r||t.endsWith("."+r))}catch{return!1}}async function Bu(e){try{let t=Nu(Au(Du(import.meta.url)),"viewer","icon.png"),r=await Iu(t);await e.Browser.setDockTile({image:r.toString("base64")})}catch{}}async function vs(e){Tu(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,r=await Pu({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,l=null,a=0,p=!1,h=_=>{e.debugLog?.(_)},w=_=>{e.verbose&&e.debugLog?.(_)},x=()=>{i!==null&&(clearInterval(i),i=null)},d=_=>_==="chrome://new-tab-page/"||_==="chrome://newtab/",c=async _=>{x(),s=null,await Bu(_),await _.Fetch.enable({patterns:xs.flatMap(g=>[{urlPattern:`*://${g}/*`,requestStage:"Response"},{urlPattern:`*://*.${g}/*`,requestStage:"Response"}])}),_.on("Fetch.requestPaused",g=>{(async()=>{let f=g,{requestId:u,request:m,responseHeaders:b,responseStatusCode:k}=f,I=m.url;w(`Fetch ${String(k??"?")} ${I}`);let E=[],R=!1;for(let M of b??[])if(!Ru.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&ws(I)){let W=M.value.split(`
1100
- `).map(ae=>/SameSite=/i.test(ae)?ae.replace(/SameSite=\w+/i,"SameSite=None"):ae+"; SameSite=None; Secure").join(`
1101
- `);E.push({name:M.name,value:W}),R=!0}else E.push(M);R&&w(` rewrote Set-Cookie SameSite on ${I}`);try{let{body:M,base64Encoded:W}=await _.Fetch.getResponseBody({requestId:u});await _.Fetch.fulfillRequest({requestId:u,responseCode:k??200,responseHeaders:E,body:M,...W&&{base64Encoded:!0}})}catch(M){w(` fulfillRequest failed (${M.message}), falling through`);try{await _.Fetch.continueRequest({requestId:u})}catch(W){w(` continueRequest also failed (${W.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:g}=await _.Network.getAllCookies(),f=0;for(let u of g){if(!ws(`https://${u.domain??""}`)||u.sameSite==="None")continue;let m=u.domain??"",b=m.startsWith(".")?m.slice(1):m;await _.Network.setCookie({url:`https://${b}`,name:u.name,value:u.value,domain:m,path:u.path??"/",secure:!0,...u.httpOnly!==void 0&&{httpOnly:u.httpOnly},...u.expirationDate!==void 0&&{expires:u.expirationDate},sameSite:"None"}),f++}f>0&&w(`cookie-patch cycle: updated ${String(f)} cookie(s) to SameSite=None`)}catch(g){w(`cookie-patch cycle failed: ${g.message}`)}})()},2e3),await _.Target.setDiscoverTargets({discover:!0});let S=g=>{if(g.type==="page"){if(d(g.url)){h(`closed stray new-tab-page target ${g.targetId}`),s!==null&&_.Target.activateTarget({targetId:s}).catch(()=>{}),_.Target.closeTarget({targetId:g.targetId}).catch(()=>{});return}s===null&&(s=g.targetId,h(`captured main target ${g.targetId} (${g.url})`))}};_.on("Target.targetCreated",g=>{let{targetInfo:f}=g;w(`target +${f.type} ${f.targetId} ${f.url}`),S(f)}),_.on("Target.targetInfoChanged",g=>{let{targetInfo:f}=g;w(`target ~${f.type} ${f.targetId} ${f.url}`),S(f)}),_.on("disconnect",()=>{p||n!==_||(h("CDP disconnected"),n=null,x(),y())})},y=()=>{if(p||l!==null)return;let _=Math.min(1e3*2**a,1e4),S=a+1;a++,h(`CDP reconnect scheduled in ${String(_)}ms (attempt #${String(S)})`),l=setTimeout(()=>{l=null,(async()=>{let g;try{g=await bs({port:o})}catch{h(`CDP reconnect attempt #${String(S)} failed`),y();return}if(p){try{await g.close()}catch{}return}n=g;try{await c(g),h(`CDP reconnected after ${String(S)} attempt(s)`),a=0}catch{n===g&&(n=null);try{await g.close()}catch{}h(`CDP reconnect attempt #${String(S)} failed during setup`),y()}})()},_)},v=30,P=300;for(let _=0;_<v;_++){await new Promise(S=>setTimeout(S,P)),h(`CDP connect attempt ${String(_+1)}/${String(v)}`);try{let S=await bs({port:o});n=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await c(S),h("CDP connected")}catch{n===S&&(n=null);try{await S.close()}catch{}h("CDP setup failed after connect")}break}catch{if(_===v-1){let S=`CDP unavailable after ${String(v)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return h(S),e.onWarn?.(S),{kill:()=>{r.kill()}}}}}return n?{kill:()=>{if(h("CDP kill requested \u2014 tearing down"),p=!0,l!==null&&(clearTimeout(l),l=null),x(),n!==null){try{n.close()}catch{}n=null}r.kill()}}:{kill:()=>{r.kill()}}}import{useCallback as $u,useState as ju}from"react";function dr(e){let[t,r]=ju([]),o=$u(n=>{r(i=>[...i,`${new Date().toLocaleTimeString()}: ${n}`].slice(-e))},[e]);return[t,o]}import{useCallback as ur,useEffect as Rn,useState as pr}from"react";import{Box as Y,Text as z,useInput as Fu}from"ink";import{jsx as D,jsxs as Z}from"react/jsx-runtime";var Be=["apiKey","userId","businessId"],Ou={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},_t=({text:e})=>D(z,{dimColor:!0,children:e}),fr=({initialMode:e,showProfileManager:t,onComplete:r,onCancel:o})=>{let[n,i]=pr(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,l]=pr(""),[a,p]=pr(null),[h,w]=pr(void 0),x=ur(g=>{if(g==="local"){r({mode:"local",credentials:null});return}i({type:"profile-loading"})},[r]),d=ur(async g=>{if(g===null){i({type:"profile-loading"});let m=await Ae();i({type:"name-entry",nameBuffer:"",existingProfiles:m});return}w(g.isDefault?void 0:g.name),i({type:"loading"});let f=g.isDefault?await te():await ve(g.name),u=f?Math.max(0,X.indexOf(f.environment)):0;i({type:"creds-entry",field:0,values:f??{},envCursor:u})},[]),c=ur(async(g,f)=>{let u=X[f]??"go",m={...at(g),environment:u};i({type:"saving"});try{await lo(h??Te,m),r({mode:"global",credentials:m,...h!==void 0&&{profileName:h}})}catch(b){p(b instanceof Error?b.message:String(b)),i({type:"creds-entry",field:0,values:g,envCursor:f})}},[r,h]);Fu((g,f)=>{if(f.ctrl&&g==="c"&&process.exit(0),f.escape){if((n.type==="creds-entry"||n.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),y();return}o?.();return}if(n.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 u=n.cursor===0?"global":"local";x(u)}return}if(n.type==="profile-select"){let{profiles:u,cursor:m}=n,b=u.length,k=u.length+1;if(f.upArrow)i({...n,cursor:(m-1+k)%k});else if(f.downArrow)i({...n,cursor:(m+1)%k});else if(f.return)if(m===b)i({type:"name-entry",nameBuffer:"",existingProfiles:u});else{let I=u[m]??u[0];I&&d(I)}return}if(n.type==="name-entry"){let{nameBuffer:u,existingProfiles:m}=n;if(f.backspace||f.delete)i({type:"name-entry",nameBuffer:u.slice(0,-1),existingProfiles:m});else if(f.return){let b=u.trim();if(!b){i({...n,nameError:"Name cannot be empty"});return}if(b===Te){i({...n,nameError:`"${Te}" is reserved`});return}if(m.some(k=>k.name===b)){i({...n,nameError:`Profile "${b}" already exists`});return}w(b),i({type:"creds-entry",field:0,values:{},envCursor:0}),l("")}else g&&!f.ctrl&&!f.meta&&i({type:"name-entry",nameBuffer:u+g,existingProfiles:m});return}if(n.type==="creds-entry"){let{field:u,values:m,envCursor:b}=n;if(u===Be.length){f.leftArrow?i({...n,envCursor:(b-1+X.length)%X.length}):f.rightArrow?i({...n,envCursor:(b+1)%X.length}):f.upArrow?(i({...n,field:u-1}),l(m[Be[u-1]]??"")):f.return&&c(m,b);return}let I=Be[u];if(!I)return;if(f.backspace||f.delete)l(E=>E.slice(0,-1));else if(f.upArrow&&u>0){let E={...m,[I]:s},R=u-1;i({...n,field:R,values:E}),l(E[Be[R]]??"")}else if(f.return||f.tab||f.downArrow){let E={...m,[I]:s},R=u+1;i({...n,field:R,values:E}),R<Be.length?l(E[Be[R]]??""):l("")}else g&&!f.ctrl&&!f.meta&&l(E=>E+g)}});let y=ur(async()=>{let g=await Ae();i({type:"profile-select",profiles:g,cursor:0})},[]);if(Rn(()=>{n.type==="profile-loading"&&y()},[n.type,y]),Rn(()=>{e==="global"&&!t&&(async()=>{let g=await te(),f=g?Math.max(0,X.indexOf(g.environment)):0;i({type:"creds-entry",field:0,values:g??{},envCursor:f})})()},[]),Rn(()=>{n.type==="creds-entry"&&n.field===0&&l(n.values.apiKey??"")},[n.type]),n.type==="loading"||n.type==="saving"||n.type==="profile-loading"){let g=n.type==="saving"?"Saving credentials\u2026":n.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return D(Y,{paddingY:1,paddingX:2,children:D(z,{dimColor:!0,children:g})})}if(n.type==="done")return null;if(n.type==="mode-select")return Z(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(K,{}),Z(Y,{flexDirection:"column",gap:0,children:[D(z,{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,u)=>{let m=n.cursor===u;return Z(Y,{gap:2,children:[D(z,{...m&&{color:"cyan"},children:m?"\u276F":" "}),D(z,{bold:m,...m&&{color:"cyan"},children:f.label}),D(z,{dimColor:!0,children:f.desc})]},f.mode)})]}),D(_t,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(n.type==="profile-select"){let{profiles:g,cursor:f}=n,u=g.length;return Z(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(K,{}),Z(Y,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:"Credential profiles"}),g.map((m,b)=>{let k=f===b;return Z(Y,{gap:2,children:[D(z,{...k&&{color:"cyan"},children:k?"\u276F":" "}),D(z,{bold:k,...k&&{color:"cyan"},children:m.isDefault?"Default":m.name}),D(z,{dimColor:!0,children:m.path})]},m.name)}),Z(Y,{gap:2,children:[D(z,{...f===u&&{color:"cyan"},children:f===u?"\u276F":" "}),D(z,{bold:f===u,...f===u&&{color:"cyan"},children:"+ Add new profile"})]})]}),D(_t,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(n.type==="name-entry"){let{nameBuffer:g,nameError:f}=n;return Z(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(K,{}),D(Y,{flexDirection:"column",gap:0,children:D(z,{bold:!0,children:"New credential profile"})}),f&&Z(z,{color:"red",children:["Error: ",f]}),Z(Y,{gap:2,children:[D(Y,{width:12,children:D(z,{bold:!0,color:"cyan",children:"Profile name"})}),D(z,{color:"cyan",children:">"}),D(z,{children:g}),D(z,{color:"cyan",children:"\u2588"})]}),D(_t,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:v,values:P,envCursor:C}=n,_=v===Be.length,S=h??Te;return Z(Y,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(K,{}),Z(Y,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:h!==void 0?`Profile: ${h}`:"Global credentials"}),Z(z,{dimColor:!0,children:["Saved to:"," ",h!==void 0?`~/.kizenappbuilder/${h}.json`:xe]})]}),a&&Z(z,{color:"red",children:["Error: ",a]}),Z(Y,{flexDirection:"column",gap:0,children:[Be.map((g,f)=>{let u=v===f,m=u?s:P[g]??"";return Z(Y,{gap:2,children:[D(Y,{width:12,children:D(z,{bold:u,...u&&{color:"cyan"},children:Ou[g]})}),D(z,{...u&&{color:"cyan"},children:">"}),D(z,{children:m}),u&&D(z,{color:"cyan",children:"\u2588"})]},g)}),Z(Y,{gap:2,children:[D(Y,{width:12,children:D(z,{bold:_,..._&&{color:"cyan"},children:"Environment"})}),D(z,{..._&&{color:"cyan"},children:">"}),D(Y,{gap:1,children:X.map((g,f)=>{let u=f===C;return _?D(z,{bold:u,...u&&{color:"cyan"},children:u?`[${g}]`:g},g):D(z,{dimColor:!u,bold:u,children:g},g)})})]})]}),_?D(_t,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):D(_t,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Z(z,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as F,jsxs as G}from"react/jsx-runtime";var Wu=[".kizenapp",".git"],Cs=({port:e,pluginDir:t,outputDir:r,credentials:o,credentialMode:n,activeCredentialProfile:i,lastPath:s,debug:l=!1,verbose:a=!1,autoViewer:p=!0,cacheEnabled:h=!0})=>{let w=Ce(o),x=Ce(i),d=Ce(s),[c,y]=ie("main"),[v,P]=ie(n),[C,_]=ie("starting"),[S,g]=ie(null),[f,u]=dr(50),[m,b]=dr(50),[k,I]=dr(50),[E,R]=ie([]),[M,W]=ie("pending"),[ae,ue]=ie(null),[pe,le]=ie(null),[se,it]=ie(null),[je,xr]=ie(null),[vr,kr]=ie(0),[Fn,aa]=ie(0),[la,ca]=ie(0),[Cr,da]=ie(0),Sr=Ce(!1),On=Ce(!1),Et=Ce(null),st=Ce(null),Se=Ce(new Set),Tt=Ce([]),ce=ot(T=>{let U=JSON.stringify(T);if(Se.current.size===0){Tt.current=[...Tt.current,U].slice(-50);return}let _e=!1;for(let fe of Se.current)if(fe.readyState===1)try{fe.send(U)}catch{Se.current.delete(fe),_e=!0}_e&&kr(Se.current.size)},[]),It=u,_r=ot(()=>{Et.current?.kill(),Et.current=null,vs({port:e,userDataDir:ks(r,".chrome"),broadcast:ce,onWarn:T=>{u(`\u26A0 ${T}`)},...d.current!==void 0&&{path:d.current},...l&&{debugLog:I},...a&&{verbose:!0}}).then(T=>{Et.current=T})},[e,r,ce,l,a,I,u]);mr(()=>{let T=()=>{Et.current?.kill()};return process.on("exit",T),()=>{process.off("exit",T)}},[]),Mu((T,U)=>{(T==="q"||U.ctrl&&T==="c")&&process.exit(0),T==="c"&&y("editing"),T==="v"&&_r()},{isActive:c==="main"}),mr(()=>{C!=="running"||On.current||!p||(On.current=!0,_r())},[C,p,_r]);let ua=ot(T=>{w.current=T.credentials,x.current=T.profileName,y("main"),P(T.mode);let U=T.profileName;Ee(r,{credentialMode:T.mode,...U!==void 0&&{activeCredentialProfile:U}}),ce({type:"credentials-updated",credentials:T.credentials})},[r,ce]),zn=ot(T=>{R(U=>[...U,`${new Date().toLocaleTimeString()}: ${An(T)}`].slice(-50)),T.kind==="request"&&(T.fromCache?ca(U=>U+1):da(U=>U+1)),ce({type:"proxy-log",entry:T})},[ce]),Fe=ot(T=>{b(T),ce({type:"log",message:T})},[b,ce]),Pr=ot(()=>{Sr.current||(Sr.current=!0,W("building"),ue(null),le(null),Fe("Build started"),jt(t,r).then(({bundleSize:T})=>{Fe(`Build finished \u2014 bundle: ${mt(T)}`),W("done"),it(new Date),xr(T),Fe("Notifying viewers to reload"),ce({type:"rebuild"})}).catch(T=>{T instanceof Lu?(le(T.issues),ue(null)):(ue(T instanceof Error?T.message:String(T)),le(null)),W("error")}).finally(()=>{Sr.current=!1}))},[t,r,Fe,ce]);if(mr(()=>{Pr();let T=Hu(t,{recursive:!0},(U,_e)=>{if(!_e)return;let fe=_e.replace(/\\/g,"/");Wu.some(At=>fe.startsWith(At))||(Fe(`File change detected: ${_e}`),st.current!==null&&clearTimeout(st.current),st.current=setTimeout(Pr,150))});return T.on("error",U=>{Fe(`File watcher error \u2014 rebuilds have stopped: ${U.message}`)}),()=>{T.close(),st.current!==null&&clearTimeout(st.current)}},[t,Pr,Fe]),mr(()=>{let T=gs();Dn(ks(T,"index.html")).then(U=>{if(!U){g("Viewer not built. Run 'pnpm build:viewer' first."),_("error");return}let _e=ys(T,It,zn,w,x,r,ce,aa,d,t,h),fe=Uu(_e),At=new Vu({server:fe});return At.on("connection",Oe=>{for(let fa of Tt.current)Oe.readyState===1&&Oe.send(fa);Tt.current=[],It("Viewer connected for live reload"),Se.current.add(Oe),kr(Se.current.size),Oe.on("close",()=>{Se.current.delete(Oe),kr(Se.current.size)})}),fe.listen(e,"127.0.0.1",()=>{_("running"),It(`Server started on 127.0.0.1:${String(e)}`)}),fe.on("error",Oe=>{g(Oe.message),_("error")}),()=>{At.close(),fe.close()}})},[e,It,zn,ce,r,t,h]),c==="editing")return F(fr,{...v!==void 0&&{initialMode:v},showProfileManager:v==="global",onComplete:ua,onCancel:()=>{y("main")}});let Er=se!==null?Math.round((Date.now()-se.getTime())/1e3):null,pa=Er===null?"":Er<5?" (just now)":` (${String(Er)}s ago)`,Mn=pe?.filter(T=>T.severity==="error").length??0;return G(Q,{flexDirection:"column",paddingY:1,paddingX:2,children:[F(K,{marginBottom:1}),G(Q,{flexDirection:"column",children:[G(Q,{gap:2,marginBottom:0,children:[F(j,{bold:!0,dimColor:!0,children:"App Build"}),M==="pending"&&F(j,{dimColor:!0,children:"waiting\u2026"}),M==="building"&&G(Q,{gap:1,children:[F(ye,{}),F(j,{children:"Building plugin package\u2026"})]}),M==="done"&&G(Q,{gap:1,children:[F(j,{color:"green",children:"\u2713 Built"}),se!==null&&G(j,{dimColor:!0,children:["at ",se.toLocaleTimeString(),pa]}),je!==null&&G(j,{dimColor:!0,children:["\xB7 bundle: ",mt(je)]})]}),M==="error"&&(pe!==null?G(j,{color:"red",children:["\u2717 ",Mn," validation ",Mn===1?"error":"errors"]}):G(j,{color:"red",children:["\u2717 ",ae??"unknown error"]}))]}),pe!==null&&F(Xt,{issues:pe}),F(Q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:m.slice(-8).map((T,U)=>F(j,{dimColor:!0,wrap:"truncate",children:T},U))})]}),G(Q,{marginTop:1,flexDirection:"column",children:[G(Q,{gap:2,children:[F(j,{bold:!0,dimColor:!0,children:"Web Server"}),C==="starting"&&F(j,{dimColor:!0,children:"starting\u2026"}),C==="running"&&G(Q,{gap:2,children:[F(j,{color:"green",children:"\u2713 Running"}),G(j,{dimColor:!0,children:["\u25CF ",vr," viewer",vr!==1?"s":""]})]}),C==="error"&&G(j,{color:"red",children:["\u2717 ",S??"Server error"]})]}),F(Q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:f.slice(-8).map((T,U)=>F(j,{dimColor:!0,wrap:"truncate",children:T},U))})]}),G(Q,{marginTop:1,flexDirection:"column",children:[G(Q,{gap:2,children:[F(j,{bold:!0,dimColor:!0,children:"Network Proxy"}),F(j,{color:"green",children:"\u2713 Active"}),F(j,{dimColor:!0,children:h?`\u25CF ${String(Fn)} key${Fn!==1?"s":""} in the network cache \xB7 ${String(la)} hit \xB7 ${String(Cr)} miss`:`\u25CF network cache disabled \xB7 ${String(Cr)} request${Cr!==1?"s":""}`})]}),F(Q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:E.length===0?F(j,{dimColor:!0,children:" No requests yet."}):E.slice(-8).map((T,U)=>F(j,{dimColor:!0,wrap:"truncate",children:T},U))})]}),l&&G(Q,{marginTop:1,flexDirection:"column",children:[G(Q,{gap:2,children:[F(j,{bold:!0,dimColor:!0,children:"CDP Debug"}),G(j,{dimColor:!0,children:["\u25CF ",k.length," event(s)"]})]}),F(Q,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:k.length===0?F(j,{dimColor:!0,children:" No CDP events yet."}):k.slice(-8).map((T,U)=>F(j,{dimColor:!0,wrap:"truncate",children:T},U))})]}),G(Q,{marginTop:1,gap:1,children:[F(j,{dimColor:!0,children:"["}),F(j,{children:"q"}),F(j,{dimColor:!0,children:"] quit ["}),F(j,{children:"c"}),F(j,{dimColor:!0,children:"] credentials ["}),F(j,{children:"v"}),G(j,{dimColor:!0,children:["] ",vr===0?"open viewer":"relaunch viewer"]})]})]})};async function Ss(e){return new Promise(t=>{let r=null,o=i=>{r?.(),t(i)},{unmount:n}=Ps(_s(fr,{...e!==void 0&&{initialMode:e},onComplete:o}),{exitOnCtrlC:!1});r=n})}function Es(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`;Ne(o);let i=null,s,l,{lastPath:a}=await he(n);if(t.credentials)i=await Ie(t.credentials);else{let c=await he(n);if(c.credentialMode==="local")s="local";else if(c.credentialMode==="global"){if(s="global",l=c.activeCredentialProfile,l?(i=await ve(l),i||(i=await te(),l=void 0)):i=await te(),!i){let y=await Ss("global");i=y.credentials,l=y.profileName}}else{let y=await Ss();i=y.credentials,s=y.mode,l=y.profileName;let v=y.profileName;await Ee(n,{credentialMode:y.mode,...v!==void 0&&{activeCredentialProfile:v}})}}let p=t.verbose===!0,h=p||t.debug===!0,w=t.viewer!==!1,x=t.cache!==!1,{waitUntilExit:d}=Ps(_s(Cs,{port:r,pluginDir:o,outputDir:n,credentials:i,...s!==void 0&&{credentialMode:s},...l!==void 0&&{activeCredentialProfile:l},...a!==void 0&&{lastPath:a},debug:h,verbose:p,autoViewer:w,cacheEnabled:x}),{exitOnCtrlC:!1});await d()})}import{createElement as op}from"react";import{render as ip}from"ink";import{useCallback as gr,useEffect as Ns,useState as yr}from"react";import{Box as be,Text as H,useApp as Zu,useInput as Qu}from"ink";import{encrypt as Ku,serializeEnvelope as Ju}from"@kizenapps/packager";function qu(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Ts(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 Is(e,t,r){try{return await fetch(`${e}${t}`,r)}catch(o){throw new Error(qu(o)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${o.message}${Dt()==="unavailable"?` ${Nt}`:""}`)}}async function As(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 Gu(e,t,r){let o=xt(e.stage),n=await Is(o,"/get-public-key",{method:"POST",headers:Ts(t),body:JSON.stringify({api_name:r})}),i=await As(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 Yu(e,t){let r=Ku(t,e),o=Ju(r);if(typeof o.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return o.value}async function Xu(e,t,r,o){let n=xt(e.stage),i=await Is(n,"/encrypt",{method:"POST",headers:Ts(t),body:JSON.stringify({api_name:r,value:o})}),s=await As(i);if(!i.ok||s.encrypted!==!0||typeof s.value!="string"){let l=typeof s.error=="string"?s.error:`HTTP ${String(i.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${l}`)}return s.value}async function hr(e,t,r,o,n){if(e.isRemote)return n?.("encrypting"),Xu(e,t,r,o);n?.("fetching-key");let i=await Gu(e,t,r);return n?.("encrypting"),Yu(i,o)}import{Fragment as br,jsx as O,jsxs as ee}from"react/jsx-runtime";var Bn=({text:e})=>O(H,{dimColor:!0,children:e}),Ds=({ctx:e,stageDefaulted:t,credentialsPath:r,initialApiName:o,defaultApiName:n,initialValue:i,onDone:s})=>{let l=Zu(),[a,p]=yr({type:"loading"}),[h,w]=yr(null),[x,d]=yr(o??""),[c,y]=yr(i??""),v=gr(u=>{process.exitCode=1,p({type:"error",message:u instanceof Error?u.message:String(u)})},[]),P=gr(async(u,m,b)=>{try{let k=await hr(e,u,m,b,R=>{p(R==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),I=JSON.stringify({encrypted:!0,value:k},null,2);s?.(k);let E=await Rt(I);p({type:"done",envelope:I,copied:E})}catch(k){v(k)}},[e,v,s]),C=gr((u,m,b)=>{if(m.trim()===""){p({type:"api-name-entry",buffer:n??""});return}if(b===""){p({type:"value-entry",buffer:""});return}P(u,m.trim(),b)},[n,P]),_=gr(async u=>{try{p({type:"loading"});let m=u.isDefault?await te():await ve(u.name);if(m===null)throw new Error(`Could not load credential profile: ${u.name}`);w(m),C(m,x,c)}catch(m){v(m)}},[x,c,C,v]);Ns(()=>{(async()=>{try{if(r!==void 0){let b;try{b=await Ie(r)}catch(k){throw new Error(`Could not load credentials from ${r}: ${k instanceof Error?k.message:String(k)}`)}w(b),C(b,x,c);return}let u=await Ae();if(u.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[m]=u;if(u.length===1&&m!==void 0){let b=m.isDefault?await te():await ve(m.name);if(b===null)throw new Error(`Could not load credential profile: ${m.name}`);w(b),C(b,x,c);return}p({type:"profile-select",profiles:u,cursor:0})}catch(u){v(u)}})()},[]),Ns(()=>{(a.type==="done"||a.type==="error")&&l.exit()},[a,l]),Qu((u,m)=>{if(m.ctrl&&u==="c"){process.exitCode=130,l.exit();return}if(a.type==="profile-select"){let{profiles:b,cursor:k}=a;if(m.upArrow)p({...a,cursor:(k-1+b.length)%b.length});else if(m.downArrow)p({...a,cursor:(k+1)%b.length});else if(m.return){let I=b[k];I!==void 0&&_(I)}return}if(a.type==="api-name-entry"){let{buffer:b}=a;if(m.backspace||m.delete)p({type:"api-name-entry",buffer:b.slice(0,-1)});else if(m.return){let k=b.trim();if(k===""){p({type:"api-name-entry",buffer:b,error:"api_name cannot be empty"});return}d(k),h?C(h,k,c):v(new Error("Internal error: credentials were not loaded"))}else u&&!m.ctrl&&!m.meta&&p({type:"api-name-entry",buffer:b+u});return}if(a.type==="value-entry"){let{buffer:b}=a;if(m.backspace||m.delete)p({type:"value-entry",buffer:b.slice(0,-1)});else if(m.return){if(b===""){p({type:"value-entry",buffer:b,error:"secret cannot be empty"});return}y(b),h?C(h,x,b):v(new Error("Internal error: credentials were not loaded"))}else u&&!m.ctrl&&!m.meta&&p({type:"value-entry",buffer:b+u});return}});let S=e.isRemote?"remote Kizen API":"on-machine",g=t===!0?`${e.stage} (default)`:e.stage,f=u=>ee(be,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[O(K,{}),ee(H,{dimColor:!0,children:["Mode: ",S," Stage: ",g]}),u]});if(a.type==="loading")return f(ee(be,{gap:1,children:[O(ye,{}),O(H,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(a.type==="profile-select"){let{profiles:u,cursor:m}=a;return f(ee(br,{children:[O(H,{bold:!0,children:"Credential profile"}),O(be,{flexDirection:"column",children:u.map((b,k)=>{let I=m===k;return ee(be,{gap:2,children:[O(H,{...I&&{color:"cyan"},children:I?"\u276F":" "}),O(H,{bold:I,...I&&{color:"cyan"},children:b.isDefault?"Default":b.name}),O(H,{dimColor:!0,children:b.path})]},b.name)})}),O(Bn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return a.type==="api-name-entry"?f(ee(br,{children:[O(H,{bold:!0,children:"Plugin api_name"}),a.error!==void 0&&ee(H,{color:"red",children:["Error: ",a.error]}),ee(be,{gap:1,children:[O(H,{color:"cyan",children:">"}),O(H,{children:a.buffer}),O(H,{color:"cyan",children:"\u2588"})]}),O(Bn,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):a.type==="value-entry"?f(ee(br,{children:[O(H,{bold:!0,children:"Secret value"}),a.error!==void 0&&ee(H,{color:"red",children:["Error: ",a.error]}),ee(be,{gap:1,children:[O(H,{color:"cyan",children:">"}),O(H,{children:"\u2022".repeat(a.buffer.length)}),O(H,{color:"cyan",children:"\u2588"})]}),O(Bn,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):a.type==="fetching-key"?f(ee(be,{gap:1,children:[O(ye,{}),ee(H,{children:["Fetching ",e.stage," public key for ",O(H,{bold:!0,children:x}),"\u2026"]})]})):a.type==="encrypting"?f(ee(be,{gap:1,children:[O(ye,{}),O(H,{children:"Encrypting\u2026"})]})):a.type==="error"?f(ee(be,{gap:1,children:[O(H,{color:"red",children:"\u2717"}),O(H,{color:"red",children:a.message})]})):f(ee(br,{children:[ee(be,{gap:1,children:[O(H,{color:"green",children:"\u2713"}),O(H,{bold:!0,children:"Encrypted secret ready"})]}),a.copied?O(H,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):O(H,{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(H,{children:a.envelope})]}))};import{readFile as ep,writeFile as tp}from"fs/promises";import{join as rp}from"path";function Rs(e){return{encrypted:!0,value:e}}function Bs(e){return JSON.stringify(Rs(e))}async function $n(e,t){await tp(e,`${JSON.stringify(Rs(t),null,2)}
1102
- `,"utf-8")}var np="prod";function $s(e){return e==="dev"||e==="prod"}function js(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function Fs(e){return{stage:e==="dev"||e==="prod"?e:np,wasDefaulted:e===void 0}}function Os(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
1103
- `}async function zs(e=process.cwd()){try{let t=await ep(rp(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 Ms(e){return e.replace(/[\r\n]+$/,"")}async function Ls(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function Hs(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(Os(e.stage));let l=t.value;if(l===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
1104
- `),l=Ms(await n.readStdin())}if(l==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let a=await n.encryptSecret(e,i,s.trim(),l);if(n.writeStdout(`${Bs(a)}
1105
- `),t.out!==void 0)try{await n.writeEnvelopeFile(t.out,a),n.writeStderr(`Wrote encrypted envelope to ${t.out}
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}
1106
1073
  `)}catch(p){n.writeStderr(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}
1107
- `),n.setExitCode(1)}}function Us(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&&!$s(t.stage)&&(console.error(js(t.stage)),process.exit(1));let o=t.apiName===void 0?await zs():{},{stage:n,wasDefaulted:i}=Fs(t.stage),s={isRemote:t.remote===!0,stage:n};if(!process.stdin.isTTY||!process.stdout.isTTY){try{await Hs(s,t,o,i,{loadCredentialsFromFile:Ie,loadGlobalCredentials:te,encryptSecret:hr,readStdin:Ls,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:p=>{process.stdout.write(p)},writeStderr:p=>{process.stderr.write(p)},writeEnvelopeFile:$n,setExitCode:p=>{process.exitCode=p}})}catch(p){console.error(`Error: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}return}let l,{waitUntilExit:a}=ip(op(Ds,{ctx:s,stageDefaulted:i,onDone:p=>{l=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 a(),l!==void 0&&t.out!==void 0)try{await $n(t.out,l),process.stderr.write(`Wrote encrypted envelope to ${t.out}
1108
- `)}catch(p){console.error(`Error writing ${t.out}: ${p instanceof Error?p.message:String(p)}`),process.exitCode=1}})}var sp=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"]),ap=[...sp].sort(),lp=new Set(["kizen-k","form-entity"]),Vs=[...ap,...[...lp].sort()];function Ws(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of Vs)console.log(t)})}import{mkdir as gp,writeFile as ra,readFile as yp}from"fs/promises";import{join as wr}from"path";var cp=new Set(["developer_business_id"]);function dp(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 Js(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 l=n.children.get(i);l&&(n=l)})}return t}function qs(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 Gs(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var up={".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 pp(e){return up[Gs(e)]??""}function Ks(e){let t=[...e.matchAll(/`+/g)].reduce((r,o)=>Math.max(r,o[0].length),0);return"`".repeat(Math.max(3,t+1))}function Ys(e,t=""){let r=qs(e);return r.map((o,n)=>{let i=n===r.length-1,s=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",l=i?" ":"\u2502 ";return o.isFile?`${t}${s}${o.name}`:`${t}${s}${o.name}/
1109
- ${Ys(o,t+l)}`}).join(`
1110
- `)}var fp=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function Xs(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!fp.test(t.path))}function Zs(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cp.has(t)).map(([t,r])=>[t,t==="services"?dp(r):r]))}var mp={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Qs(e){return`<ul>${qs(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>${Qs(o)}</li>`).join("")}</ul>`}function hp(e){let t;return e.base64Image!==void 0?t=`<img src="data:${mp[Gs(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 ea(e,t){let r=Zs(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Xs(t),l=[];l.push(`# ${o}${n?` v${n}`:""}`),i&&l.push("",i);let a=JSON.stringify(r,null,2),p=Ks(a);l.push("","## Configuration (`kizen.json`)","",`${p}json`,a,p),l.push("","## File Tree","","```",Ys(Js(s)),"```"),l.push("","## Files");for(let h of s)if(l.push("",`### \`${h.path}\``,""),h.base64Image!==void 0)l.push(`[Image file: ${h.path}]`);else if(h.binaryData!==void 0)l.push(`[Binary file: ${String(h.binaryData.length)} bytes]`);else{let w=Ks(h.content);l.push(`${w}${pp(h.path)}`,h.content,w)}return l.join(`
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(`
1111
1078
  `)+`
1112
- `}function ta(e,t){let r=Zs(e),o=typeof e.name=="string"?e.name:"Plugin",n=typeof e.version=="string"?e.version:"",i=typeof e.description=="string"?e.description:"",s=Xs(t),l=Qs(Js(s)),a=s.map(hp).join(`
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(`
1113
1080
  `);return`<!DOCTYPE html>
1114
1081
  <html lang="en">
1115
1082
  <head>
@@ -1158,11 +1125,11 @@ img{border:1px solid var(--bd);border-radius:4px}
1158
1125
  <div class="layout">
1159
1126
  <nav>
1160
1127
  <a href="#config" class="cfg" data-id="config">kizen.json (config)</a>
1161
- ${l}
1128
+ ${a}
1162
1129
  </nav>
1163
1130
  <main>
1164
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>
1165
- ${a}
1132
+ ${l}
1166
1133
  </main>
1167
1134
  </div>
1168
1135
  <script>
@@ -1175,7 +1142,9 @@ ${a}
1175
1142
  })();
1176
1143
  </script>
1177
1144
  </body>
1178
- </html>`}var na=wr(ze,"examples");function oa(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${na}/<api_name>.html)`).action(async t=>{let r=process.cwd(),o;try{let a=await yp(wr(r,"kizen.json"),"utf-8"),p=JSON.parse(a);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??wr(na,`${n}.html`),s=i.replace(/\.html$/,".md"),l=await $t(r,{detectBinaryByContent:!0});await gp(wr(i,".."),{recursive:!0}),await Promise.all([ra(i,ta(o,l),"utf-8"),ra(s,ea(o,l),"utf-8")]),console.log(`Plugin report written to:
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:
1179
1146
  ${i}
1180
- ${s}`)})}function ia(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").action(async t=>{await Jo(process.cwd(),t)})}function Cp(){let e=xp(wp(vp(import.meta.url)),"..","package.json");return JSON.parse(bp(e,"utf-8")).version}function sa(){let e=new kp;return e.name("appbuilder").description("Kizen plugin app builder").version(Cp()),Ki(e),ia(e),yi(e),Es(e),Us(e),oa(e),Ws(e),pi(e),e}Hn({env:process.env,http:Sp});sa().parse();
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(`
1148
+ 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();
1181
1150
  //# sourceMappingURL=index.js.map