@kizenapps/cli 1.17.0 → 1.18.1-a517cfb
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/README.md +642 -26
- package/dist/index.js +132 -112
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import*as Cy from"http";var un="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.",Vl=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],Wl=e=>e!==void 0&&e!=="",Le="not-configured";function ui({env:e,http:t}){return Le==="applied"||(Vl.some(n=>Wl(e[n]))?e.NODE_USE_ENV_PROXY==="1"?Le="already-set":typeof t.setGlobalProxyFromEnv!="function"?Le="unavailable":(t.setGlobalProxyFromEnv(e),Le="applied"):Le="not-configured"),Le}var pn=()=>Le;import{readFileSync as yy}from"fs";import{dirname as by,join as wy}from"path";import{fileURLToPath as vy}from"url";import{Command as xy}from"commander";import{spawn as tp}from"child_process";import{Command as np}from"commander";import{constants as pu}from"os";var _r={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"},ze=e=>new URL(_r[e]).origin,pi={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"},ql=["go","fmo"];function Ar(e){return ql.includes(e)}import{posix as Gl}from"path";var O=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Te=(e,t)=>e?.code===t,fn=e=>e instanceof Error&&Te(e,"ENOENT"),fe=async e=>{try{return await e}catch(t){if(Te(t,"ENOENT"))return;throw t}},ie=e=>typeof e=="string"&&e!==""?e:void 0,oe=e=>e instanceof Error?e.message:String(e),Me=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},mn=e=>{let t=Gl.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as ed}from"child_process";import{createHash as td,randomBytes as nd}from"crypto";import{createServer as rd}from"http";import{platform as mi}from"process";var Jl=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Yl=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${Jl.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,Xl={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Zl=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${Xl[e]}</svg>`,Ql=`
|
|
2
|
+
import*as vE from"http";var vi="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.",Dh=["HTTPS_PROXY","https_proxy","HTTP_PROXY","http_proxy"],Lh=e=>e!==void 0&&e!=="",zt="not-configured";function Dl({env:e,http:t}){return zt==="applied"||(Dh.some(n=>Lh(e[n]))?e.NODE_USE_ENV_PROXY==="1"?zt="already-set":typeof t.setGlobalProxyFromEnv!="function"?zt="unavailable":(t.setGlobalProxyFromEnv(e),zt="applied"):zt="not-configured"),zt}var ki=()=>zt;import{readFileSync as fE}from"fs";import{dirname as gE,join as hE}from"path";import{fileURLToPath as yE}from"url";import{Command as bE}from"commander";import{spawn as Jb}from"child_process";import{Command as qb}from"commander";import{constants as ob}from"os";var Os={go:"https://app.go.kizen.com/api",fmo:"https://app.fmo.kizen.com/api",staging:"https://staging.kizen.com/api",integration:"https://integration.kizen.dev/api",test1:"https://test1.kizen.dev/api"},Ut=e=>new URL(Os[e]).origin,Ll={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"},Bh=["go","fmo"];function Kn(e){return Bh.includes(e)}import{posix as Fh}from"path";var F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),He=(e,t)=>e?.code===t,tt=e=>e instanceof Error&&He(e,"ENOENT"),_e=async e=>{try{return await e}catch(t){if(He(t,"ENOENT"))return;throw t}},Oe=e=>typeof e=="string"&&e!==""?e:void 0,ke=e=>e instanceof Error?e.message:String(e),xe=e=>{let t=e;return t.cause?.code??t.code??t.cause?.message??t.message??String(e)},Ai=e=>{let t=Fh.normalize(e.trim().replaceAll("\\","/")).replace(/\/+$/,"");return t==="."?"":t};import{spawn as Hh}from"child_process";import{createHash as Kh,randomBytes as Wh}from"crypto";import{createServer as Gh}from"http";import{platform as Fl}from"process";var jh=["M22.8852 7.03547C22.8112 7.5787 22.5356 8.0447 22.1428 8.36712C21.336 7.31995 20.1615 6.55456 18.7791 6.28228C18.6674 6.2606 18.5549 6.24164 18.4404 6.22606C17.0417 6.03708 15.6939 6.37914 14.6 7.09712C14.4293 7.20955 14.2646 7.33079 14.1068 7.46084C13.9084 7.62408 13.655 7.70942 13.3997 7.68233C13.3841 7.68098 13.3686 7.67894 13.353 7.67624C12.698 7.58073 12.2245 6.98196 12.2842 6.32291C12.2855 6.3087 12.2869 6.29447 12.2889 6.28092C12.3181 6.04522 12.442 5.83117 12.6249 5.67946C12.8246 5.51418 13.0326 5.35907 13.2473 5.21412C14.8059 4.16358 16.7417 3.65828 18.7513 3.92989C19.665 4.05317 20.5212 4.32749 21.2981 4.72441C21.5392 4.84701 21.7722 4.9818 21.9978 5.12743C22.6183 5.52908 22.9712 6.24503 22.8919 6.97926C22.8899 6.99822 22.8878 7.01719 22.8852 7.03547Z","M23.2333 16.1537C22.797 16.4857 22.2721 16.6198 21.7662 16.571C21.9369 15.2604 21.6476 13.8887 20.8626 12.7197C20.7996 12.6255 20.7325 12.532 20.6628 12.4406C19.8073 11.3183 18.6125 10.6077 17.331 10.3429C17.1304 10.3016 16.9286 10.2711 16.7254 10.2515C16.4694 10.2271 16.2297 10.1078 16.0684 9.90806C16.0582 9.89587 16.0488 9.88368 16.0393 9.87082C15.6437 9.34044 15.7325 8.58183 16.2411 8.15849C16.2519 8.14969 16.2628 8.1402 16.2743 8.13208C16.462 7.98645 16.701 7.9221 16.9375 7.94446C17.1955 7.96884 17.4522 8.00609 17.7069 8.05554C19.5526 8.41385 21.2785 9.42512 22.5072 11.0372C23.0659 11.7701 23.4771 12.5693 23.746 13.399C23.8293 13.6564 23.8991 13.9165 23.9553 14.1786C24.1097 14.9006 23.853 15.6566 23.2773 16.1199C23.2624 16.1314 23.2475 16.1436 23.2326 16.1551L23.2333 16.1537Z","M16.9978 22.8858C16.4545 22.8127 15.9878 22.5363 15.6654 22.1441C16.7132 21.3381 17.4793 20.1636 17.7516 18.7825C17.7732 18.6708 17.7923 18.5583 17.8078 18.4438C17.9968 17.0458 17.6547 15.6986 16.936 14.6053C16.8236 14.4347 16.7024 14.2701 16.5724 14.113C16.4091 13.9152 16.3231 13.6612 16.3508 13.4058C16.3523 13.3903 16.3543 13.3746 16.357 13.3591C16.4525 12.7041 17.0519 12.2313 17.7109 12.2909C17.7252 12.2922 17.7394 12.2937 17.7537 12.2957C17.9893 12.3248 18.204 12.4487 18.3551 12.6316C18.5203 12.8315 18.6755 13.0387 18.8204 13.2534C19.8716 14.8113 20.377 16.7458 20.1053 18.7541C19.982 19.6671 19.7071 20.5233 19.3108 21.2994C19.1882 21.5406 19.0534 21.7736 18.9078 21.9985C18.5061 22.6183 17.7895 22.9712 17.0553 22.8919C17.0364 22.8899 17.0173 22.8878 16.9991 22.8852L16.9978 22.8858Z","M7.86115 23.2332C7.52858 22.797 7.39447 22.2728 7.44391 21.7668C8.75523 21.9375 10.1275 21.6483 11.2973 20.864C11.3915 20.801 11.4849 20.7339 11.5764 20.6641C12.6994 19.8093 13.4105 18.6145 13.6754 17.3337C13.7167 17.1339 13.7472 16.9313 13.7668 16.7281C13.7912 16.4727 13.9104 16.233 14.1103 16.0718C14.1225 16.0617 14.1353 16.0522 14.1475 16.0427C14.6785 15.6471 15.4371 15.7365 15.8605 16.2445C15.8693 16.2554 15.8788 16.2662 15.8869 16.2777C16.0332 16.4653 16.0969 16.7037 16.0745 16.9408C16.0501 17.1989 16.0129 17.4556 15.9635 17.7096C15.6044 19.554 14.5932 21.2792 12.9798 22.5072C12.2462 23.0652 11.4469 23.4771 10.6165 23.7453C10.3592 23.8286 10.0991 23.8984 9.83693 23.9546C9.11422 24.1091 8.35831 23.8524 7.89502 23.2773C7.88282 23.2624 7.87131 23.2475 7.85979 23.2326L7.86115 23.2332Z","M1.13386 17.0634C1.20769 16.5202 1.48336 16.0542 1.87621 15.7318C2.68292 16.779 3.85742 17.5443 5.23986 17.8166C5.35163 17.8382 5.46406 17.8572 5.57853 17.8728C6.97722 18.0618 8.32512 17.7198 9.41902 17.0018C9.58971 16.8894 9.75427 16.7681 9.9121 16.638C10.1105 16.4748 10.3639 16.3895 10.6192 16.4166C10.6348 16.4179 10.6504 16.4199 10.666 16.4226C11.321 16.5181 11.7945 17.1169 11.7348 17.7759C11.7335 17.7902 11.7322 17.8044 11.73 17.818C11.701 18.0537 11.577 18.2677 11.3941 18.4194C11.1943 18.5847 10.9863 18.7398 10.7717 18.8847C9.21311 19.9354 7.27728 20.4406 5.26764 20.169C4.35391 20.0458 3.49776 19.7714 2.72085 19.3745C2.47972 19.2518 2.24672 19.1171 2.02117 18.9714C1.40073 18.5699 1.04784 17.8539 1.12709 17.1197C1.12911 17.1007 1.13115 17.0817 1.13386 17.0634Z","M0.766739 7.8774C1.20294 7.5455 1.72788 7.41139 2.23385 7.46016C2.06316 8.77081 2.35238 10.1424 3.13741 11.3115C3.20041 11.4057 3.26746 11.4991 3.33722 11.5906C4.1927 12.7129 5.38752 13.4234 6.66903 13.6883C6.86953 13.7295 7.07138 13.7601 7.27457 13.7797C7.5306 13.8041 7.77038 13.9233 7.93158 14.1231C7.94175 14.1353 7.95123 14.1475 7.96071 14.1604C8.35628 14.6907 8.26755 15.4493 7.75887 15.8726C7.74803 15.8815 7.73719 15.891 7.72567 15.899C7.53805 16.0447 7.29895 16.1091 7.06256 16.0867C6.8045 16.0623 6.54779 16.0251 6.29311 15.9756C4.44738 15.6173 2.72153 14.606 1.49284 12.994C0.934041 12.2611 0.522899 11.4618 0.253997 10.6321C0.170684 10.3747 0.100919 10.1147 0.0447005 9.85248C-0.109732 9.13047 0.146978 8.37457 0.722712 7.91127C0.737614 7.89975 0.752515 7.88756 0.767417 7.87605L0.766739 7.8774Z","M7.0287 1.14538C7.57192 1.21853 8.03861 1.49487 8.36102 1.88705C7.31318 2.69308 6.54711 3.86758 6.27483 5.24867C6.25315 5.36043 6.23419 5.47286 6.21861 5.58733C6.02963 6.98535 6.37168 8.33257 7.09034 9.42579C7.20277 9.59648 7.32402 9.76109 7.45407 9.91824C7.6173 10.116 7.70333 10.37 7.67555 10.6254C7.6742 10.6409 7.67216 10.6565 7.66946 10.6721C7.57396 11.327 6.97451 11.7998 6.31546 11.7402C6.30125 11.7389 6.28702 11.7375 6.27279 11.7355C6.03708 11.7063 5.82237 11.5824 5.67132 11.3995C5.50605 11.1997 5.35094 10.9925 5.20599 10.7777C4.15477 9.21988 3.64948 7.28541 3.92109 5.27711C4.04436 4.36406 4.31936 3.50792 4.7156 2.73169C4.8382 2.49056 4.97299 2.25755 5.11861 2.03268C5.52028 1.41292 6.2369 1.06003 6.97112 1.13928C6.99009 1.14131 7.00905 1.14334 7.02734 1.14605L7.0287 1.14538Z","M16.1579 0.766744C16.4904 1.20295 16.6245 1.7272 16.5751 2.23317C15.2637 2.06248 13.8915 2.3517 12.7217 3.13606C12.6276 3.19906 12.534 3.26611 12.4427 3.33588C11.3196 4.19067 10.6084 5.38549 10.3436 6.66633C10.3022 6.86614 10.2718 7.06866 10.2521 7.27187C10.2277 7.52723 10.1085 7.767 9.90873 7.92821C9.89654 7.93837 9.88368 7.94785 9.87149 7.95733C9.34044 8.35289 8.58183 8.26349 8.15849 7.75549C8.14969 7.74465 8.1402 7.73381 8.13208 7.7223C7.98578 7.53468 7.9221 7.29625 7.94446 7.05919C7.96884 6.80112 8.00609 6.54441 8.05554 6.29041C8.41452 4.44603 9.42579 2.72085 11.0392 1.49285C11.7728 0.934723 12.572 0.522903 13.4025 0.254678C13.6598 0.171366 13.9199 0.101601 14.1821 0.0453817C14.9048 -0.109051 15.6607 0.147659 16.124 0.722716C16.1362 0.737618 16.1477 0.752519 16.1592 0.76742L16.1579 0.766744Z","M37.833 18.812L33.0705 12.364L31.0715 14.5591V18.812H28.896V5.0929H31.0715V11.5801L36.9707 5.0929H39.6949L34.5601 10.7177L40.4593 18.812H37.833ZM41.3079 18.812V8.79706H43.3658V18.812H41.3079ZM41.0531 6.36192C41.0531 5.65636 41.6411 5.088 42.3467 5.088C43.0523 5.088 43.6206 5.65636 43.6206 6.36192C43.6206 7.06747 43.0523 7.63584 42.3467 7.63584C41.6411 7.63584 41.0531 7.06747 41.0531 6.36192ZM45.1032 18.812V17.1069L50.8653 10.6197H45.1032V8.79706H53.4523V10.5022L47.6903 16.9893H53.4523V18.812H45.1032ZM54.2765 13.8143C54.2765 10.8549 56.5303 8.60107 59.4898 8.60107C62.7039 8.60107 65.0166 11.2273 64.6442 14.5003H56.3539C56.6479 16.0878 57.9218 17.2245 59.6465 17.2245C60.9596 17.2245 62.0376 16.5386 62.6059 15.441L64.3307 16.2054C63.4683 17.8517 61.7828 19.008 59.5877 19.008C56.5695 19.008 54.2765 16.7541 54.2765 13.8143ZM56.4127 12.8932H62.5668C62.2335 11.4429 61.0772 10.3846 59.4898 10.3846C57.9022 10.3846 56.7655 11.4233 56.4127 12.8932ZM66.2386 18.812V8.79706H68.2964V10.2278C69.0216 9.24783 70.1975 8.60107 71.589 8.60107C74.0193 8.60107 75.744 10.3846 75.744 12.8344V18.812H73.6861V13.148C73.6861 11.5997 72.5494 10.4825 71.0011 10.4825C69.4528 10.4825 68.2964 11.5997 68.2964 13.148V18.812H66.2386Z"],Mh=`<svg class="wordmark" role="img" aria-label="Kizen" width="76" height="24" viewBox="0 0 76 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="kizen-callback-wordmark-clip"><rect width="75.648" height="24"/></clipPath></defs><g clip-path="url(#kizen-callback-wordmark-clip)">${jh.map(e=>`<path d="${e}"/>`).join("")}</g></svg>`,zh={success:'<path d="M6 12.5l4 4 8-9"/>',error:'<path d="M8 8l8 8M16 8l-8 8"/>'},Uh=e=>`<svg class="status-icon" aria-hidden="true" focusable="false" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg">${zh[e]}</svg>`,Vh=`
|
|
3
3
|
:root {
|
|
4
4
|
color-scheme: light dark;
|
|
5
5
|
--page-bg: #F4F9F7;
|
|
@@ -82,65 +82,72 @@ main {
|
|
|
82
82
|
.error { --accent: var(--error-accent); --tint: var(--error-bg); --glyph: var(--error-text); }
|
|
83
83
|
h1 { margin: 0 0 10px; font-size: 22px; line-height: 1.3; font-weight: 600; }
|
|
84
84
|
p { margin: 0; font-size: 15px; line-height: 1.5; color: var(--text-secondary); }
|
|
85
|
-
`.trim().replace(/\n\s*/g,"");function fi(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${Ql}</style></head><body><main>${Yl}<section class="card ${e}" data-status="${e}"><div class="status">${Zl(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var hn="127.0.0.1",Tr="/callback",od=`http://${hn}${Tr}`,id="read write offline_access",sd="Kizen App Builder CLI",ad=300*1e3,Ue="go",_t=2e4,q=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},xe=e=>e===Ue?"appbuilder login":`appbuilder login --env ${e}`,ke=(e,t,n={})=>new q("login_required",`${t} Run \`${xe(e)}\` to sign in${n.again===!0?" again":""}.`),cd=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Ir(e,t,n,r){let o=AbortSignal.timeout(r);try{let i=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:o});return{res:i,body:cd(await i.text())}}catch(i){let s=o.aborted?`timed out after ${String(Math.round(r/1e3))}s`:Me(i);throw new q("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function gi(e,t,n){let r=O(n)?n:{},o=ie(r.error);if(o!==void 0){let i=ie(r.error_description);return new q(o,`${e} failed (${o}${i===void 0?"":`: ${i}`})`)}return new q("server_error",`${e} failed with HTTP ${String(t)}`)}async function yi(e,t,n=_t){let r=`${e}/.well-known/oauth-authorization-server`,o=a=>new q("server_error",`OAuth discovery at ${r} ${a}`),{res:i,body:s}=await Ir(t,r,{},n);if(!i.ok)throw o(`failed with HTTP ${String(i.status)}`);if(!O(s))throw o("didn't return valid JSON");if(s.issuer!==e)throw o(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function bi(e,t,n=_t){let{res:r,body:o}=await Ir(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:sd,redirect_uris:[od],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw gi("App registration",r.status,o);let i=O(o)?ie(o.client_id):void 0;if(i===void 0)throw new q("server_error","App registration returned no client_id");return i}var ld=e=>td("sha256").update(e,"ascii").digest("base64url"),$r=()=>nd(32).toString("base64url");function wi(){let e=$r();return{verifier:e,challenge:ld(e)}}function vi(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",id),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function Nr(e,t,n,r=_t){let{res:o,body:i}=await Ir(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!o.ok)throw gi("The token request",o.status,i);let s=O(i)?ie(i.access_token):void 0,a=O(i)?ie(i.refresh_token):void 0;if(!O(i)||s===void 0||a===void 0)throw new q("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:i.expires_in}}var hi=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(fi(n.kind,n.heading,n.text))},dd={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},ud={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},pd={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},fd=e=>{try{return new URL(e??"/",`http://${hn}`)}catch{return}};async function xi(e){let t=e.timeoutMs??ad,n,r=new Promise((h,y)=>{n={resolve:h,reject:y}});r.catch(()=>{});let o=!1,i,s=rd((h,y)=>{let f=fd(h.url);if(o||h.method!=="GET"||f?.pathname!==Tr){y.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let u=f.searchParams;if(u.get("state")!==e.state){hi(y,400,pd);return}let w=u.get("error"),k=u.get("error_description"),_=u.get("code")??"",P=w!==null?new q(w,`Kizen denied the sign-in (${w}${k?`: ${k}`:""})`):_?void 0:new q("invalid_callback","The sign-in callback had no authorization code");hi(y,P?400:200,P?ud:dd),c(P,_)}),a=()=>(i??=new Promise(h=>{clearTimeout(g),s.close(()=>{h()}),s.closeAllConnections()}),i);function c(h,y=""){o||(o=!0,h?n.reject(h):n.resolve({code:y}),a())}await new Promise((h,y)=>{s.once("error",y),s.listen(0,hn,()=>{s.off("error",y),h()})});let g=setTimeout(()=>{c(new q("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),m=s.address();return{port:m.port,redirectUri:`http://${hn}:${String(m.port)}${Tr}`,result:r,close:a}}function ki(e){let[t,n]=mi==="darwin"?["open",[e]]:mi==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=ed(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var le=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var At="APPBUILDER_BUSINESS",Tt="APPBUILDER_USER";function It(e,t){if(e.business!==void 0)return{ok:!0,request:{business:e.business,user:e.user,source:"flags"}};if(e.user!==void 0)return{ok:!1,message:"--user only applies with --business."};let n=t[At]||void 0,r=t[Tt]||void 0;return n===void 0?r===void 0?{ok:!0,request:void 0}:{ok:!1,message:`${Tt} only applies with ${At}.`}:{ok:!0,request:{business:n,user:r,source:"env"}}}var md="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function Ci(e,t){let n=e.credentials!==void 0||e.profile!==void 0;if(n&&e.env!==void 0)return{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."};if(n&&(e.business!==void 0||e.user!==void 0))return{ok:!1,message:`${e.business===void 0?"--user":"--business"} selects a saved sign-in account, so it can't be combined with -c or --profile.`};if(e.credentials!==void 0)return{ok:!0,selection:{kind:"api-key",credentials:e.credentials}};if(e.profile!==void 0)return{ok:!0,selection:{kind:"api-key",profile:e.profile}};let r=It(e,t);return r.ok?{ok:!0,selection:{kind:"oauth",...e.env!==void 0&&{env:e.env},...r.request!==void 0&&{account:r.request}}}:r}var Si=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${le(e)} to use the API key.`}`,Pi=e=>`${e} ${md}`;import{mkdir as Ei,readFile as hd,readdir as gd,writeFile as _i}from"fs/promises";import{homedir as yd}from"os";import{dirname as bd,join as gn}from"path";var W=["go","fmo","staging","integration","test1"];function $t(e){return typeof e=="string"?e.trim():""}function Nt(e){return{apiKey:$t(e.apiKey),userId:$t(e.userId),businessId:$t(e.businessId)}}var ye=gn(yd(),".kizenappbuilder"),He=gn(ye,"credentials.json"),Ke="credentials",Dt=e=>W.includes(e),wd=e=>`Unknown --env "${e}". Use one of: ${W.join(", ")}.`,ot=e=>Dt(e)?{environment:e}:{message:wd(e)};function vd(e){return typeof e=="string"?e.trim():e}function xd(e){return Dt(e)?"explicit":e==null||e===""?"missing":"invalid"}function kd(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=vd(t.environment);return{credentials:{...Nt(t),environment:Dt(n)?n:"go"},environmentSource:xd(n)}}async function yn(e){let t=await hd(e,"utf-8");return kd(JSON.parse(t))}async function Ve(e){return(await yn(e)).credentials}async function se(){try{return await Ve(He)}catch{return null}}async function Cd(e){await Ei(bd(He),{recursive:!0,mode:448}),await _i(He,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function Ai(e){return gn(ye,`${e}.json`)}async function We(){let e=[{name:Ke,path:He,isDefault:!0}];try{let t=await gd(ye);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Ke&&e.push({name:r,path:gn(ye,n),isDefault:!1})}}catch{}return e}async function Ti(e,t){if(e===Ke){await Cd(t);return}await Ei(ye,{recursive:!0,mode:448}),await _i(Ai(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ie(e){try{return await Ve(Ai(e))}catch{return null}}async function Ii(){let e=await We(),t=await Promise.all(e.map(n=>yn(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}var Sd="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",Pd="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",Ed=e=>ke(e,"Kizen rejected the signed-in session.",{again:!0}).message,_d="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",Ad={authFailed:Sd,forbidden:Pd},Td=100,Id=new Set(["detail","non_field_errors"]),Z=class extends Error{kind;status;hint;constructor(t,n,r={}){super(n),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint}},Rt=encodeURIComponent,Ot=(e,t)=>t===void 0?`/dashboards/${Rt(e)}/dashlet`:`/dashboards/${Rt(e)}/dashlet/${Rt(t)}`;function Dr(e,t,n){let r=o=>{n.push(t===""?o:`${t}: ${o}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let o=e.filter(i=>typeof i=="string"&&i.trim()!==""||typeof i=="number"||typeof i=="boolean");o.length>0&&r(o.map(String).join(" "));for(let i of e)typeof i=="object"&&i!==null&&Dr(i,t,n);return}if(O(e))for(let[o,i]of Object.entries(e)){let s=t===""&&Id.has(o)?"":t===""?o:`${t}.${o}`;Dr(i,s,n)}}function $d(e){if(typeof e!="object"||e===null)return;let t=[];return Dr(e,"",t),t.length>0?t.join("; "):void 0}async function Nd(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 Dd(e,t,n,r,o){let i=$d(r),s=`${e} ${t} failed with ${String(n)}${i===void 0?"":`: ${i}`}`;return n===401?new Z("auth_failed",s,{status:n,hint:o.authFailed}):n===403?new Z("forbidden",s,{status:n,hint:o.forbidden}):n===404?new Z("not_found",s,{status:n}):new Z("api_error",s,{status:n})}function $i(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(O(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new Z("api_error",`${e} ${t} returned an unexpected response shape`)}var bn=e=>O(e)?e:{};function Ni(e){let t=bn(e);return{business:bn(t.business),team:bn(t.team)}}var Rd=new Map([["login_required","auth_failed"],["network_error","network_error"]]);function Od(e,t){let n=oe(e),r=e instanceof q?Rd.get(e.code):void 0;return r===void 0?new Z("api_error",`Couldn't refresh the ${t} session: ${n}`):new Z(r,n)}function Bt(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??_r[n],o=e.bearer?{authFailed:Ed(n),forbidden:_d}:Ad,i=m=>{throw Od(m,n)},s=async()=>{if(!e.bearer){let{apiKey:y,userId:f,businessId:u}=e.credentials;return{headers:{"X-API-KEY":y,"X-USER-ID":f,"X-BUSINESS-ID":u}}}let{bearer:m}=e,h=await m.getAccessToken().catch(i);return{headers:{Authorization:`Bearer ${h}`},retry:async()=>({Authorization:`Bearer ${await m.refreshAccessToken(h).catch(i)}`})}},a=async(m,h,y)=>{let f=/^https?:\/\//.test(h)?h:`${r}${h}`,u=f.startsWith(r)?f.slice(r.length):f,w=async v=>{let l={...v,Accept:"application/json"},d={method:m,headers:l};y!==void 0&&(l["Content-Type"]="application/json",d.body=JSON.stringify(y));try{return await t(f,d)}catch(p){throw new Z("network_error",`Couldn't reach Kizen at ${r}: ${Me(p)}${pn()==="unavailable"?` ${un}`:""}`)}},{headers:k,retry:_}=await s(),P=await w(k);P.status===401&&_&&(await P.body?.cancel().catch(()=>{}),P=await w(await _()));let C,T;try{({text:C,json:T}=await Nd(P))}catch(v){throw new Z("network_error",`${m} ${u}: couldn't read the response: ${Me(v)}. The request may have been applied; check Kizen before retrying.`,{status:P.status})}if(!P.ok)throw Dd(m,u,P.status,T,o);if(T===void 0&&C!=="")throw new Z("api_error",`${m} ${u} returned a response that is not JSON`,{status:P.status});return T},c=m=>{let h=new URL(r),y=new URL(m,h.origin);if(y.protocol=h.protocol,y.port=h.port,y.username="",y.password="",y.hash="",y.origin!==h.origin)throw new Z("api_error",`GET /custom-objects pagination pointed at an unexpected location ${y.origin}${y.pathname}`);return y.toString()},g;return{async listDashboards(m,h){let y=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:m});h!==void 0&&y.set("custom_object_id",h);let f=`/dashboards/mine?${y.toString()}`;return $i("GET",f,await a("GET",f)).results},async listCustomObjects(){let m=[],h=new Set,y="/custom-objects?page_size=200";for(;y!==void 0&&!h.has(y)&&h.size<Td;){h.add(y);let f=$i("GET",y,await a("GET",y));m.push(...f.results),y=typeof f.next=="string"&&f.next!==""?c(f.next):void 0}return m},async getCustomObject(m){let h=`/custom-objects/${Rt(m)}`,y=await a("GET",h);if(!O(y)||typeof y.id!="string"||typeof y.fetch_url!="string")throw new Z("api_error",`GET ${h} returned an unexpected response shape`);return y},async getIdentity(){let m=await a("GET","/auth/bootstrap"),{business:h,team:y}=Ni(m),f=ie(h.id),u=ie(y.user);if(f===void 0||u===void 0)throw new Z("api_error","GET /auth/bootstrap returned an unexpected response shape");return g=m,{userId:u,businessId:f,businessName:ie(h.name),fullName:ie(y.full_name),email:ie(y.email)}},async getClientObjectId(){let m=g??await a("GET","/auth/bootstrap"),{business:h}=Ni(m);return ie(bn(h.client_object).id)??null},async getDashboard(m){return await a("GET",`/dashboards/${Rt(m)}`)},async createDashlet(m,h){return await a("POST",Ot(m),h)},async updateDashlet(m,h,y){return await a("PATCH",Ot(m,h),y)}}}var Bd=6e4,Di=(e,t)=>fetch(e,t),Ri=()=>Date.now(),Oi=(e,t,n)=>({store:e,fetch:Di,now:Ri,print:t,openBrowser:ki,startLoopbackServer:xi,identify:n}),Fd=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(ke(e,`Kizen rejected the new ${e} sign-in.`))}),Ft=e=>ke(e,`You're not signed in to ${e}.`),jd=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),Bi=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ld=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function zd(e,t,n,r){let{verifier:o,challenge:i}=wi(),s=$r(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=vi(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:i});n.print(r),n.print(c),n.openBrowser(c);let{code:g}=await a.result;return await Nr(e.tokenEndpoint,{grant_type:"authorization_code",code:g,redirect_uri:a.redirectUri,client_id:t,code_verifier:o},n.fetch)}finally{await a.close()}}async function Rr(e,t,n={}){let r=Ld(e,n.interactive??!0),o=await yi(ze(e),t.fetch),i=await t.store.readClientId(o.issuer),s=i??await bi(o,t.fetch);i===void 0&&await t.store.writeClientId(o.issuer,s);let a;try{a=await zd(o,s,t,r)}catch(h){throw h instanceof q&&h.code==="timeout"&&i!==void 0?(await t.store.forgetClientId(o.issuer),new q("timeout",`${h.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${xe(e)}\` again.`)):h}let c=await t.identify(Fd(e,a.accessToken)),g={businessId:c.businessId,userId:c.userId},m=Bi({environment:e,...g,...jd(c),issuer:o.issuer,clientId:s,tokenEndpoint:o.tokenEndpoint},a,t.now());if(await t.store.writeSession(m),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,g)===null)throw Ft(e);return m}if(await t.store.setCurrent(e,g),await t.store.readSession(e)===null)throw Ft(e);return m}async function Fi(e,t,n){try{await n.identify(n.provider)}catch(o){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw o}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw Ft(e);return r}function Md(e,t){let n,r=t.account,o,i=m=>m.expiresAt-t.now()>Bd,s=m=>{if(m===null)throw Ft(e);return m},a=async()=>r!==void 0?s(await t.store.readAccount(e,r)):(o??=t.store.readSession(e).then(m=>{let h=s(m);return r={businessId:h.businessId,userId:h.userId},h}).finally(()=>{o=void 0}),o),c=async(m,h)=>{let y=await a();if(y.accessToken!==m&&i(y))return y.accessToken;let f=h??t.now()+(t.requestTimeoutMs??_t),u=async()=>{let P=await a();return{stored:P,rotated:P.refreshToken!==y.refreshToken}},w=f-t.now();if(w<=0)return y.accessToken;let k;try{k=await Nr(y.tokenEndpoint,{grant_type:"refresh_token",refresh_token:y.refreshToken,client_id:y.clientId},t.fetch,w)}catch(P){if(P instanceof q&&(P.code==="invalid_grant"||P.code==="invalid_client")){let{stored:C,rotated:T}=await u();if(T)return i(C)||h!==void 0?C.accessToken:c(C.accessToken,f);if(await t.store.deleteSession(e,y)&&P.code==="invalid_client")try{await t.store.readClientId(y.issuer)===y.clientId&&await t.store.forgetClientId(y.issuer)}catch{}throw ke(e,`The ${e} session is no longer valid.`)}throw P}let _=Bi(y,k,t.now());if(await t.store.commitRefresh(_,y.refreshToken)==="gone")throw Ft(e);return _.accessToken},g=m=>(n??=c(m).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let m=await a();return i(m)?m.accessToken:g(m.accessToken)},refreshAccessToken:g}}var wn=(e,t,n={})=>Md(e,{store:t,now:Ri,...n,fetch:n.fetch??Di}),Ud=`You're not signed in. Run \`${xe(Ue)}\` (add \`--env <env>\` to sign in to an environment other than ${Ue}).`;async function jt(e,t){if(e!==void 0){let{environment:o,message:i}=ot(e);return o===void 0?{ok:!1,problem:"unknown_environment",message:i}:{ok:!0,environment:o}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:Ud}:{ok:!0,environment:r}}import{randomBytes as Br}from"crypto";import{chmod as Hd,mkdir as Kd,open as Mi,readdir as Vd,readFile as vn,rename as ji,rm as Fr,stat as Ui,unlink as Lt}from"fs/promises";import{join as yt}from"path";import{setTimeout as Wd}from"timers/promises";var qd="clients.json",Gd=10*6e4,Jd={waitMs:2e3,staleMs:3e4,pollMs:25};async function Yd(e,{waitMs:t,staleMs:n,pollMs:r}){let o=Date.now()+t;for(;;){let i;try{i=await Mi(e,"wx",384)}catch(a){if(!Te(a,"EEXIST"))return;try{let c=await fe(Ui(e));if(c===void 0)continue;if(Date.now()-c.mtimeMs>n){await fe(Lt(e));continue}}catch{return}if(Date.now()>=o)return;await Wd(r);continue}let s=Br(16).toString("hex");try{await i.writeFile(s,"utf-8")}catch{s=void 0}try{await i.close()}catch{s=void 0}return s===void 0&&await Fr(e,{force:!0}).catch(()=>{}),s}}async function Xd(e,t,n){let r=await Yd(e,t);try{return{value:await n(),held:r!==void 0}}finally{if(r!==void 0)try{await fe(vn(e,"utf-8"))===r&&await fe(Lt(e))}catch{}}}var Zd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Li=e=>typeof e=="string"&&Zd.test(e),xn=e=>O(e)&&Li(e.businessId)&&Li(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,it=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,st=e=>{if(xn(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function zi(e){let t;try{t=JSON.parse(e)}catch{return}return xn(t)}var Or=e=>typeof e=="string"?e:void 0;function Qd(e,t){let n=xn(e);return!O(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:Or(e.businessName),fullName:Or(e.fullName),email:Or(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function Ce(e=ye,t={}){let n=yt(e,"oauth"),r={...Jd,...t.lock},o=l=>yt(n,`${l}.json`),i=(l,d)=>yt(n,`${l}.${st(d)}.json`),s=(l,d)=>yt(n,`${l}.${st(d)}.lock`),a=async(l,d,p)=>(await Xd(s(l,d),r,p)).value,c=yt(n,qd),g=(l,d)=>{let p=`${l}.`;if(!d.startsWith(p)||!d.endsWith(".json"))return;let b=d.slice(p.length,-5).split(".");if(b.length!==2)return;let[x,S]=b;return xn({businessId:x,userId:S})},m=async()=>await fe(Vd(n))??[],h=async()=>{await Kd(n,{recursive:!0,mode:448}),await Hd(n,448)},y=async(l,d)=>{await h();let p=`${l}.${Br(6).toString("hex")}.tmp`;try{let b=await Mi(p,"wx",384);try{await b.writeFile(JSON.stringify(d,null,2),"utf-8"),await b.sync()}finally{await b.close()}await ji(p,l)}catch(b){throw await Fr(p,{force:!0}),b}},f=(l,d)=>ke(l,`The saved ${l} session at ${d} can't be read.`,{again:!0}),u=async l=>{try{let d=new RegExp(`^${l}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let p of await m()){let b=d.exec(p)?.[1];b!==void 0&&Date.now()-Number(b)>Gd&&await fe(Lt(yt(n,p)));let x=p.endsWith(".lock")?g(l,`${p.slice(0,-5)}.json`):void 0;if(x!==void 0){let S=s(l,x),E=await fe(Ui(S));E!==void 0&&Date.now()-E.mtimeMs>r.staleMs&&await fe(Lt(S))}}}catch{}},w=async()=>{let l;try{l=JSON.parse(await fe(vn(c,"utf-8"))??"{}")}catch(d){if(d instanceof SyntaxError)return{};throw d}return O(l)?l:{}},k=async(l,d)=>{try{return await fe(vn(d,"utf-8"))}catch{throw f(l,d)}},_=async(l,d)=>{let p=i(l,d),b=await k(l,p);if(b===void 0)return null;try{let x=Qd(JSON.parse(b),l);if(x!==null&&it(x,d))return x}catch{}throw f(l,p)},P=async l=>{let d=o(l),p=await k(l,d);if(p===void 0)return;let b=zi(p);if(b===void 0)throw f(l,d);return b},C=async l=>{let d=await P(l);return d===void 0?null:_(l,d)},T=async l=>{let d=o(l),p=`${d}.${String(Date.now())}-${Br(6).toString("hex")}.signout`;if(await fe(ji(d,p).then(()=>!0))===!0)try{return{account:zi(await vn(p,"utf-8"))}}catch{return{account:void 0}}finally{await Fr(p,{force:!0})}},v=(l,d)=>a(l,d,async()=>await fe(Lt(i(l,d)).then(()=>!0))??!1);return{dir:n,sessionPath:o,accountPath:i,readSession:C,readAccount:_,async listAccounts(l){let d;try{d=await P(l)}catch{}let p=(await m()).map(S=>g(l,S)).filter(S=>S!==void 0),b=await Promise.all(p.map(async S=>{let E;try{let $=await _(l,S);if($===null)return;E=$}catch($){if(!($ instanceof q&&$.code==="login_required"))throw $}return{account:S,session:E,current:d!==void 0&&it(d,S)}})),x=S=>(S.session?.businessName??S.account.businessId).toLowerCase();return b.filter(S=>S!==void 0).sort((S,E)=>x(S).localeCompare(x(E))||st(S.account).localeCompare(st(E.account)))},async writeSession(l){await y(i(l.environment,l),l)},async commitRefresh(l,d){let{environment:p}=l;return a(p,l,async()=>{let b=await _(p,l);return b===null?"gone":b.refreshToken!==d?"rotated":(await y(i(p,l),l),"written")})},async setCurrent(l,d){let{businessId:p,userId:b}=d;await y(o(l),{businessId:p,userId:b}),await u(l)},async deleteSession(l,d){return v(l,d)},async signOut(l){let d=await T(l),p=d!==void 0;return d?.account!==void 0&&(p=await v(l,d.account)),await u(l),p},async removeAccount(l,d){let p=!1,b;try{b=await P(l)}catch{}b!==void 0&&it(b,d)&&(p=await T(l)!==void 0);let x=await v(l,d);return await u(l),{removed:x,current:p}},async signOutAll(l){let d=await T(l),p=d!==void 0&&d.account===void 0,b=0;for(let x of await m()){let S=g(l,x);S!==void 0&&await v(l,S)&&(b+=1,p||=d?.account!==void 0&&it(d.account,S))}return await u(l),{signedIn:p,removed:b}},async listSessions(){return(await Promise.all(W.map(async d=>{try{return await C(d)===null?void 0:d}catch(p){if(p instanceof q&&p.code==="login_required")return d;throw p}}))).filter(d=>d!==void 0)},async readClientId(l){let d=(await w())[l];return O(d)?ie(d.clientId):void 0},async writeClientId(l,d){await y(c,{...await w(),[l]:{clientId:d}})},async forgetClientId(l){let d=await w();l in d&&await y(c,Object.fromEntries(Object.entries(d).filter(([p])=>p!==l)))}}}var eu=5e3,tu=(e,t)=>e.isTTY===!0&&t.isTTY===!0;function Ki(e=Ce(),t){let n=(i,s)=>wn(i,e,s),r=i=>{process.stderr.write(i)},o=i=>Bt({bearer:i}).getIdentity();return{store:e,loginDeps:Oi(e,i=>{r(`${i}
|
|
86
|
-
`)},o),identify:o,tokenProvider:
|
|
85
|
+
`.trim().replace(/\n\s*/g,"");function Bl(e,t,n){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Kizen App Builder</title><style>${Vh}</style></head><body><main>${Mh}<section class="card ${e}" data-status="${e}"><div class="status">${Uh(e)}</div><h1>${t}</h1><p>${n}</p></section></main></body></html>`}var xi="127.0.0.1",Ds="/callback",Jh=`http://${xi}${Ds}`,qh="read write offline_access",Yh="Kizen App Builder CLI",Zh=300*1e3,Ht="go",gr=2e4,ue=class extends Error{constructor(n,r){super(r);this.code=n;this.name="OAuthError"}code},Ml=["ENOSPC","EDQUOT"],zl=["EPERM","EACCES","EROFS",...Ml],Vt=class extends ue{hint;constructor(t,n,r){let i=Ml.includes(r);super("session_store_unwritable",i?`Can't write to ${t} (${r}): the disk is full or over quota. appbuilder keeps its sign-in sessions there.`:`Can't write to ${t} (${r}), where appbuilder keeps its sign-in sessions.`),this.name="SessionStoreUnwritableError",this.hint=i?`Free some disk space (or quota) for ${n}, then run the command again.`:`appbuilder needs write access to ${n} to keep you signed in. Under Codex, re-run the command with sandbox_permissions: "require_escalated" (prefix_rule: ["appbuilder"]). Under the Claude Code sandbox, add "appbuilder *" to sandbox.excludedCommands in your user settings (~/.claude/settings.json); allowing writes to ${n} alone isn't enough, since appbuilder also needs network access the sandbox blocks.`}},ut=e=>e===Ht?"appbuilder login":`appbuilder login --env ${e}`,dt=(e,t,n={})=>new ue("login_required",`${t} Run \`${ut(e)}\` to sign in${n.again===!0?" again":""}.`),Xh=e=>{try{return e===""?void 0:JSON.parse(e)}catch{return}};async function Ls(e,t,n,r){let i=AbortSignal.timeout(r);try{let o=await e(t,{...n,headers:{Accept:"application/json",...n.headers},signal:i});return{res:o,body:Xh(await o.text())}}catch(o){let s=i.aborted?`timed out after ${String(Math.round(r/1e3))}s`:xe(o);throw new ue("network_error",`Couldn't reach ${new URL(t).origin}: ${s}`)}}function Ul(e,t,n){let r=F(n)?n:{},i=Oe(r.error);if(i!==void 0){let o=Oe(r.error_description);return new ue(i,`${e} failed (${i}${o===void 0?"":`: ${o}`})`)}return new ue("server_error",`${e} failed with HTTP ${String(t)}`)}async function Vl(e,t,n=gr){let r=`${e}/.well-known/oauth-authorization-server`,i=a=>new ue("server_error",`OAuth discovery at ${r} ${a}`),{res:o,body:s}=await Ls(t,r,{},n);if(!o.ok)throw i(`failed with HTTP ${String(o.status)}`);if(!F(s))throw i("didn't return valid JSON");if(s.issuer!==e)throw i(`returned issuer ${typeof s.issuer=="string"?JSON.stringify(s.issuer):"none"}, expected ${e}`);return{issuer:e,authorizationEndpoint:s.authorization_endpoint,tokenEndpoint:s.token_endpoint,registrationEndpoint:s.registration_endpoint}}async function Hl(e,t,n=gr){let{res:r,body:i}=await Ls(t,e.registrationEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Yh,redirect_uris:[Jh],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"})},n);if(!r.ok)throw Ul("App registration",r.status,i);let o=F(i)?Oe(i.client_id):void 0;if(o===void 0)throw new ue("server_error","App registration returned no client_id");return o}var Qh=e=>Kh("sha256").update(e,"ascii").digest("base64url"),Bs=()=>Wh(32).toString("base64url");function Kl(){let e=Bs();return{verifier:e,challenge:Qh(e)}}function Wl(e,t){let n=new URL(e.authorizationEndpoint);return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",t.clientId),n.searchParams.set("redirect_uri",t.redirectUri),n.searchParams.set("scope",qh),n.searchParams.set("state",t.state),n.searchParams.set("code_challenge",t.codeChallenge),n.searchParams.set("code_challenge_method","S256"),n.toString()}async function Fs(e,t,n,r=gr){let{res:i,body:o}=await Ls(n,e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t).toString()},r);if(!i.ok)throw Ul("The token request",i.status,o);let s=F(o)?Oe(o.access_token):void 0,a=F(o)?Oe(o.refresh_token):void 0;if(!F(o)||s===void 0||a===void 0)throw new ue("server_error","The token endpoint returned an unexpected response");return{accessToken:s,refreshToken:a,expiresIn:o.expires_in}}var jl=(e,t,n)=>{e.writeHead(t,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",Connection:"close"}).end(Bl(n.kind,n.heading,n.text))},ey={kind:"success",heading:"You\u2019re signed in",text:"Sign-in complete. You can close this window."},ty={kind:"error",heading:"Sign-in failed",text:"Sign-in failed. Return to the terminal for details. You can close this window."},ny={kind:"error",heading:"Outdated link",text:"This sign-in link is out of date. Use the latest link from the terminal."},ry=e=>{try{return new URL(e??"/",`http://${xi}`)}catch{return}};async function Gl(e){let t=e.timeoutMs??Zh,n,r=new Promise((u,f)=>{n={resolve:u,reject:f}});r.catch(()=>{});let i=!1,o,s=Gh((u,f)=>{let g=ry(u.url);if(i||u.method!=="GET"||g?.pathname!==Ds){f.writeHead(404,{"Content-Type":"text/plain",Connection:"close"}).end("Not found");return}let m=g.searchParams;if(m.get("state")!==e.state){jl(f,400,ny);return}let p=m.get("error"),h=m.get("error_description"),b=m.get("code")??"",y=p!==null?new ue(p,`Kizen denied the sign-in (${p}${h?`: ${h}`:""})`):b?void 0:new ue("invalid_callback","The sign-in callback had no authorization code");jl(f,y?400:200,y?ty:ey),c(y,b)}),a=()=>(o??=new Promise(u=>{clearTimeout(l),s.close(()=>{u()}),s.closeAllConnections()}),o);function c(u,f=""){i||(i=!0,u?n.reject(u):n.resolve({code:f}),a())}await new Promise((u,f)=>{s.once("error",f),s.listen(0,xi,()=>{s.off("error",f),u()})});let l=setTimeout(()=>{c(new ue("timeout",`Timed out after ${String(Math.round(t/1e3))}s waiting for the browser sign-in`))},t),d=s.address();return{port:d.port,redirectUri:`http://${xi}:${String(d.port)}${Ds}`,result:r,close:a}}function Jl(e){let[t,n]=Fl==="darwin"?["open",[e]]:Fl==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{let r=Hh(t,n,{stdio:"ignore",detached:!0});r.on("error",()=>{}),r.unref()}catch{}}var ge=e=>/^[\w@%+:,./-][\w@%+=:,./-]*$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`;var hr="APPBUILDER_BUSINESS",yr="APPBUILDER_USER";function bn(e,t){if(e.business!==void 0)return{ok:!0,request:{business:e.business,user:e.user,source:"flags"}};if(e.user!==void 0)return{ok:!1,message:"--user only applies with --business."};let n=t[hr]||void 0,r=t[yr]||void 0;return n===void 0?r===void 0?{ok:!0,request:void 0}:{ok:!1,message:`${yr} only applies with ${hr}.`}:{ok:!0,request:{business:n,user:r,source:"env"}}}var iy="To use an API key instead (deprecated), pass --profile <name> or -c <path>.";function ql(e,t){let n=e.credentials!==void 0||e.profile!==void 0;if(n&&e.env!==void 0)return{ok:!1,message:"--env selects a sign-in session, so it can't be combined with -c or --profile."};if(n&&(e.business!==void 0||e.user!==void 0))return{ok:!1,message:`${e.business===void 0?"--user":"--business"} selects a saved sign-in account, so it can't be combined with -c or --profile.`};if(e.credentials!==void 0)return{ok:!0,selection:{kind:"api-key",credentials:e.credentials}};if(e.profile!==void 0)return{ok:!0,selection:{kind:"api-key",profile:e.profile}};let r=bn(e,t);return r.ok?{ok:!0,selection:{kind:"oauth",...e.env!==void 0&&{env:e.env},...r.request!==void 0&&{account:r.request}}}:r}var Yl=e=>`Ignoring the API-key profile ${JSON.stringify(e)} pinned in .kizenapp/config.json and using your sign-in session.${/[\x00-\x1f\x7f]/.test(e)?"":` Pass --profile ${ge(e)} to use the API key.`}`,Zl=e=>`${e} ${iy}`;import{mkdir as Xl,readFile as oy,readdir as sy,writeFile as Ql}from"fs/promises";import{homedir as ay}from"os";import{dirname as cy,join as Pi}from"path";var pe=["go","fmo","staging","integration","test1"];function br(e){return typeof e=="string"?e.trim():""}function wr(e){return{apiKey:br(e.apiKey),userId:br(e.userId),businessId:br(e.businessId)}}var nt=Pi(ay(),".kizenappbuilder"),Kt=Pi(nt,"credentials.json"),Wt="credentials",vr=e=>pe.includes(e),ly=e=>`Unknown --env "${e}". Use one of: ${pe.join(", ")}.`,wn=e=>vr(e)?{environment:e}:{message:ly(e)};function uy(e){return typeof e=="string"?e.trim():e}function dy(e){return vr(e)?"explicit":e==null||e===""?"missing":"invalid"}function py(e){if(typeof e!="object"||e===null)throw new Error("Credentials must be a JSON object");let t=e,n=uy(t.environment);return{credentials:{...wr(t),environment:vr(n)?n:"go"},environmentSource:dy(n)}}async function Ci(e){let t=await oy(e,"utf-8");return py(JSON.parse(t))}async function Gt(e){return(await Ci(e)).credentials}async function De(){try{return await Gt(Kt)}catch{return null}}async function my(e){await Xl(cy(Kt),{recursive:!0,mode:448}),await Ql(Kt,JSON.stringify(e,null,2),{encoding:"utf-8",mode:384})}function eu(e){return Pi(nt,`${e}.json`)}async function Jt(){let e=[{name:Wt,path:Kt,isDefault:!0}];try{let t=await sy(nt);for(let n of t){if(!n.endsWith(".json"))continue;let r=n.slice(0,-5);r!==Wt&&e.push({name:r,path:Pi(nt,n),isDefault:!1})}}catch{}return e}async function tu(e,t){if(e===Wt){await my(t);return}await Xl(nt,{recursive:!0,mode:448}),await Ql(eu(e),JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}async function Ct(e){try{return await Gt(eu(e))}catch{return null}}async function nu(){let e=await Jt(),t=await Promise.all(e.map(n=>Ci(n.path).then(()=>!0,()=>!1)));return e.filter((n,r)=>t[r]===!0)}var iu="APPBUILDER_NO_INTERACTIVE",ru=e=>e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false";function fy(e){return ru(e.CI)||e.CODEX_CI!==void 0||e.CLAUDECODE!==void 0||e.TERM==="dumb"||ru(e[iu])}function gy({stdin:e,stdout:t,json:n,noInteractive:r,env:i}){return e.isTTY===!0&&t.isTTY===!0&&n!==!0&&r!==!0&&!fy(i)}var pt=(e={})=>gy({stdin:process.stdin,stdout:process.stdout,env:process.env,...e}),mt=`run headless even at a terminal (also $${iu})`;function Ae(e){let{interactive:t,...n}=e;return{noInteractive:t===!1,options:n}}var hy="The API key is invalid for this business, or the user id doesn't match. Check the credentials file's apiKey, userId and businessId.",yy="The API key's user needs the Standard API Keys permission and edit access to this dashboard. Homepages also need the Customize Homepages permission.",by=e=>dt(e,"Kizen rejected the signed-in session.",{again:!0}).message,wy="The signed-in user needs edit access to this dashboard. Homepages also need the Customize Homepages permission.",vy={authFailed:hy,forbidden:yy},ky=100,Ay=new Set([301,302,303,307,308]),xy=5,Py=new Set(["detail","non_field_errors"]),q=class extends Error{kind;status;hint;details;constructor(t,n,r={}){super(n,r.cause===void 0?void 0:{cause:r.cause}),this.name="KizenApiError",this.kind=t,this.status=r.status,this.hint=r.hint,this.details=r.details}},kr=encodeURIComponent,Ar=(e,t)=>t===void 0?`/dashboards/${kr(e)}/dashlet`:`/dashboards/${kr(e)}/dashlet/${kr(t)}`;function js(e,t,n){let r=i=>{n.push(t===""?i:`${t}: ${i}`)};if(typeof e=="string"){e.trim()!==""&&r(e);return}if(typeof e=="number"||typeof e=="boolean"){r(String(e));return}if(Array.isArray(e)){let i=e.filter(o=>typeof o=="string"&&o.trim()!==""||typeof o=="number"||typeof o=="boolean");i.length>0&&r(i.map(String).join(" "));for(let o of e)typeof o=="object"&&o!==null&&js(o,t,n);return}if(F(e))for(let[i,o]of Object.entries(e)){let s=t===""&&Py.has(i)?"":t===""?i:`${t}.${i}`;js(o,s,n)}}function Cy(e){if(typeof e!="object"||e===null)return;let t=[];return js(e,"",t),t.length>0?t.join("; "):void 0}async function ou(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 su(e,t,n,r,i){let o=Cy(r),s=`${e} ${t} failed with ${String(n)}${o===void 0?"":`: ${o}`}`,a=r;return n===401?new q("auth_failed",s,{status:n,hint:i.authFailed,details:a}):n===403?new q("forbidden",s,{status:n,hint:i.forbidden,details:a}):n===404?new q("not_found",s,{status:n,details:a}):new q("api_error",s,{status:n,details:a})}function au(e,t,n){if(Array.isArray(n))return{results:n,next:null};if(F(n)&&Array.isArray(n.results))return{results:n.results,next:n.next};throw new q("api_error",`${e} ${t} returned an unexpected response shape`)}var Si=e=>F(e)?e:{};function cu(e){let t=Si(e);return{business:Si(t.business),team:Si(t.team)}}var Sy=new Map([["login_required","auth_failed"],["network_error","network_error"],["session_store_unwritable","session_store_unwritable"]]);function _y(e,t){let n=ke(e),r=e instanceof ue?Sy.get(e.code):void 0;return r===void 0?new q("api_error",`Couldn't refresh the ${t} session: ${n}`,{cause:e}):new q(r,n,{cause:e,...e instanceof Vt&&{hint:e.hint}})}function xr(e){let t=e.fetch??fetch,n=e.bearer?e.bearer.environment:e.credentials.environment,r=e.baseUrl??Os[n],i=new URL(r).origin,o=e.bearer?{authFailed:by(n),forbidden:wy}:vy,s=h=>{throw _y(h,n)},a=async()=>{if(!e.bearer){let{apiKey:y,userId:C,businessId:S}=e.credentials;return{headers:{"X-API-KEY":y,"X-USER-ID":C,"X-BUSINESS-ID":S}}}let{bearer:h}=e,b=await h.getAccessToken().catch(s);return{headers:{Authorization:`Bearer ${b}`},retry:async()=>({Authorization:`Bearer ${await h.refreshAccessToken(b).catch(s)}`})}},c=async(h,b,y,C)=>{let S=async(w,A,_,T)=>{let L={...T,Accept:y},$={method:A,headers:L,redirect:"manual"};_!==void 0&&(L["Content-Type"]=_.contentType,$.body=_.payload);try{return await t(w,$)}catch(V){throw new q("network_error",`Couldn't reach Kizen at ${r}: ${xe(V)}${ki()==="unavailable"?` ${vi}`:""}`)}},x=async w=>{let A=b,_=h,T=C;for(let L=0;;L+=1){let $=await S(A,_,T,w);if($.type==="opaqueredirect")throw new q("api_error",`${h} ${b} was redirected to an unknown location`);let V=Ay.has($.status)?$.headers.get("location"):null;if(V===null)return $;await $.body?.cancel().catch(()=>{});let X;try{X=new URL(V,A)}catch{throw new q("api_error",`${h} ${b} was redirected to an invalid location`,{status:$.status})}if(X.origin!==i)throw new q("api_error",`${h} ${b} was redirected to ${X.origin}, outside the Kizen API; the request was not sent there.`,{status:$.status});if(L>=xy)throw new q("api_error",`${h} ${b} redirected too many times`,{status:$.status});($.status===303||($.status===301||$.status===302)&&_==="POST")&&(_="GET",T=void 0),A=X.toString()}},{headers:v,retry:k}=await a(),P=await x(v);return P.status===401&&k&&(await P.body?.cancel().catch(()=>{}),P=await x(await k())),P},l=(h,b,y,C)=>new q("network_error",`${h} ${b}: couldn't read the response: ${xe(C)}. The request may have been applied; check Kizen before retrying.`,{status:y}),d=h=>{let b=/^https?:\/\//.test(h)?h:`${r}${h}`;return{url:b,path:b.startsWith(r)?b.slice(r.length):b}},u=async(h,b,y)=>{let{url:C,path:S}=d(b),x=await c(h,C,"application/json",y),v,k;try{({text:v,json:k}=await ou(x))}catch(P){throw l(h,S,x.status,P)}if(!x.ok)throw su(h,S,x.status,k,o);if(k===void 0&&v!=="")throw new q("api_error",`${h} ${S} returned a response that is not JSON`,{status:x.status});return k},f=h=>h===void 0?void 0:{contentType:"application/json",payload:JSON.stringify(h)},g=(h,b)=>{if(!b.startsWith("/")||b.startsWith("//"))throw new q("api_error",`${h} ${b}: expected a path under the Kizen API`);return b},m=h=>{let b=new URL(r),y=new URL(h,b.origin);if(y.protocol=b.protocol,y.port=b.port,y.username="",y.password="",y.hash="",y.origin!==b.origin)throw new q("api_error",`GET /custom-objects pagination pointed at an unexpected location ${y.origin}${y.pathname}`);return y.toString()},p;return{async listDashboards(h,b){let y=new URLSearchParams({size:"10000",include_sharing:"true",dashboard_type:h});b!==void 0&&y.set("custom_object_id",b);let C=`/dashboards/mine?${y.toString()}`;return au("GET",C,await u("GET",C)).results},async listCustomObjects(h={}){let b=[],y=new Set,C=`/custom-objects?page_size=200${h.customOnly===!1?"&custom_only=false":""}`;for(;C!==void 0&&!y.has(C)&&y.size<ky;){y.add(C);let S=au("GET",C,await u("GET",C));b.push(...S.results),C=typeof S.next=="string"&&S.next!==""?m(S.next):void 0}return b},async getCustomObject(h){let b=`/custom-objects/${kr(h)}`,y=await u("GET",b);if(!F(y)||typeof y.id!="string"||typeof y.fetch_url!="string")throw new q("api_error",`GET ${b} returned an unexpected response shape`);return y},async getIdentity(){let h=await u("GET","/auth/bootstrap"),{business:b,team:y}=cu(h),C=Oe(b.id),S=Oe(y.user);if(C===void 0||S===void 0)throw new q("api_error","GET /auth/bootstrap returned an unexpected response shape");return p=h,{userId:S,businessId:C,businessName:Oe(b.name),fullName:Oe(y.full_name),email:Oe(y.email)}},async getClientObjectId(){let h=p??await u("GET","/auth/bootstrap"),{business:b}=cu(h);return Oe(Si(b.client_object).id)??null},async getDashboard(h){return await u("GET",`/dashboards/${kr(h)}`)},async createDashlet(h,b){return await u("POST",Ar(h),f(b))},async updateDashlet(h,b,y){return await u("PATCH",Ar(h,b),f(y))},async requestJson(h,b,y){return u(h,g(h,b),f(y))},async postForm(h,b){return u("POST",g("POST",h),{contentType:"application/x-www-form-urlencoded",payload:new URLSearchParams(b).toString()})},async getBinary(h){let{url:b,path:y}=d(g("GET",h)),C=await c("GET",b,"*/*");if(!C.ok){let S;try{({json:S}=await ou(C))}catch(x){throw l("GET",y,C.status,x)}throw su("GET",y,C.status,S,o)}try{return new Uint8Array(await C.arrayBuffer())}catch(S){throw l("GET",y,C.status,S)}}}}var Ey=6e4,lu=(e,t)=>fetch(e,t),uu=()=>Date.now(),du=(e,t,n)=>({store:e,fetch:lu,now:uu,print:t,openBrowser:Jl,startLoopbackServer:Gl,identify:n}),Iy=(e,t)=>({environment:e,getAccessToken:()=>Promise.resolve(t),refreshAccessToken:()=>Promise.reject(dt(e,`Kizen rejected the new ${e} sign-in.`))}),Pr=e=>dt(e,`You're not signed in to ${e}.`),Ty=e=>({businessName:e.businessName,fullName:e.fullName,email:e.email}),pu=(e,t,n)=>({...e,accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:n+t.expiresIn*1e3}),Ny=(e,t)=>t?"Opening your browser to sign in to Kizen. If it does not open, visit:":`A browser window should open for the user to sign in to Kizen ${e}. If it doesn't, give them this URL:`;async function Ry(e,t,n,r){let{verifier:i,challenge:o}=Kl(),s=Bs(),a=await n.startLoopbackServer({state:s,...n.timeoutMs!==void 0&&{timeoutMs:n.timeoutMs}});try{let c=Wl(e,{clientId:t,redirectUri:a.redirectUri,state:s,codeChallenge:o});n.print(r),n.print(c),n.openBrowser(c);let{code:l}=await a.result;return await Fs(e.tokenEndpoint,{grant_type:"authorization_code",code:l,redirect_uri:a.redirectUri,client_id:t,code_verifier:i},n.fetch)}finally{await a.close()}}async function Ms(e,t,n={}){let r=Ny(e,n.interactive??!0);await t.store.probeWritable();let i=await Vl(Ut(e),t.fetch),o=await t.store.readClientId(i.issuer),s=o??await Hl(i,t.fetch);o===void 0&&await t.store.writeClientId(i.issuer,s);let a;try{a=await Ry(i,s,t,r)}catch(u){throw u instanceof ue&&u.code==="timeout"&&o!==void 0?(await t.store.forgetClientId(i.issuer),new ue("timeout",`${u.message}. If the browser showed an error instead of a consent page, the saved app registration was stale; it has been cleared. Run \`${ut(e)}\` again.`)):u}let c=await t.identify(Iy(e,a.accessToken)),l={businessId:c.businessId,userId:c.userId},d=pu({environment:e,...l,...Ty(c),issuer:i.issuer,clientId:s,tokenEndpoint:i.tokenEndpoint},a,t.now());if(await t.store.writeSession(d),n.makeCurrent!==void 0&&!n.makeCurrent(c)){if(await t.store.readAccount(e,l)===null)throw Pr(e);return d}if(await t.store.setCurrent(e,l),await t.store.readSession(e)===null)throw Pr(e);return d}async function mu(e,t,n){try{await n.identify(n.provider)}catch(i){if(await n.store.readAccount(e,t).then(s=>s===null,()=>!1))return;throw i}await n.store.setCurrent(e,t);let r=await n.store.readSession(e);if(r===null)throw Pr(e);return r}function $y(e,t){let n,r=t.account,i,o=d=>d.expiresAt-t.now()>Ey,s=d=>{if(d===null)throw Pr(e);return d},a=async()=>r!==void 0?s(await t.store.readAccount(e,r)):(i??=t.store.readSession(e).then(d=>{let u=s(d);return r={businessId:u.businessId,userId:u.userId},u}).finally(()=>{i=void 0}),i),c=async(d,u)=>{let f=await a();if(f.accessToken!==d&&o(f))return f.accessToken;let g=u??t.now()+(t.requestTimeoutMs??gr),m=async()=>{let y=await a();return{stored:y,rotated:y.refreshToken!==f.refreshToken}},p=g-t.now();if(p<=0)return f.accessToken;await t.store.probeWritable();let h;try{h=await Fs(f.tokenEndpoint,{grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:f.clientId},t.fetch,p)}catch(y){if(y instanceof ue&&(y.code==="invalid_grant"||y.code==="invalid_client")){let{stored:C,rotated:S}=await m();if(S)return o(C)||u!==void 0?C.accessToken:c(C.accessToken,g);if(await t.store.deleteSession(e,f)&&y.code==="invalid_client")try{await t.store.readClientId(f.issuer)===f.clientId&&await t.store.forgetClientId(f.issuer)}catch{}throw dt(e,`The ${e} session is no longer valid.`)}throw y}let b=pu(f,h,t.now());if(await t.store.commitRefresh(b,f.refreshToken)==="gone")throw Pr(e);return b.accessToken},l=d=>(n??=c(d).finally(()=>{n=void 0}),n);return{environment:e,async getAccessToken(){if(n)return n;let d=await a();return o(d)?d.accessToken:l(d.accessToken)},refreshAccessToken:l}}var _i=(e,t,n={})=>$y(e,{store:t,now:uu,...n,fetch:n.fetch??lu}),Oy=`You're not signed in. Run \`${ut(Ht)}\` (add \`--env <env>\` to sign in to an environment other than ${Ht}).`;async function Cr(e,t){if(e!==void 0){let{environment:i,message:o}=wn(e);return i===void 0?{ok:!1,problem:"unknown_environment",message:o}:{ok:!0,environment:i}}let n=await t(),[r]=n;return n.length>1?{ok:!1,problem:"several_sessions",message:`You're signed in to several environments; pass --env <env>: ${n.join(", ")}`}:r===void 0?{ok:!1,problem:"not_signed_in",message:Oy}:{ok:!0,environment:r}}import{randomBytes as Ei}from"crypto";import{chmod as Dy,mkdir as Ly,open as yu,readdir as By,readFile as Ii,rename as fu,rm as Us,stat as bu,unlink as Wn}from"fs/promises";import{dirname as Fy,join as vn}from"path";import{setTimeout as jy}from"timers/promises";var My="clients.json",zy=" ".repeat(4096),Uy=10*6e4,Vy={waitMs:2e3,staleMs:3e4,pollMs:25};async function Hy(e,{waitMs:t,staleMs:n,pollMs:r}){let i=Date.now()+t;for(;;){let o;try{o=await yu(e,"wx",384)}catch(a){if(!He(a,"EEXIST"))return;try{let c=await _e(bu(e));if(c===void 0)continue;if(Date.now()-c.mtimeMs>n){await _e(Wn(e));continue}}catch{return}if(Date.now()>=i)return;await jy(r);continue}let s=Ei(16).toString("hex");try{await o.writeFile(s,"utf-8")}catch{s=void 0}try{await o.close()}catch{s=void 0}return s===void 0&&await Us(e,{force:!0}).catch(()=>{}),s}}async function Ky(e,t,n){let r=await Hy(e,t);try{return{value:await n(),held:r!==void 0}}finally{if(r!==void 0)try{await _e(Ii(e,"utf-8"))===r&&await _e(Wn(e))}catch{}}}var Wy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,gu=e=>typeof e=="string"&&Wy.test(e),Ti=e=>F(e)&&gu(e.businessId)&&gu(e.userId)?{businessId:e.businessId,userId:e.userId}:void 0,kn=(e,t)=>e.businessId===t.businessId&&e.userId===t.userId,An=e=>{if(Ti(e)===void 0)throw new Error("Refusing a session file name built from an invalid account id.");return`${e.businessId}.${e.userId}`};function hu(e){let t;try{t=JSON.parse(e)}catch{return}return Ti(t)}var zs=e=>typeof e=="string"?e:void 0;function Gy(e,t){let n=Ti(e);return!F(e)||n===void 0||e.environment!==t||typeof e.issuer!="string"||typeof e.clientId!="string"||typeof e.tokenEndpoint!="string"||typeof e.accessToken!="string"||typeof e.refreshToken!="string"||typeof e.expiresAt!="number"?null:{environment:t,...n,businessName:zs(e.businessName),fullName:zs(e.fullName),email:zs(e.email),issuer:e.issuer,clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt}}function ft(e=nt,t={}){let n=vn(e,"oauth"),r={...Vy,...t.lock},i=w=>vn(n,`${w}.json`),o=(w,A)=>vn(n,`${w}.${An(A)}.json`),s=(w,A)=>vn(n,`${w}.${An(A)}.lock`),a=async(w,A,_)=>(await Ky(s(w,A),r,_)).value,c=vn(n,My),l=(w,A)=>{let _=`${w}.`;if(!A.startsWith(_)||!A.endsWith(".json"))return;let T=A.slice(_.length,-5).split(".");if(T.length!==2)return;let[L,$]=T;return Ti({businessId:L,userId:$})},d=async()=>await _e(By(n))??[],u=async w=>{try{return await w()}catch(A){let _=zl.find(T=>He(A,T));throw _!==void 0?new Vt(n,Fy(n),_):A}},f=async()=>{await Ly(n,{recursive:!0,mode:448}),await Dy(n,448)},g=async(w,A,_)=>{let T=`${w}.${Ei(6).toString("hex")}.tmp`;try{let L=await yu(T,"wx",384);try{await L.writeFile(A,"utf-8"),await L.sync()}finally{await L.close()}await fu(T,_)}catch(L){throw await Us(T,{force:!0}).catch(()=>{}),L}},m=(w,A)=>u(async()=>{await f(),await g(w,JSON.stringify(A,null,2),w)}),p=()=>u(async()=>{await f();let w=vn(n,`.write-probe.${Ei(6).toString("hex")}`);await g(w,zy,w),await Wn(w)}),h=(w,A)=>dt(w,`The saved ${w} session at ${A} can't be read.`,{again:!0}),b=async w=>{try{let A=new RegExp(`^${w}\\.json\\.([0-9]{1,16})-[0-9a-f]{12}\\.signout$`);for(let _ of await d()){let T=A.exec(_)?.[1];T!==void 0&&Date.now()-Number(T)>Uy&&await _e(Wn(vn(n,_)));let L=_.endsWith(".lock")?l(w,`${_.slice(0,-5)}.json`):void 0;if(L!==void 0){let $=s(w,L),V=await _e(bu($));V!==void 0&&Date.now()-V.mtimeMs>r.staleMs&&await _e(Wn($))}}}catch{}},y=async()=>{let w;try{w=JSON.parse(await _e(Ii(c,"utf-8"))??"{}")}catch(A){if(A instanceof SyntaxError)return{};throw A}return F(w)?w:{}},C=async(w,A)=>{try{return await _e(Ii(A,"utf-8"))}catch{throw h(w,A)}},S=async(w,A)=>{let _=o(w,A),T=await C(w,_);if(T===void 0)return null;try{let L=Gy(JSON.parse(T),w);if(L!==null&&kn(L,A))return L}catch{}throw h(w,_)},x=async w=>{let A=i(w),_=await C(w,A);if(_===void 0)return;let T=hu(_);if(T===void 0)throw h(w,A);return T},v=async w=>{let A=await x(w);return A===void 0?null:S(w,A)},k=async w=>{let A=i(w),_=`${A}.${String(Date.now())}-${Ei(6).toString("hex")}.signout`;if(await u(()=>_e(fu(A,_).then(()=>!0)))===!0)try{return{account:hu(await Ii(_,"utf-8"))}}catch{return{account:void 0}}finally{await Us(_,{force:!0})}},P=(w,A)=>a(w,A,async()=>await u(()=>_e(Wn(o(w,A)).then(()=>!0)))??!1);return{dir:n,sessionPath:i,accountPath:o,readSession:v,readAccount:S,async listAccounts(w){let A;try{A=await x(w)}catch{}let _=(await d()).map($=>l(w,$)).filter($=>$!==void 0),T=await Promise.all(_.map(async $=>{let V;try{let X=await S(w,$);if(X===null)return;V=X}catch(X){if(!(X instanceof ue&&X.code==="login_required"))throw X}return{account:$,session:V,current:A!==void 0&&kn(A,$)}})),L=$=>($.session?.businessName??$.account.businessId).toLowerCase();return T.filter($=>$!==void 0).sort(($,V)=>L($).localeCompare(L(V))||An($.account).localeCompare(An(V.account)))},async writeSession(w){await m(o(w.environment,w),w)},probeWritable:p,async commitRefresh(w,A){let{environment:_}=w;return a(_,w,async()=>{let T=await S(_,w);return T===null?"gone":T.refreshToken!==A?"rotated":(await m(o(_,w),w),"written")})},async setCurrent(w,A){let{businessId:_,userId:T}=A;await m(i(w),{businessId:_,userId:T}),await b(w)},async deleteSession(w,A){return P(w,A)},async signOut(w){let A=await k(w),_=A!==void 0;return A?.account!==void 0&&(_=await P(w,A.account)),await b(w),_},async removeAccount(w,A){let _=!1,T;try{T=await x(w)}catch{}T!==void 0&&kn(T,A)&&(_=await k(w)!==void 0);let L=await P(w,A);return await b(w),{removed:L,current:_}},async signOutAll(w){let A=await k(w),_=A!==void 0&&A.account===void 0,T=0;for(let L of await d()){let $=l(w,L);$!==void 0&&await P(w,$)&&(T+=1,_||=A?.account!==void 0&&kn(A.account,$))}return await b(w),{signedIn:_,removed:T}},async listSessions(){return(await Promise.all(pe.map(async A=>{try{return await v(A)===null?void 0:A}catch(_){if(_ instanceof ue&&_.code==="login_required")return A;throw _}}))).filter(A=>A!==void 0)},async readClientId(w){let A=(await y())[w];return F(A)?Oe(A.clientId):void 0},async writeClientId(w,A){await m(c,{...await y(),[w]:{clientId:A}})},async forgetClientId(w){let A=await y();w in A&&await m(c,Object.fromEntries(Object.entries(A).filter(([_])=>_!==w)))}}}var Jy=5e3;function vu(e=ft(),t,n=!1){let r=(s,a)=>_i(s,e,a),i=s=>{process.stderr.write(s)},o=s=>xr({bearer:s}).getIdentity();return{store:e,loginDeps:du(e,s=>{i(`${s}
|
|
86
|
+
`)},o),identify:o,tokenProvider:r,isInteractive:()=>pt({noInteractive:n}),...t!==void 0&&{pickAccount:t},authHeaderTimeouts:{requestTimeoutMs:Jy},processEnv:process.env,writeStdout:s=>{process.stdout.write(s)},writeStderr:i,setExitCode:s=>{process.exitCode=s}}}function ku(e){let{environment:t,message:n}=wn(e);if(t===void 0)throw new Error(n);return t}async function Au(e,t,n){let r=await _r(e,n,t);if(!r.ok)throw new Error(r.message);return r.environment}var Ni=(e,t)=>e?`${e} (${t})`:t,Ri=(e,t)=>{let n=[t.fullName,t.email&&`<${t.email}>`].filter(Boolean).join(" ");return`Environment: ${e}
|
|
87
87
|
User: ${n===""?t.userId:`${n} (${t.userId})`}
|
|
88
|
-
Business: ${
|
|
89
|
-
`};function
|
|
90
|
-
${t.hint}`:"";e.writeStderr(`${n}: ${r?
|
|
91
|
-
`),e.setExitCode(1)}var
|
|
92
|
-
`),e.writeStdout(
|
|
93
|
-
${
|
|
94
|
-
${
|
|
88
|
+
Business: ${Ni(t.businessName,t.businessId)}
|
|
89
|
+
`};function xu(e,t,{prefix:n="Error",oneLine:r=!1}={}){let i=ke(t),o=(t instanceof q||t instanceof Vt)&&t.hint!==void 0?`
|
|
90
|
+
${t.hint}`:"";e.writeStderr(`${n}: ${r?i.replace(/\s+/g," ").trim():`${i}${o}`}
|
|
91
|
+
`),e.setExitCode(1)}var Hs=e=>async(t,n)=>{try{await e(t,n)}catch(r){xu(n,r)}},Vs=(e,t)=>{e.writeStdout(`Signed in to ${t.environment}.
|
|
92
|
+
`),e.writeStdout(Ri(t.environment,t))},Pn="browser",St=({account:e,session:t})=>`${Ni(t?.businessName,e.businessId)} ${t?.email??`user ${e.userId}`}${t===void 0?" (can't be read)":""}`,qy=e=>[...e.map(({account:t,session:n,current:r})=>({key:An(t),label:Ni(n?.businessName,t.businessId),description:[n?.email??t.userId,n===void 0?"(can't be read)":"",r?"(current)":""].filter(Boolean).join(" ")})),{key:Pn,label:"Sign in with the browser"}],Yy=(e,t)=>e===Pn?Pn:t.find(({account:n})=>An(n)===e),Zy=(e,{business:t,user:n})=>(e.businessId===t||e.businessName?.toLowerCase()===t.toLowerCase())&&(n===void 0||e.userId===n);function Sr(e,t,n){let r=e.filter(({account:a})=>a.businessId===t),i=r.length>0?r:e.filter(({session:a})=>a?.businessName?.toLowerCase()===t.toLowerCase()),o=n===void 0?i:i.filter(({account:a})=>a.userId===n),[s]=o;return o.length===1&&s!==void 0?{kind:"one",account:s}:o.length===0?{kind:"none",candidates:[...e]}:{kind:"several",candidates:o}}var wu=e=>e.map(t=>`
|
|
93
|
+
${St(t)}`).join(""),Pu=(e,t)=>e==="env"?`${yr}=${ge(t)}`:`--user ${ge(t)}`,xn=({business:e,user:t,source:n})=>`${n==="env"?`${hr}=${ge(e)}`:`--business ${ge(e)}`}${t===void 0?"":` ${Pu(n,t)}`}`;function Ks(e,t,n,r=Sr(t,n.business,n.user)){if(r.kind==="one")return r.account;let i=xn(n);if(r.kind==="none")throw new Error(`No saved ${e} account matches ${i}. Saved accounts:${wu(r.candidates)}`);let[o]=r.candidates;if(o!==void 0&&r.candidates.every(({account:a})=>a.businessId===o.account.businessId)){let{source:a}=n;throw new Error(`${i} matches several saved ${e} users of the same business. ${a==="env"?`Set ${yr}`:"Pass --user"} too, for example \`${xn({business:o.account.businessId,user:o.account.userId,source:a})}\`:${r.candidates.map(c=>`
|
|
94
|
+
${Pu(a,c.account.userId)}: ${St(c)}`).join("")}`)}throw new Error(`${i} matches several saved ${e} accounts. ${n.source==="env"?`Set ${hr} to`:"Pass"} one of these business ids instead:${wu(r.candidates)}`)}async function _r(e,t,n){let r=async a=>{let c=[],l=await Cr(e,async()=>(c=await a(),c));return l.ok?l:{...l,environments:c}};if(t===void 0||e!==void 0)return r(()=>n.listSessions());let i=await Promise.all(pe.map(async a=>({environment:a,accounts:await n.listAccounts(a)}))),o=i.filter(({accounts:a})=>Sr(a,t.business,t.user).kind!=="none").map(({environment:a})=>a),[s]=o;return o.length===1&&s!==void 0?{ok:!0,environment:s}:o.length>1?{ok:!1,problem:"several_sessions",message:`${xn(t)} matches saved accounts in several environments; pass --env <env>: ${o.join(", ")}`,environments:o}:r(()=>Promise.resolve(i.filter(({accounts:a})=>a.length>0).map(({environment:a})=>a)))}var Er=(e,t,n)=>Ks(e,t,n).account;function Ws(e,t){let n=bn(e,t);if(!n.ok)throw new Error(n.message);return n.request}function Xy(e,t,n,r){if(n){r.writeStdout(`${JSON.stringify(t.map(({account:i,session:o,current:s})=>({businessId:i.businessId,userId:i.userId,businessName:o?.businessName??null,fullName:o?.fullName??null,email:o?.email??null,current:s,readable:o!==void 0})))}
|
|
95
95
|
`);return}if(t.length===0){r.writeStdout(`No saved accounts for ${e}.
|
|
96
|
-
`);return}for(let
|
|
97
|
-
`)}async function
|
|
98
|
-
`),
|
|
96
|
+
`);return}for(let i of t)r.writeStdout(`${St(i)}${i.current?" (current)":""}
|
|
97
|
+
`)}async function Qy(e,t,n,r){if(t.business!==void 0){let i={business:t.business,user:t.user},o=Sr(n,i.business,i.user);return o.kind==="none"?{kind:"not_saved",request:i}:Ks(e,n,i,o)}return n.length===0?Pn:r.pickAccount===void 0||!r.isInteractive()?(r.writeStderr(`Saved accounts for ${e} exist; pass --business <id> to switch without the browser, or --list to see them.
|
|
98
|
+
`),Pn):Yy(await r.pickAccount(`Sign in to ${e}`,qy(n)),n)}function eb(e,t,n){let r=t.kind==="expired"?`The saved sign-in for ${St(t.account)} has expired and was removed.`:`There's no saved ${e} account for ${JSON.stringify(t.request.business)}${t.request.user===void 0?"":` with user ${JSON.stringify(t.request.user)}`}.`,i=t.kind==="expired"?Ni(t.account.session?.businessName&&JSON.stringify(t.account.session.businessName),t.account.account.businessId):JSON.stringify(t.request.business),o=t.kind==="expired"?t.account.session?.email??t.account.account.userId:t.request.user,s=`the business ${i}${o===void 0?"":`, signed in as ${o}`}`;return n?`${r}
|
|
99
99
|
A browser window is opening to sign in to Kizen ${e}. On the consent page, choose ${s}.
|
|
100
100
|
`:`${r}
|
|
101
101
|
Waiting for the user to sign in to Kizen ${e} in a browser window. Ask them to choose ${s}.
|
|
102
|
-
`}function
|
|
103
|
-
`),t.setExitCode(1);return}if(
|
|
104
|
-
`);let
|
|
105
|
-
`),
|
|
106
|
-
${
|
|
107
|
-
`),t.setExitCode(1)}),
|
|
108
|
-
`);return}let{environment:r}=n;if(e.business!==void 0){let
|
|
109
|
-
`);return}let s=
|
|
110
|
-
`:`No saved ${r} account ${
|
|
111
|
-
`);return}if(e.all===!0){let{signedIn:
|
|
102
|
+
`}function tb(e,t){if(t.kind==="expired"){let{account:n}=t.account;return{accepts:r=>kn(r,n),requested:St(t.account),retry:`${ut(e)} ${xn({business:n.businessId,user:n.userId})}`}}return{accepts:n=>Zy(n,t.request),requested:xn(t.request),retry:`${ut(e)} ${xn(t.request)}`}}var Cu=Hs(async(e,t)=>{let n=ku(e.env??Ht);if(e.json===!0&&e.list!==!0)throw new Error("--json only applies with --list.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");if(e.list===!0&&e.business!==void 0)throw new Error("--list can't be combined with --business.");let r=await t.store.listAccounts(n);if(e.list===!0){Xy(n,r,e.json===!0,t);return}let i=await Qy(n,e,r,t);if(i===void 0){t.writeStderr(`Cancelled.
|
|
103
|
+
`),t.setExitCode(1);return}if(i!==Pn&&!("kind"in i)){let p=i,{account:h}=p;t.writeStderr(`Switching to ${St(p)} on ${n}.
|
|
104
|
+
`);let b=await mu(n,h,{store:t.store,provider:t.tokenProvider(n,{account:h}),identify:t.identify});if(b!==void 0){Vs(t,b);return}i={kind:"expired",account:p}}if(i===Pn){t.writeStderr(`Signing in to ${n}.
|
|
105
|
+
`),Vs(t,await Ms(n,t.loginDeps,{interactive:t.isInteractive()}));return}let o=t.isInteractive(),s=tb(n,i);t.writeStderr(eb(n,i,o));let a=await Ms(n,t.loginDeps,{makeCurrent:s.accepts,interactive:o});if(s.accepts(a)){Vs(t,a);return}let c=await t.store.readSession(n).catch(()=>null),l=c!==null&&kn(c,a),d=St({account:a,session:a,current:!1}),u=o?"You":"The user",f=l?`That's already the current ${n} account; its saved session was updated.`:`It was saved, but it isn't the current ${n} account.`,g=l?"":`To use it, run \`${ut(n)} ${xn({business:a.businessId,user:a.userId})}\`. `,m=o?"To try again":"To have them try again";t.writeStderr(`${u} signed in as ${d}, not ${s.requested}. ${f}
|
|
106
|
+
${g}${m}, run \`${s.retry}\`.
|
|
107
|
+
`),t.setExitCode(1)}),Su=Hs(async(e,t)=>{if(e.all===!0&&e.business!==void 0)throw new Error("--all can't be combined with --business.");if(e.user!==void 0&&e.business===void 0)throw new Error("--user only applies with --business.");let n=await Cr(e.env,()=>t.store.listSessions());if(!n.ok){if(n.problem!=="not_signed_in")throw new Error(n.message);if(e.business!==void 0)throw new Error("Pass --env <env> with --business to remove a saved account.");if(e.all===!0)throw new Error("Pass --env <env> with --all to remove every saved account.");t.writeStdout(`Not signed in.
|
|
108
|
+
`);return}let{environment:r}=n;if(e.business!==void 0){let o=await t.store.listAccounts(r);if(o.length===0){t.writeStdout(`No saved accounts for ${r}.
|
|
109
|
+
`);return}let s=Ks(r,o,{business:e.business,user:e.user}),{removed:a,current:c}=await t.store.removeAccount(r,s.account);t.writeStdout(a||c?`Removed the saved ${r} account ${St(s)} from this machine.${c?` You're no longer signed in to ${r}.`:""}
|
|
110
|
+
`:`No saved ${r} account ${St(s)}.
|
|
111
|
+
`);return}if(e.all===!0){let{signedIn:o,removed:s}=await t.store.signOutAll(r);t.writeStdout(o||s>0?`Signed out of ${r}. Removed ${String(s)} saved ${s===1?"account":"accounts"} from this machine.
|
|
112
112
|
`:`No saved accounts for ${r}.
|
|
113
|
-
`);return}let
|
|
113
|
+
`);return}let i=await t.store.signOut(r);t.writeStdout(i?`Signed out of ${r}. The session was removed from this machine.
|
|
114
114
|
`:`Not signed in to ${r}.
|
|
115
|
-
`)}),
|
|
116
|
-
`}catch(r){
|
|
117
|
-
`),e.setExitCode(1)};async function
|
|
118
|
-
`)}async function
|
|
119
|
-
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function
|
|
120
|
-
`).slice(-
|
|
121
|
-
`);
|
|
122
|
-
`),
|
|
123
|
-
`),
|
|
115
|
+
`)}),_u=Hs(async(e,t)=>{let n=Ws(e,t.processEnv),r=await Au(e.env,t.store,n),i=n===void 0?void 0:Er(r,await t.store.listAccounts(r),n);t.writeStdout(Ri(r,await t.identify(t.tokenProvider(r,i===void 0?void 0:{account:i}))))});function nb(e){let t;try{t=new URL(e).origin}catch{throw new Error("CLAUDE_CODE_MCP_SERVER_URL is not a valid URL, so auth-header won't send a token.")}let n=pe.find(r=>Ut(r)===t);if(n===void 0)throw new Error(`No Kizen environment matches the MCP server ${t}, so auth-header won't send it a token.`);return{environment:n,origin:t}}async function rb(e,t){let n=e===void 0?void 0:ku(e),r=t.processEnv.CLAUDE_CODE_MCP_SERVER_URL;if(r!==void 0&&r!==""){let i=nb(r);if(n!==void 0&&n!==i.environment)throw new Error(`--env ${n} doesn't match the MCP server ${i.origin} (${i.environment}), so auth-header won't send it a token.`);return i.environment}return n??Au(void 0,t.store)}function ib(e){let{business:t,user:n}=e;if(!(t===void 0&&n===void 0)){if(t===void 0||n===void 0)throw new Error("auth-header takes --business and --user together.");return{businessId:t,userId:n}}}var Eu=async(e,t)=>{let n;try{let r=ib(e),i=await rb(e.env,t),{requestTimeoutMs:o}=t.authHeaderTimeouts,s=await t.tokenProvider(i,{requestTimeoutMs:o,...r!==void 0&&{account:r}}).getAccessToken();n=`${JSON.stringify({Authorization:`Bearer ${s}`})}
|
|
116
|
+
`}catch(r){xu(t,r,{prefix:"appbuilder auth-header",oneLine:!0});return}t.writeStdout(n)};var $i="appbuilder admin",sb={env:["--env","<env>"],business:["--business","<id-or-name>"],user:["--user","<userId>"]},Iu=["-h","--help"],ab="--force";function cb(e){let t={},n=0,r=o=>({kind:"run",env:t.env,...t.business!==void 0&&{business:t.business},...t.user!==void 0&&{user:t.user},args:o});e:for(;n<e.length;){let o=e[n]??"";if(o==="--")return r(e.slice(n+1));if(Iu.includes(o))return{kind:"help"};for(let[s,[a,c]]of Object.entries(sb))if(o===a||o.startsWith(`${a}=`)){let l=o===a?e[n+1]:o.slice(a.length+1);if(l===void 0||l==="")return{kind:"error",message:`option '${a} ${c}' argument missing`};t[s]=l,n+=o===a?2:1;continue e}break}let i=e.slice(n);if(i[0]==="init"){let o=i.slice(1);return o.length===0?{kind:"init",force:!1}:o.length===1&&o[0]===ab?{kind:"init",force:!0}:o.length===1&&Iu.includes(o[0]??"")?{kind:"init-help"}:{kind:"error",message:`admin init takes only --force, but got: ${o.map(ge).join(" ")}`}}return r(i)}var lb=(e,t,n,r)=>[e,t,"auth-header","--env",n,"--business",r.businessId,"--user",r.userId].map(ge).join(" "),ub=["KIZEN_PROFILE","CLAUDE_CODE_MCP_SERVER_URL"];function db(e,t){let n={};for(let[r,i]of Object.entries(e))i!==void 0&&!ub.includes(r)&&(n[r]=i);return{...n,...t}}var Tu=["SIGTERM","SIGHUP"];function pb(e,t,n,r,i,o){return new Promise((s,a)=>{let c;try{c=r(e.python,[e.kizen,...t],{stdio:"inherit",env:n})}catch(g){a(g instanceof Error?g:new Error(String(g)));return}let d=[...(o?Tu:[...Tu,"SIGINT"]).map(g=>[g,()=>{c.kill(g)}]),...o?[["SIGINT",()=>{}]]:[]];for(let[g,m]of d)i.on(g,m);let u=!1,f=g=>{if(!u){u=!0;for(let[m,p]of d)i.off(m,p);g()}};c.on("error",g=>{f(()=>{a(g)})}),c.on("close",(g,m)=>{f(()=>{s(g??128+(m===null?0:ob.signals[m]))})})})}var Gn=(e,t)=>{e.writeStderr(`${$i}: ${t}
|
|
117
|
+
`),e.setExitCode(1)};async function mb(e,t=!1){let n;try{n=await e.ensureKizen(t?{force:t}:void 0)}catch(r){Gn(e,ke(r));return}e.writeStderr(`${$i}: kizen ${n.version} is ready in ${n.dir}.
|
|
118
|
+
`)}async function fb(e,t){let n=Ws(e,t.processEnv),r=await _r(e.env,n,t.store);if(!r.ok)return{ok:!1,message:r.message};let{environment:i}=r,o;if(n===void 0)o=await t.store.readSession(i);else{let s=Er(i,await t.store.listAccounts(i),n);o=await t.store.readAccount(i,s)}return o===null?{ok:!1,message:dt(i,`You're not signed in to ${i}.`).message}:t.scriptPath===void 0?{ok:!1,message:"can't tell which script is running, so kizen can't call back."}:{ok:!0,session:{KIZEN_AUTH_HELPER:lb(t.execPath,t.scriptPath,i,o),KIZEN_BASE_URL:Ut(i),KIZEN_BUSINESS_ID:o.businessId,KIZEN_USER_ID:o.userId}}}async function Nu(e,t){let n=cb(e);switch(n.kind){case"help":t.outputHelp();return;case"init-help":t.outputInitHelp();return;case"init":await mb(t,n.force);return;case"error":Gn(t,n.message);return;case"run":break}let r;try{r=await fb(n,t)}catch(s){Gn(t,ke(s));return}if(!r.ok){Gn(t,r.message);return}let i;try{i=await t.ensureKizen()}catch(s){Gn(t,ke(s));return}let o=db(t.processEnv,r.session);try{t.setExitCode(await pb(i,n.args,o,t.spawn,t.signals,t.interactive))}catch(s){Gn(t,`couldn't start kizen: ${ke(s)}`)}}import{spawn as yb}from"child_process";import{createHash as Bu,randomBytes as bb}from"crypto";import{createReadStream as wb,createWriteStream as vb}from"fs";import{access as Du,mkdir as Lu,readdir as kb,readFile as Ab,rename as xb,rm as Tr,stat as Di,utimes as Pb,writeFile as Cb}from"fs/promises";import{basename as Xs,join as qt}from"path";import{Readable as Sb,Transform as _b}from"stream";import{pipeline as Fu}from"stream/promises";import{spawn as gb}from"child_process";function Ru(e){return e.split(`
|
|
119
|
+
`).map(t=>t.trim().replace(/\s+#.*$/,"")).filter(t=>t.length>0&&!t.startsWith("#"))}function $u(e){let t=/^python-(\d+)[.-](\d+)$/.exec(e),n=t?.[1],r=t?.[2];return n!==void 0&&r!==void 0?`python${n}.${r}`:"python3"}function Gs([e,t],n){return e>n[0]||e===n[0]&&t>=n[1]}function Cn(e){return`${String(e[0])}.${String(e[1])}`}var hb=(e,t)=>e[0]>t[0]||e[0]===t[0]&&e[1]>t[1];function Oi(e){return new Promise(t=>{let n=gb(e,["-c","import sys; print('%d.%d' % sys.version_info[:2])"],{stdio:["ignore","pipe","ignore"]}),r="";n.stdout.on("data",i=>{r+=i.toString("utf-8")}),n.on("error",()=>{t(null)}),n.on("close",i=>{let o=/(\d+)\.(\d+)/.exec(r);if(i!==0||!o){t(null);return}t([Number(o[1]),Number(o[2])])})})}async function Js(e,t,n,r=Oi){let i=[],o;for(let s of e){let a=await r(s);if(!a){i.push(`${s}: not found`);continue}if(!Gs(a,t)){i.push(`${s}: ${Cn(a)} (too old)`);continue}if((o===void 0||hb(a,o.version))&&(o={bin:s,version:a}),n==="first")break}return{found:o,tried:i}}var Ir=[3,10];async function Ou(e,t=Oi){let n=$u(e),r=n==="python3"?["python3"]:[n,"python3"],{found:i,tried:o}=await Js(r,Ir,"first",t);if(i!==void 0)return i.bin;throw new Error(`No Python >= ${Cn(Ir)} found for runtime "${e}". The local runner needs Python ${Cn(Ir)}+ 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.`)}var Eb=e=>`https://github.com/kizen/kizen-admin-cli/releases/download/v${e}/kizen_builder-${e}-py3-none-any.whl`,Ib={version:"0.3.0",wheelUrl:Eb("0.3.0"),sha256:"9f2017dd43bdc4554b655c87e25d1b5c754b04e0b8a32f1ed7516e30b9edf2d7"},Li="APPBUILDER_KIZEN_WHEEL",Tb=qt(nt,"kizen"),Nb=".appbuilder-ready.json",qs=[3,12],Rb=["python3.14","python3.13","python3.12","python3"],$b=720*60*6e4,Ob=60*6e4,Db=5*6e4,Lb=/^[0-9][\w.+!]*-[0-9a-f]{12}$/,Bb=/^kizen_builder-([^-]+)-.*\.whl$/;async function Fb(e){let{found:t,tried:n}=await Js(Rb,qs,"newest",e);if(t===void 0)throw new Error(`No Python ${Cn(qs)} or newer found to run kizen. Tried ${n.join(", ")}. Install Python ${Cn(qs)} or newer and retry.`);return t}var jb=20,Mb=e=>(t,n)=>new Promise((r,i)=>{let o=yb(t,n,{stdio:["ignore","pipe","pipe"]}),s="",a=c=>{s+=c.toString("utf-8")};o.stdout.on("data",a),o.stderr.on("data",a),o.on("error",c=>{i(new Error(`couldn't run ${t}: ${c.message}`))}),o.on("close",(c,l)=>{if(c===0){r();return}let d=s.trimEnd().split(`
|
|
120
|
+
`).slice(-jb).join(`
|
|
121
|
+
`);d!==""&&e(`${d}
|
|
122
|
+
`),i(new Error(`${Xs(t)} exited with ${c===null?String(l):`code ${String(c)}`}`))})});function ju(e,t,n=process.env){let r=n[Li];return{baseDir:Tb,pin:Ib,localWheel:r===""?void 0:r,fetch:(...i)=>fetch(...i),findPython:()=>Fb(),run:Mb(t),log:e,now:Date.now}}var zb=async e=>{let t=Bu("sha256");return await Fu(wb(e),t),t.digest("hex")},Bi=e=>qt(e,Nb),Nr=(e,t)=>qt(e,"bin",t);async function Zs(e,t){try{let n=JSON.parse(await Ab(Bi(e),"utf-8"));return!F(n)||n.sha256!==t?!1:(await Du(Nr(e,"python")),await Du(Nr(e,"kizen")),!0)}catch{return!1}}async function Ys(e,t){let n=new Date(t);await Pb(Bi(e),n,n).catch(()=>{})}async function Ub(e){if(e.localWheel!==void 0){let t=e.localWheel,n=Bb.exec(Xs(t))?.[1];if(n===void 0)throw new Error(`${Li} must name a kizen_builder wheel (kizen_builder-<version>-\u2026.whl), not ${t}.`);let r;try{r=await zb(t)}catch(i){throw new Error(`Couldn't read ${Li} ${t}: ${xe(i)}`)}return{version:n,sha256:r,localPath:t}}return{version:e.pin.version,sha256:e.pin.sha256,localPath:void 0}}async function Vb(e,t,n){let r=Bu("sha256");try{let i=await e.fetch(t,{signal:AbortSignal.timeout(Db)});if(!i.ok||i.body===null)throw new Error(`HTTP ${String(i.status)}`);await Fu(Sb.fromWeb(i.body),new _b({transform(o,s,a){r.update(o),a(null,o)}}),vb(n))}catch(i){throw new Error(`Couldn't download kizen from ${t}: ${xe(i)}`)}return r.digest("hex")}var Hb=e=>`.tmp-${e}-${String(process.pid)}-${bb(4).toString("hex")}`;async function Kb(e,t,n){let r;try{r=await kb(e)}catch{return}await Promise.all(r.map(async i=>{if(i===t)return;let o=qt(e,i);try{if(Lb.test(i)){let{mtimeMs:s}=await Di(Bi(o)).catch(()=>Di(o));n-s>$b&&await Tr(o,{recursive:!0,force:!0})}else if(i.startsWith(".tmp-")){let{mtimeMs:s}=await Di(o);n-s>Ob&&await Tr(o,{recursive:!0,force:!0})}}catch{}}))}var Wb=e=>Di(e).then(()=>!0,()=>!1),Mu=e=>new Error(`kizen's install at ${e} is damaged. Run \`appbuilder admin init --force\` to reinstall it.`);async function Gb(e,t,n){try{return await xb(e,t),!0}catch(r){if(!He(r,"ENOTEMPTY")&&!He(r,"EEXIST"))throw r}if(await Zs(t,n))return!1;throw Mu(t)}async function zu(e,t={}){let n=await Ub(e),r=`${n.version}-${n.sha256.slice(0,12)}`,i=qt(e.baseDir,r),o=u=>({version:n.version,dir:i,python:Nr(i,"python"),kizen:Nr(i,"kizen"),built:u});if(t.force===!0)e.log(`Removing ${i}.`),await Tr(i,{recursive:!0,force:!0});else{if(await Zs(i,n.sha256))return await Ys(i,e.now()),o(!1);if(await Wb(i)){if(await Zs(i,n.sha256))return await Ys(i,e.now()),o(!1);throw Mu(i)}}e.log(`Installing kizen ${n.version} into ${i} (first run only).`);let s=await e.findPython();e.log(`Using ${s.bin} (Python ${Cn(s.version)}).`),await Lu(e.baseDir,{recursive:!0,mode:448});let a=qt(e.baseDir,Hb(r)),c=qt(a,"venv"),l;try{await Lu(a);let u;if(n.localPath===void 0){u=qt(a,Xs(new URL(e.pin.wheelUrl).pathname)),e.log(`Downloading ${e.pin.wheelUrl}`);let f=await Vb(e,e.pin.wheelUrl,u);if(f!==n.sha256)throw await Tr(u,{force:!0}),new Error(`The kizen ${n.version} download doesn't match its pinned sha256 (expected ${n.sha256}, got ${f}), so nothing was installed.`)}else u=n.localPath,e.log(`Using the local wheel ${u} (${Li}).`);e.log("Creating a virtual environment.");try{await e.run(s.bin,["-m","venv",c])}catch(f){throw new Error(`Couldn't create a virtual environment: ${ke(f)}`)}e.log(`Installing kizen ${n.version} from the wheel and its dependencies from PyPI.`);try{await e.run(Nr(c,"python"),["-m","pip","install","--disable-pip-version-check",u])}catch(f){throw new Error(`Couldn't install kizen: ${ke(f)}`)}await Cb(Bi(c),`${JSON.stringify({version:n.version,sha256:n.sha256},null,2)}
|
|
123
|
+
`),l=await Gb(c,i,n.sha256)}finally{await Tr(a,{recursive:!0,force:!0}).catch(()=>{})}let d=e.now();return await Ys(i,d),l&&(e.log(`kizen ${n.version} is installed.`),await Kb(e.baseDir,r,d)),o(l)}var Qs="admin",Yb=`Usage: appbuilder admin init [--force]
|
|
124
124
|
|
|
125
125
|
Install kizen for appbuilder admin, or confirm it's installed. Needs Python 3.12 or newer.
|
|
126
126
|
|
|
127
127
|
Options:
|
|
128
128
|
--force remove kizen's install and install it again, to repair a damaged one; don't run it
|
|
129
129
|
while appbuilder admin is running
|
|
130
|
-
`,
|
|
131
|
-
`)},t),r=process.stdin;return{store:
|
|
130
|
+
`,ea=class extends qb{parseOptions(t){return{operands:[...t],unknown:[]}}};function Zb(e){let t=i=>{process.stderr.write(i)},n=ju(i=>{t(`${$i}: ${i}
|
|
131
|
+
`)},t),r=process.stdin;return{store:ft(),ensureKizen:i=>zu(n,i),spawn:Jb,signals:process,interactive:r.isTTY===!0,processEnv:process.env,execPath:process.execPath,scriptPath:process.argv[1],outputHelp:()=>{e.outputHelp()},outputInitHelp:()=>{process.stdout.write(Yb)},writeStderr:t,setExitCode:i=>{process.exitCode=i}}}function Uu(e){let t=new ea(Qs).copyInheritedSettings(e).description("Run Kizen's admin CLI (kizen) with the signed-in session").usage(`[--env <env>] [--business <id-or-name> [--user <userId>]] [--] <kizen args...>
|
|
132
132
|
appbuilder admin init [--force]`).option("--env <env>","environment to use (default: the only signed-in one, or with --business the only one where it's saved)").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").allowExcessArguments().addHelpText("after",`
|
|
133
133
|
Wrapper options end at the first other argument or at --; everything after goes to kizen.
|
|
134
|
-
"appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await ns(t.args,op(t))});e.addCommand(t);let n=e.parseOptions.bind(e);e.parseOptions=r=>r[0]===Jr?{operands:[Jr],unknown:r.slice(1)}:n(r)}import{render as dp}from"ink";import{useMemo as ip,useState as sp}from"react";import{Box as Xr,Text as dt,useInput as ap}from"ink";var An=(e,t,n)=>Math.min(Math.max(e,t),n);function Tn(e,t,n,r={}){if(t<=0)return 0;let o=An(Math.trunc(e)||0,0,t-1),i=c=>r.disabled?.[c]!==!0;if(n===0)return o;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let g=((o+s*c)%t+t)%t;if(i(g))return g}return o}let a=An(o+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(i(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(i(c))return c;return o}function ms(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let o=An(Math.trunc(e)||0,0,t-1),i=An(o-Math.floor(r/2),0,t-r);return{start:i,end:i+r}}import{jsx as ut,jsxs as Qr}from"react/jsx-runtime";var cp="\u2191/\u2193 to move, Enter to select, Esc to cancel",Zr=10,lp=e=>{let t=Tn(0,e.length,0);if(e[t]?.disabled!==!0)return t;let n=e.findIndex(r=>r.disabled!==!0);return n===-1?t:n},Ne=({title:e,items:t,onSelect:n,onCancel:r,hint:o=cp})=>{let[i,s]=sp(()=>lp(t)),a=ip(()=>t.map(f=>f.disabled===!0),[t]),c=Tn(i,t.length,0);ap((f,u)=>{let w=k=>{s(Tn(c,t.length,k,{disabled:a}))};if(u.upArrow||f==="k")w(-1);else if(u.downArrow||f==="j")w(1);else if(u.pageUp)w(-Zr);else if(u.pageDown)w(Zr);else if(u.return){let k=t[c];k!==void 0&&k.disabled!==!0&&n(k,c)}else u.escape&&r?.()});let{start:g,end:m}=ms(c,t.length,Zr),h=g,y=t.length-m;return Qr(Xr,{flexDirection:"column",gap:1,children:[ut(dt,{bold:!0,children:e}),Qr(Xr,{flexDirection:"column",children:[h>0&&ut(dt,{dimColor:!0,children:` \u2191 ${String(h)} more`}),t.slice(g,m).map((f,u)=>{let k=g+u===c,_=f.disabled===!0,P=k&&!_;return Qr(Xr,{gap:2,children:[ut(dt,{...P&&{color:"cyan"},dimColor:_,children:k?"\u276F":" "}),ut(dt,{bold:P,dimColor:_,...P&&{color:"cyan"},children:f.label}),f.description!==void 0&&ut(dt,{dimColor:!0,children:f.description})]},f.key)}),y>0&&ut(dt,{dimColor:!0,children:` \u2193 ${String(y)} more`})]}),ut(dt,{dimColor:!0,children:o})]})};import{jsx as up}from"react/jsx-runtime";var hs=async(e,t)=>{let n,r=dp(up(Ne,{title:e,items:t,onSelect:o=>{n=o.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var pp=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"]],run:Yi},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Xi},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one, or with --business the only one where it's saved)",options:[["--business <id-or-name>","check this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)"],["--user <userId>","with --business, check the saved account of this user id (default: $APPBUILDER_USER)"]],run:Zi},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",options:[["--business <id>","with --user, use this saved account, current or not"],["--user <userId>","with --business, the user id of that account"]],run:Qi}];function gs(e){for(let{name:t,description:n,env:r,options:o=[],run:i}of pp){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of o)s.option(a,c);s.action(async a=>{await i(a,Ki(void 0,hs))})}}import{createElement as Mm}from"react";import{render as Um}from"ink";import{PluginValidationError as Hm}from"@kizenapps/packager";import{spawn as fp}from"child_process";import{platform as ys}from"process";function mp(){return ys==="darwin"?[{cmd:"pbcopy",args:[]}]:ys==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var hp=2e3;function gp(e,{cmd:t,args:n}){return new Promise(r=>{let o;try{o=fp(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let i=o,s=!1;function a(g){s||(s=!0,clearTimeout(c),r(g))}let c=setTimeout(()=>{i.kill(),a(!1)},hp);c.unref(),i.on("error",()=>{a(!1)}),i.on("close",g=>{a(g===0)}),i.stdin.on("error",()=>{a(!1)});try{i.stdin.end(e)}catch{a(!1)}})}async function In(e){for(let t of mp())if(await gp(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as Yp,CONFIG_FILE_NAME as Xp,MANIFEST_FILE_NAME as Zp,sanitizeToAPIName as Qp}from"@kizenapps/packager";var $n=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as yp}from"crypto";import{mkdir as bp,readFile as wp,writeFile as vp}from"fs/promises";import{dirname as xp,join as vs}from"path";var eo="appbuilder:",pt=".kizenapp/pushes.json",kp=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function to(e){return typeof e=="number"&&Number.isFinite(e)}function Nn(e,t,n){return Math.min(Math.max(e,t),n)}function Cp(e){let t={...e};return delete t.custom_object,t}function xs(e,t){return`${eo}${e}/${t}`}function ks(e){if(!e.startsWith(eo))return null;let t=e.slice(eo.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Cs(e){let t={};for(let n of $n){let r=e[n];to(r)&&(t[n]=r)}return t}function Ss(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Ps=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function Sp(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:Ps(e.event_scripts)}}function ro(e){return e.length>0?{views:e.map(Sp)}:{}}function Es(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Ps(e.event_scripts),...Cs(e),...Ss(e),...ro(t)}}function Pp(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function Ep(e){let t=0;for(let n of e){let r=n.layout;if(!O(r))continue;let{y:o,h:i}=r;!to(o)||!to(i)||(t=Math.max(t,o+i))}return t}function _p(e,t,n){let r=Nn(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),o=Nn(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:Ep(e),w:Nn(r,2,12),h:Nn(o,1,99)}}function _s(e){return{name:xs(e.pluginApiName,e.blockApiName),layout:_p(e.dashlets,e.content,e.layoutId),config:Pp({content:e.content,objectId:e.objectId})}}function As(e,t){let n=e.config;return{config:{...Cp(O(n)?n:{}),content:t}}}function Ts(e){let t=e.config;return O(t)?t.content:void 0}function wt(e){let t=e.config;if(!O(t)||t.chart_type!=="html")return!1;let n=t.content;return O(n)&&n.kind==="custom_code"}function Is(e){return e.dashlets.filter(wt)}function Dn(e){let t=Ts(e);return O(t)&&typeof t.name=="string"?t.name:e.name}var Ge=e=>typeof e=="string"?e:"";function $s(e){return Array.isArray(e)?e.filter(O).map(t=>({name:Ge(t.name),script:Ge(t.script)})):O(e)?Object.entries(e).map(([t,n])=>({name:t,script:Ge(n)})):[]}function no(e){if(Array.isArray(e))return e.map(no);if(O(e)){let t={};for(let n of Object.keys(e).sort())t[n]=no(e[n]);return t}return e}function Ns(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function Ap(e){return Array.isArray(e)?e.filter(O).map(t=>({api_name:Ge(t.api_name),name:Ns(t.name),type:Ge(t.type),script:Ge(t.script),html:Ge(t.html),css:Ge(t.css),event_scripts:$s(t.event_scripts)})):[]}function oo(e){let t=O(e)?e:{},n=Ap(t.views),r={name:Ns(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:$s(t.event_scripts),...Cs(t),...Ss(t),...n.length>0&&{views:n}};return yp("sha256").update(JSON.stringify(no(r))).digest("hex")}function Ds(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let i=e.dashlets.find(s=>s.id===t.dashletId);if(i&&wt(i))return{kind:"map",dashlet:i,entry:t}}let n=xs(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(i=>i.name===n&&wt(i)),[o]=r;return r.length===1&&o?{kind:"name",dashlet:o}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function Rs(e,t){return t?.dashletId!==e.id?!1:oo(Ts(e))!==t.contentHash}function io(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function so(e,t){return e.find(n=>io(n,t))}function Os(e,t){let n=e.findIndex(r=>io(r,t));return n===-1?[...e,t]:e.map((r,o)=>o===n?t:r)}function Bs(e,t){return e.filter(n=>!io(n,t))}function Tp(e){if(!O(e))return null;for(let n of kp)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:$t(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var bs=e=>Date.parse(e.pushedAt)||0;function Ip(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),o=t.get(r);(o===void 0||bs(n)>bs(o))&&t.set(r,n)}return[...t.values()]}var ws=e=>e instanceof Error?e.message:String(e);async function Fs(e){let t;try{t=await wp(vs(e,pt),"utf8")}catch(r){if(fn(r))return[];throw new Error(`Couldn't read ${pt}: ${ws(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${pt} is not valid JSON (${ws(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${pt} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return Ip(n.map(Tp).filter(r=>r!==null))}async function js(e,t){let n=vs(e,pt);await bp(xp(n),{recursive:!0}),await vp(n,`${JSON.stringify(t,null,2)}
|
|
135
|
-
|
|
136
|
-
`));return[
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
`)
|
|
140
|
-
`)
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
`+i;vt.writeFileSync(t,n+s)}import{spawn as Lf}from"child_process";import{join as Hn}from"path";var oa="---\nname: kizen-custom-block\ndescription: Use this skill when the user asks to build, change or publish a Kizen content block, custom block, chart, or dashboard/homepage visualization in this plugin. It covers the block file layout, the plugin engine runtime rules, and the appbuilder validate, preview and push loop.\n---\n\n# Kizen custom blocks\n\nFollow these rules exactly. The runtime is strict, and a push changes a live Kizen dashlet.\n\n## Keep this skill current\n\nAt the start of any block task, run `appbuilder setup-claude --include-lib` in the plugin directory.\n\n- If it reports `updated` for `.claude/skills/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `.claude/skills/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file, or `updated` for `.claude/skills/kizen-custom-block/design.md`, read that file before writing any markup or styles.\n- If it reports `created` or `updated` for `lib/kizenData.js` (under the plugin's entry directory, usually `src/`), re-read its exports before using them.\n- If every file line reports `unchanged`, continue.\n- If the command doesn't exist (an older CLI), skip it and continue.\n- If it fails (for example, you aren't in the plugin directory that holds `kizen.json`), switch to that directory and run it once more. If it still fails, continue without it.\n\n`setup-claude` only rewrites the CLI-managed files: the ones in this skill directory and `src/lib/kizenData.js`. It never touches block code, so it's always safe to run.\n\n## What a block is\n\nA block is a directory under `src/blocks/<dir>/`:\n\n- `config.json` (required): `name`, `api_name` (always set it explicitly), `types` (any of `homepages`, `dashboards`, `charts` for chart groups, and `records`; a block only appears on the surfaces it lists), and the optional sizes `min_w`, `max_w`, `min_h`, `max_h`, `default_w` and `default_h`. Widths are grid columns (1 to 12) and heights are grid rows. Each size you set is a positive integer, each `min_*` is no greater than its `max_*`, and each `default_*` falls within whichever of its `min_*` and `max_*` you set. `default_w` and `default_h` are the starting size when `block push` creates a new dashlet; updates never resize an existing dashlet. Only the sizes you write are exported and pushed.\n - `host_chrome` (optional boolean, default `true`): whether the host paints the dashlet card around the block. Omit it unless you are turning chrome off. Only a value you write is exported and pushed, and any value other than `true` or `false` fails validation.\n- `script.js` (required): the render script.\n- `styles.css` (optional).\n- `eventScripts/<name>.js` (optional): one file per interactive handler.\n\nShared helpers live in `src/lib/*.js`. Import them with relative named imports only, for example `import { formatMoney } from '../../lib/format.js';`. No default imports, no bare package names.\n\n`src/lib/kizenData.js` is managed by appbuilder: `setup-claude` and CLI updates replace it. Never edit it. Put your own helpers in another file under `src/lib/`.\n\n### Host chrome\n\nDecide the mode yourself from the request. Ask the user only if they already raised it and their choice is unclear.\n\n- Keep host chrome (omit `host_chrome`) for standard data dashlets such as charts, KPIs, tables and lists that should match native cards.\n- Set `\"host_chrome\": false` for full-bleed heroes, imagery, custom-shaped cards, or any design whose background is part of the visual.\n\nChrome off, in `config.json`:\n\n```json\n{\n \"name\": \"Welcome hero\",\n \"api_name\": \"welcome_hero\",\n \"types\": [\"homepages\", \"dashboards\"],\n \"host_chrome\": false\n}\n```\n\nFollow \"Chrome off\" in `design.md` for the layout rules. In your summary to the user, state which mode you chose and why in one line. `block push --dry-run --json` shows the value as `body.config.content.host_chrome` (absent when chrome is on by default), so check it there. Changing `host_chrome` on a block you already pushed is an ordinary update: validate, then `block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\n1. **Validate.** Run `appbuilder block export <api_name>`. Fix every validation error it prints, then run it again until it passes.\n2. **Choose the target with the user (first publish only).**\n - `appbuilder block targets --json` returns `{ surfaces: { dashboard: [...], homepage: [...] }, customObjects: [{ id, objectName, fetchUrl }] }`. Contacts appears in `customObjects` when available.\n - `appbuilder block targets --object <id> --json` returns `{ surfaces: { chart_group: [...] } }` for that object.\n - Only offer rows where `canEdit !== false`. Ask the user which surface and which specific one. Don't pick for them.\n - Optionally run `appbuilder block push <api_name> --dashboard <id> --json` to get a `needs_choice` result listing the existing custom blocks and \"new\".\n3. **Preview.** Run `appbuilder block push <api_name> --dashboard <id> [--dashlet <id> | --create] --dry-run --json`. Show the user the `environment`, `businessId`, `dashboard.name`, `action` and any `warnings`.\n4. **Apply** once the user agrees: run the same command with `--yes` in place of `--dry-run`. Treat the push as done only when `applied === true`. Give the user the returned `url`, then refresh the browser (below).\n5. **Change requests.** Edit the files, validate again (step 1), then run `appbuilder block push <api_name> --yes --json`. With no target flags it updates the remembered dashlet. Refresh the browser (below) after each push. Repeat for each change.\n\nA headless run without `--yes` is always a dry run.\n\n### Refresh the browser after a push\n\nDo this after every applied push, only when Claude-in-Chrome tools are available. Dashlets don't poll, so the user's open tab keeps the old block until it's refreshed. Don't reload the page.\n\n1. List the open tabs (`tabs_context_mcp`) and find the one whose URL has the same origin and path as the result's `url`.\n2. If there is no such tab, open `url` in a new tab (`tabs_create_mcp`) and go to step 5.\n3. If the result has a `refresh` field, run `refresh.script` exactly as given in that tab with the page JavaScript tool (`javascript_tool`). If it has no `refresh` field, navigate that tab to `url` (`navigate`) and go to step 5.\n4. Check what the script returned:\n - `{ refreshed: true, ... }`: the dashboard refetched in place.\n - `undefined`: the refresh hook isn't available on this page (an older Kizen build, or a page without the hook). Navigate the tab to `url` instead.\n5. Wait a couple of seconds, take a screenshot (`computer`), and check that the block rendered: not blank, and no visible error. Report what you saw to the user. If the block is blank or shows an error, read the console and fix the block before pushing again.\n\nNever run any other injected code in the user's tabs. `refresh.script` is the only script you may run.\n\n### JSON results\n\n- Dry run: `{ ok: true, applied: false, dryRun: true, action: 'create' | 'update', environment, businessId, dashboard: { id, name, type }, dashletId | null, url, method, path, body, warnings }`.\n- Applied: `{ ok: true, applied: true, dryRun: false, action: 'created' | 'updated', ..., dashletId, url, refresh?: { dashboardId, script }, remembered }`. `refresh` is absent when the dashboard id isn't a uuid.\n- If a `block push` result's `warnings` contains `Claude files managed by appbuilder are out of date; run appbuilder setup-claude`, run `appbuilder setup-claude --include-lib`, re-read `.claude/skills/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, choice?, choices? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`, where `args` is a string array. Ask the user using each option's `label`, then re-run the same command with the chosen option's `args` appended exactly. Never construct these flags by hand. The \"new\" option is `{ value: 'new', args: ['--dashboard', <id>, '--create'] }`.\n\n## Guardrails\n\n- Never pass `--allow-production` unless the user explicitly asked, in this conversation, to publish to production (`go` or `fmo`).\n- On `drift_detected`, stop and ask the user. Someone edited the block in Kizen since your last push, and `--force` overwrites their changes. Pass `--force` only when the user says to discard them.\n- On `needs_choice`, ask the user using the returned `choices` as described above. Never guess.\n- On `remembered_target_missing`, the remembered dashboard or dashlet is gone. Ask the user where to publish instead, then push with `--dashboard <id>` plus `--create` or a `--dashlet` choice, or use `--forget` to clear the memory. `--create` alone won't work.\n- On `credentials_invalid`, if `message` says they're not signed in, tell the user to run `appbuilder login` (add `--env <env>` for an environment other than `go`). Otherwise tell them to fix the credential file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `production_requires_flag`, the target is `go` or `fmo`. Apply the production rule above.\n- Never push to a new target without first showing the user a dry run.\n- Blocks run with the viewing user's permissions for every viewer. Don't write code that creates, updates or deletes data unless the user asked for it.\n";var ia=`# Designing a Kizen custom block
|
|
134
|
+
"appbuilder admin init" installs kizen ahead of time; it's otherwise installed on first use.`).action(async()=>{await Nu(t.args,Zb(t))});e.addCommand(t);let n=e.parseOptions.bind(e);e.parseOptions=r=>r[0]===Qs?{operands:[Qs],unknown:r.slice(1)}:n(r)}import{createElement as oP}from"react";import{render as sP}from"ink";import{createHash as zk}from"crypto";import{access as Uk,mkdtemp as Vk,readFile as op,rm as Hk}from"fs/promises";import{tmpdir as Kk}from"os";import{dirname as Wk,join as $n,resolve as np,sep as Gk}from"path";import{execFile as Bw}from"child_process";import{createHash as Fw,randomUUID as jw}from"crypto";import{constants as sd}from"fs";import{chmod as Mw,lstat as En,mkdir as Xt,mkdtemp as zw,open as Uw,readdir as Vw,readFile as Hw,rename as Kw,rm as ad,rmdir as cd,stat as Ww,writeFile as ld}from"fs/promises";import{devNull as Mr,tmpdir as Gw}from"os";import{dirname as td,join as he,resolve as Vi,sep as ud}from"path";import{execFile as ew}from"child_process";import{accessSync as tw,constants as nw,statSync as rw}from"fs";import{lstat as aa,mkdir as ta,readdir as iw,readFile as Gu,writeFile as ow}from"fs/promises";import{dirname as Ku,isAbsolute as sw,join as Yn,posix as aw,resolve as Wu,sep as cw,win32 as lw}from"path";import{promisify as uw}from"util";import{unzipSync as ra,zipSync as Ju}from"fflate";import dw from"ignore";import{MANIFEST_FILE_NAME as qu}from"@kizenapps/packager";var Fi=["claude","codex"],Ke={claude:{filesLabel:"Claude",skillsDir:".claude/skills",setupCommand:"appbuilder setup-claude",staleWarning:"Claude files managed by appbuilder are out of date; run appbuilder setup-claude"},codex:{filesLabel:"Codex",skillsDir:".agents/skills",setupCommand:"appbuilder setup-codex",staleWarning:"Codex files managed by appbuilder are out of date; run appbuilder setup-codex"}},ji=["kizen-custom-block","kizen-business-apps"],Vu=Fi.flatMap(e=>ji.map(t=>`${Ke[e].skillsDir}/${t}`)),Xb={SKILLS_DIR:e=>e.skillsDir,SETUP_COMMAND:e=>e.setupCommand,STALE_WARNING:e=>e.staleWarning},Qb=/^\{\{([#/])(claude|codex)\}\}$/;function Hu(e,t){let n=Ke[t],r=[],i;for(let o of e.split(`
|
|
135
|
+
`)){let s=Qb.exec(o);if(s!==null){let[,a,c]=s;if(a==="#"&&i===void 0)i=c;else if(a==="/"&&i===c)i=void 0;else throw new Error(`Unbalanced skill template block: ${o}`);continue}(i===void 0||i===t)&&r.push(o)}if(i!==void 0)throw new Error(`Unclosed skill template block: {{#${i}}}`);return r.join(`
|
|
136
|
+
`).replace(/\{\{([^}]*)\}\}/g,(o,s)=>{let a=Xb[s];if(a===void 0)throw new Error(`Unknown skill template token: ${o}`);return a(n)})}var pw=uw(ew),mw=new Set(["node_modules",".git",".kizenapp",".kizenappbuilder",".copilot-docs","__pycache__","dist"]),fw=new Set([".DS_Store",".env",".npmrc","credentials.json"]),ca=".kizenignore",gw=new Set([...mw,...fw].map(e=>e.toLowerCase())),Yu=e=>{let t=e.toLowerCase().replace(/[. ]+$/,"");return gw.has(t)||t.startsWith(".env.")},Zu=e=>e.toLowerCase().replace(/[. ]+$/,""),hw=Vu.map(e=>e.split("/").map(Zu)),yw=e=>{let t=e.replace(/\/$/,"").split("/").map(Zu);return hw.some(n=>t.length>=n.length&&n.every((r,i)=>t[i]===r))},jr=e=>e.replace(/\/$/,"").split("/").some(Yu)||yw(e),$r=new Date(1980,0,1,0,0,0),bw=15e3,ww=new Set(["GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_NOSYSTEM","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"]);function la(e=process.env){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("GIT_")||ww.has(t)))}var vw=["--no-optional-locks","-c","core.fsmonitor=false","-c","core.hooksPath=/dev/null"],kw=e=>{try{return rw(e).isFile()?(tw(e,nw.X_OK),!0):!1}catch{return!1}};function Aw(e,{env:t,platform:n,isExecutable:r}){let i=n==="win32",o=i?lw:aw,s=c=>i?Object.entries(t).find(([l])=>l.toUpperCase()===c)?.[1]:t[c],a=i?(s("PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").filter(c=>c!==""):[""];for(let c of(s("PATH")??"").split(o.delimiter))if(!(c===""||!o.isAbsolute(c)))for(let l of a){let d=o.join(c,`${e}${l}`);if(r(d))return d}}var na;function ua(){if(na??=Aw("git",{env:process.env,platform:process.platform,isExecutable:kw})??null,na===null)throw Object.assign(new Error("git was not found on PATH"),{code:"ENOENT"});return na}var da=async(e,t)=>(await pw(ua(),[...vw,...e],{cwd:t,env:la(),timeout:bw,maxBuffer:64*1024*1024,encoding:"utf8"})).stdout,Mi="so the source zip honors only the root .gitignore and .kizenignore.";function xw(e){let t=e?.code;return t==="ENOENT"?`git isn't installed, ${Mi}`:t===128?`Not in a git work tree, ${Mi}`:`Couldn't list files with git (${xe(e)}), ${Mi}`}var Or=class extends Error{constructor(){super("The enclosing git repository ignores this folder, so none of its files can be picked for the source zip. Nothing was uploaded."),this.name="SourceZipIgnoredDirError"}},Dr=class extends Error{mode;constructor(t){super(`${qu} isn't among the files picked for the source zip. Check that .gitignore${t==="git"?" (or a git exclude)":""} or .kizenignore doesn't exclude it.`),this.name="SourceZipMissingManifestError",this.mode=t}},ia=(e,t)=>e<t?-1:e>t?1:0,Lr=class extends Error{file;constructor(t,n){super(`${t} exists but couldn't be read (${xe(n)}), so the files it excludes can't be left out of the source zip. Nothing was uploaded; fix its permissions and try again.`,{cause:n}),this.name="SourceZipIgnoreUnreadableError",this.file=t}};async function Br(e,t){let n;try{n=await Gu(Yn(e,t),"utf-8")}catch(r){if(He(r,"ENOENT")||He(r,"ENOTDIR"))return;throw new Lr(t,r)}return dw().add(n)}async function Pw(e,t,n){let r=t.split("/");for(let i=1;i<r.length;i+=1)if(!await n(r.slice(0,i).join("/")))return!1;try{return(await aa(Yn(e,...r))).isFile()}catch{return!1}}function Cw(e){let t=new Map;return n=>{let r=t.get(n);return r===void 0&&(r=aa(Yn(e,...n.split("/"))).then(i=>i.isDirectory(),()=>!1),t.set(n,r)),r}}async function Sw(e,t){try{if((await t(["rev-parse","--is-inside-work-tree"],e)).trim()!=="true")return{notice:`Not in a git work tree, ${Mi}`};let r=await t(["ls-files","--cached","--others","--exclude-standard","-z"],e),i=[...new Set(r.split("\0"))].filter(Zn);if(i.length===0)return{ignored:!0};let o=Cw(e),s=await Promise.all(i.map(c=>Pw(e,c,o)));return{files:i.filter((c,l)=>s[l])}}catch(n){return{notice:xw(n)}}}async function _w(e,t){let n=[],r=async(i,o)=>{let s=await iw(i,{withFileTypes:!0});for(let a of s){let c=`${o}${a.name}`;a.isDirectory()?!Yu(a.name)&&t?.ignores(`${c}/`)!==!0&&await r(Yn(i,a.name),`${c}/`):a.isFile()&&t?.ignores(c)!==!0&&n.push(c)}};return await r(e,""),n}async function pa(e,t={}){let n=await Sw(e,t.git??da);if("ignored"in n)throw new Or;let r=await Br(e,ca),i="files"in n?{files:n.files,mode:"git"}:{files:await _w(e,await Br(e,".gitignore")),mode:"walk",notice:n.notice};if(i.files=i.files.filter(o=>Zn(o)&&r?.ignores(o)!==!0&&!jr(o)).sort(ia),!i.files.includes(qu))throw new Dr(i.mode);return i}var qn=class extends Error{constructor(t){super(t),this.name="SourceZipTooLargeError"}};async function Ew(e,t,n){let r=0;for(let i of t){let{size:o}=await aa(Yn(e,...i.split("/")));if(o>n.entryBytes)throw new qn(`${i} is ${String(o)} bytes, over the ${String(n.entryBytes)}-byte limit for one file in an app's source. Exclude it with .kizenignore.`);if(r+=o,r>n.totalBytes)throw new qn(`The app's source is over the ${String(n.totalBytes)}-byte limit. Exclude large files with .kizenignore.`)}}async function Xu(e,t={}){let n=await pa(e,t);await Ew(e,n.files,t.limits??{entryBytes:oa,totalBytes:sa});let r=await Promise.all(n.files.map(o=>Gu(Yn(e,...o.split("/"))))),i={};return n.files.forEach((o,s)=>{i[o]=[new Uint8Array(r[s]),{mtime:$r}]}),{...n,bytes:Ju(i,{level:6,mtime:$r})}}var Sn=class extends Error{entry;constructor(t,n="is unsafe"){super(`The source zip entry "${t}" ${n}; nothing was extracted.`),this.name="UnsafeZipEntryError",this.entry=t}},Fr=class extends Error{destination;constructor(t){super(`${t} already exists; the source zip is only extracted into a new directory.`),this.name="ZipDestinationExistsError",this.destination=t}};function Zn(e){let t=(e.endsWith("/")?e.slice(0,-1):e).split("/");return!(e===""||e.includes("\\")||e.includes("\0")||sw(e)||/^[A-Za-z]:/.test(e)||t.some(n=>n===""||n==="."||n===".."))}function Iw(e){if(!Zn(e))throw new Sn(e)}var Ui=e=>e.normalize("NFC").toLowerCase();function Tw(e){let t=new Map,n=new Map;for(let r of e){let i=r.endsWith("/"),o=Ui(i?r.slice(0,-1):r),s=o.split("/");if(t.has(o)||!i&&n.has(o))throw new Sn(r,"collides with another entry");(i?n:t).set(o,r);for(let a=1;a<s.length;a+=1)n.set(s.slice(0,a).join("/"),r)}for(let[r,i]of t)if(n.has(r))throw new Sn(i,"is a file where another entry needs a directory")}var oa=50*1024*1024,sa=200*1024*1024,Yt=class extends Error{entry;constructor(t,n){super(t),this.name="ZipLimitError",this.entry=n}},Jn=(e,t)=>(e[t]??0)|(e[t+1]??0)<<8,Rr=(e,t)=>(Jn(e,t)|Jn(e,t+2)<<16)>>>0;function Nw(e){let t=e.length-22;for(;t>=0&&Rr(e,t)!==101010256;)t-=1;if(t<0)throw new Yt("The source zip isn't a valid zip file; nothing was extracted.");if(t>=20&&Rr(e,t-20)===117853008)throw new Yt("The source zip uses ZIP64, which a source zip never needs; nothing was extracted.");let n=[],r=Rr(e,t+16);for(let i=Jn(e,t+8);i>0;i-=1){if(Rr(e,r)!==33639248)throw new Yt("The source zip isn't a valid zip file; nothing was extracted.");n.push(Rr(e,r+16)),r+=46+Jn(e,r+28)+Jn(e,r+30)+Jn(e,r+32)}return n}var Rw=Uint32Array.from({length:256},(e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function $w(e){let t=4294967295;for(let n of e)t=(Rw[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function _n(e){let t=Nw(e),n=[];if(ra(e,{filter:u=>(n.push(u),!1)}),n.length!==t.length)throw new Yt("The source zip isn't a valid zip file; nothing was extracted.");let r=n.map(u=>u.name);r.forEach(Iw),Tw(r);let i=[],o=new Map,s=0;n.forEach((u,f)=>{if(!u.name.endsWith("/")){if(jr(u.name)){i.push(u.name);return}if(u.originalSize>oa)throw new Yt(`The source zip entry "${u.name}" expands to ${String(u.originalSize)} bytes, over the ${String(oa)}-byte limit; nothing was extracted.`,u.name);if(s+=u.originalSize,s>sa)throw new Yt(`The source zip expands to more than ${String(sa)} bytes; nothing was extracted.`);o.set(f,u)}});let a=0,c=ra(e,{filter:()=>o.has(a++)}),l=new Map;for(let[u,f]of o){let g=c[f.name];if(g?.length!==f.originalSize||$w(g)!==t[u])throw new Sn(f.name,"doesn't match its recorded size or checksum");l.set(f.name,g)}let d=i.filter(u=>u!==zi).sort(ia);return{files:new Map([...l].sort(([u],[f])=>ia(u,f))),skipped:d}}var zi=".kizenapp/lineage.json",Qu=1,Ow=4096,Dw=e=>typeof e=="string"&&/^[1-9]\d*$/.test(e);function Lw(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=t.baseLiveVersion,r=t.baseSourcePackageId;return t.format!==Qu?null:n===null&&r===null?{baseLiveVersion:null,baseSourcePackageId:null}:Dw(n)&&typeof r=="string"&&r!==""?{baseLiveVersion:n,baseSourcePackageId:r}:null}function ma(e){try{let t=-1,r=ra(e,{filter:i=>i.name!==zi||i.originalSize>Ow?!1:(t=i.originalSize,!0)})[zi];return r?.length!==t?null:Lw(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r)))}catch{return null}}function fa(e,t){let{files:n}=_n(e),r={};for(let[o,s]of n)r[o]=[s,{mtime:$r}];let i={format:Qu,...t};return r[zi]=[new TextEncoder().encode(`${JSON.stringify(i,null,2)}
|
|
137
|
+
`),{mtime:$r}],Ju(r,{level:6,mtime:$r})}async function ed(e,t){let n=Wu(t),{files:r,skipped:i}=_n(e),o=[];for(let[s,a]of r){let c=Wu(n,...s.split("/"));if(!c.startsWith(n+cw))throw new Sn(s);o.push([s,c,a])}await ta(Ku(n),{recursive:!0});try{await ta(n)}catch(s){throw s.code==="EEXIST"?new Fr(t):s}for(let[,s,a]of o)await ta(Ku(s),{recursive:!0}),await ow(s,a,{flag:"wx"});return{written:o.map(([s])=>s),skipped:i}}var _t=class extends Error{step;constructor(t,n){super(`git ${t} failed while merging (${n}). Nothing was written.`),this.name="MergeGitError",this.step=t}},nd=10,Hi=class extends Error{paths;constructor(t){let n=t.slice(0,nd).join(", "),r=t.length-nd;super(`The plugin folder changed after the merge was planned (${r>0?`${n} and ${String(r)} more`:n}). Nothing was written; run the merge again.`),this.name="MergeStaleError",this.paths=t}},ga=class extends Error{recoveryDir;constructor(t,n){super(`Applying the merge stopped partway (${xe(n)}). Files it removed are in ${he(t,"removed")}, and merged files it hadn't put in place yet are in ${he(t,"merged")}, each at its path in the plugin folder.`,{cause:n}),this.name="MergeApplyError",this.recoveryDir=t}},ha=class extends Error{path;constructor(t,n){super(`${t} ${n}, so the merge has nowhere safe to stage files. Nothing was written.`),this.name="MergeStagingError",this.path=t}},zr=class extends Error{path;constructor(t){super(`The merge plan includes "${t}", which isn't a writable source file. Nothing was written.`),this.name="UnsafeMergePathError",this.path=t}},Jw=[2,24],qw="git isn't installed or isn't on PATH.",Yw=6e4,Zw=1024*1024*1024,Xw=[["user.name","appbuilder"],["user.email","appbuilder@localhost"],["commit.gpgSign","false"],["core.autocrlf","false"],["core.safecrlf","false"],["core.fsmonitor","false"],["core.hooksPath",Mr],["core.attributesFile",Mr],["core.excludesFile",Mr],["merge.conflictStyle","merge"],["merge.renormalize","false"],["core.precomposeUnicode","false"],["init.defaultBranch","main"],["rerere.enabled","false"],["gc.auto","0"],["maintenance.auto","false"],["color.ui","false"]].flatMap(([e,t])=>["-c",`${e}=${t}`]),Qw=`* -text -eol -filter -ident -working-tree-encoding merge conflict-marker-size=7
|
|
138
|
+
`,ev="appbuilder <appbuilder@localhost> 0 +0000",ya=new TextEncoder,tv=e=>Fw("sha256").update(e).digest("hex"),nv=e=>e.subarray(0,8e3).includes(0),Le=e=>e.split("/");function rv(){try{return ua()}catch{return}}function iv(e,t){return{...la(e),HOME:t,XDG_CONFIG_HOME:t,GIT_CONFIG_GLOBAL:Mr,GIT_CONFIG_SYSTEM:Mr,GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0"}}function dd(e,t,n,r,i){return new Promise((o,s)=>{let a=Bw(e,[...Xw,...t],{cwd:n,env:r,timeout:Yw,maxBuffer:Zw,encoding:"buffer",windowsHide:!0},(c,l,d)=>{let u=c===null?0:c.code;if(typeof u!="number"){s(c??new Error("git did not exit"));return}o({code:u,stdout:l,stderr:d.toString("utf8")})});a.stdin?.on("error",()=>{});for(let c of i??[])a.stdin?.write(c);a.stdin?.end()})}async function ov(e,t,n){let r;try{r=await dd(e,["--version"],n,t)}catch(l){return`git couldn't be run (${xe(l)}).`}let i=/git version (\d+)\.(\d+)/.exec(r.stdout.toString("utf8"));if(r.code!==0||i===null)return"git couldn't report its version.";let[o,s]=[Number(i[1]),Number(i[2])],[a,c]=Jw;if(o<a||o===a&&s<c)return`git ${String(o)}.${String(s)} is older than ${String(a)}.${String(c)}, which merging needs.`}function sv(e){let t='"';for(let n of e){let r=n.charCodeAt(0);n==='"'||n==="\\"?t+=`\\${n}`:r<32||r===127?t+=`\\${r.toString(8).padStart(3,"0")}`:t+=n}return`${t}"`}function av(e,t,n){let r=[],i=a=>{r.push(ya.encode(a))},o=a=>{i(`data ${String(a.length)}
|
|
139
|
+
`),r.push(a),i(`
|
|
140
|
+
`)},s=(a,c,l,d)=>{i(`commit refs/heads/${a}
|
|
141
|
+
mark :${String(c)}
|
|
142
|
+
committer ${ev}
|
|
143
|
+
`),o(ya.encode(a)),d!==void 0&&i(`from :${String(d)}
|
|
144
|
+
deleteall
|
|
145
|
+
`);for(let[u,f]of l)i(`M 100644 inline ${sv(u)}
|
|
146
|
+
`),o(f)};return s("base",1,e),s("live",2,t,1),s("local",3,n,1),i(`done
|
|
147
|
+
`),r}var pd=e=>e.toString("utf8").split("\0").filter(t=>t!=="");function cv(e){let t=new Map;for(let n of pd(e)){let r=n.indexOf(" "),[,i,o]=n.slice(0,r).split(" "),s=n.slice(r+1),a=t.get(s)??new Map;a.set(Number(o),i??""),t.set(s,a)}return t}function lv(e){let t=new Map,n=0;for(;n<e.length;){let r=e.indexOf(10,n),[i="",,o]=e.subarray(n,r).toString("utf8").split(" ");if(o===void 0)throw new _t("cat-file",`missing object ${i}`);let s=r+1,a=s+Number(o);t.set(i,e.subarray(s,a)),n=a+1}return t}async function uv(e,t,n,r){await Xt(n);let i=async(b,y,C)=>{let S;try{S=await dd(e,y,n,t,C)}catch(x){throw new _t(b,xe(x))}if(S.code!==0&&!(b==="merge"&&S.code===1))throw new _t(b,S.stderr.trim()||`exit ${String(S.code)}`);return S};await i("init",["init","-q","--template=","."]),await Xt(he(n,".git","info"),{recursive:!0}),await ld(he(n,".git","info","attributes"),Qw),await i("fast-import",["fast-import","--quiet","--done"],av(r.base,r.live,r.local));let o=(await i("rev-parse",["rev-parse","--verify","local^{tree}"])).stdout.toString("utf8").trim();await i("checkout",["checkout","-q","local","--"]);let s=await i("merge",["merge","--no-ff","--no-edit","--no-verify","-q","live"]),a=cv((await i("ls-files",["ls-files","-u","-z"])).stdout),c=a.size>0;if(s.code===1!==c)throw new _t("merge",s.stderr.trim()||`exit ${String(s.code)}`);let l=[...a].filter(([,b])=>b.has(2)&&b.has(3)),d=[...new Set(l.flatMap(([,b])=>[...b.values()]))],u=d.length===0?new Map:lv((await i("cat-file",["cat-file","--batch"],[ya.encode(d.map(b=>`${b}
|
|
148
|
+
`).join(""))])).stdout),f=new Set(l.filter(([,b])=>[...b.values()].some(y=>nv(u.get(y)??new Uint8Array))).map(([b])=>b));await i("add",["add","-A","-f"]);let g=(await i("write-tree",["write-tree"])).stdout.toString("utf8").trim(),m=pd((await i("diff-tree",["diff-tree","-r","-z","--no-renames","--no-ext-diff","--no-textconv","--name-status",o,g])).stdout),p=[];for(let b=0;b+1<m.length;b+=2)p.push({status:m[b]??"",path:m[b+1]??""});let h=new Map;for(let{status:b,path:y}of p){if(!Zn(y))throw new _t("merge",`unexpected path "${y}"`);b!=="D"&&h.set(y,await Hw(he(n,...Le(y))))}return{changes:p,contents:h,unmerged:a,binary:f}}var dv=sd.O_NOFOLLOW??0;async function pv(e){let t=await Uw(e,sd.O_RDONLY|dv);try{return new Uint8Array(await t.readFile())}finally{await t.close()}}async function md(e,t){let n=await pa(e,t===void 0?{}:{git:t}),r=await Promise.all(n.files.map(l=>pv(he(e,...Le(l))))),i=n.files.map(l=>l.normalize("NFC")),o=new Set(i).size===i.length?i:n.files,s=new Map,a=new Map,c=new Map;return n.files.forEach((l,d)=>{let u=o[d]??l,f=r[d]??new Uint8Array;s.set(u,f),a.set(u,tv(f)),c.set(u,l)}),{files:s,hashes:a,diskPaths:c,mode:n.mode}}var rd=e=>new Map([...e].map(([t,n])=>[t.normalize("NFC"),n]));async function mv(e,t){let n=Le(t);for(let r=1;r<=n.length;r+=1){let i=await _e(En(he(e,...n.slice(0,r))));if(i===void 0)return"absent";if(r===n.length)return i.isFile()?"file":"blocked";if(!i.isDirectory())return"blocked"}return"blocked"}var ba=e=>e.isFile()&&e.nlink===1n?`${String(e.dev)}:${String(e.ino)}`:void 0;async function fd(e,t){let n=new Set;for(let r of t){let i=await _e(En(he(e,...Le(r)),{bigint:!0})),o=i===void 0?void 0:ba(i);o!==void 0&&n.add(o)}return n}async function gd(e,t){let n=await Vw(e);if(n.length===0)return!1;for(let r of n){let i=he(e,r),o=await En(i,{bigint:!0});if(!(o.isDirectory()?await gd(i,t):t.has(ba(o)??"")))return!1}return!0}async function hd(e,t,n){let r=Le(t);for(let i=1;i<=r.length;i+=1){let o=he(e,...r.slice(0,i)),s=await _e(En(o,{bigint:!0}));if(s===void 0)return"absent";if(s.isFile())return n.has(ba(s)??"")?"absent":"blocked";if(!s.isDirectory())return"blocked";if(i===r.length)return await gd(o,n)?"absent":"blocked"}return"blocked"}async function fv(e,t,n,r){let i=new Set;if(t.length===0)return i;let o=[await Br(e,ca),n==="walk"?await Br(e,".gitignore"):void 0];for(let s of t)o.some(a=>a?.ignores(s)===!0)&&i.add(s);if(n==="git"){let s=l=>/["\\\p{Cc}]/u.test(l),a=async l=>{try{let d=await r(["-c","core.quotePath=false","check-ignore","--",...l.map(u=>`./${u}`)],e);return new Set(d.split(`
|
|
149
|
+
`))}catch(d){if(d?.code===1)return new Set;let u=d?.stderr;throw new _t("check-ignore",typeof u=="string"&&u.trim()!==""?u.trim():xe(d))}},c=t.filter(l=>!s(l));for(let l=0;l<c.length;l+=100){let d=c.slice(l,l+100),u=await a(d);d.filter(f=>u.has(`./${f}`)).forEach(f=>i.add(f))}for(let l of t.filter(s))(await a([l])).size>0&&i.add(l)}return i}var Zt=e=>[...e].sort();function id(e,t){let[n,r]=[Ui(e),Ui(t)];return n===r||n.startsWith(`${r}/`)||r.startsWith(`${n}/`)}async function gv(e,t,n,r){let i=b=>t.diskPaths.get(b)??b;for(let{path:b}of n.changes)if(jr(b))throw new _t("merge",`unexpected path "${b}"`);let o=new Set(n.changes.filter(({status:b,path:y})=>b==="D"&&t.files.has(y)).map(({path:b})=>b)),s=await fd(e,[...o].map(i)),a=new Set,c=new Set,l=[];for(let{status:b,path:y}of n.changes)b!=="D"&&(t.files.has(y)?a.add(y):await hd(e,y,s)==="absent"?l.push(y):c.add(y));let d=await fv(e,l,t.mode,r);for(let b of l)(d.has(b)?c:a).add(b);let u=new Set,f=[],g=[],m=[];for(let[b,y]of n.unmerged)n.binary.has(b)?m.push(b):c.has(b)||(u.add(b),y.has(1)&&y.has(2)&&!y.has(3)?f.push(b):y.has(1)&&y.has(3)&&!y.has(2)&&g.push(b));let p=[...o].filter(b=>[...c].some(y=>id(y,b)));for(let b of p)o.delete(b),u.add(b);for(let b of[...c,...a])!t.files.has(b)&&p.some(y=>id(b,y))&&(c.delete(b),a.delete(b),u.add(b));let h=new Map;for(let b of a)h.set(b,n.contents.get(b)??new Uint8Array);return{written:Zt(a),deleted:Zt(o),conflicted:Zt(u),deletedOnLive:Zt(f),deletedLocally:Zt(g),binaryConflicts:Zt(m),ignoredIncoming:Zt(c),contents:h}}async function yd(e,t={}){if(e.base===null)return{status:"no_base"};let n=(t.findGit??rv)();if(n===void 0)return{status:"git_unavailable",reason:qw};let r=Vi(e.pluginDir),i=Vi(t.tmpDir??Gw());if(i===r||i.startsWith(r+ud))throw new Error("The merge workspace must not be inside the plugin folder.");let o=await zw(he(i,"appbuilder-merge-"));try{let s=he(o,"home");await Xt(s);let a=iv(t.env??process.env,s),c=await ov(n,a,o);if(c!==void 0)return{status:"git_unavailable",reason:c};let l=rd(_n(e.base.zip).files),d=rd(_n(e.live.zip).files),u=await md(r,t.git),f=await uv(n,a,he(o,"repo"),{base:l,live:d,local:u.files}),g=await gv(r,u,f,t.git??da);return g.written.length===0&&g.deleted.length===0&&g.conflicted.length===0&&g.binaryConflicts.length===0?{status:"up_to_date",ignoredIncoming:g.ignoredIncoming}:{status:"ready",pluginDir:r,baseVersion:e.base.version,liveVersion:e.live.version,...g,localHashes:u.hashes}}finally{await ad(o,{recursive:!0,force:!0})}}function od(e,t){let n=Vi(e,...Le(t));if(!Zn(t)||jr(t)||!n.startsWith(e+ud))throw new zr(t)}async function hv(e,t){let n=Le(t);for(let r=1;r<n.length;r+=1){let i=he(e,...n.slice(0,r));try{await Xt(i)}catch(o){if(o.code!=="EEXIST"||!(await En(i)).isDirectory())throw o}}}async function yv(e,t){let n=new Set;for(let i of t){let o=Le(i);for(let s=1;s<o.length;s+=1)n.add(o.slice(0,s).join("/"))}let r=[...n].sort((i,o)=>Le(o).length-Le(i).length);for(let i of r)await cd(he(e,...Le(i))).catch(()=>{})}var bv=".kizenapp",wv=(e,t)=>t?Ww(e,{bigint:!0}):En(e,{bigint:!0});async function vv(e,t){let n=he(e,bv),r=!1;try{await Xt(n),r=!0}catch(l){if(l.code!=="EEXIST")throw l}let i=async()=>{r&&await cd(n).catch(()=>{})},[o,s]=await Promise.all([t(n,!1),t(e,!0)]),a=o.isDirectory()?o.dev!==s.dev?"is on a different disk than the plugin folder":void 0:"isn't a real folder";if(a!==void 0)throw await i(),new ha(n,a);let c=he(n,`merge-${jw()}`);return await Xt(c),{staging:c,cleanUp:async()=>{await ad(c,{recursive:!0,force:!0}),await i()}}}async function bd(e,t={}){if(e.status!=="ready")return e;let n=Vi(e.pluginDir);for(let g of e.written){if(!e.contents.has(g))throw new zr(g);od(n,g)}for(let g of e.deleted){if(!e.localHashes.has(g))throw new zr(g);od(n,g)}let r=await md(n,t.git),i=Zt(new Set([...e.localHashes.keys(),...r.hashes.keys()].filter(g=>e.localHashes.get(g)!==r.hashes.get(g))));if(i.length>0)throw new Hi(i);let o=g=>r.diskPaths.get(g)??g,s=await fd(n,e.deleted.map(o)),a=[];for(let g of[...e.written,...e.deleted])(e.localHashes.has(g)?await mv(n,o(g))==="file":await hd(n,g,s)==="absent")||a.push(g);if(a.length>0)throw new Hi(a);let{staging:c,cleanUp:l}=await vv(n,t.stat??wv),d=[];try{for(let g of e.written){let m=he(n,...Le(o(g))),p=he(c,"merged",...Le(o(g)));await Xt(td(p),{recursive:!0}),await ld(p,e.contents.get(g)??new Uint8Array,{flag:"wx"}),e.localHashes.has(g)&&await Mw(p,(await En(m)).mode&4095),d.push({path:o(g),source:p,target:m})}}catch(g){throw await l(),g}if(t.isAborted?.()===!0)return await l(),{status:"cancelled"};let u=t.rename??Kw;try{for(let g of e.deleted.map(o)){let m=he(c,"removed",...Le(g));await Xt(td(m),{recursive:!0}),await u(he(n,...Le(g)),m)}await yv(n,e.deleted.map(o));for(let{path:g,source:m,target:p}of d)await hv(n,g),await u(m,p)}catch(g){throw new ga(c,g)}await l();let f={written:e.written,deleted:e.deleted,ignoredIncoming:e.ignoredIncoming};return e.conflicted.length===0&&e.binaryConflicts.length===0?{status:"merged",...f}:{status:"conflicts",...f,conflicted:e.conflicted,deletedOnLive:e.deletedOnLive,deletedLocally:e.deletedLocally,binaryConflicts:e.binaryConflicts}}import{randomUUID as kv}from"crypto";import{mkdir as Av,readFile as xv,rename as wd,rm as Pv,stat as Cv,writeFile as Sv}from"fs/promises";import{dirname as _v,join as kd}from"path";var In=".kizenapp/apps.json",Ad=".corrupt",Ur=class extends Error{constructor(){super(`${In} changed while this command ran, so it wasn't written.`),this.name="AppStateChangedError"}},wa=class extends Error{constructor(){super(`${In} exists but couldn't be read, so it wasn't overwritten. Fix its permissions and run the command again.`),this.name="AppStateUnreadableError"}},Vr=()=>({rest:{},entries:[],corrupt:!1,fingerprint:null}),xd=["environment","businessId","baseApiName","userId"],Pd=e=>e===null||typeof e=="string",Ev=e=>e===void 0||Pd(e),Cd=(e,t)=>F(e)&&xd.every(n=>e[n]===t[n]);function Sd(e){return F(e)&&xd.every(t=>typeof e[t]=="string"&&e[t]!=="")&&Ev(e.folderBaseLiveVersion)&&(typeof e.folderBaseLiveVersion=="string"?typeof e.folderBaseSourcePackageId=="string"&&e.folderBaseSourcePackageId!=="":e.folderBaseSourcePackageId===void 0)&&(e.previewSourcePackageId===void 0||typeof e.previewSourcePackageId=="string")&&Pd(e.lastPushedSourceHash)&&(e.previewRestoredFrom===void 0||typeof e.previewRestoredFrom=="string")&&(e.conflictedPaths===void 0||Array.isArray(e.conflictedPaths)&&e.conflictedPaths.every(t=>typeof t=="string"))}async function _d(e){try{let t=await Cv(e,{bigint:!0});return`${String(t.ino)}:${String(t.size)}:${String(t.mtimeNs)}`}catch(t){if(tt(t))return null;throw t}}var vd=(e,t)=>({doc:{...Vr(),corrupt:!0,fingerprint:t},notice:`${In} ${e}, so it was ignored. It will be moved to ${In}${Ad} on the next write.`});async function Ed(e){let t=kd(e,In),n,r;try{n=await _d(t),r=await xv(t,"utf8")}catch(c){return tt(c)?{doc:Vr()}:{doc:{...Vr(),unreadable:!0},notice:`Couldn't read ${In} (${ke(c)}), so it was ignored and won't be written.`}}let i;try{i=JSON.parse(r)}catch{return vd("is not valid JSON",n)}if(!F(i)||i.apps!==void 0&&!Array.isArray(i.apps))return vd("is not in the expected format",n);let{apps:o,...s}=i,a=Array.isArray(o)?[...o]:[];return{doc:{rest:s,entries:a,corrupt:!1,fingerprint:n}}}function va(e,t){let r=e.entries.filter(i=>Cd(i,t)).at(-1);return r===void 0?{status:"missing"}:Sd(r)?{status:"found",entry:r}:{status:"malformed"}}var Iv=["environment","businessId","baseApiName"];function Id(e,t,n){let r=e.entries.map(i=>{if(!F(i)||!Iv.every(s=>i[s]===t[s])||!Sd(i))return i;let o=n(i);return JSON.stringify(o)===JSON.stringify(i)?i:o});return r.some((i,o)=>i!==e.entries[o])?{...e,entries:r}:null}function ka(e,t){return{...e,entries:[...e.entries.filter(n=>!Cd(n,t)),t]}}async function Td(e,t){if(t.unreadable===!0)throw new wa;let n=kd(e,In),r=`${n}.${kv()}.tmp`;await Av(_v(n),{recursive:!0});let i={...t.rest,apps:t.entries};try{if(await Sv(r,`${JSON.stringify(i,null,2)}
|
|
150
|
+
`,{encoding:"utf8",flag:"wx"}),await _d(n)!==(t.fingerprint??null))throw new Ur;if(t.corrupt)try{await wd(n,`${n}${Ad}`)}catch(o){if(!tt(o))throw o}await wd(r,n)}catch(o){throw await Pv(r,{force:!0}).catch(()=>{}),o}}import{join as qi}from"path";var Nd="---\nname: kizen-business-apps\ndescription: Publish, preview, merge, roll back or pull this plugin as a Kizen Business App with `appbuilder app` (versions, push, publish, merge, rollback, pull, actions, preview). Use it when the user wants to release this plugin to their Kizen business, save, update or delete their preview, publish a new Live version, resolve a publish conflict or merge someone else's Live changes, restore an earlier release, download a released version's or their preview's source, or link the app's JS actions to objects.\n---\n\n# Kizen Business Apps\n\n`appbuilder app` publishes the plugin in this folder as a Business App on the business the user is signed in to. Publishing replaces Live for everyone in that business, so every write is a dry run first. Follow these rules exactly.\n\n## Before you start\n\n- Run every command from the plugin folder (the one with `kizen.json`), with `--json`.\n- If `appbuilder app` is an unknown command, the CLI is too old. Ask the user to upgrade `@kizenapps/cli` to 1.18.0 or later, then continue.\n- If a result's `warnings` contains `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}}`, re-read `{{SKILLS_DIR}}/kizen-business-apps/SKILL.md`, and follow the new copy.\n- Never edit, delete or commit anything in `.kizenapp/`. `.kizenapp/apps.json` records what this folder is based on; push and merge depend on it. Your preview's base isn't in it: it lives only in the preview's source on the server (see \"Another machine or folder\"), so publishing works from any machine.\n- The server numbers releases with whole numbers (1, 2, 3\u2026) when you publish. They aren't semver, and they can skip numbers, so never predict one: the publish dry run's `nextReleaseAtLeast` is only a lower bound.\n- Business App releases don't publish release notes and don't use `kizen.json` `version` (it isn't sent), so for an app release don't bump `version` or create or edit files in `release_notes_directory`.\n\n## The contract\n\n- `--json` prints one JSON object on stdout. Human text goes to stderr. Parse stdout only.\n- Exit `0`: success, dry runs included. Exit `2`: a decision is needed (`needs_choice` or `base_required`); its `choices` say how to go on. Exit `1`: any other failure, `{ ok: false, code, message, hint? }`.\n- Every `argv` you get (`choices[].argv`, `next[].argv`, `applyArgv`, `login.argv`, and a JS action's `linkArgv`, `linkMenuArgv`, `linkNoMenuArgv` and `unlinkArgv`) is a whole command starting with `appbuilder`. Run it exactly as given. Never add, drop or reorder its flags, and never build these commands yourself. The only edit you may make to any argv is replacing an element that is exactly `<object>` (in `linkArgv`, `linkMenuArgv` and `linkNoMenuArgv`) with an object's api name or id. They carry the account the run used (`--env`, `--business`, `--user`, or its `-c`/`--profile`), so they act on the same business.\n- `push`, `publish`, `merge`, `rollback` and `preview delete` without `--yes` are dry runs: `{ ok: true, applied: false, dryRun: true, \u2026, applyArgv, requiresProductionConsent, next: [] }`. `applyArgv` is that command with `--yes` (and `--allow-production` on `go` or `fmo`). It is pinned to what the dry run showed: `publish` to the preview it reviewed (`--expect-preview <id>`), `merge` to the version it planned (`--release <n>`), `rollback` to its version, `preview delete` to the preview's owner (`--owner <userId>`, yours included) and the preview it reviewed (`--expect-updated <ts>`), with `--delete-app` only when it warned that the app goes too. A `push` apply uploads the folder as it is when the apply runs.\n- `requiresProductionConsent: true` means the target is production (`go` or `fmo`). Show the user the dry run and get their explicit go-ahead in this conversation before running `applyArgv`.\n- Applied results have `applied: true` and `next`: the commands to run next, in order, each `{ step, argv }`. After a merge with conflicts, `next` starts with `{ step: \"resolve\", files, markers }`.\n- An applied publish whose `warnings` say \"this folder's base wasn't advanced\" did publish, but this folder still counts as based on the old Live. The next publish from it stops with `publish_conflict`; run the merge it offers, then push and publish.\n\n## Workflow\n\n1. **Look.** `appbuilder app versions --json` returns `live`, `released`, `previews`, `yourPreview`, `base` and `next`. `published: false` means the app isn't on this business yet; the first push and publish create it.\n2. **Push your preview.** `appbuilder app push --json` is a dry run. Show the user `environment`, `businessId`, `app`, `source.files`, `base` and `warnings`. When they agree, run `applyArgv`. A push saves only the user's own preview; Live doesn't change.\n3. **Link its JS actions.** Read the applied push's `jsActions` and link every action that needs it, `unlinked` and `unknown` alike (see \"JS actions\" below), before you move on.\n4. **Publish.** Run the applied push's `next` step `publish` (`appbuilder app publish --json`), a dry run. Show the user `app`, `conflictCheck`, `nextReleaseAtLeast` and `warnings`. When they agree, run `applyArgv`. It's done when `applied` is `true`; tell the user the new `liveVersion`, then check its `jsActions` again.\n5. **Every change after that:** edit, push (dry run, then `applyArgv`), link new JS actions, publish (dry run, then `applyArgv`).\n\n### Live moved: `publish_conflict`\n\nSomeone published since your preview's base, and publishing now would overwrite their changes. Never answer with `--force`.\n\n1. Run `next[0].argv` (`appbuilder app merge \u2026`), a dry run. Show the user `written`, `deleted`, `conflicted` and any other lists, then run `applyArgv` when they agree. A merge changes only local files.\n2. If the applied merge's `next` starts with a `resolve` step, edit every file in its `files`. The side between `<<<<<<< HEAD` and `=======` is this folder's; the side between `=======` and `>>>>>>> live` is Live's (or the merged `--release`). Keep both sides' intended changes and delete the three marker lines. `appbuilder app push` refuses with `unresolved_conflicts` (listing `files`) until no markers are left.\n3. Then follow the rest of `next`: push (dry run, `applyArgv`), publish (dry run, `applyArgv`).\n\n### No recorded base: `base_required` (exit 2)\n\nThis happens when Live exists, the folder matches neither your preview nor a released version exactly (an exact match is detected and used automatically: `base.source` is `\"preview\"` or `\"detected\"`), and no usable base is recorded for it. That's the first push from a fresh clone, another machine or another developer's folder, or a push whose recorded base no longer applies (that version was deleted, or the app was deleted and created again; a notice in the `message` says which). Show the user the `message` and each choice's `label`:\n\n- \"Preview merging Live vN into this folder\" is a dry run. You may run it without asking. With no base to merge from, it always comes back with `kind: \"fallback\"`, whose `choices` are \"Merge, if this folder was copied from vM\" (`--base <M>`) for recent releases, and \"This folder already contains vN\".\n- \"This folder already contains Live vN\" records the base without merging (`--accept-live-base`). Run it only when the user confirms the folder really contains that version, or the next publish drops Live's changes.\n- \"This folder continues your preview (based on vN)\" (`appbuilder app push --base-from-preview <id>`) is a push dry run that gives this folder your preview's base. Never run it on your own judgment: ask the user whether this folder really is the work they pushed as that preview (for example, carried on from another machine). Run it only when they say yes; a wrong yes lets the next publish overwrite Live's changes. Then show its dry run and run its `applyArgv` as for any push. If the user isn't sure, use the merge preview instead.\n\nAfter the fallback, ask the user which release this folder was copied from:\n\n- They know it: run that release's `--base <M>` choice. It merges for real; continue as after any merge (resolve markers, push, publish). A wrong base drops the changes made since then, so never guess one.\n- They don't know: run the fallback's `applyArgv`. It extracts Live's source into `.kizenapp/live-v<N>-<time>/` (reported as `extracted.dir`) and changes nothing else. Help the user merge Live's changes into this folder by hand, then run the \"This folder already contains vN\" choice, and push.\n\n### Another machine or folder\n\nEvery push and rollback stores the preview's base inside the preview's source on the server, and publish reads it from there. So:\n\n- Publishing a preview the user pushed from another machine or folder needs no merge and no `--force`, unless Live moved since (then it's the usual `publish_conflict`).\n- A push from a folder with nothing recorded takes the preview's base by itself when the folder's files equal the preview's (`base.source: \"preview\"`); otherwise `base_required` offers \"This folder continues your preview\", which only the user may choose.\n- `conflict.reason: \"base_replaced\"` (a `publish_conflict`) means the version your preview was based on has been replaced on the business (the app was deleted and created again). Handle it like any `publish_conflict`: run `next[0].argv`, the merge dry run.\n- `conflict.reason: \"base_unknown\"` (a `publish_conflict`) means the preview's source doesn't say what it's based on. Run `next[0].argv`, a push dry run of this folder; with the user's go-ahead, its `applyArgv`, then publish again.\n- A preview pushed from this folder and published outside the CLI (in Kizen, say) is recognised: the folder's base becomes that Live version, with a notice; don't merge because of the old base.\n\n### Roll back and pull\n\n- `appbuilder app rollback <n> --json` restores released version n as the user's preview (dry run, then `applyArgv`). Its `next` is the publish dry run that makes it Live.\n- `appbuilder app pull <n> --json` downloads release n into a new folder, `../<api_name>-v<n>` or `--out <dir>`, and records n as that folder's base. It never writes into an existing folder and needs no `--yes`. Continue in the folder it reports as `dir`.\n- `appbuilder app pull --preview --json` does the same with the user's own preview, into `../<api_name>-preview` or `--out <dir>`. Pass `<n>` or `--preview`, never both. The result has `source: \"preview\"`, `preview` and `base` instead of `version`. `base.recorded: true` means the folder's base is the preview's base, so you can push and publish from it as usual; `false` (with a warning) means the preview doesn't say what it's based on, and the first push from the folder may stop with `base_required`. `no_preview` means the user has no preview to pull.\n\n### Delete a preview\n\nOnly when the user asks to delete a preview:\n\n1. Run `appbuilder app preview delete --json`, a dry run for the user's own preview. For another developer's preview, add `--owner <userId>` with the user id from `previews[].previewOwner.id` in `appbuilder app versions --json`, and only when the user explicitly named that developer's preview.\n2. Show the user `owner`, `preview` and every `warnings` entry. They say when the preview is the app's only version (deleting it deletes the whole app from the business, settings and secrets included), when it belongs to someone else, and when other users are using it.\n3. When the user agrees to every warning, run `applyArgv`. Never add `--delete-app` yourself; `applyArgv` carries it only when the dry run warned that the app goes too. A dry run with no `applyArgv` can't be applied: relay its `notices` to the user. The result has `status: \"deleted\"` and `appDeleted` (`true` when the app went with it). After deleting their own preview, its `next` is a push dry run, which makes a new preview.\n\n`preview_changed` means the preview was pushed again after the dry run, or deleting it would now delete the whole app when the dry run said it stays: nothing was deleted. Run `next[0].argv`, a new dry run, and show it to the user again.\n\n### JS actions: link them to objects\n\nA JS action template does nothing until it's linked to an object. Always create these links with the CLI, even though the app's setup assistant may have a step for it. `push`, `publish` and `versions` results carry `jsActions`: `{ status, liveVersion, actions, next }`; `appbuilder app actions list --json` returns the same `actions`. Each action is `{ apiName, name, hintObjectName, status, inLive, links, linkArgv, linkMenuArgv, linkNoMenuArgv }`:\n\n- `linked`: it has at least one link (`links[]`, each with the object's `objectName`, `includePerformAction` (the Perform Action menu setting) and `unlinkArgv`). Nothing to do.\n- `unlinked`: in Live (or the app isn't on the business yet) with no link. Link it.\n- `unknown`: only in a preview, so its links can't be listed, and it may not be linked yet. Link it right after the push, like an `unlinked` one.\n\nHow to link:\n\n1. Pick the object with the user. For an `unlinked` action with a hint object, `jsActions.next` has a `link` step naming `hintObjectName`: it only suggests that object. Confirm it with the user, or ask which object (no hint, an `unknown` action, or the user wants another one). Don't run the `link` step itself; step 2's argv makes the one dry run.\n2. Ask whether the action should show in the object's Perform Action menus. Take the action's `linkMenuArgv` if it should, and its `linkNoMenuArgv` if it shouldn't (for a link that exists, that turns the menu off); `linkArgv` leaves a new link off the menus and an existing one as it is. Replace the one element that is exactly `<object>` with the object's api name (like `client_client`) or id, change nothing else, and run it: a dry run of `appbuilder app actions link \u2026`. Contacts counts as an object. Exit 2 with `choice: \"object\"` means several objects match: show the user the `choices` and run the one they pick.\n3. Show the user the dry run (`environment`, `businessId`, `jsAction`, `object`, `change`, `includePerformAction`, `warnings`). When they agree, run `applyArgv`. `status` is `created`, `updated`, `up_to_date` or `already_linked` (the link already existed and its menu setting wasn't changed: for an action only in a preview, linked before while its links couldn't be listed; for an action in Live, linked after this command listed the links, in which case run `appbuilder app actions list` and link it again to set the menu setting the user wants).\n4. Review with `appbuilder app actions list --json`: every action with its `status`, `links` and argvs, and link dry runs in `next`. It lists the links of Live's actions only; a preview-only action stays `unknown` until it's published.\n\nIf a link of an `unknown` action fails with `api_error` and a `hint` saying Kizen couldn't find it, that Kizen environment can only link actions in Live. Relay the hint: publish first, then link it.\n\nA link change to an action in Live (`inLive: true`), whether a new link, a menu setting or an unlink, reaches everyone using Live as soon as it's applied; its dry run's `warnings` say so. Treat it like a publish: confirm the object and the menu setting with the user before running its `applyArgv`.\n\nRemove a link only when the user asks: run that link's `unlinkArgv` (`appbuilder app actions unlink \u2026`, a dry run), then its `applyArgv` when they agree.\n\n### What a push uploads\n\nGit's file list (tracked files, plus untracked ones `.gitignore` doesn't exclude; outside git, everything minus the root `.gitignore`), minus the root `.kizenignore` (gitignore syntax; it can only exclude more). These are never uploaded, whatever either file says: `node_modules`, `.git`, `.kizenapp`, `.kizenappbuilder`, `.copilot-docs`, `__pycache__`, `dist`, `.DS_Store`, `.env`, `.env.*`, `.npmrc`, `credentials.json`, and the skill folders appbuilder manages (`kizen-custom-block` and `kizen-business-apps` under `.claude/skills/` and `.agents/skills/`). Other skills in those folders are uploaded like any file. Check `source.files` in the dry run, and suggest a `.kizenignore` entry for anything that shouldn't ship. A release needs a thumbnail.\n\n## Failures\n\n| `code` | What to do |\n| --- | --- |\n| `not_signed_in` | Ask the user to sign in by running `login.argv` themselves: it opens a browser (see Sandboxes). Then run your command again. |\n| `needs_choice` | `choice` is `environment`: the user is signed in to several. Ask which, then run that choice's `argv`. |\n| `base_required` | See \"No recorded base\" above. |\n| `publish_conflict` | Run `next[0].argv`: a merge dry run; a push dry run when `conflict.reason` is `base_unknown`; or, when your preview changed since the dry run, a new publish dry run. |\n| `unresolved_conflicts` | Resolve the markers in `files`, then push again. |\n| `no_preview` | Push first. For `pull --preview`, the user has no preview: tell them, or pull a release instead. |\n| `preview_changed` | Nothing was deleted. Run `next[0].argv`, a new `preview delete` dry run, and show it to the user before going on. |\n| `preview_incomplete` | Push again, then publish (or pull). |\n| `thumbnail_required` | Add a thumbnail to the plugin, push, then publish. |\n| `source_invalid` | The folder can't be zipped (no `kizen.json`, an unreadable `.kizenignore`, a folder git ignores, or a file over 50 MiB or 200 MiB in all). Fix what `message` says, for example with a `.kizenignore` entry. |\n| `validation_failed` | Fix every item in `issues`, then run the command again. |\n| `forbidden` | Tell the user they need the Marketplace \u203A Business App Developer permission at the Delete/All level. Don't retry. |\n| `production_requires_flag` | You ran a write against `go` or `fmo` without `--allow-production`. Run the dry run, get consent, then its `applyArgv`. |\n| `credentials_invalid` | The API-key file from `-c` or `--profile` is bad. Tell the user what `message` says. Use API keys only when the user asks. |\n| `auth_failed` | Kizen refused the session. Ask the user to sign in again (`appbuilder login`, with `--env <env>` for an environment other than `go`). |\n| `session_store_unwritable`, `network_error` | Usually a sandbox; see below. Otherwise relay `message` and `hint`. |\n| `not_found`, `usage_error`, `api_error`, `local_error` | Relay `message` to the user. |\n\n## Sandboxes\n\n`appbuilder` needs the network and write access to `~/.kizenappbuilder`, where it keeps the sign-in session and refreshes its tokens. It talks to the Kizen environment's hosts, and `push` uploads go to whichever file-storage host Kizen names for each upload.\n\n{{#codex}}\n- Codex's sandbox turns the network off and allows writes only to the workspace and `/tmp`. Run `appbuilder` commands with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]` so the user approves `appbuilder` once. A `network_error` with `sandbox: \"codex_network_disabled\"`, or a `session_store_unwritable`, means it ran without that.\n- `.agents/` is read-only in the sandbox, so `appbuilder setup-codex` needs the escalation too.\n- `appbuilder app pull` writes next to the plugin folder by default, outside the workspace. Escalate it, or pass an `--out <dir>` inside the workspace that `.gitignore` or `.kizenignore` excludes.\n- `not_signed_in`: the user runs `login.argv` in their own terminal. It opens a browser and waits for the sign-in.\n{{/codex}}\n{{#claude}}\n- Claude Code's sandbox, when enabled, allows writes only to the working directory and the network only to allowed domains. Because uploads go to a storage host Kizen picks, a domain list can't cover `appbuilder`. If it fails with `session_store_unwritable` or a `network_error`, ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n- `not_signed_in`: the user types `! ` followed by the `login.argv` command in this session, or runs it in their own terminal. It opens a browser and waits for the sign-in.\n{{/claude}}\n\n## Guardrails\n\n- Never pass `--force`, `--allow-production` or `--accept-live-base`, or run a choice whose `argv` contains one, unless the user explicitly asked for it in this conversation.\n- Always show the user a dry run before you run its `applyArgv`.\n- On exit 2, show the user the `choices` and run the one they pick. The merge preview is the only choice you may run without asking. Never pick \"This folder continues your preview\" for the user.\n- Never edit `.kizenapp/`.\n- Publish only when the user asked to publish.\n- Link a JS action only to an object the user confirmed, and unlink only when the user asked.\n- Delete a preview only when the user asked, and another developer's (`--owner`) only when the user named it.\n";var Rd="---\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 `{{SETUP_COMMAND}} --include-lib` in the plugin directory.\n\n- If it reports `updated` for `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, your loaded copy of this skill is stale. Re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md` before doing anything else, and follow the new copy.\n- If it reports `created` for any file in this skill directory, or `updated` for `{{SKILLS_DIR}}/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{{#codex}}\n- In the Codex sandbox `.agents/` is read-only, so run it with `sandbox_permissions: \"require_escalated\"`.\n{{/codex}}\n\n`{{SETUP_COMMAND}}` 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_COMMAND}}` 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 `appbuilder block push <api_name> --yes --json`.\n\n## Runtime rules\n\nBlocks run in the plugin engine web worker.\n\n- `script.js` is the body of an async function, and `this` is the worker context. Use `await` at the top level.\n- There is no DOM: no `document` or `window`. There are no npm packages. Don't use `eval` or `Function`.\n- Render with `this.outputUI(htmlString)`. The output is sanitized with DOMPurify, so `<script>` tags and `on*` attributes are stripped. Don't rely on them.\n- Charts are hand-built inline SVG strings. There are no chart libraries.\n- Interactivity: put `data-script=\"<eventScriptName>\"` on a `<button>` whose content is text only. Clicking it runs `eventScripts/<eventScriptName>.js` in a fresh worker, so no state carries over from `script.js`.\n- Args:\n - `this.args.dateFilter`: `{ start, end }`, or `undefined`.\n - `this.args.teamFilter`.\n - `this.args.objectId`: set on chart groups.\n - Homepages have no date or team filter. Handle both being absent.\n- Data: read records with the `kizenData.js` helpers (see \"Reading Kizen data\"). They call `this.getWithErrors` and `this.postWithErrors`, which use relative URLs and run as the viewing user.\n- Toasts: `this.showToast(message, options)`. `message` MUST be a string. Passing an object crashes the host app.\n- Styling:\n - The host applies `* { font-size: 10px }`. Set explicit px font sizes on everything.\n - With host chrome (the default), the host paints the card (background, border, border radius and shadow) from the dashboard's style settings, like native dashlets. The block root is transparent, fills the card, and paints no card of its own.\n - With `\"host_chrome\": false`, the host paints nothing: no background, border, radius or shadow. The block root fills the card edge to edge and owns its whole look (see \"Chrome off\" in `design.md`).\n - Put chart labels inside the SVG as `<text>` so they scale with the `viewBox`.\n- The code is stored in a Kizen dashlet. Never include a NUL character or the literal text `{__ref:` anywhere in any file.\n\n## Reading Kizen data\n\nRead records through `src/lib/kizenData.js`. Always import it from `../../lib/kizenData.js`. Its helpers take the worker context as their first argument, so pass `this`.\n\n- `getFields(this, object)` loads an object's fields. `object` is the object's id or name, and Contacts is `client_client`. Match fields by `name`.\n- `blockFilters(this.args, fields)` returns `{ filters, unapplied }`. Always apply `filters`, so the block reacts to the dashboard's date and team filters the way native dashlets do (date on `created`, team on `owner`). When `unapplied` contains `'teamFilter'`, the team filter couldn't be applied (a roles-only selection, or an object with no owner field). Show \"(team filter not applied)\".\n- `dropdownFilter(field, 'Name')` or `dropdownFilter(field, ['A', 'B'])` filters a dropdown by option names.\n- `searchRecords(this, { object, fieldNames, filters })` returns `{ records, count, truncated }`. When `truncated` is true, show \"Showing first N\" with N = `records.length`.\n- `fieldValue(record, name)`, `fieldLabel(record, name)`, `countBy(records, name, field?)`, `sumBy(records, name, valueOf?)` and `formatNumber(n, prefix)` read and summarize the results. `countBy` groups empty values under `key: ''`. Filter that group out, or give it a label.\n- Every record value or label you put into markup goes through `escapeHtml(value)`, including option names, owner names and text fields. `this.outputUI` sanitizes scripts, but it keeps images, links, forms and styles, and the block renders for every viewer. `escapeHtml` is the only escaping helper; never write your own.\n- Never hand-build filter or search JSON when a helper exists. Every helper throws a readable `Error`, so wrap the fetch in `try` and render the error state from `design.md`.\n\nCount Contacts by a dropdown field named `status` for the current dashboard filters. Use a field name from `getFields`:\n\n```js\nimport {\n blockFilters,\n countBy,\n escapeHtml,\n getFields,\n searchRecords,\n} from '../../lib/kizenData.js';\n\ntry {\n const fields = await getFields(this, 'client_client');\n const { filters, unapplied } = blockFilters(this.args, fields);\n const search = { object: 'client_client', fieldNames: ['status'], filters };\n const { records, count, truncated } = await searchRecords(this, search);\n const rows = countBy(records, 'status').filter((row) => row.key !== '');\n const items = rows.map((row) => `<li>${escapeHtml(row.label)}: ${row.count}</li>`).join('');\n const note = truncated ? `Showing first ${records.length} of ${count}. ` : '';\n const team = unapplied.includes('teamFilter') ? '(team filter not applied)' : '';\n this.outputUI(`<ul>${items}</ul><p>${note}${team}</p>`);\n} catch {\n this.outputUI('<div class=\"kz-state kz-state--error\">Couldn\\'t load data.</div>');\n}\n```\n\n## Design\n\nBefore writing any markup or styles, read `design.md` in this skill directory and follow it exactly.\n\n## The loop\n\nRun these exact commands. The flags and JSON keys are the contract. `<api_name>` is the block's `config.json` `api_name`. `block targets` and `block push` use the user's `appbuilder login` session by default. `-c/--credentials <path>` and `--profile <name>` opt in to a deprecated API key; use them only when the user asks.\n\nWith `--json` (`block targets` and `block push`), stdout is one JSON object and human text goes to stderr. Exit `0` is success (dry runs included), exit `2` means a decision is needed (`needs_choice`), and exit `1` is any other failure. Every `argv` a result gives you (`applyArgv`, `choices[].argv`, `login.argv`) is a whole command starting with `appbuilder`: run it exactly as given, without adding, dropping or reordering flags.\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 dry run's `applyArgv` exactly. It is the same push with `--yes`, pinned to the dashboard and dashlet the dry run showed. If `requiresProductionConsent` is `true` (the target is `go` or `fmo`), it also carries `--allow-production`: run it only after the user explicitly agreed to publish to production in this conversation. 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, applyArgv, requiresProductionConsent }`.\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 `{{STALE_WARNING}}`, run `{{SETUP_COMMAND}} --include-lib`, re-read `{{SKILLS_DIR}}/kizen-custom-block/SKILL.md`, then continue.\n- Error: `{ ok: false, code, message, hint?, choice?, choices?, login?, sandbox? }`. `code` is one of `needs_choice`, `validation_failed`, `invalid_block`, `not_signed_in`, `auth_failed`, `forbidden`, `remembered_target_missing`, `drift_detected`, `network_error`, `session_store_unwritable`, `credentials_invalid`, `production_requires_flag`, `not_found`, `usage_error`, `api_error` or `local_error`. When `hint` is present, follow it.\n\n### `needs_choice`\n\n`choice` is `'environment'`, `'block'`, `'dashboard'` or `'target'`. `choices` is a list of `{ value, label, argv, args, surface?, canEdit?, pushKey?, isFromThisPlugin? }`. Ask the user using each option's `label`, then run the chosen option's `argv` exactly as given: it is the push with that choice, as a dry run, so continue from its result (show it, then run its `applyArgv`). Ignore `args`, and never construct these flags by hand.\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 `not_signed_in`, ask the user to sign in by running the `login.argv` command themselves (it opens a browser), then run your command again.\n{{#claude}}\n In Claude Code they can type `! ` followed by that command in this session.\n{{/claude}}\n- On `credentials_invalid`, the API-key file from `-c` or `--profile` is bad. Tell the user to fix the file named in `message`. Don't run `--profile` or `-c` unless the user asks for an API key.\n- On `session_store_unwritable`, or a `network_error` with `sandbox: \"codex_network_disabled\"`, a sandbox is blocking `appbuilder`, which needs the network and write access to `~/.kizenappbuilder`.\n{{#codex}}\n Re-run the command with `sandbox_permissions: \"require_escalated\"`, and suggest `prefix_rule: [\"appbuilder\"]`.\n{{/codex}}\n{{#claude}}\n Ask the user to add `\"appbuilder *\"` to `sandbox.excludedCommands` in their user settings (`~/.claude/settings.json`), so `appbuilder` runs outside the sandbox. Project settings don't work for this when Claude Code runs in strict mode.\n{{/claude}}\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 $d=`# Designing a Kizen custom block
|
|
144
151
|
|
|
145
152
|
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".
|
|
146
153
|
|
|
@@ -489,7 +496,7 @@ render(
|
|
|
489
496
|
color: var(--color-font-placeholder);
|
|
490
497
|
}
|
|
491
498
|
\`\`\`
|
|
492
|
-
`;var
|
|
499
|
+
`;var Od=`# Copilot review instructions for this Kizen plugin
|
|
493
500
|
|
|
494
501
|
This repo is a Kizen plugin app: a \`kizen.json\` manifest plus the artifacts
|
|
495
502
|
that \`@kizenapps/packager\` finds by walking the directory tree under the
|
|
@@ -542,7 +549,7 @@ This file covers repo structure and general review. Two path-scoped files cover
|
|
|
542
549
|
the rest: \`.github/instructions/security.instructions.md\` for security-sensitive
|
|
543
550
|
patterns and \`.github/instructions/version-discipline.instructions.md\` for
|
|
544
551
|
manifest version bumps.
|
|
545
|
-
`;var
|
|
552
|
+
`;var Dd='---\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 Ld=`---
|
|
546
553
|
applyTo: "kizen.json"
|
|
547
554
|
---
|
|
548
555
|
|
|
@@ -555,7 +562,7 @@ cannot drift out of date here.
|
|
|
555
562
|
Check every \`kizen.json\` diff against the "How big a bump?" matrix in
|
|
556
563
|
\`.copilot-docs/16-release-and-publish.md\` and the "Release & publish" section of
|
|
557
564
|
\`.copilot-docs/17-gotchas.md\`, and name the change that sets the required level.
|
|
558
|
-
`;var
|
|
565
|
+
`;var Bd=`# Copilot only reads this file from the default branch, and only if the job is named copilot-setup-steps.
|
|
559
566
|
name: Copilot code review setup
|
|
560
567
|
|
|
561
568
|
on:
|
|
@@ -594,7 +601,7 @@ jobs:
|
|
|
594
601
|
echo "Fetched $count markdown files into .copilot-docs/ ($numbered numbered docs)"
|
|
595
602
|
test "$count" -ge 24
|
|
596
603
|
du -sh .copilot-docs
|
|
597
|
-
`;var
|
|
604
|
+
`;var Fd=`const MAX_PAGE_SIZE = 1000;
|
|
598
605
|
const DEFAULT_MAX_PAGES = 10;
|
|
599
606
|
|
|
600
607
|
const fieldCache = new Map();
|
|
@@ -839,22 +846,35 @@ export const sumBy = (records, name, valueOf) =>
|
|
|
839
846
|
total + (valueOf ? numberOf(valueOf(record)) : numberOf(fieldValue(record, name))),
|
|
840
847
|
0,
|
|
841
848
|
);
|
|
842
|
-
`;function jn(){return[{path:".github/copilot-instructions.md",content:sa},{path:".github/instructions/security.instructions.md",content:aa},{path:".github/instructions/version-discipline.instructions.md",content:ca},{path:".github/workflows/copilot-code-review.yml",content:la}]}var ua="lib/kizenData.js",go=(e="src")=>e===""?ua:`${e}/${ua}`;function Ln(e=[]){return[{path:".claude/skills/kizen-custom-block/SKILL.md",content:oa},{path:".claude/skills/kizen-custom-block/design.md",content:ia},...[...new Set(e)].map(t=>({path:go(t),content:da}))]}import{access as Df,mkdir as Rf,readFile as Of,writeFile as Bf}from"fs/promises";import{dirname as Ff,join as pa}from"path";var zn={readFile:async e=>{try{return await Of(e,"utf-8")}catch(t){if(fn(t))return;throw t}},writeFile:async(e,t)=>{await Rf(Ff(e),{recursive:!0}),await Bf(e,t,"utf-8")},exists:async e=>{try{return await Df(e),!0}catch{return!1}}},jf=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function yo(e,t,n=zn){return Promise.all(t.map(async r=>({path:r.path,status:jf(await n.readFile(pa(e,r.path)),r.content)})))}async function Mn(e,t,n={},r=zn){let o=await yo(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((i,s)=>o[s]?.status!=="unchanged").map(i=>r.writeFile(pa(e,i.path),i.content))),o}var Un=e=>`${e.status.padEnd(9)} ${e.path}`;var fa=".claude/skills/kizen-custom-block/SKILL.md",ha="Claude files managed by appbuilder are out of date; run appbuilder setup-claude",wo=zn,zf=e=>{if(typeof e!="string"||e.trim()==="")return;let t=mn(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Mf(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?zf(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var Uf=async(e,t)=>{try{let n=await t.readFile(Hn(e,"kizen.json"));return n===void 0?["src"]:Mf(JSON.parse(n))}catch{return["src"]}};async function ga(e,t=wo,n={}){let r=await Uf(e,t),o=n.includeLib===!0?r:(await Promise.all(r.map(async i=>await t.exists(Hn(e,go(i)))?i:void 0))).filter(i=>i!==void 0);return Ln(o)}async function ya(e,t=wo){try{let n=await ga(e,t);return!n.some(o=>o.path===fa)||await t.readFile(Hn(e,fa))===void 0?!1:(await yo(e,n,t)).some(o=>o.status!=="unchanged")}catch{return!1}}var Hf="@kizenapps/cli",Kf=6e4,Vf=(e,t)=>new Promise((n,r)=>{let o=Lf(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:Kf}),i="",s="";o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",a=>{i+=a}),o.stderr.on("data",a=>{s+=a}),o.on("error",r),o.on("close",a=>{n({code:a,stdout:i,stderr:s})})}),ba=e=>({run:Vf,hasOAuthSession:async t=>await Ce().readSession(t)!==null,cliVersion:e,fs:wo,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}}),bo=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;function Wf(e,t){let n=`kizen-${e}`,r=`${ze(e)}/api/mcp`,o=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${Hf}@${t} auth-header`}),i=["mcp","add-json","--scope","user",n,o];return{environment:e,name:n,url:r,addArgs:i,addCommand:["claude",...i].map(le).join(" ")}}function qf(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.mcp===!0&&e.includeLib===!0?"--mcp and --include-lib can't be combined. Run `appbuilder setup-claude --include-lib` and `appbuilder setup-claude --mcp` separately.":e.env===void 0?void 0:ot(e.env).message}var Gf=e=>/already\s+exists/i.test(`${e.stdout}
|
|
843
|
-
${e.stderr}`),ma=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function Jf(e,t,n){let r=Wf(e,n.cliVersion),{name:o}=r,i=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${o}: ${a}`),i&&(n.error(`The old ${o} registration was already removed, so Claude Code has no ${o} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&Gf(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${ma(c)}`);return}i=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${ma(a)}`);return}}catch(a){if(!i&&Te(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(oe(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${xe(e)}\` before using ${r.name}.`)}catch(a){n.log(oe(a))}}async function wa(e,t,n){let r=qf(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}let o=t.dryRun===!0;if(t.mcp===!0){await Jf((t.env===void 0?void 0:ot(t.env).environment)??Ue,{dryRun:o,force:t.force===!0},n);return}if(!await n.fs.exists(Hn(e,"kizen.json"))){n.error("Error: kizen.json not found. Run this command from a plugin directory, or pass --mcp to only register the MCP server."),n.setExitCode(1);return}let i;try{i=await Mn(e,await ga(e,n.fs,{includeLib:t.includeLib===!0}),{dryRun:o},n.fs)}catch(c){n.error(`Error: ${oe(c)}`),n.setExitCode(1);return}for(let c of i)n.log(Un(c));let s=`${bo(i,"created")}, ${bo(i,"updated")}, ${bo(i,"unchanged")}`,a="these files are managed by appbuilder, so local edits to them are replaced";n.log(o?`Dry run: ${s}; nothing written (${a}).`:`Claude files: ${s} (${a}).`)}function Qf(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),listAccounts:r=>e.listAccounts(r),connect:async(r,o)=>{let i=wn(r,e,{...n&&{fetch:n},...o!==void 0&&{account:o}}),s=Bt({bearer:i,...n&&{fetch:n}});return{identity:await s.getIdentity(),client:s}}}}function xo(e){return{cwd:e,loadCredentialsDetailed:yn,listLoadableCredentialProfiles:Ii,loadConfig:Se,packageBlocks:po,createClient:t=>Bt({credentials:t}),readPushMap:Fs,writePushMap:js,ensureGitignore:Pe,isClaudeSkillStale:t=>ya(t),randomUUID:Yf,now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},processEnv:process.env,oauth:Qf(Ce())}}var em=new Set(["owner","admin","edit"]),tm="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",Vn=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function K(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var ge=e=>({ok:!0,value:e});function Re(e){return e instanceof Z?K(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof Zf?K("validation_failed",De(e.issues),{issues:e.issues}):K("local_error",Vn(e))}async function ka(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(i){return K("credentials_invalid",`Couldn't read credentials from ${e}: ${Vn(i)}`)}if(n.environmentSource!=="explicit"){let i=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return K("credentials_invalid",`${e} ${i}. Set it to one of: ${W.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,o=["apiKey","userId","businessId"].filter(i=>r[i].trim()==="");return o.length>0?K("credentials_invalid",`${e} is missing ${o.map(i=>`"${i}"`).join(", ")}.`):ge({credentials:r,client:t.createClient(r),notices:[]})}async function nm(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(o=>o.name===e);if(!r){let o=n.map(i=>i.name);return K("credentials_invalid",o.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${He} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${o.join(", ")}`)}return ka(r.path,t)}async function rm(e){let{activeCredentialProfile:t}=await e.loadConfig(Xf(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[Si(t)]}async function om(e,t,n){let r=await zt(e,t,n.oauth);if(!r.ok)switch(r.problem){case"not_signed_in":return K("credentials_invalid",Pi(r.message));case"several_sessions":return K("needs_choice",r.message,{choice:"environment",choices:r.environments.map(a=>({value:a,label:a,args:["--env",a]}))});case"unknown_environment":return K("usage_error",r.message)}let{environment:o}=r,i;if(t!==void 0){let a;try{a=await n.oauth.listAccounts(o)}catch(c){return Re(c)}try{i=Mt(o,a,t)}catch(c){return K("usage_error",Vn(c))}}let s;try{s=await n.oauth.connect(o,i)}catch(a){return Re(a)}return ge({credentials:{environment:o,businessId:s.identity.businessId},client:s.client,notices:await rm(n)})}async function Wn(e,t){let n=Ci(e,t.processEnv);if(!n.ok)return K("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?om(r.env,r.account,t):r.credentials===void 0?nm(r.profile,t):ka(r.credentials,t)}function im(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:o})=>{let i=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===o),s=n?`${r}/${o}`:o;return{value:o,label:`${i?.name??o} (${s})`,args:[o]}})}async function ko(e,t){let n=await t.packageBlocks(t.cwd),r=fo(n,e,"push");if(!r.ok){let{reason:g,message:m,field:h}=r;return g==="no_blocks"||g==="invalid_block"?K("invalid_block",m,h===void 0?{}:{field:h}):K("needs_choice",m,{choice:"block",choices:im(n.deployable,r.available)})}let{block:o,pluginApiName:i,views:s,warnings:a}=r.value,c=Es(o,s);return ge({block:o,pluginApiName:i,content:c,contentHash:oo(c),warnings:a})}var Ca=e=>e==null?null:em.has(e.toLowerCase());function Wt(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:Ca(e.employee_access)}}var Sa=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),sm="Contacts";async function Co(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Sa).sort((o,i)=>o.objectName.localeCompare(i.objectName));return n!==null&&n!==""&&!r.some(o=>o.id===n)&&r.push({id:n,objectName:sm,fetchUrl:"client"}),r}async function am(e,t,n){let{environment:r,businessId:o}=t;try{if(n.object!==void 0){let c=n.object,[g,m]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return ge({ok:!0,environment:r,businessId:o,object:g?Sa(g):null,surfaces:{chart_group:m.map(h=>Wt(h,"chart_group"))}})}let[i,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),Co(e)]);return ge({ok:!0,environment:r,businessId:o,surfaces:{dashboard:i.map(c=>Wt(c,"dashboard")),homepage:s.map(c=>Wt(c,"homepage"))},customObjects:a})}catch(i){return Re(i)}}var So=(e,t)=>t.dashboard===e.id;function qn(e,t){return[...Is(e).filter(r=>So(e,r)).map(r=>{let o=ks(r.name);return{value:r.id,label:Dn(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:o?r.name:null,isFromThisPlugin:o?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var Po=(e,t)=>Ds({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),Pa=(e,t)=>ge({dashboard:e,surface:ao(e.type),action:"create",dashlet:void 0,resolvedBy:t}),Kn=(e,t,n)=>ge({dashboard:e,surface:ao(e.type),action:"update",dashlet:t,resolvedBy:n});async function cm(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=o=>i=>({value:i.id,label:i.name,args:["--dashboard",i.id],surface:o,canEdit:Ca(i.employee_access)});return K("needs_choice",`Choose where to push; pass --dashboard <id>. ${tm}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function lm(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return Pa(r,"flag");let o=()=>qn(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&So(r,c));return a?wt(a)?Kn(r,a,"flag"):K("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.`):K("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:o()})}let i=Po(e,r);return i.kind==="map"?Kn(r,i.dashlet,"push_map"):i.kind==="name"?Kn(r,i.dashlet,"name"):K("needs_choice",i.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(i.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:o()})}async function dm(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(i){if(i instanceof Z&&i.kind==="not_found")return K("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw i}if(n.create)return Pa(r,"remembered");let o=r.dashlets.find(i=>i.id===t.dashletId&&So(r,i));return o&&wt(o)?Kn(r,o,"remembered"):K("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:qn(r,e.block)})}async function Eo(e,t){if(t.dashlet!==void 0&&t.create)return K("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return K("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await lm(e,t.dashboard,t):e.entry?await dm(e,e.entry,t):await cm(e)}catch(n){return Re(n)}}async function um(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:o,fetch_url:i}=r;return typeof i=="string"?{id:o,fetchUrl:i}:{id:o}}if(n!=="chart_group")return{id:r};try{let o=await e.getCustomObject(r);return{id:r,fetchUrl:o.fetch_url}}catch{return{id:r}}}async function _o(e,t,n,r){let{credentials:o,block:i}=e,{dashboard:s,surface:a}=t,c=[],g,m;if(t.action==="update"){let{dashlet:y}=t;if(Rs(y,e.entry)){let f=`"${Dn(y)}" (dashlet ${y.id}) was changed in Kizen since the last push.`;if(!n.force)return K("drift_detected",`${f} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${f} Overwriting it because of --force.`)}g={action:"update",method:"PATCH",path:Ot(s.id,y.id),body:As(y,i.content),dashletId:y.id},m=`Update "${Dn(y)}" (dashlet ${y.id})`}else g={action:"create",method:"POST",path:Ot(s.id),body:_s({pluginApiName:i.pluginApiName,blockApiName:i.block.api_name,content:i.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},m=`Create a new block on "${s.name}"`;let h=zs({appBaseUrl:pi[o.environment],surface:a,dashboardId:s.id,customObject:await um(e.client,s,a)});return ge({...g,dashboard:{id:s.id,name:s.name,type:a},url:h,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:o.environment,businessId:o.businessId,isProduction:Ar(o.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:m,dashletId:g.dashletId,blockName:i.block.name,blockApiName:i.block.api_name,pluginApiName:i.pluginApiName,scriptBytes:Buffer.byteLength(i.content.script,"utf8"),stylesBytes:Buffer.byteLength(i.content.styles,"utf8"),...i.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(i.content.views),"utf8")}}})}var Ao=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function To(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return K("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Re(a)}let o=[...t.warnings],i={...Ao(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,Os(e.pushMap,i)),s=!0}catch(a){o.push(`The push succeeded, but ${pt} couldn't be written, so this target isn't remembered: ${Vn(a)}`)}return ge({dashletId:r,remembered:s,warnings:o})}var pm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Io(e){return pm.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function fm(e,t){let n=Ao(e);if(!so(e.pushMap,n))return null;let r=Bs(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function $o(e,t){let{client:n,credentials:r,block:o}=e,i=await t.readPushMap(t.cwd),s=!1;if(e.forget){let a=await fm({credentials:r,block:o,pushMap:i},t);a&&(i=a,s=!0)}return{context:{client:n,credentials:r,block:o,pushMap:i,entry:so(i,Ao({credentials:r,block:o}))},forgotten:s}}function No(e,t){return e.dryRun?ge({kind:"dry-run",reason:"flag"}):e.yes?Ar(t)&&!e.allowProduction?K("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 mm="Dry run only: pass --yes to write.",ft=e=>e.map(t=>`Warning: ${t}`);function qt(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 hm=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;function gm(e,t,n){let r=[`Error: ${e.message}`];if(e.hint!==void 0&&r.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){r.push("Choices:");for(let o of e.choices){let i=n(o,e.choice).map(le).join(" ");r.push(` ${o.label} \u2192 ${t} ${i}`)}}return`${r.join(`
|
|
849
|
+
`;function Ki(){return[{path:".github/copilot-instructions.md",content:Od},{path:".github/instructions/security.instructions.md",content:Dd},{path:".github/instructions/version-discipline.instructions.md",content:Ld},{path:".github/workflows/copilot-code-review.yml",content:Bd}]}var jd="lib/kizenData.js",Aa=(e="src")=>e===""?jd:`${e}/${jd}`,Fv={"kizen-custom-block":[["SKILL.md",Rd],["design.md",$d]],"kizen-business-apps":[["SKILL.md",Nd]]};var Md=e=>ji.map(t=>`${Ke[e].skillsDir}/${t}/SKILL.md`);function Wi(e,t=[]){let{skillsDir:n}=Ke[e];return[...ji.flatMap(r=>Fv[r].map(([i,o])=>({path:`${n}/${r}/${i}`,content:Hu(o,e)}))),...[...new Set(t)].map(r=>({path:Aa(r),content:Fd}))]}var zd=(e=[])=>Wi("claude",e),Ud=(e=[])=>Wi("codex",e);import{access as jv,lstat as Mv,mkdir as zv,readFile as Uv,realpath as Vd,writeFile as Vv}from"fs/promises";import{dirname as Hv,join as xa,sep as Kv}from"path";var Xn=class extends Error{constructor(n,r){super(`Refusing to write ${n}: ${r}. appbuilder writes its managed files only as regular files inside the plugin folder, so nothing was written. Remove or replace it, then run this command again.`);this.path=n;this.name="UnsafeManagedPathError"}path},Wv=(e,t)=>t===e||t.startsWith(e+Kv);async function Gv(e,t){let n=t.split("/");if(n.some(o=>o===""||o==="."||o===".."))throw new Xn(t,"it is not a plain relative path");let r=await Vd(e),i=e;for(let[o,s]of n.entries()){i=xa(i,s);let a=n.slice(0,o+1).join("/"),c;try{c=await Mv(i)}catch(d){if(tt(d))return;throw d}if(c.isSymbolicLink())throw new Xn(t,`${a} is a symbolic link`);let l=o===n.length-1;if(l?!c.isFile():!c.isDirectory())throw new Xn(t,`${a} is not a ${l?"regular file":"directory"}`)}if(!Wv(r,await Vd(i)))throw new Xn(t,"it resolves outside the plugin folder")}var gt={readFile:async e=>{try{return await Uv(e,"utf-8")}catch(t){if(tt(t))return;throw t}},writeFile:async(e,t)=>{await zv(Hv(e),{recursive:!0}),await Vv(e,t,"utf-8")},exists:async e=>{try{return await jv(e),!0}catch{return!1}},checkPath:Gv},Jv=(e,t)=>e===void 0?"created":e===t?"unchanged":"updated";async function Pa(e,t,n=gt){for(let r of t)await n.checkPath(e,r.path);return Promise.all(t.map(async r=>({path:r.path,status:Jv(await n.readFile(xa(e,r.path)),r.content)})))}async function Gi(e,t,n={},r=gt){let i=await Pa(e,t,r);return n.dryRun===!0||await Promise.all(t.filter((o,s)=>i[s]?.status!=="unchanged").map(o=>r.writeFile(xa(e,o.path),o.content))),i}var Ji=e=>`${e.status.padEnd(9)} ${e.path}`;var qv=e=>{if(typeof e!="string"||e.trim()==="")return;let t=Ai(e);if(!(t===".."||t.startsWith("../")||t.startsWith("/")))return t};function Hd(e){let n=(Array.isArray(e)?e:[e]).map(r=>typeof r=="object"&&r!==null&&"entry"in r?qv(r.entry):void 0).filter(r=>r!==void 0);return n.length>0?[...new Set(n)]:["src"]}var Yv=async(e,t)=>{try{let n=await t.readFile(qi(e,"kizen.json"));return n===void 0?["src"]:Hd(JSON.parse(n))}catch{return["src"]}};async function Sa(e,t,n=gt,r={}){let i=await Yv(e,n),o=r.includeLib===!0?i:(await Promise.all(i.map(async s=>await n.exists(qi(e,Aa(s)))?s:void 0))).filter(s=>s!==void 0);return Wi(t,o)}async function _a(e,t,n=gt){try{return(await Promise.all(Md(t).map(async o=>await n.readFile(qi(e,o))!==void 0))).includes(!0)?(await Pa(e,await Sa(e,t,n),n)).some(o=>o.status!=="unchanged"):!1}catch{return!1}}async function Yi(e,t=gt){let n=await Promise.all(Fi.map(r=>_a(e,r,t)));return Fi.filter((r,i)=>n[i]===!0).map(r=>Ke[r].staleWarning)}var Ca=(e,t)=>`${String(e.filter(n=>n.status===t).length)} ${t}`;async function Zi(e,t,n,r){if(!await r.fs.exists(qi(e,"kizen.json"))){r.error(`Error: kizen.json not found. Run this command from a plugin directory${n.notFoundHint??""}.`),r.setExitCode(1);return}let i;try{i=await Gi(e,await Sa(e,t,r.fs,{includeLib:n.includeLib}),{dryRun:n.dryRun},r.fs)}catch(a){r.error(`Error: ${ke(a)}`),r.setExitCode(1);return}for(let a of i)r.log(Ji(a));let o=`${Ca(i,"created")}, ${Ca(i,"updated")}, ${Ca(i,"unchanged")}`,s="these files are managed by appbuilder, so local edits to them are replaced";r.log(n.dryRun?`Dry run: ${o}; nothing written (${s}).`:`${Ke[t].filesLabel} files: ${o} (${s}).`)}var tn=class extends Error{code;constructor(t,n){super(n),this.name="BusinessAppError",this.code=t}},Ea="A thumbnail is required to publish a release. Add a thumbnail image to the app.",Qt=encodeURIComponent,Zv="Business Apps aren't available on this Kizen environment yet.",Xv="Kizen has no Business Apps list on this environment (it answered 404). Use an environment where Business Apps are available, with --env.",Qv=e=>e instanceof q&&e.kind==="not_found",ek=e=>new q("not_found",Zv,{...e.status!==void 0&&{status:e.status},hint:Xv,details:e.details,cause:e}),en=(e,t)=>new q("api_error",`${e} ${t} returned an unexpected response shape`);function Tn(e,t,n){if(!F(n))throw en(e,t);return n}var Kd=(e,t)=>t.every(n=>typeof e[n]=="string");function tk(e,t){let n=Tn("GET",e,t),{url:r,fields:i,s3object_id:o,max_file_size:s}=n;if(typeof r!="string"||!F(i)||!Object.values(i).every(a=>typeof a=="string")||typeof i.key!="string"||typeof o!="string"||typeof s!="number")throw en("GET",e);return{url:r,fields:i,key:i.key,s3objectId:o,maxFileSize:s}}var Qn=e=>typeof e=="string"?e:void 0;function nk(e){if(!F(e)||typeof e.id!="string")return null;let t=e.browser_js_action_template,n=e.custom_object,r=e.include_perform_action;if(!F(t)||typeof t.api_name!="string"||!F(n)||typeof n.id!="string"||r!=null&&typeof r!="boolean")return null;let i=Qn(n.object_name),o=Qn(n.entity_name);return{id:e.id,include_perform_action:r??null,browser_js_action_template:{id:Qn(t.id)??"",api_name:t.api_name,name:Qn(t.name)??t.api_name,hint_object_name:Qn(t.hint_object_name)??null},custom_object:{id:n.id,name:Qn(n.name)??"",...i===void 0?{}:{object_name:i},...o===void 0?{}:{entity_name:o}}}}function Wd(e,t,n={}){let r=n.fetch??fetch,i=`/external-integrations/plugin-apps/${Qt(t)}`,o=u=>`${i}/${Qt(u)}`,s=(u,f)=>`${o(u)}/previews/${Qt(f)}`,a=u=>`/external-integrations/business-plugin-apps/${Qt(u)}/browser-js-action-template-associations`,c="/external-integrations/browser-js-action-template-association",l=async u=>Tn("GET",u,await e.requestJson("GET",u)),d=async(u,f,g,m)=>{let p=new FormData;for(let[b,y]of Object.entries(u.fields))p.append(b,y);p.append("file",new Blob([f],{type:g}),m);let h;try{h=await r(u.url,{method:"POST",body:p})}catch(b){throw new q("network_error",`Couldn't upload ${m} to file storage: ${xe(b)}`)}if(!h.ok){let b=await h.text().catch(()=>""),y=/<Code>([^<]+)<\/Code>/.exec(b)?.[1];throw new q("api_error",`Uploading ${m} to file storage failed with ${String(h.status)}${y===void 0?"":`: ${y}`}`,{status:h.status,details:b===""?void 0:b})}return await h.body?.cancel().catch(()=>{}),h.headers.get("etag")??""};return{async listApps(u){let f=u===void 0||u===""?"":`?${new URLSearchParams({search:u}).toString()}`,g=`${i}/apps${f}`,m;try{m=await e.requestJson("GET",g)}catch(p){throw Qv(p)?ek(p):p}if(!Array.isArray(m)||!m.every(F))throw en("GET",g);return m},async getApp(u,f={}){let g=f.previewOwner===void 0?"":`?${new URLSearchParams({preview_owner:f.previewOwner}).toString()}`,m=`${o(u)}${g}`;return Tn("GET",m,await e.requestJson("GET",m))},async getVersion(u,f){return l(`${o(u)}/versions/${Qt(String(f))}`)},async getPreview(u,f){return l(s(u,f))},async publish(u){if(u.release&&!u.thumbnail)throw new tn("thumbnail_required",Ea);let f=`${i}/publish`,g=Tn("POST",f,await e.requestJson("POST",f,u));if(!Kd(g,["api_name","base_api_name","version"]))throw en("POST",f);return g},async promotePreview(u,f){let g=`${s(u,f)}/promote`,m=Tn("POST",g,await e.requestJson("POST",g));if(!Kd(m,["api_name","version"]))throw en("POST",g);return m},async deletePreview(u,f){await e.requestJson("DELETE",s(u,f))},async uploadFile(u,f){let m=`/s3/presigned-post?${new URLSearchParams({filename:f.filename,contenttype:f.contentType,source:f.source}).toString()}`,p=tk(m,await e.requestJson("GET",m));if(u.byteLength>p.maxFileSize)throw new tn("file_too_large",`${f.filename} is ${String(u.byteLength)} bytes; the limit is ${String(p.maxFileSize)} bytes.`);let h=await d(p,u,f.contentType,f.filename),b=`/s3/success?${new URLSearchParams({source:f.source}).toString()}`,y={uuid:p.s3objectId,key:p.key,name:f.filename,etag:h};f.isPublic===!0&&(y.is_public="true");let C=Tn("POST",b,await e.postForm(b,y));if(typeof C.id!="string")throw en("POST",b);return C.id},async downloadFile(u){return e.getBinary(`/files/${Qt(u)}/download`)},async listActionAssociations(u){let f=a(u),g=Tn("GET",f,await e.requestJson("GET",f));if(!Array.isArray(g.associations))throw en("GET",f);return g.associations.map(m=>{let p=nk(m);if(p===null)throw en("GET",f);return p})},async createActionAssociation(u){await e.requestJson("POST",c,{browser_js_action_template:{api_name:u.actionApiName,plugin_app_api_name:u.appApiName},custom_object:{id:u.objectId},include_perform_action:u.includePerformAction})},async updateActionAssociation(u,f,g){await e.requestJson("PATCH",`${a(u)}/${Qt(f)}`,{include_perform_action:g})},async deleteActionAssociation(u){await e.requestJson("DELETE",`${c}/${Qt(u)}`)},async listObjects(){return(await e.listCustomObjects({customOnly:!1})).map(f=>({id:f.id,name:f.name??"",objectName:f.object_name,entityName:f.entity_name??null}))}}}function rk(e){return structuredClone(Object.fromEntries(Object.entries(e??{}).filter(([,t])=>t!==void 0)))}function ik(e){let t=n=>structuredClone(n??[]);return{data_adornments:t(e.data_adornments),floating_frames:t(e.floating_frames),custom_blocks:t(e.custom_blocks),routable_pages:t(e.routable_pages),toolbar_items:t(e.toolbar_items),object_settings_menu_items:t(e.object_settings_menu_items),calendar_sources:t(e.calendar_sources),js_action_templates:t(e.js_action_templates),route_script_templates:t(e.route_scripts),automation_action_configs:t(e.automation_action_configs)}}var Xi=e=>typeof e=="string"?e:void 0;function Ia(e,t){if(t.release&&!t.thumbnailId)throw new tn("thumbnail_required",Ea);let n=e,r={name:e.name,api_name:e.api_name,engine:e.engine,services:structuredClone(e.services??[]),base_config:rk(e.base_config),artifacts:ik(e.artifacts),release:t.release,source_filesystem_package:t.sourcePackageId,thumbnail:t.thumbnailId},i=Xi(e.description),o=Xi(e.agentic_description),s=Xi(n.external_link),a=Xi(e.releaseNotes);return i!==void 0&&(r.description=i),o!==void 0&&(r.agentic_description=o),s!==void 0&&(r.external_link=s),e.config_template!==void 0&&(r.config_template=structuredClone(e.config_template)),Array.isArray(n.catalogs)&&n.catalogs.every(c=>typeof c=="string")&&(r.catalogs=[...n.catalogs]),a!==void 0&&(r.release_notes=a),r}import{join as lk}from"path";import{PluginValidationError as uk}from"@kizenapps/packager";import{mkdir as ok,readFile as sk,writeFile as ak}from"fs/promises";import{join as Gd}from"path";async function ht(e){try{let t=await sk(Gd(e,"config.json"),"utf-8");return JSON.parse(t)}catch{return{}}}async function nn(e,t){await ok(e,{recursive:!0}),await ak(Gd(e,"config.json"),JSON.stringify(t,null,2),"utf-8")}var Ta=(e,t,n)=>`${String(e)} ${e===1?t:n}`,Na=e=>{let t=new Map;for(let n of e){let r=n.path??n.pluginApiName??"general",i=t.get(r)??[];i.push(n),t.set(r,i)}return t},ck=e=>{let t=e.filter(i=>i.severity==="error").length,n=e.length-t;if(t===0)return`\u26A0 ${Ta(n,"validation warning","validation warnings")}`;let r=`\u2717 ${Ta(t,"validation error","validation errors")}`;return n===0?r:`${r}, ${Ta(n,"warning","warnings")}`};function We(e){if(e.length===0)return"";let t=[...Na(e)].map(([n,r])=>[n,...r.map(i=>` ${i.severity==="error"?"\u2717":"\u26A0"} ${i.message} (${i.rule})`)].join(`
|
|
850
|
+
`));return[ck(e),...t].join(`
|
|
851
|
+
|
|
852
|
+
`)}function me(e,t,n={}){return{ok:!1,code:e,message:t,...n}}var I=e=>({ok:!0,value:e}),je=e=>e instanceof Error?e.message:typeof e=="string"?e:"Unknown error";function Me(e){return e instanceof q?me(e.kind,e.message,e.hint===void 0?{}:{hint:e.hint}):e instanceof uk?me("validation_failed",We(e.issues),{issues:e.issues}):me("local_error",je(e))}function Yd(e,t={}){let{fetch:n}=t;return{listSessions:()=>e.listSessions(),listAccounts:r=>e.listAccounts(r),connect:async(r,i)=>{let o=_i(r,e,{...n&&{fetch:n},...i!==void 0&&{account:i}}),s=xr({bearer:o,...n&&{fetch:n}});return{identity:await s.getIdentity(),client:s}}}}function Qi(e){return{cwd:e,loadCredentialsDetailed:Ci,listLoadableCredentialProfiles:nu,loadConfig:ht,createClient:t=>xr({credentials:t}),now:()=>new Date,writeStdout:t=>{process.stdout.write(t)},writeStderr:t=>{process.stderr.write(t)},setExitCode:t=>{process.exitCode=t},processEnv:process.env,oauth:Yd(ft())}}var dk=(e,t)=>["appbuilder","login",...e===void 0?[]:["--env",e],...t===void 0?[]:["--business",t.business,...t.user===void 0?[]:["--user",t.user]]];function pk(e,t){return t.CODEX_CI!==void 0?`Ask the user to sign in: they run \`${e}\` in their own terminal, where it opens a browser and waits for the sign-in. Then run this command again.`:t.CLAUDECODE!==void 0?`Ask the user to sign in: they type \`! ${e}\` in this Claude Code session, or you run it in the background and give them the URL it prints. Then run this command again.`:`Ask the user to sign in: they run \`${e}\` in a terminal, or you run it in the background and give them the URL it prints. Then run this command again.`}function Ra(e,t,n,r){let i=dk(t,n);return me("not_signed_in",e,{login:{argv:i},hint:pk(i.map(ge).join(" "),r)})}var mk=e=>e instanceof q&&e.cause instanceof ue&&e.cause.code==="login_required";async function Zd(e,t){let n;try{n=await t.loadCredentialsDetailed(e)}catch(o){return me("credentials_invalid",`Couldn't read credentials from ${e}: ${je(o)}`)}if(n.environmentSource!=="explicit"){let o=n.environmentSource==="missing"?'has no "environment"':'has an invalid "environment"';return me("credentials_invalid",`${e} ${o}. Set it to one of: ${pe.join(", ")}. The CLI won't default to production.`)}let{credentials:r}=n,i=["apiKey","userId","businessId"].filter(o=>r[o].trim()==="");return i.length>0?me("credentials_invalid",`${e} is missing ${i.map(o=>`"${o}"`).join(", ")}.`):I({credentials:{environment:r.environment,businessId:r.businessId,userId:r.userId},client:t.createClient(r),notices:[]})}async function fk(e,t){let n=await t.listLoadableCredentialProfiles(),r=n.find(i=>i.name===e);if(!r){let i=n.map(o=>o.name);return me("credentials_invalid",i.length===0?`No loadable credential profile named "${e}". No profiles are loadable; create ${Kt} or pass -c <path>.`:`No loadable credential profile named "${e}". Loadable profiles: ${i.join(", ")}`)}return Zd(r.path,t)}async function gk(e){let{activeCredentialProfile:t}=await e.loadConfig(lk(e.cwd,".kizenapp"));return t===void 0||t===""?[]:[Yl(t)]}async function $a(e,t,n){let{sessions:r,processEnv:i,signedOutMessage:o=l=>l}=n,s=await _r(e,t,r);if(!s.ok)switch(s.problem){case"not_signed_in":return Ra(o(s.message),e,t,i);case"several_sessions":return me("needs_choice",s.message,{choice:"environment",choices:s.environments.map(l=>({value:l,label:l,args:["--env",l]}))});case"unknown_environment":return me("usage_error",s.message)}let{environment:a}=s,c;if(t!==void 0){let l;try{l=await r.listAccounts(a)}catch(d){return Me(d)}try{c=Er(a,l,t)}catch(d){return Sr(l,t.business,t.user).kind==="none"?Ra(je(d),a,t,i):me("usage_error",je(d))}}try{return I({environment:a,connected:await n.connect(a,c)})}catch(l){return mk(l)?Ra(je(l),a,t,i):Me(l)}}async function hk(e,t,n){let r=await $a(e,t,{sessions:n.oauth,connect:(s,a)=>n.oauth.connect(s,a),processEnv:n.processEnv,signedOutMessage:Zl});if(!r.ok)return r;let{environment:i,connected:o}=r.value;return I({credentials:{environment:i,businessId:o.identity.businessId,userId:o.identity.userId},client:o.client,notices:await gk(n)})}async function Nn(e,t){let n=ql(e,t.processEnv);if(!n.ok)return me("usage_error",n.message);let{selection:r}=n;return r.kind==="oauth"?hk(r.env,r.account,t):r.credentials===void 0?fk(r.profile,t):Zd(r.credentials,t)}function Ye(e,t){return e.dryRun?I({kind:"dry-run",reason:"flag"}):e.yes?Kn(t)&&!e.allowProduction?me("production_requires_flag",`${t} is a production environment. Pass --allow-production with --yes to write to it.`):I({kind:"apply"}):I({kind:"dry-run",reason:"no_yes"})}var eo="Dry run only: pass --yes to write.",Q=e=>e.map(t=>`Warning: ${t}`),Oa=e=>e.json?["--json"]:[],Et=(e,t,n)=>[...e.split(" "),...t,...Oa(n)],yk=2,bk=new Set(["needs_choice","base_required"]),wk=e=>bk.has(e)?yk:1,vk="CODEX_SANDBOX_NETWORK_DISABLED",Jd=`The Codex sandbox has network access turned off, so appbuilder can't reach Kizen. Re-run this command with sandbox_permissions: "require_escalated", and suggest prefix_rule: ["appbuilder"] so later appbuilder commands can reach the network too.`;function kk(e,t){return e.code!=="network_error"||t[vk]!=="1"?e:{...e,sandbox:"codex_network_disabled",hint:e.hint===void 0?Jd:`${Jd} ${e.hint}`}}var qd=e=>e.map(ge).join(" ");function Ak(e){let t=[`Error: ${e.message}`];if(e.hint!==void 0&&t.push(`Hint: ${e.hint}`),e.choices&&e.choices.length>0){t.push("Choices:");for(let n of e.choices)t.push(` ${n.label} \u2192 ${qd(n.argv)}`)}if(e.next&&e.next.length>0){t.push("Next:");for(let n of e.next)t.push(` ${n.step} \u2192 ${qd(n.argv)}`)}return`${t.join(`
|
|
853
|
+
`)}
|
|
854
|
+
`}function It(e,t,n){let r=kk(t,e.deps.processEnv),{choices:i,...o}=r,s=i===void 0?o:{...r,choices:i.map(a=>({...a,argv:n(a,o.choice)}))};e.json?e.deps.writeStdout(`${JSON.stringify(s,null,2)}
|
|
855
|
+
`):e.deps.writeStderr(Ak(s)),e.deps.setExitCode(wk(t.code))}function Pe(e,t,n,r=n){e.json?(e.deps.writeStdout(`${JSON.stringify(t,null,2)}
|
|
856
|
+
`),e.deps.writeStderr(r)):e.deps.writeStdout(n)}var ze=(e,t)=>{for(let n of t)e.writeStderr(`${n}
|
|
857
|
+
`)},rn=(e,t)=>{let n=bn(e,t);if(!n.ok||n.request===void 0)return[];let{business:r,user:i}=n.request;return["--business",r,...i===void 0?[]:["--user",i]]},Rn=(e,t)=>e.credentials!==void 0?["-c",e.credentials]:e.profile!==void 0?["--profile",e.profile]:[...e.env===void 0?[]:["--env",e.env],...rn(e,t)],to=(e,t)=>e.credentials!==void 0||e.profile!==void 0?Rn(e,{}):["--env",t.environment,"--business",t.businessId,"--user",t.userId];import*as er from"fs";import*as Xd from"path";var xk=[".kizenapp/",".copilot-docs/"];function Ze(e){let t=Xd.join(e,".gitignore"),n="";er.existsSync(t)&&(n=er.readFileSync(t,"utf8"));let r=new Set(n.split(`
|
|
858
|
+
`).map(a=>a.trim())),i=xk.filter(a=>!r.has(a)&&!r.has(a.replace(/\/$/,"")));if(i.length===0)return!1;let o=i.join(`
|
|
859
|
+
`)+`
|
|
860
|
+
`,s=n===""||n.endsWith(`
|
|
861
|
+
`)?o:`
|
|
862
|
+
`+o;return er.writeFileSync(t,n+s),!0}import{mkdir as Nk,writeFile as Rk}from"fs/promises";import{join as $k}from"path";import{PluginValidationError as Ok,packagePlugin as Dk,parseManifestFromFiles as Lk,transformDeployablePlugin as Bk,transformFiles as Fk,validatePluginApp as jk}from"@kizenapps/packager";import{readdir as Pk,readFile as Qd}from"fs/promises";import{join as ep,relative as Ck}from"path";var Sk=new Set([".png",".svg"]),_k=new Set([".kzn"]),Ek=new Set([".DS_Store"]),no=new Set(["node_modules",".git",".kizenapp",".copilot-docs",".github",".claude","__pycache__"]),Ik=8e3;function Tk(e){return e.subarray(0,Ik).includes(0)}async function tp(e,t){let n=await Pk(e,{withFileTypes:!0}),r=[];for(let i of n)if(i.isDirectory()){if(no.has(i.name))continue;r.push(...await tp(ep(e,i.name),t))}else i.isFile()&&(Ek.has(i.name)||r.push(ep(e,i.name)));return r}async function ro(e,{detectBinaryByContent:t=!1}={}){let n=await tp(e,e);return Promise.all(n.map(async r=>{let i=Ck(e,r).split("\\").join("/"),o=i.lastIndexOf("."),s=o>=0?i.slice(o).toLowerCase():"";if(Sk.has(s)){let c=await Qd(r);return{path:i,content:"",base64Image:c.toString("base64")}}let a=await Qd(r);return _k.has(s)||t&&Tk(a)?{path:i,content:"",binaryData:a}:{path:i,content:a.toString("utf-8")}}))}var Mk=(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 n=await ro(e);t?.("validating");let r=jk(n);if(r.some(c=>c.severity==="error"))throw new Ok(r);t?.("minifying");let i=await Fk(n);t?.("packaging");let o=Lk(i),s=Dk(i,o),a=Object.values(s).map(Bk);return{files:n,deployable:a,issues:r}}async function io(e,t,n){await Nk(t,{recursive:!0});let{files:r,deployable:i}=await Hr(e,n);n?.("writing-bundle");let o=i.map(l=>{let d=l.release_notes_directory?.replace(/\/$/,""),u=d?r.filter(f=>f.path.startsWith(d+"/")&&f.path.endsWith(".md")&&f.content).map(f=>({version:f.path.slice(f.path.lastIndexOf("/")+1,-3),notes:f.content})).sort((f,g)=>g.version.localeCompare(f.version,void 0,{numeric:!0})):[];return Mk(l,u)}),s=JSON.stringify(o,null,2),a=(l,d)=>l==="allReleaseNotes"?void 0:d,c=Buffer.byteLength(JSON.stringify(o,a,2),"utf-8");return await Rk($k(t,"bundle.json"),s,"utf-8"),{bundleSize:c}}var H=me,Kr="kizen.json";async function Jk(e){let t;try{t=await op($n(e,Kr),"utf8")}catch(o){throw tt(o)?new Error(`No ${Kr} in ${e}. Run this command from the plugin folder.`):o}let n;try{n=JSON.parse(t)}catch(o){throw new Error(`${Kr} isn't valid JSON (${je(o)}). If it has merge conflict markers, resolve them first.`)}let r=Array.isArray(n)?n[0]:n,i=F(r)?r.api_name:void 0;if(typeof i!="string"||i==="")throw new Error(`${Kr} has no api_name.`);return i}var qk=async e=>{try{return await Uk(e),!0}catch{return!1}};function sp(e){return{...Qi(e),packageLocalPlugin:t=>Hr(t),zipSourceDir:t=>Xu(t),readManifestApiName:Jk,businessApps:(t,n)=>Wd(t,n),readAppState:Ed,writeAppState:Td,ensureGitignore:Ze,planMerge:t=>yd(t),applyMerge:(t,n)=>bd(t,n),unzipToDir:ed,pathExists:qk,readTextFile:t=>op(t,"utf8"),makeTempDir:()=>Vk($n(Kk(),"appbuilder-version-")),removeDir:t=>Hk(t,{recursive:!0,force:!0}),staleAgentFileWarnings:t=>Yi(t)}}var Yk="Business Apps need the Marketplace \u203A Business App Developer permission at the Delete/All level.";function z(e){if(e instanceof Or||e instanceof Dr||e instanceof Lr||e instanceof qn)return H("source_invalid",e.message);if(e instanceof tn)return H(e.code==="thumbnail_required"?"thumbnail_required":"local_error",e.message);let t=Me(e);return t.code==="forbidden"?{...t,hint:Yk}:t}function On(e,t){return/^\d+$/.test(e)&&/^\d+$/.test(t)?Number(e)-Number(t):e.localeCompare(t,void 0,{numeric:!0})}var on=(e,t)=>e===null||t===null?e===t:On(e,t)===0;function oo(e){let t=e.trim();return/^[1-9]\d*$/.test(t)?I(t):H("usage_error",`"${e}" isn't a version number; pass a release number like 3.`)}var lo=e=>zk("sha256").update(e).digest("hex"),Bn=e=>Array.isArray(e.versions)?e.versions:[],uo=e=>[...new Set(Bn(e).filter(t=>t.status==="live"||t.status==="released").map(t=>t.version))].sort((t,n)=>On(n,t));function ap(e){return typeof e=="string"&&e!==""?e:F(e)&&typeof e.full_name=="string"&&e.full_name!==""?e.full_name:null}function Zk(e){let t=Bn(e);return t.find(n=>n.status==="live")??t.find(n=>e.live_version!==null&&on(n.version,e.live_version))}var rt=e=>e.state.status==="found"?e.state.entry:void 0,Wr=(e,t)=>e.find(n=>n.base_api_name===t)??null,za=(e,t)=>e===null?null:Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null;async function qr(e,t){let{credentials:n,baseApiName:r}=e,i=t.businessApps(e.client,n.businessId),o,s;try{[o,s]=await Promise.all([i.listApps(r),t.readAppState(t.cwd)])}catch(h){return z(h)}let a=Wr(o,r),c={environment:n.environment,businessId:n.businessId,baseApiName:r,userId:n.userId},l=va(s.doc,c),d=s.notice===void 0?[]:[s.notice];l.status==="malformed"&&d.push(`The saved state for ${r} in .kizenapp/apps.json is malformed, so it was ignored.`);let u=await Qk(i,a,l.status==="found"?l.entry:void 0),f=za(a,n.userId),g=l.status==="found"?lp(l.entry,u):void 0,m=a!==null&&f===null&&g!==void 0&&Ln.some(h=>h in g)?{sourceId:g.previewSourcePackageId??null}:void 0,p=g===void 0?l:{status:"found",entry:cp(g,m)};return u!==void 0&&d.push(Xk(u.version)),I({credentials:n,api:i,baseApiName:r,app:a,yourPreview:f,stateKey:c,state:p,...u===void 0?{}:{promoted:u},...m===void 0?{}:{previewGone:m},notices:d})}function cp(e,t){return t===void 0?e:(e.previewSourcePackageId??null)===t.sourceId?an(e,...Ln):e}var Xk=e=>`The preview this folder pushed was published as Live v${e} outside this command, so v${e} is now this folder's base.`;async function Qk(e,t,n){let r=t?.live_version??null,i=n?.previewSourcePackageId,o=n?.folderBaseLiveVersion;if(!(t===null||r===null||i===void 0||n?.previewRestoredFrom!==void 0||o===void 0||on(o,r)))try{if((await e.getVersion(t.api_name,r)).source_filesystem_package!==i)return;let a=ma(await e.downloadFile(i));return a!==null&&a.baseSourcePackageId===(n?.folderBaseSourcePackageId??null)?{version:r,sourceId:i}:void 0}catch{return}}function lp(e,t){return t===void 0||e.previewSourcePackageId!==t.sourceId?e:nr(an(e,...Ln),t.version,t.sourceId)}async function up(e){let t;try{t=await e.api.listApps(e.baseApiName)}catch(r){return z(r)}let n=Wr(t,e.baseApiName);return I({...e,app:n,yourPreview:za(n,e.credentials.userId)})}function Xe(e){let{credentials:t,app:n}=e;return{environment:t.environment,businessId:t.businessId,userId:t.userId,isProduction:Kn(t.environment),baseApiName:e.baseApiName,apiName:n?.api_name??null,name:n?.name??null,liveVersion:n?.live_version??null}}var Ua=e=>({...e,lastPushedSourceHash:null});async function dp(e,t,n){for(let r=0;;r+=1)try{let{doc:i}=await n.readAppState(e),o=t(i);return o===null||(r===0&&n.ensureGitignore(e),await n.writeAppState(e,o)),null}catch(i){if(!(i instanceof Ur)||r>=1)return je(i)}}var eA=(e,t,n,r)=>dp(e,i=>{let o=va(i,t);return ka(i,n(o.status==="found"?o.entry:Ua(t)))},r),Yr=(e,t,n)=>eA(n.cwd,e.stateKey,r=>t(cp(lp(r,e.promoted),e.previewGone)),n);function an(e,...t){return Object.fromEntries(Object.entries(e).filter(([n])=>!t.includes(n)))}function nr(e,t,n){let r=an(e,"folderBaseLiveVersion","folderBaseSourcePackageId");return t===null?{...r,folderBaseLiveVersion:null}:n===null?r:{...r,folderBaseLiveVersion:t,folderBaseSourcePackageId:n}}var Va=e=>e?.folderBaseLiveVersion,tA=(e,t)=>e.app===null?void 0:t(rt(e)),nA=e=>e.app===null?Va(rt(e)):void 0,rA=e=>`The base recorded for this folder (v${e}) is from a version of the app that's no longer on this business, so it's ignored.`,Gr=e=>e===null?"no Live version":`v${e}`,Ha=(e,t,n)=>t===null?`${e} ${n}`:`${e} is based on ${Gr(t)}`,pp="was started before the app had a Live version",iA="was pushed before the app had a Live version",Dn=e=>`.kizenapp/apps.json couldn't be written, so this isn't remembered: ${e}`,Nt=e=>e instanceof q&&e.kind==="not_found",oA=(e,t)=>H("not_found",`Version ${t} of ${e.baseApiName} doesn't exist on this business.`),Zr=(e,t)=>H("not_found",`${e.baseApiName} isn't published to this business yet, so there's nothing to ${t}.`),Rt=e=>e.app===null?null:e;async function so(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return Nt(i)?oA(e,t):z(i)}let r=n.source_filesystem_package;return typeof r!="string"||r===""?H("not_found",`Version ${t} of ${e.baseApiName} has no source package.`):I({...n,source_filesystem_package:r})}async function Jr(e,t){let n=await so(e,t);if(!n.ok)return n;let r=n.value.source_filesystem_package;try{return I({sourceId:r,zip:await e.api.downloadFile(r)})}catch(i){return z(i)}}var Fa={baseLiveVersion:null,baseSourcePackageId:null};async function mp(e,t){let n=await fp(e,t);return n.ok?I(n.value.found?n.value.sourceId:null):n}async function fp(e,t){let n;try{n=await e.api.getVersion(e.app.api_name,t)}catch(i){return Nt(i)?I({found:!1}):z(i)}let r=n.source_filesystem_package;return I({found:!0,sourceId:typeof r=="string"&&r!==""?r:null})}async function sA(e,t){let n=Rt(e);if(t===null)return I(Fa);if(n===null)return Zr(e,"restore");let r=await so(n,t);return r.ok?I({baseLiveVersion:t,baseSourcePackageId:r.value.source_filesystem_package}):r}async function Ka(e,t){try{let n=await e.downloadFile(t);return I({sourcePackageId:t,zip:n,lineage:ma(n)})}catch(n){return z(n)}}async function aA(e){let t=Rt(e);if(t===null||e.yourPreview===null)return I(null);let n;try{n=await t.api.getPreview(t.app.api_name,t.credentials.userId)}catch(i){return Nt(i)?I(null):z(i)}let r=n.source_filesystem_package;return typeof r=="string"&&r!==""?Ka(t.api,r):I(null)}async function gp(e,t){if(t===null)return I(null);let n=t.baseLiveVersion;if(n===null)return I(t);let r=Rt(e);if(r===null)return I(null);let i=await mp(r,n);return i.ok?I(i.value!==null&&i.value===t.baseSourcePackageId?t:null):i}var hp=5;function tr(e){let{files:t}=_n(e);return new Map([...t].map(([n,r])=>[n,lo(r)]))}var yp=(e,t)=>e.size===t.size&&[...e].every(([n,r])=>t.get(n)===r);async function bp(e,t){let n=Rt(e);if(n===null)return I(null);let r=n.app.live_version,i=[...new Set([...r===null?[]:[r],...uo(n.app)])].slice(0,hp),o;try{o=tr(t)}catch{return I(null)}for(let s of i){let a=await Jr(n,s);if(!a.ok){if(a.code==="not_found")continue;return a}let c;try{c=tr(a.value.zip)}catch{continue}if(yp(o,c))return I({version:s,sourceId:a.value.sourceId})}return I(null)}function cA(e,t){try{return yp(tr(e),tr(t))}catch{return!1}}var wp=e=>`No base is recorded for this folder, but its files match v${e} exactly, so v${e} is used as its base.`,lA=e=>`No base is recorded for this folder, but its files match your preview exactly, so your preview's base (${e===null?"no Live version":`v${e}`}) is used as its base.`,Wa=e=>`The base recorded for this folder (v${e}) no longer matches v${e} on this business (the app or that version was deleted and created again), so it's ignored.`,uA="Your preview changed since this folder was said to continue it, so its base wasn't used.",dA=e=>e===null?"This folder continues your preview (pushed before the app had a Live version)":`This folder continues your preview (based on v${e})`;function pA(e,t,n={}){let{preview:r}=n,i=[{value:"merge",label:`Preview merging Live v${t} into this folder`,args:[],argv:["appbuilder","app","merge","--release",t]},{value:"accept",label:`This folder already contains Live v${t}`,args:[],argv:["appbuilder","app","merge","--release",t,"--accept-live-base","--yes"]},...r==null?[]:[{value:"preview",label:dA(r.lineage.baseLiveVersion),args:[],argv:["appbuilder","app","push","--base-from-preview",r.sourcePackageId]}]],o=r==null?"":" Or, if this folder continues your preview, push it with your preview's base.";return H("base_required",`${(n.notices??[]).map(s=>`${s} `).join("")}No base version is recorded for this folder, and Live is v${t}. Merge Live into this folder, or record that it already contains Live, then push.${o}`,{choice:"base",choices:i})}async function rr(e){let t=tA(e,Va),n=Rt(e);if(t===void 0)return I({status:"none"});if(t===null||n===null)return I({status:"recorded",version:null,sourceId:null});let r=rt(e)?.folderBaseSourcePackageId??"";if(e.promoted!==void 0&&on(e.promoted.version,t))return I({status:"recorded",version:t,sourceId:e.promoted.sourceId});let i=await fp(n,t);return i.ok?i.value.found?i.value.sourceId===r?I({status:"recorded",version:t,sourceId:r}):I({status:"replaced",version:t}):I({status:"gone",version:t}):i}var Ga=e=>`The base recorded for this folder (v${e}) no longer exists on this business, so it's ignored.`;async function mA(e,t,n={}){let r=[],i,o=async()=>{if(i===void 0){let m=await aA(e);if(!m.ok)return m;if(m.value===null)i=null;else{let p=await gp(e,m.value.lineage);if(!p.ok)return p;i={source:m.value,lineage:p.value}}}return I(i)};if(n.baseFromPreview!==void 0){let m=await o();if(!m.ok)return m;let p=m.value?.source.sourcePackageId===n.baseFromPreview?m.value.lineage:null;if(p!==null)return I({version:p.baseLiveVersion,source:"base_from_preview",lineage:p,previewSourcePackageId:n.baseFromPreview,notices:r});r.push(uA)}let s=await rr(e);if(!s.ok)return s;if(s.value.status==="replaced")r.push(Wa(s.value.version));else if(s.value.status==="gone")r.push(Ga(s.value.version));else if(s.value.status==="recorded"){let{version:m,sourceId:p}=s.value;return I({version:m,source:"recorded",lineage:m===null||p===null?Fa:{baseLiveVersion:m,baseSourcePackageId:p},notices:r})}let a=e.app?.live_version??null;if(a===null)return I({version:null,source:"never_published",lineage:Fa,notices:r});let c=await o();if(!c.ok)return c;let l=c.value?.lineage??null,d=c.value===null||l===null?null:{sourcePackageId:c.value.source.sourcePackageId,lineage:l};if(d!==null&&c.value!==null&&cA(t,c.value.source.zip)){let m=d.lineage.baseLiveVersion;return I({version:m,source:"preview",lineage:d.lineage,notices:[...r,lA(m)]})}let u=await bp(e,t);if(!u.ok)return u;if(u.value===null)return pA(e,a,{preview:d,notices:r});let{version:f,sourceId:g}=u.value;return I({version:f,source:"detected",lineage:{baseLiveVersion:f,baseSourcePackageId:g},notices:r})}function fA(e,t){let n=e.preview_owner;return{version:e.version,status:e.status,previewOwner:n?{id:n.id,fullName:n.full_name}:null,yours:e.status==="preview"&&n?.id===t,updated:e.updated,publishedAt:e.published_at,publishedBy:ap(e.published_by)}}var gA=(e,t)=>On(t.version,e.version),vp=e=>({recorded:e!==void 0,version:e??null});function po(e,t){let n=Xe(e),r=t.status==="gone"?Ga(t.version):t.status==="replaced"?Wa(t.version):void 0,i=vp(t.status==="recorded"?t.version:void 0),o=n.liveVersion,s=i.recorded&&o!==null&&!on(i.version,o),a=[...r===void 0?[]:[r],...s?[`Live is now ${Gr(o)}, but ${Ha("this folder",i.version,pp)}. Run \`appbuilder app merge\` before publishing.`]:[]],c={folder:i,liveMoved:s};if(e.app===null)return{summary:n,published:!1,live:null,released:[],previews:[],yourPreview:null,base:c,warnings:a};let l=Bn(e.app).map(u=>fA(u,n.userId)),d=l.filter(u=>u.status==="preview");return{summary:n,published:!0,live:l.find(u=>u.status==="live")??null,released:l.filter(u=>u.status==="released").sort(gA),previews:d,yourPreview:d.find(u=>u.yours)??null,base:c,warnings:a}}var Ja="Cancelled.",Tt=()=>H("local_error",Ja);async function kp(e,t){let n;try{n=await t.packageLocalPlugin(e)}catch(o){return z(o)}let[r,...i]=n.deployable;return r===void 0||i.length>0?H("local_error",`Expected one app in ${Kr}; found ${String(n.deployable.length)}.`):I({...n,deployable:[r]})}async function mo(e){let t=await kp(e.cwd,e);if(!t.ok)return t;let n;try{n=await e.zipSourceDir(e.cwd)}catch(r){return z(r)}return I({deployable:t.value.deployable[0],issues:t.value.issues.filter(r=>r.severity==="warning"),source:n,sourceHash:lo(n.bytes)})}var hA=/^(<{7} HEAD|>{7} live)(:[^\r\n]*)?[ \t\r]*$/m,yA=/^(?:(?:<{7} HEAD|>{7} live)(?::[^\r\n]*)?|={7})[ \t\r]*$/m;async function Ap(e,t,n){let r=[];for(let i of e){let o;try{o=await t.readTextFile($n(t.cwd,...i.split("/")))}catch{continue}n.test(o)&&r.push(i)}return r}var qa=(e,t)=>Ap(e?.conflictedPaths??[],t,yA);async function fo(e,t,n,r){let i=await qa(rt(e),r);if(i.length>0&&n.force!==!0)return H("unresolved_conflicts",`These files still have merge conflict markers: ${i.join(", ")}. Resolve them. Only if the user explicitly wants to push them anyway: pass --force.`,{files:i});let o=await mA(e,t.source.bytes,n.baseFromPreview===void 0?{}:{baseFromPreview:n.baseFromPreview});if(!o.ok)return o;let s=Xe(e),{version:a}=o.value,c=s.liveVersion!==null&&!on(a,s.liveVersion),l=nA(e),{source:d}=t,u=t.deployable.thumbnail,f=[...c?[`Live is now ${Gr(s.liveVersion)}, but ${Ha("this folder",a,pp)}. Publishing will stop on a conflict; run \`appbuilder app merge\` first.`]:[],...i.length>0?[`Pushing files that still have merge conflict markers because of --force: ${i.join(", ")}`]:[]];return I({summary:s,appName:t.deployable.name,source:{files:d.files.length,mode:d.mode,bytes:d.bytes.byteLength,hash:t.sourceHash,...d.notice===void 0?{}:{notice:d.notice}},thumbnail:u!==null&&u.byteLength>0,preview:{exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},base:{version:a,source:o.value.source,liveMoved:c},lineage:o.value.lineage,...o.value.previewSourcePackageId===void 0?{}:{basePreviewSourcePackageId:o.value.previewSourcePackageId},conflictMarkers:i,notices:[...l==null?[]:[rA(l)],...o.value.notices,...o.value.source==="detected"&&a!==null?[wp(a)]:[]],warnings:f})}var xp="application/zip",bA=".gitignore";function wA(e,t){let n=tr(e),r=tr(t);return[...new Set([...n.keys(),...r.keys()])].filter(i=>i!==bA&&n.get(i)!==r.get(i)).sort()}var vA=(e,t=5)=>e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")} and ${String(e.length-t)} more`,kA=e=>`Files changed since this push was planned (${vA(e)}), so nothing was uploaded. Run \`appbuilder app push\` again to review and push them.`,Pp=(e,t)=>t===null||t.byteLength===0?Promise.resolve(null):e.uploadFile(t,{filename:"thumbnail.png",contentType:"image/png",source:"public_image",isPublic:!0}),Da="Your preview changed after this push was planned, so its base can't be taken for this folder and nothing was uploaded. Run `appbuilder app push` again to review it.";async function go(e,t,n,r,{isAborted:i=()=>!1}={}){let{api:o}=e,{source:s,sourceHash:a}=t,c,l,d,u;if(n.basePreviewSourcePackageId!==void 0){let m=Rt(e),p;if(m===null)return H("local_error",Da);try{p=await o.getPreview(m.app.api_name,e.credentials.userId)}catch(h){return Nt(h)?H("local_error",Da):z(h)}if(p.source_filesystem_package!==n.basePreviewSourcePackageId)return H("local_error",Da);if(i())return Tt()}try{u=r.ensureGitignore(r.cwd)}catch{u=!1}if(u){try{s=await r.zipSourceDir(r.cwd)}catch(p){return z(p)}a=lo(s.bytes);let m;try{m=wA(t.source.bytes,s.bytes)}catch(p){return z(p)}if(m.length>0)return H("local_error",kA(m));if(i())return Tt()}let f;try{f=fa(s.bytes,n.lineage)}catch(m){return z(m)}try{if([c,l]=await Promise.all([o.uploadFile(f,{filename:`${e.baseApiName}-source.zip`,contentType:xp,source:"plugin_app_source_filesystem"}),Pp(o,n.thumbnail?t.deployable.thumbnail:null)]),i())return Tt();let m=Ia(t.deployable,{release:!1,sourcePackageId:c,thumbnailId:l});d=await o.publish(m)}catch(m){return z(m)}let g=await Yr(e,m=>{let p={...nr(an(m,"previewRestoredFrom","conflictedPaths"),n.base.version,n.lineage.baseSourcePackageId),previewSourcePackageId:c,lastPushedSourceHash:a};return n.conflictMarkers.length>0?{...p,conflictedPaths:n.conflictMarkers}:p},r);return I({apiName:d.api_name,source:{files:s.files.length,mode:s.mode,bytes:s.bytes.byteLength,hash:a,...s.notice===void 0?{}:{notice:s.notice}},version:d.version,sourcePackageId:c,thumbnailId:l,remembered:g===null,warnings:g===null?[]:[Dn(g)]})}var Cp=e=>e.live_version??uo(e)[0]??null;function ao(e){let{entry:t,app:n,previewUpdatedAt:r,lineage:i,comparedSourcePackageId:o}=e,s=n.live_version,a=Cp(n),c=Zk(n),l=t?.previewSourcePackageId,d=i?.baseLiveVersion??null,u=null;return a!==null&&(i===null?u="base_unknown":d===null||On(a,d)>0?u="live_moved":On(a,d)<0?u="base_ahead":i.baseSourcePackageId!==o&&(u="base_replaced")),{conflict:u!==null,reason:u,baseLiveVersion:d,liveVersion:s,comparedVersion:a,baseSourcePackageId:i?.baseSourcePackageId??null,comparedSourcePackageId:o,previewSourceMatches:l===void 0?null:l===e.previewSourcePackageId,livePublishedAt:c?.published_at??null,livePublishedBy:c===void 0?null:ap(c.published_by),previewUpdatedAt:r}}async function Sp(e,t,n){let r=Cp(t),i=n?.baseLiveVersion??null;return r===null||i===null||On(r,i)!==0?I(null):mp({...e,app:t},r)}var AA="Run `appbuilder app merge` to merge Live into this folder, then `appbuilder app push` and publish again. Only if the user explicitly wants to overwrite Live: pass --force.",xA="Run `appbuilder app push` to save this folder as your preview again (the push records what it is based on), then publish. Only if the user explicitly wants to publish the preview as it is: pass --force.";function _p(e){let t=e.livePublishedBy===null?"":` by ${e.livePublishedBy}`,n=e.livePublishedAt===null?"":` at ${e.livePublishedAt}`,r=Ha("your preview",e.baseLiveVersion,iA),i=e.liveVersion===null?`There's no Live version, and the latest release is ${Gr(e.comparedVersion)}`:`Live is ${Gr(e.liveVersion)}`;switch(e.reason){case"live_moved":return`${i}${e.liveVersion===null?"":` (published${t}${n})`}, but ${r}. Publishing would overwrite the changes in between.`;case"base_ahead":return`${i}, but ${r}, a later version that is no longer Live. Publishing could overwrite changes this folder doesn't have.`;case"base_unknown":return`Your preview's source doesn't say what it's based on (that record is missing or can't be read), so publishing it could overwrite changes. ${i}.`;case"preview_replaced":return Ip;case"base_replaced":return`${i}, and ${r}, but v${e.baseLiveVersion??""} on this business isn't the version your preview was based on (the app or that version was deleted and created again). Publishing could overwrite changes your preview doesn't have.`;case null:return"No conflict."}}function Ep(e){return{...H("publish_conflict",_p(e),{hint:e.reason==="base_unknown"?xA:AA}),conflict:e}}var PA="Your preview isn't the one this folder last pushed or restored: it was saved again from another folder or machine, and that's what publishing releases.";async function CA(e,t,n){let r=rt(e);if(r?.previewSourcePackageId!==void 0&&r.previewSourcePackageId!==t)return[PA];if(r?.previewRestoredFrom!==void 0)return[`Your preview is version ${r.previewRestoredFrom} restored with \`appbuilder app rollback\`, not this folder's source.`];let i=r?.lastPushedSourceHash??null;if(i===null)return["No push from this folder is recorded, so your preview could not be compared with it."];let o;try{o=lo((await n.zipSourceDir(n.cwd)).bytes)}catch(s){return[`Couldn't compare this folder with your preview: ${je(s)}`]}return o===i?[]:["This folder changed since your last push. Publishing releases the preview as pushed; run `appbuilder app push` first to include the changes."]}function SA(e,t){let n=e.artifacts,r=F(n)?n[t]:void 0;return Array.isArray(r)?r:[]}var sn=e=>`You have no preview of ${e} on this business. Push one first with \`appbuilder app push\`.`;function _A(e){let t=[...uo(e),...e.live_version===null?[]:[e.live_version]].filter(n=>/^\d+$/.test(n)).map(Number).reduce((n,r)=>Math.max(n,r),0);return String(t+1)}var EA="Your preview's source couldn't be read, so what it's based on can't be checked, and publish stops even with --force. Try again; if it keeps failing, run `appbuilder app push` to save your preview again.";async function ho(e,t,n){let{app:r,api:i,credentials:o}=e,s=t.force===!0;if(r===null)return H("no_preview",sn(e.baseApiName));let a;try{a=await i.getPreview(r.api_name,o.userId)}catch(b){return Nt(b)?H("no_preview",sn(e.baseApiName)):z(b)}let c=a.thumbnail;if(c==null||c==="")return H("thumbnail_required","Your preview has no thumbnail, and a release needs one. Add thumbnail.png to the app, run `appbuilder app push`, then publish again.");if(typeof a.source_filesystem_package!="string"||a.source_filesystem_package==="")return H("preview_incomplete","Your preview has no source package. Run `appbuilder app push` to save it again, then publish.");let l=e.yourPreview?.updated??null,d=a.source_filesystem_package,u={entry:rt(e),app:r,previewUpdatedAt:l,previewSourcePackageId:d};if(t.expectPreview!==void 0&&d!==t.expectPreview)return ja(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Ka(i,d);if(!f.ok)return{...f,hint:f.hint??EA};let{lineage:g}=f.value,m=await Sp(e,r,g);if(!m.ok)return m;let p=ao({...u,lineage:g,comparedSourcePackageId:m.value});if(p.conflict&&!s)return Ep(p);let h=await CA(e,d,n);return p.conflict&&h.push(`${_p(p)} Publishing anyway because of --force.`),I({summary:Xe(e),apiName:r.api_name,previewUpdatedAt:l,conflictCheck:p,force:s,forced:p.conflict,nextReleaseAtLeast:_A(r),previewSourcePackageId:d,lineage:g,jsActionTemplates:SA(a,"js_action_templates"),warnings:h})}var Ip="Your preview changed after this publish was planned (it was pushed again, from this or another folder or machine), so it wasn't published.",IA="Run `appbuilder app publish` again to review the preview as it is now.",TA="The preview published isn't the one this publish reviewed (it was pushed again, from another folder or machine), so this folder's base wasn't advanced.",NA=(e,t)=>`Couldn't confirm that release ${e} is the preview this publish reviewed (${t}), so this folder's base wasn't advanced.`;function ja(e){return{...H("publish_conflict",Ip,{hint:IA}),conflict:{...e,conflict:!0,reason:"preview_replaced"}}}async function yo(e,t,n,{isAborted:r=()=>!1}={}){let i=rt(e),o;try{if(t.force){let l;try{l=(await e.api.getPreview(t.apiName,e.credentials.userId)).source_filesystem_package}catch(d){return Nt(d)?H("no_preview",sn(e.baseApiName)):z(d)}if(l!==t.previewSourcePackageId)return ja(t.conflictCheck)}else{let l=Wr(await e.api.listApps(e.baseApiName),e.baseApiName);if(l===null)return H("no_preview",sn(e.baseApiName));let d;try{d=await e.api.getPreview(l.api_name,e.credentials.userId)}catch(m){return Nt(m)?H("no_preview",sn(e.baseApiName)):z(m)}let u={entry:i,app:l,previewUpdatedAt:za(l,e.credentials.userId)?.updated??null,previewSourcePackageId:d.source_filesystem_package};if(d.source_filesystem_package!==t.previewSourcePackageId)return ja(ao({...u,lineage:null,comparedSourcePackageId:null}));let f=await Sp(e,l,t.lineage);if(!f.ok)return f;let g=ao({...u,lineage:t.lineage,comparedSourcePackageId:f.value});if(g.conflict)return Ep(g)}if(r())return Tt();o=await e.api.promotePreview(t.apiName,e.credentials.userId)}catch(l){return z(l)}let s=[];if(i===void 0)return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:!1,warnings:s});let a=i.previewRestoredFrom===void 0&&t.conflictCheck.previewSourceMatches===!0;if(a)try{(await e.api.getVersion(o.api_name,o.version)).source_filesystem_package!==t.previewSourcePackageId&&(a=!1,s.push(TA))}catch(l){a=!1,s.push(NA(o.version,je(l)))}let c=await Yr(e,l=>{let d=an(l,...Ln);return a?nr(d,o.version,t.previewSourcePackageId):d},n);return I({apiName:o.api_name,liveVersion:o.version,previousLiveVersion:t.summary.liveVersion,remembered:c===null,warnings:[...s,...c===null?[]:[Dn(c)]]})}var RA=e=>e.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");function $A(e,t){return e===void 0?"No base version is recorded for this folder, and its files don't match a released version.":e===null?"This folder was started before the app had a Live version, so there is nothing to merge against.":t?`The base version v${e} no longer exists, so there is nothing to merge against.`:`The base version v${e} couldn't be used.`}function OA(e,t){let n=["--release",t];return[...uo(e).filter(r=>On(r,t)<0).slice(0,hp).map(r=>({value:`base:${r}`,label:`Merge, if this folder was copied from v${r}`,args:[],argv:["appbuilder","app","merge",...n,"--base",r,"--yes"]})),{value:"accept",label:`This folder already contains v${t}`,args:[],argv:["appbuilder","app","merge",...n,"--accept-live-base","--yes"]}]}async function DA(e){try{return I((await e.zipSourceDir(e.cwd)).bytes)}catch(t){return z(t)}}async function bo(e,t,n){let r=Rt(e);if(r===null)return Zr(e,"merge");let i;if(t.version===void 0){if(r.app.live_version===null)return H("not_found",`${e.baseApiName} has no Live version to merge.`);i=r.app.live_version}else{let y=oo(t.version);if(!y.ok)return y;i=y.value}let o=Va(rt(e)),s=o===void 0?"none":"recorded",a=null,c=[];if(t.base!==void 0){let y=oo(t.base);if(!y.ok)return y;o=y.value,s="flag"}else if(t.acceptLiveBase!==!0&&typeof o=="string"){let y=await rr(e);if(!y.ok)return y;(y.value.status==="replaced"||y.value.status==="gone")&&(c.push((y.value.status==="replaced"?Wa:Ga)(y.value.version)),o=void 0,s="none")}let l=await qa(rt(e),n),d=l.length===0?[]:[`These files still have conflict markers from an earlier merge: ${l.join(", ")}. Resolve them before pushing.`],u=()=>({summary:Xe(e),targetVersion:i,targetIsLive:on(r.app.live_version,i),baseVersion:o,baseSource:s,targetSourcePackageId:a,notices:c,warnings:d});if(t.acceptLiveBase===!0){let y=await so(r,i);return y.ok?(a=y.value.source_filesystem_package,I({...u(),kind:"accept"})):y}if(o===void 0){let y=await DA(n);if(!y.ok)return y;let C=await bp(e,y.value);if(!C.ok)return C;C.value!==null&&(o=C.value.version,s="detected",c.push(wp(C.value.version)),on(C.value.version,i)&&(a=C.value.sourceId))}if(typeof o=="string"&&on(o,i)){if(s==="flag"){let y=await so(r,i);if(!y.ok)return y;a=y.value.source_filesystem_package}return I({...u(),kind:"up_to_date",ignoredIncoming:[],advancesBase:s!=="recorded"})}let f=await Jr(r,i);if(!f.ok)return f;let g=f.value.zip,m=null;a=f.value.sourceId;let p=!1;if(typeof o=="string"){let y=await Jr(r,o);if(y.ok)m={version:o,zip:y.value.zip};else if(y.code==="not_found")p=!0;else return y}let h;try{h=await n.planMerge({pluginDir:n.cwd,base:m,live:{version:i,zip:g}})}catch(y){return z(y)}let b=(y,C)=>I({...u(),kind:"fallback",reason:y,detail:C,liveZip:g,dir:$n(n.cwd,".kizenapp",`live-v${i}-${RA(n.now())}`),choices:OA(r.app,i)});switch(h.status){case"no_base":return b("no_base",$A(o,p));case"git_unavailable":return b("git_unavailable",h.reason);case"up_to_date":return I({...u(),kind:"up_to_date",ignoredIncoming:h.ignoredIncoming,advancesBase:!0});case"ready":return I({...u(),kind:"merge",plan:h})}}var La={written:[],deleted:[],conflicted:[],deletedOnLive:[],deletedLocally:[],binaryConflicts:[],ignoredIncoming:[]};function LA(e){return{written:e.written??[],deleted:e.deleted??[],conflicted:e.conflicted??[],deletedOnLive:e.deletedOnLive??[],deletedLocally:e.deletedLocally??[],binaryConflicts:e.binaryConflicts??[],ignoredIncoming:e.ignoredIncoming??[]}}var BA=e=>e.conflicted.filter(t=>!e.deletedOnLive.includes(t)&&!e.deletedLocally.includes(t));async function wo(e,t,n,r={}){let i=async s=>{let a=await Yr(e,c=>{let l=nr(c,t.targetVersion,t.targetSourcePackageId);return s===void 0?l:s.length===0?an(l,"conflictedPaths"):{...l,conflictedPaths:s}},n);return a===null?[]:[`${Dn(a)} Run \`appbuilder app merge --accept-live-base${t.targetIsLive?"":` --release ${t.targetVersion}`} --yes\` once it can be written.`]},o=(s,a,c,l)=>({status:s,targetVersion:t.targetVersion,targetIsLive:t.targetIsLive,baseLiveVersion:l?t.targetVersion:t.baseVersion,lists:a,markedPaths:[],remembered:l&&c.length===0,warnings:c});switch(t.kind){case"accept":return I(o("accepted",La,await i(),!0));case"up_to_date":{let s={...La,ignoredIncoming:t.ignoredIncoming};return t.advancesBase?I(o("up_to_date",s,await i(),!0)):I({...o("up_to_date",s,[],!1),remembered:!0})}case"merge":{let s;try{s=await n.applyMerge(t.plan,r)}catch(u){return z(u)}if(s.status==="cancelled")return Tt();if(s.status!=="merged"&&s.status!=="conflicts")return H("local_error",`The merge didn't apply (${s.status}). Run it again.`);let a=LA(s),c=await qa(rt(e),n),l=await Ap(a.written,n,hA),d=[...new Set([...c,...BA(a),...l])].sort();return I({...o(s.status,a,await i(d),!0),markedPaths:d})}case"fallback":{let s;try{n.ensureGitignore(n.cwd),s=await n.unzipToDir(t.liveZip,t.dir)}catch(a){return z(a)}return I({...o("fallback",La,[],!1),extracted:{dir:t.dir,written:s.written.length,skipped:s.skipped},remembered:!1})}}}async function vo(e,t,n){let r=oo(t);if(!r.ok)return r;let i=Rt(e);if(i===null)return Zr(e,"roll back");let o=r.value,s=await Jr(i,o);if(!s.ok)return s;let a;try{a=await n.makeTempDir()}catch(m){return z(m)}let c;try{let m=$n(a,"source");await n.unzipToDir(s.value.zip,m),c=await kp(m,n)}catch(m){c=z(m)}finally{await n.removeDir(a).catch(()=>{})}if(!c.ok)return{...c,message:`Version ${o}'s source couldn't be packaged, so it can't be restored: ${c.message}`};let[l]=c.value.deployable;if(l.api_name!==e.baseApiName)return H("local_error",`Version ${o}'s source is for ${l.api_name}, not ${e.baseApiName}.`);let d=await sA(e,Xe(e).liveVersion);if(!d.ok)return d;let u;try{u=fa(s.value.zip,d.value)}catch(m){return z(m)}let f={exists:e.yourPreview!==null,updated:e.yourPreview?.updated??null},g=[...f.exists?[`This replaces your current preview (last updated ${f.updated??"unknown"}).`]:[],`This folder's source isn't changed, and the next \`appbuilder app push\` replaces the restored preview with it. To keep working from version ${o}'s source, publish this preview, then pull the new Live version with \`appbuilder app pull\`.`];return I({summary:Xe(e),version:o,preview:f,deployable:l,source:u,warnings:g})}async function ko(e,t,n,{isAborted:r=()=>!1}={}){let i,o;try{let a;if([o,a]=await Promise.all([e.api.uploadFile(t.source,{filename:`${e.baseApiName}-source.zip`,contentType:xp,source:"plugin_app_source_filesystem"}),Pp(e.api,t.deployable.thumbnail)]),r())return Tt();let c=Ia(t.deployable,{release:!1,sourcePackageId:o,thumbnailId:a});i=await e.api.publish(c)}catch(a){return z(a)}let s=await Yr(e,a=>({...a,previewSourcePackageId:o,previewRestoredFrom:t.version,lastPushedSourceHash:null}),n);return I({apiName:i.api_name,version:t.version,sourcePackageId:o,remembered:s===null,warnings:s===null?[]:[Dn(s)]})}function Ao(e,t){return e!==void 0&&t?H("usage_error","Pass either <version> or --preview, not both."):e!==void 0?I({kind:"release",version:e}):t?I({kind:"preview"}):H("usage_error","Missing argument <version>. Usage: appbuilder app pull <version>, or appbuilder app pull --preview for your preview.")}var Ba=(e,t)=>t.startsWith(e+Gk),FA="Your preview has no source package. Push it again with `appbuilder app push`.";async function xo(e,t,n,r){let i;if(t.kind==="release"){let c=oo(t.version);if(!c.ok)return c;if(e.app===null)return Zr(e,"pull");i={source:"release",version:c.value}}else{if(e.app===null||e.yourPreview===null)return H("no_preview",sn(e.baseApiName));i={source:"preview",updated:e.yourPreview.updated}}let o=np(r.cwd),s=n.out===void 0||n.out===""?$n(Wk(o),i.source==="release"?`${e.baseApiName}-v${i.version}`:`${e.baseApiName}-preview`):np(o,n.out);if(s===o||Ba(s,o))return H("usage_error",`${s} holds the plugin folder; pass --out <dir> to choose a new folder.`);if(await r.pathExists(s))return H("usage_error",`${s} already exists; pass --out <dir> to choose a new folder.`);let a=Ba(o,s)&&!Ba($n(o,".kizenapp"),s)?[`${s} is inside the plugin folder, so the next \`appbuilder app push\` includes it unless .gitignore or .kizenignore excludes it.`]:[];return I({summary:Xe(e),...i,dir:s,warnings:a})}var jA=e=>`No base is recorded for ${e}. A push from there finds one when it can, or stops with \`base_required\`.`;async function MA(e,t){let n=await Jr(e,t);return n.ok?I({zip:n.value.zip,entry:nr(Ua(e.stateKey),t,n.value.sourceId)}):n}async function zA(e){let t;try{t=await e.api.getPreview(e.app.api_name,e.credentials.userId)}catch(a){return Nt(a)?H("no_preview",sn(e.baseApiName)):z(a)}let n=t.source_filesystem_package;if(typeof n!="string"||n==="")return H("preview_incomplete",FA);let r=await Ka(e.api,n);if(!r.ok)return r;let i=await gp(e,r.value.lineage);if(!i.ok)return i;let o=Ua(e.stateKey),s=i.value;return I({zip:r.value.zip,entry:{...s===null?o:nr(o,s.baseLiveVersion,s.baseSourcePackageId),previewSourcePackageId:n},preview:{sourcePackageId:n,base:vp(s?.baseLiveVersion)}})}async function Po(e,t,n,{isAborted:r=()=>!1}={}){let i=Rt(e);if(i===null)return t.source==="release"?Zr(e,"pull"):H("no_preview",sn(e.baseApiName));let o=t.source==="release"?await MA(i,t.version):await zA(i);if(!o.ok)return o;if(r())return Tt();let s;try{s=await n.unzipToDir(o.value.zip,t.dir)}catch(u){return u instanceof Fr?H("usage_error",`${t.dir} already exists; pass --out <dir> to choose a new folder.`):z(u)}let a;try{await n.writeAppState(t.dir,ka(Vr(),o.value.entry)),a=null}catch(u){a=je(u)}let{preview:c}=o.value,l=t.source==="release"?t.version:c?.base.version??null,d=c!==void 0&&!c.base.recorded;return I({dir:t.dir,written:s.written,skipped:s.skipped,remembered:a===null,warnings:[...d?[jA(t.dir)]:[],...a===null?[]:[l===null?Dn(a):`${Dn(a)} Before pushing from ${t.dir}, run \`appbuilder app merge --accept-live-base --release ${l} --yes\` there.`]],...c===void 0?{}:{preview:c}})}var Ln=["previewSourcePackageId","previewRestoredFrom"],UA=["folderBaseLiveVersion","folderBaseSourcePackageId",...Ln],Tp=(e,t)=>Bn(e).find(n=>n.status==="preview"&&n.preview_owner?.id===t)??null,Np=(e,t)=>Bn(e).every(n=>n.status==="preview"&&n.preview_owner?.id===t),rp=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null,Rp=e=>e.fullName??e.id,co=e=>typeof e=="string"&&e!==""?e:null,VA=e=>{let t=Bn(e).flatMap(n=>n.status==="preview"&&n.preview_owner!==null?[`${co(n.preview_owner.full_name)??"unknown"} (${n.preview_owner.id})`]:[]);return t.length===0?void 0:`Previews of ${e.base_api_name}: ${t.join(", ")}. Pass one of these user ids to --owner.`},HA=(e,t,n)=>n?`You have no preview of ${e} on this business.`:`User ${t} has no preview of ${e} on this business.`,$p=e=>`This preview is the only version of ${e}, so deleting it deletes the whole app from this business, with its settings and secrets.`,KA=e=>`This is ${e}'s preview, not yours.`,Ma=(e,t)=>`${String(e)} other ${e===1?"user is":"users are"} using this preview.${t?"":" Deleting it switches them to their own preview, or Live, and notifies them."}`,Ya=e=>e.yours?"Your preview":`${Rp(e)}'s preview`,Op=e=>`Run \`appbuilder app preview delete --owner ${e.id}\` to review it as it is now.`,ip=(e,t)=>`${Ya(t)} of ${e} no longer exists, so nothing was deleted.`,Dp=e=>`${Ya(e)} was pushed again after this delete was reviewed, so nothing was deleted. ${Op(e)}`,Lp=e=>`${Ya(e)} is now the app's only version, so deleting it would delete the whole app, which wasn't agreed to. Nothing was deleted. ${Op(e)}`;function Co(e,t){let{app:n,credentials:r}=e,i=(t.owner??r.userId).trim();if(i==="")return H("usage_error","--owner needs the user id of the preview to delete.");let o=i===r.userId;if(n===null)return H("not_found",`${e.baseApiName} isn't published to this business yet, so it has no preview to delete.`);let s=Tp(n,i);if(s===null){let f=VA(n);return H("not_found",HA(e.baseApiName,i,o),f===void 0?{}:{hint:f})}let a={id:i,fullName:co(s.preview_owner?.full_name),yours:o};if(t.expectUpdated!==void 0&&s.updated!==t.expectUpdated)return H("preview_changed",Dp(a));let c=rp(s.active_users_count),l=c===null?null:Math.max(0,c-(s.is_current_for_viewer?1:0)),d=Np(n,i),u=[...d?[$p(co(n.name)??e.baseApiName)]:[],...o?[]:[KA(Rp(a))],...l!==null&&l>0?[Ma(l,d)]:[]];return I({summary:Xe(e),apiName:n.api_name,owner:a,preview:{updated:s.updated,activeUsersCount:c,installedCount:rp(s.installed_count),otherActiveUsersCount:l},deletesApp:d,warnings:u})}var Bp=(e,t)=>e.deletesApp&&!t?H("preview_changed",Lp(e.owner)):null,WA=e=>`The preview was deleted, but whether the app still exists couldn't be checked: ${e}`;async function So(e,t,n,{isAborted:r=()=>!1}={}){let{api:i,baseApiName:o}=e;if(r())return Tt();let s;try{s=Wr(await i.listApps(o),o)}catch(g){return z(g)}let a=s===null?null:Tp(s,t.owner.id);if(s===null||a===null)return H("not_found",ip(o,t.owner));if(a.updated!==t.preview.updated)return H("preview_changed",Dp(t.owner));if(!t.deletesApp&&Np(s,t.owner.id))return H("preview_changed",Lp(t.owner));if(r())return Tt();try{await i.deletePreview(s.api_name,t.owner.id)}catch(g){return Nt(g)?H("not_found",ip(o,t.owner)):z(g)}let c=[],l;try{l=Wr(await i.listApps(o),o)===null}catch(g){l=null,c.push(WA(je(g)))}let d=rt(e),u=t.owner.yours&&d!==void 0&&Ln.some(g=>g in d),f=null;if(l===!0){let{environment:g,businessId:m,baseApiName:p}=e.stateKey,h={environment:g,businessId:m,baseApiName:p};f=await dp(n.cwd,b=>Id(b,h,y=>({...an(y,...UA),lastPushedSourceHash:null})),n)}else u&&(f=await Yr(e,g=>an(g,...Ln),n));return I({status:"deleted",appDeleted:l,remembered:f===null,warnings:[...c,...f===null?[]:[Dn(f)]]})}function _o(e,t){if(!e.deletesApp||t.appDeleted!==!1)return e;let n=$p(co(e.summary.name)??e.summary.baseApiName),r=e.preview.otherActiveUsersCount;return{...e,deletesApp:!1,warnings:e.warnings.flatMap(i=>i===n?[]:r!==null&&i===Ma(r,!0)?[Ma(r,!1)]:[i])}}var ir=me;function Fn(e){return Array.isArray(e)?e.flatMap(t=>{if(!F(t)||typeof t.api_name!="string"||t.api_name==="")return[];let n=t.hint_object_name;return[{apiName:t.api_name,name:typeof t.name=="string"&&t.name!==""?t.name:t.api_name,hintObjectName:typeof n=="string"&&n!==""?n:null}]}):[]}var Fp=e=>{let t=e.artifacts;return Fn(F(t)?t.js_action_templates:void 0)},GA=e=>e.object_name??e.entity_name??e.name,JA=e=>({id:e.id,objectId:e.custom_object.id,objectName:e.custom_object.name,label:GA(e.custom_object),includePerformAction:e.include_perform_action});function jp(e){let{templates:t,installed:n,liveApiNames:r,associations:i}=e;return t.map(o=>{let s=i.filter(l=>l.browser_js_action_template.api_name===o.apiName).map(JA),a=r?.has(o.apiName)??!1,c=s.length>0?"linked":!n||a?"unlinked":"unknown";return{...o,status:c,inLive:a,links:s}})}var Xa=e=>{let t=new Set;return e.filter(n=>t.has(n.apiName)?!1:(t.add(n.apiName),!0))},qA=e=>e instanceof q&&e.kind==="not_found";async function Qa(e,t){let{app:n,api:r}=e;if(n===null){let s=t.kind==="version"?Xa(t.templates):[];return I({status:"not_installed",liveVersion:null,actions:jp({templates:s,installed:!1,liveApiNames:null,associations:[]})})}let i=t.kind==="live"?t.version:n.live_version;if(t.kind==="version"&&t.templates.length===0)return I({status:"checked",liveVersion:i,actions:[]});let o=e.yourPreview;try{let[s,a,c]=await Promise.all([i===null?null:r.getVersion(n.api_name,i).then(Fp),t.kind==="app"&&o!==null?r.getPreview(n.api_name,e.credentials.userId).then(Fp).catch(d=>{if(qA(d))return[];throw d}):[],i===null?[]:r.listActionAssociations(n.api_name)]),l=t.kind==="version"?t.templates:[...s??[],...a];return I({status:i===null?"no_live_version":"checked",liveVersion:i,actions:jp({templates:Xa(l),installed:!0,liveApiNames:s===null?null:new Set(s.map(d=>d.apiName)),associations:c})})}catch(s){return z(s)}}async function it(e,t){let n=await Qa(e,t);return n.ok?n.value:Up(e,t,n.message)}function Up(e,t,n){let r=t.kind==="version"?Xa(t.templates):[];return{status:"failed",liveVersion:t.kind==="live"?t.version:e.app?.live_version??null,actions:r.map(i=>({...i,status:"unknown",inLive:!1,links:[]})),error:n}}async function Eo(e,t){let n={kind:"version",templates:t},r=await up(e);return r.ok?it(r.value,n):Up(e,n,r.message)}var Mp=e=>e.map(t=>t.apiName).join(", "),zp="with `--json`, run an action's `linkArgv`, `linkMenuArgv` or `linkNoMenuArgv`; at a terminal, run `appbuilder app actions link` to pick them";function Ge(e){let t=e.actions.filter(i=>i.status==="unlinked"),n=e.actions.filter(i=>i.status==="unknown"),r=[];return t.length>0&&r.push(`These JS actions aren't linked to any object: ${Mp(t)}. Link them: ${zp}.`),n.length>0&&e.status!=="failed"&&r.push(`These JS actions aren't in the Live version, so their links can't be listed and they may not be linked to any object: ${Mp(n)}. To make sure, link them: ${zp}.`),r}var ot=e=>e.status==="failed"?[`Couldn't check which JS actions are linked to objects: ${e.error??"unknown error"}. Run \`appbuilder app actions list\` to check.`]:[];function Io(e){return!e.actions.some(n=>n.status!=="linked")&&e.status!=="failed"?[]:[{step:"actions",args:["actions","list"]},...e.actions.flatMap(n=>n.status==="unlinked"&&n.hintObjectName!==null?[{step:"link",args:["actions","link",n.apiName,n.hintObjectName]}]:[])]}var Za=(e,t)=>e.localeCompare(t,void 0,{sensitivity:"accent"})===0;function To(e,t,n){let r=t.trim(),i=e.find(a=>a.id===r)??e.find(a=>a.name===r);if(i!==void 0)return I(i);let o=e.filter(a=>Za(a.name,r)||Za(a.objectName,r)||a.entityName!==null&&Za(a.entityName,r)),[s]=o;if(s!==void 0&&o.length===1)return I(s);if(o.length>1){let a=o.map(c=>({value:c.id,label:`${c.objectName} (${c.name})`,args:[],argv:n(c)}));return ir("needs_choice",`Several objects match "${t}". Pick one by its api name or id.`,{choice:"object",choices:a})}return ir("not_found",`No object "${t}" on this business that you can see. Pass an object's api name (like client_client) or its id.`)}var Vp=e=>({id:e.id,name:e.name,label:e.objectName});async function No(e){let t=await Qa(e,{kind:"app"});return t.ok?I({summary:Xe(e),check:t.value}):t}var YA=e=>ir("not_found",`${e.baseApiName} isn't on this business yet, so it has no JS actions to link. Push it first with \`appbuilder app push\`.`),ZA=(e,t)=>ir("not_found",`${e.baseApiName} has no JS action "${t}" in its Live version or your preview. If it's new, push this folder first with \`appbuilder app push\`.`);async function ec(e){let{app:t}=e;if(t===null)return YA(e);let n,r;try{[r,n]=await Promise.all([Qa(e,{kind:"app"}),e.api.listObjects()])}catch(i){return z(i)}return r.ok?I({appApiName:t.api_name,check:r.value,objects:n}):r}function Ro(e,t,n){let r=t.check.actions.find(i=>i.apiName===n);return r===void 0?ZA(e,n):I(r)}async function Hp(e,t,n,r){let i=await ec(e);if(!i.ok)return i;let o=To(i.value.objects,n,r);if(!o.ok)return o;let s=Ro(e,i.value,t);return s.ok?I({choices:i.value,action:s.value,object:o.value}):s}var XA=(e,t)=>`${e} is in the Live version, so this change to its link to ${t} applies to everyone using Live as soon as it's made.`,Kp=(e,t)=>e.inLive?[XA(e.apiName,t)]:[],QA=e=>`${e} isn't in the Live version, so an existing link to this object can't be seen. If there is one, linking reports it as already linked and leaves its menu setting as it is.`;async function Wp(e,t,n){let r=await Hp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return I(tc(e,i,o,s,{...t.menu!==void 0&&{menu:t.menu}}))}function tc(e,t,n,r,{menu:i}){let o=n.links.find(l=>l.objectId===r.id),s=o===void 0?null:{id:o.id,includePerformAction:o.includePerformAction},a,c;return s===null?(a="create",c=i??!1):i===void 0||i===s.includePerformAction?(a="up_to_date",c=s.includePerformAction):(a="update",c=i),{summary:Xe(e),appApiName:t.appApiName,action:n,object:Vp(r),change:a,includePerformAction:c,existing:s,notices:a==="create"&&!n.inLive?[QA(n.apiName)]:[],warnings:a==="up_to_date"?[]:Kp(n,r.name)}}var ex=(e,t)=>`${e} was already linked to ${t}. Its link isn't listed (the action isn't in the Live version), so its menu setting couldn't be checked or changed.`,tx=(e,t)=>`${e} was already linked to ${t} (the link was made after this command listed the links), so nothing was changed and its menu setting wasn't set. Run \`appbuilder app actions list\`, then link it again to set the menu setting.`,nx=e=>e instanceof q&&e.status===400&&/already exists/i.test(e.message),rx=e=>e instanceof q&&e.status===400&&/Browser JS action template not found/i.test(e.message),ix=e=>`${e} is only in your preview, and Kizen couldn't find it to link it. Kizen environments without the fix for linking preview-only actions (KZN-19521) only link actions in Live: publish it first, then link it.`,Gp=()=>ir("local_error",Ja);async function $o(e,t,{isAborted:n=()=>!1}={}){let r=t.includePerformAction;if(t.change==="up_to_date"||r===null)return I({status:"up_to_date",warnings:[]});if(n())return Gp();try{return t.change==="update"&&t.existing!==null?(await e.api.updateActionAssociation(t.appApiName,t.existing.id,r),I({status:"updated",warnings:[]})):(await e.api.createActionAssociation({appApiName:t.appApiName,actionApiName:t.action.apiName,objectId:t.object.id,includePerformAction:r}),I({status:"created",warnings:[]}))}catch(i){return t.change==="create"&&nx(i)?I({status:"already_linked",warnings:[(t.action.inLive?tx:ex)(t.action.apiName,t.object.name)]}):t.change==="create"&&!t.action.inLive&&rx(i)?{...z(i),hint:ix(t.action.apiName)}:z(i)}}var ox=(e,t)=>`${e} isn't linked to ${t}.`,nc=e=>`${e} isn't in the Live version, so its links can't be listed or removed here. If it was linked while only in a preview, publish it first, then unlink it.`;async function Jp(e,t,n){let r=await Hp(e,t.action,t.object,n);if(!r.ok)return r;let{choices:i,action:o,object:s}=r.value;return rc(e,i,o,s)}function rc(e,t,n,r){let i=n.links.find(o=>o.objectId===r.id);return i===void 0?ir("not_found",ox(n.apiName,r.name),n.inLive?{}:{hint:nc(n.apiName)}):I({summary:Xe(e),appApiName:t.appApiName,action:n,object:Vp(r),associationId:i.id,includePerformAction:i.includePerformAction,warnings:Kp(n,r.name)})}async function Oo(e,t,{isAborted:n=()=>!1}={}){if(n())return Gp();try{await e.api.deleteActionAssociation(t.associationId)}catch(r){return z(r)}return I({status:"unlinked"})}var sx={local:"HEAD",incoming:"live"};function Je(e,t,n,r){let i={json:n.json===!0,deps:r},o=Rn(n,r.processEnv),s=d=>[...d,...d[2]==="push"&&n.allowProduction===!0?["--allow-production"]:[],...o,...Oa(i)],a=d=>d.map(u=>({...u,argv:s(u.argv??[])})),c=(d,u)=>u==="base"||u==="object"?s(d.argv??[]):Et(e,[...t,...d.args,...rn(n,r.processEnv)],i),l=d=>Et("appbuilder app",[...d,...o],i);return{output:i,runnable:a,appArgv:l,pin:d=>{o=to(n,d)},apply:(d,u)=>({applyArgv:l([...d,"--yes",...u?["--allow-production"]:[]]),requiresProductionConsent:u}),fail:d=>{let u=d.conflict?.reason,f=d.code==="publish_conflict"?[u==="preview_replaced"?{step:"publish",argv:l(["publish"])}:u==="base_unknown"?{step:"push",argv:l(["push"])}:{step:"merge",argv:l(["merge"])}]:void 0;It(i,f===void 0?d:{...d,next:f},c)}}}async function Zp(e,t,n){let r=await Nn(e,t);return r.ok?(n(r.value.credentials),ze(t,r.value.notices),I({credentials:r.value.credentials,client:r.value.client})):r}async function Xp(e,t,n){let r=t;if(r===void 0)try{r=await n.readManifestApiName(n.cwd)}catch(o){return z(o)}let i=await qr({...e,baseApiName:r},n);return i.ok&&ze(n,i.value.notices),i}async function $t(e,t,{fail:n,pin:r}){let i=await Zp(e,t,r);if(!i.ok)return n(i),null;let o=await Xp(i.value,void 0,t);return o.ok?o.value:(n(o),null)}var ti=e=>e===null?"none":`v${e}`;function qe(e){return[`Environment: ${e.environment}${e.isProduction?" (production)":""}`,`Business: ${e.businessId}`,e.apiName===null?`App: ${e.baseApiName} (not published to this business yet)`:`App: ${e.name??e.baseApiName} (${e.apiName})`,`Live: ${ti(e.liveVersion)}`]}var yt=e=>({environment:e.environment,businessId:e.businessId,userId:e.userId,app:{baseApiName:e.baseApiName,apiName:e.apiName,name:e.name,liveVersion:e.liveVersion}}),Ce=(...e)=>`${e.filter(t=>typeof t=="string").join(`
|
|
844
863
|
`)}
|
|
845
|
-
`
|
|
846
|
-
`):e.
|
|
847
|
-
`),
|
|
848
|
-
`)};async function ym(e){try{return await e.isClaudeSkillStale(e.cwd)?[ha]:[]}catch{return[]}}async function Aa(e,t,n){let r={json:t.json===!0,deps:n},o="appbuilder block push",i=e===void 0?[]:[e],s=(c,g)=>g==="environment"?[...i,...c.args,...Do(t,n.processEnv)]:g==="block"?[...c.args,...xa(t,n.processEnv)]:[...i,...xa(t,n.processEnv),...c.args],a=c=>{Ea(r,c,o,s)};try{let c=await Wn(t,n);if(!c.ok){a(c);return}let{credentials:g,client:m,notices:h}=c.value;_a(n,h);let y=await ko(e,n);if(!y.ok){a(y);return}let f=y.value;i=[f.block.api_name],f.warnings.length>0&&n.writeStderr(`${De(f.warnings)}
|
|
849
|
-
`);let{context:u,forgotten:w}=await $o({client:m,credentials:g,block:f,forget:t.forget===!0},n);w&&n.writeStderr(`Forgot the remembered target for ${f.block.api_name}.
|
|
850
|
-
`);let
|
|
851
|
-
`),[...
|
|
852
|
-
`)),
|
|
853
|
-
`)
|
|
854
|
-
`)
|
|
864
|
+
`;async function bt(e){try{return await e.staleAgentFileWarnings(e.cwd)}catch{return[]}}var ax=(e,t)=>t.length===0?[]:[e,...t.map(n=>` ${n.label} \u2192 ${n.argv.map(ge).join(" ")}`)];function cx(e){let t=`${e.apiName} (${e.name})`;switch(e.status){case"linked":return` ${t}: linked to ${e.links.map(n=>`${n.label} (${n.objectName}, menu: ${n.includePerformAction===!0?"on":"off"})`).join(", ")}`;case"unlinked":return` ${t}: not linked${e.hintObjectName===null?"":` (hint: ${e.hintObjectName})`}`;case"unknown":return` ${t}: not in Live, so its links can't be listed`}}var Qe=e=>e.actions.length===0?[]:["JS actions:",...e.actions.map(cx)],Xr=(e,t)=>Io(e).map(({step:n,args:r})=>({step:n,argv:t(r)})),ic="<object>",Qp=(e,t)=>e.map(n=>({...n,links:n.links.map(r=>({...r,unlinkArgv:t(["actions","unlink",n.apiName,r.objectId])})),linkArgv:t(["actions","link",n.apiName,ic]),linkMenuArgv:t(["actions","link",n.apiName,ic,"--menu"]),linkNoMenuArgv:t(["actions","link",n.apiName,ic,"--no-menu"])})),Lo=(e,t,n)=>({status:e.status,liveVersion:e.liveVersion,...e.error===void 0?{}:{error:e.error},actions:Qp(e.actions,n),next:t});function jn(e,t,n,r,i){Pe(e,{ok:!0,applied:!1,dryRun:!0,reason:t.reason,...n,...r??{},next:[]},i),t.reason==="no_yes"&&e.deps.writeStderr(`${eo}
|
|
865
|
+
`)}function qp(e){let t=[e.publishedAt===null?void 0:`published ${e.publishedAt}`,e.publishedBy===null?void 0:`by ${e.publishedBy}`].filter(n=>n!==void 0);return`v${e.version}${t.length===0?"":` (${t.join(" ")})`}`}var em=e=>e.recorded?ti(e.version):"not recorded";function lc(e){let t=qe(e.summary).filter(r=>!r.startsWith("Live:")),n=[`Folder base: ${em(e.base.folder)}`];return e.published?[...t,`Live: ${e.live===null?"none":qp(e.live)}`,"Released:",...e.released.length===0?[" (none)"]:e.released.map(r=>` ${qp(r)}`),"Previews:",...e.previews.length===0?[" (none)"]:e.previews.map(r=>` ${r.previewOwner?.fullName??"unknown"}${r.yours?" (yours)":""}, updated ${r.updated??"unknown"}`),...n]:[...t,"",`${e.summary.baseApiName} isn't published to this business yet.`,...n]}function lx(e,t){return e.base.liveMoved?[{step:"merge",argv:t(["merge"])}]:[{step:"push",argv:t(["push"])},{step:"publish",argv:t(["publish"])}]}async function tm(e,t){let n=Je("appbuilder app versions",[],e,t),{output:r,fail:i}=n;try{let o=await $t(e,t,n);if(o===null)return;let s=await rr(o);if(!s.ok){i(s);return}let a=po(o,s.value),c=await it(o,{kind:"app"}),l=ot(c),d=Xr(c,n.appArgv),u={...a,warnings:[...a.warnings,...Ge(c),...await bt(t)]};ze(t,l),Pe(r,{ok:!0,...yt(u.summary),published:u.published,live:u.live,released:u.released,previews:u.previews,yourPreview:u.yourPreview,base:u.base,jsActions:Lo(c,d,n.appArgv),notices:l,warnings:u.warnings,next:[...lx(u,n.appArgv),...d]},Ce(...lc(u),...Qe(c),...Q(u.warnings)))}catch(o){i(z(o))}}var ux=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`,dx={recorded:"recorded for this folder",never_published:"the app has no Live version yet",detected:"matched exactly",preview:"matches your preview exactly; your preview's base, read from the server",base_from_preview:"continues your preview; your preview's base, read from the server"},Qr=e=>[...qe(e.summary),`Source: ${String(e.source.files)} files (${e.source.mode}), ${String(e.source.bytes)} bytes`,`Thumbnail: ${e.thumbnail?"yes":"no"}`,e.preview.exists?`Preview: replaces yours (last updated ${e.preview.updated??"unknown"})`:"Preview: new",`Base: ${ti(e.base.version)} (${dx[e.base.source]})`],uc=(e,t)=>`\u2713 Saved your preview of ${e} (${t.apiName})`;async function nm(e,t){let n=Je("appbuilder app push",[],e,t),{output:r,fail:i,appArgv:o,apply:s}=n,a=["push",...e.force===!0?["--force"]:[],...e.baseFromPreview===void 0?[]:["--base-from-preview",e.baseFromPreview]];try{let c=await Zp(e,t,n.pin);if(!c.ok){i(c);return}let l=await mo(t);if(!l.ok){i(l);return}let{deployable:d,issues:u,source:f}=l.value;u.length>0&&t.writeStderr(`${We(u)}
|
|
866
|
+
`),f.notice!==void 0&&t.writeStderr(`${f.notice}
|
|
867
|
+
`);let g=await Xp(c.value,d.api_name,t);if(!g.ok){i(g);return}let m=g.value,p=await fo(m,l.value,{force:e.force===!0,...e.baseFromPreview!==void 0&&{baseFromPreview:e.baseFromPreview}},t);if(!p.ok){i(p);return}let h=p.value;ze(t,h.notices);let b=Ye(e,m.credentials.environment);if(!b.ok){i(b);return}let y=Fn(d.artifacts.js_action_templates),C=await bt(t),S=$=>{let V=ot($),X=Xr($,o);return ze(t,V),{jsNext:X,warnings:[...u.map(ux),...h.warnings,...Ge($),...C],notices:[...h.notices,...V],jsActions:Lo($,X,o)}},x={...yt(h.summary),source:h.source,thumbnail:h.thumbnail,preview:h.preview,base:h.base,conflictMarkers:h.conflictMarkers};if(b.value.kind==="dry-run"){let $=await it(m,{kind:"version",templates:y}),{warnings:V,notices:X,jsActions:ve}=S($);jn(r,b.value,{action:"push",...x,jsActions:ve,notices:X,warnings:V},s(a,h.summary.isProduction),Ce(...Qr(h),...Qe($),...Q(V)));return}let v=await go(m,l.value,h,t);if(!v.ok){i(v);return}let k=await Eo(m,y),{jsNext:P,warnings:w,notices:A,jsActions:_}=S(k),T=[...w,...v.value.warnings],L={...h,source:v.value.source};Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"push",...x,jsActions:_,source:v.value.source,previewVersion:v.value.version,apiName:v.value.apiName,sourcePackageId:v.value.sourcePackageId,thumbnailId:v.value.thumbnailId,remembered:v.value.remembered,notices:A,warnings:T,next:[...P,{step:"publish",argv:o(["publish"])}]},Ce(uc(d.name,v.value),...Qr(L),...Qe(k),...Q(T)))}catch(c){i(z(c))}}function px(e,t){let n=e.reason==="base_unknown"?"your preview's source doesn't say what it's based on":`your preview's base ${ti(e.baseLiveVersion)}, read from its source on the server`;return`Conflict check: ${e.conflict?t?"conflict, overridden by --force":"conflict":"none"} (${n})`}var dc=e=>[...qe(e.summary),`Preview: last updated ${e.previewUpdatedAt??"unknown"}`,px(e.conflictCheck,e.forced)],pc=e=>`Publish: Live becomes the next release number (at least v${e.nextReleaseAtLeast})`,mc=(e,t)=>`\u2713 Published Live v${t.liveVersion} of ${e.summary.name??e.summary.baseApiName}`;async function rm(e,t){let n=Je("appbuilder app publish",[],e,t),{output:r,fail:i,apply:o,appArgv:s}=n,a=["publish",...e.force===!0?["--force"]:[]];try{let c=await $t(e,t,n);if(c===null)return;let l=await ho(c,{force:e.force===!0,...e.expectPreview!==void 0&&{expectPreview:e.expectPreview}},t);if(!l.ok){i(l);return}let d=l.value,u=Ye(e,c.credentials.environment);if(!u.ok){i(u);return}let f=dc(d),g=[...d.warnings,...await bt(t)],m={...yt(d.summary),previewUpdatedAt:d.previewUpdatedAt,conflictCheck:d.conflictCheck,forced:d.forced};if(u.value.kind==="dry-run"){let S=await it(c,{kind:"version",templates:Fn(d.jsActionTemplates)}),x=ot(S),v=[...g,...Ge(S)];ze(t,x),jn(r,u.value,{action:"publish",...m,nextReleaseAtLeast:d.nextReleaseAtLeast,jsActions:Lo(S,Xr(S,s),s),notices:x,warnings:v},o([...a,"--expect-preview",d.previewSourcePackageId],d.summary.isProduction),Ce(...f,pc(d),...Qe(S),...Q(v)));return}let p=await yo(c,d,t);if(!p.ok){i(p);return}let h=await it(c,{kind:"live",version:p.value.liveVersion}),b=ot(h),y=Xr(h,s),C=[...g,...p.value.warnings,...Ge(h)];ze(t,b),Pe(r,{ok:!0,applied:!0,dryRun:!1,action:"publish",...m,apiName:p.value.apiName,liveVersion:p.value.liveVersion,previousLiveVersion:p.value.previousLiveVersion,remembered:p.value.remembered,jsActions:Lo(h,y,s),notices:b,warnings:C,next:y},Ce(mc(d,p.value),...f,...Qe(h),...Q(C)))}catch(c){i(z(c))}}var st=(e,t)=>t.length===0?[]:[`${e} (${String(t.length)}):`,...t.map(n=>` ${n}`)];function cc(e){return[...st("Written",e.written),...st("Deleted",e.deleted),...st("Conflicted",e.conflicted),...st("Edited here, deleted on Live (kept)",e.deletedOnLive),...st("Deleted here, changed on Live (restored)",e.deletedLocally),...st("Binary files changed on both sides (yours kept)",e.binaryConflicts),...st("On Live but excluded here (not written)",e.ignoredIncoming)]}var Bo=(e,t)=>t?`Live v${e}`:`v${e}`,mx=e=>`Resolve the conflict markers in the files above: the side marked <<<<<<< HEAD is your file and the side marked >>>>>>> live is ${e}. Then run \`appbuilder app push\` and \`appbuilder app publish\`.`,fc="Merge it into this folder by hand and then record its base, or merge from the release this folder was copied from with --base <n>. Use --base only with the release it was really copied from: a wrong one drops the changes made since then.";function gc(e){let t=e.baseVersion===void 0?"not recorded":ti(e.baseVersion),n=Bo(e.targetVersion,e.targetIsLive);switch(e.kind){case"accept":return[`Base: ${t}`,`Record v${e.targetVersion} as this folder's base without merging.`];case"up_to_date":return[`Base: ${t}`,`This folder already includes v${e.targetVersion}.`,...st("On Live but excluded here (not written)",e.ignoredIncoming)];case"merge":return[`Merge ${n} into this folder (base ${t}).`,...cc(e.plan)];case"fallback":return[`Base: ${t}`,`Can't merge automatically: ${e.detail}`,`${n}'s source goes into ${e.dir}.`]}}function fx(e){let t={kind:e.kind,targetVersion:e.targetVersion,targetIsLive:e.targetIsLive,baseVersion:e.baseVersion??null,baseSource:e.baseSource,notices:e.notices};switch(e.kind){case"accept":return t;case"up_to_date":return{...t,ignoredIncoming:e.ignoredIncoming};case"merge":{let{written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}=e.plan;return{...t,written:n,deleted:r,conflicted:i,deletedOnLive:o,deletedLocally:s,binaryConflicts:a,ignoredIncoming:c}}case"fallback":return{...t,fallback:{reason:e.reason,detail:e.detail,dir:e.dir}}}}function gx(e){let t=(e.baseSource==="flag"||e.baseSource==="detected")&&typeof e.baseVersion=="string";return["merge","--release",e.targetVersion,...t&&typeof e.baseVersion=="string"?["--base",e.baseVersion]:[],...e.kind==="accept"?["--accept-live-base"]:[]]}function hx(e,t){return e.status!=="merged"&&e.status!=="conflicts"&&e.status!=="accepted"?[]:[...e.markedPaths.length===0?[]:[{step:"resolve",files:e.markedPaths,markers:sx}],{step:"push",argv:t(["push"])},{step:"publish",argv:t(["publish"])}]}function hc(e,t){let{targetVersion:n}=t,r=Bo(e.targetVersion,e.targetIsLive);switch(t.status){case"accepted":return[`\u2713 Recorded v${n} as this folder's base.`];case"up_to_date":return[`\u2713 This folder already includes v${n}.`,...st("On Live but excluded here (not written)",t.lists.ignoredIncoming)];case"merged":return[`\u2713 Merged ${r} into this folder.`,...cc(t.lists),"Run `appbuilder app push`, then `appbuilder app publish`."];case"conflicts":return[`Merged ${r} into this folder with conflicts.`,...cc(t.lists),mx(r)];case"fallback":return[...e.kind==="fallback"?[`Can't merge automatically: ${e.detail}`]:[],`${r}'s source is in ${t.extracted?.dir??""}.`,...st("Left out (safety list)",t.extracted?.skipped??[])]}}async function im(e,t){let n=[...e.release===void 0?[]:["--release",e.release],...e.base===void 0?[]:["--base",e.base],...e.acceptLiveBase===!0?["--accept-live-base"]:[]],r=Je("appbuilder app merge",n,e,t),{output:i,fail:o,runnable:s,appArgv:a,apply:c}=r;try{let l=await $t(e,t,r);if(l===null)return;let d=await bo(l,{...e.release===void 0?{}:{version:e.release},...e.base===void 0?{}:{base:e.base},...e.acceptLiveBase===!0?{acceptLiveBase:!0}:{}},t);if(!d.ok){o(d);return}let u=d.value;ze(t,u.notices);let f=Ye({dryRun:e.dryRun===!0,yes:e.yes===!0,allowProduction:!0},l.credentials.environment);if(!f.ok){o(f);return}let g=qe(u.summary),m=[...u.warnings,...await bt(t)],p=u.kind==="fallback"?s(u.choices):[],h={...yt(u.summary),...fx(u),...u.kind==="fallback"?{choices:p}:{}};if(f.value.kind==="dry-run"){jn(i,f.value,{action:"merge",...h,warnings:m},c(gx(u),!1),Ce(...g,...gc(u),...Q(m)));return}let b=await wo(l,u,t);if(!b.ok){o(b);return}let y=b.value,C=[...hc(u,y),...y.status==="fallback"?ax(fc,p):[]];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"merge",...h,status:y.status,baseLiveVersion:y.baseLiveVersion??null,...y.lists,...y.extracted===void 0?{}:{extracted:y.extracted},remembered:y.remembered,warnings:[...m,...y.warnings],next:hx(y,a)},Ce(...g,...C,...Q([...m,...y.warnings])))}catch(l){o(z(l))}}var yc=e=>[...qe(e.summary),`Rollback: restore v${e.version} as your preview`],bc=e=>`\u2713 Restored v${e.version} as your preview of ${e.summary.name??e.summary.baseApiName}`;async function om(e,t,n){let r=Je("appbuilder app rollback",[e],t,n),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await $t(t,n,r);if(c===null)return;let l=await vo(c,e,n);if(!l.ok){o(l);return}let d=l.value,u=Ye(t,c.credentials.environment);if(!u.ok){o(u);return}let f=yc(d),g=[...d.warnings,...await bt(n)],m={...yt(d.summary),version:d.version,preview:d.preview};if(u.value.kind==="dry-run"){jn(i,u.value,{action:"rollback",...m,warnings:g},a(["rollback",e],d.summary.isProduction),Ce(...f,...Q(g)));return}let p=await ko(c,d,n);if(!p.ok){o(p);return}let h=[...g,...p.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"rollback",...m,apiName:p.value.apiName,sourcePackageId:p.value.sourcePackageId,remembered:p.value.remembered,warnings:h,next:[{step:"publish",argv:s(["publish"])}]},Ce(bc(d),...f,...Q(h)))}catch(c){o(z(c))}}var wc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName,r=`(${String(t.written.length)} files)`;return[e.source==="release"?`\u2713 Extracted v${e.version} of ${n} into ${t.dir} ${r}`:`\u2713 Extracted your preview of ${n} into ${t.dir} ${r}`,...t.preview===void 0?[]:[`Folder base: ${em(t.preview.base)}`],...st("Left out (safety list)",t.skipped)]},yx=(e,t)=>e.source==="release"?{version:e.version}:{source:"preview",preview:{updated:e.updated,sourcePackageId:t.preview?.sourcePackageId??null},base:t.preview?.base??null};async function sm(e,t,n){let r=Ao(e,t.preview===!0);if(!r.ok){Je("appbuilder app pull",[],t,n).fail(r);return}let i=[...r.value.kind==="release"?[r.value.version]:["--preview"],...t.out===void 0?[]:["--out",t.out]],o=Je("appbuilder app pull",i,t,n),{output:s,fail:a}=o;try{let c=await $t(t,n,o);if(c===null)return;let l=await xo(c,r.value,t,n);if(!l.ok){a(l);return}let d=l.value,u=await Po(c,d,n);if(!u.ok){a(u);return}let{dir:f,written:g,skipped:m,remembered:p}=u.value,h=[...d.warnings,...u.value.warnings,...await bt(n)];Pe(s,{ok:!0,...yt(d.summary),...yx(d,u.value),dir:f,written:g,skipped:m,remembered:p,warnings:h,next:[]},Ce(...wc(d,u.value),...Q(h)))}catch(c){a(z(c))}}var vc=(e,t)=>[...qe(e),...t.actions.length===0?["No JS actions."]:Qe(t)],oc=e=>e===!0?"shown in its Perform Action menus":"not shown in its Perform Action menus",Do=e=>`${e.object.label} (${e.object.name})`;function kc(e){let t=e.action.apiName;switch(e.change){case"create":return[`Link ${t} to ${Do(e)}, ${oc(e.includePerformAction)}.`];case"update":return[`Change ${t}'s link to ${Do(e)}: ${oc(e.includePerformAction)}.`];case"up_to_date":return[`${t} is already linked to ${Do(e)}, ${oc(e.includePerformAction)}.`]}}var Ac=e=>[`Unlink ${e.action.apiName} from ${Do(e)}.`],xc=(e,t)=>t==="updated"?`\u2713 Updated ${e.action.apiName}'s link to ${e.object.label}`:t==="already_linked"?`${e.action.apiName} was already linked to ${e.object.label}`:`\u2713 Linked ${e.action.apiName} to ${e.object.label}`,Pc=e=>`\u2713 Unlinked ${e.action.apiName} from ${e.object.label}`;function am(e,t){let{action:n,object:r}=t;return n!==void 0&&r!==void 0?I({action:n,object:r}):me("usage_error",`Missing argument <${n===void 0?"action":"object"}>. Usage: appbuilder app actions ${e} <action> <object>. A headless run needs both; at a terminal, leave them out to pick them.`)}var sc=e=>({...yt(e.summary),jsAction:{apiName:e.action.apiName,name:e.action.name,hintObjectName:e.action.hintObjectName,inLive:e.action.inLive},object:e.object,change:e.change,includePerformAction:e.includePerformAction,existing:e.existing});async function cm(e,t){let n=Je("appbuilder app actions list",[],e,t),{output:r,fail:i,appArgv:o}=n;try{let s=await $t(e,t,n);if(s===null)return;let a=await No(s);if(!a.ok){i(a);return}let{summary:c,check:l}=a.value,d=[...Ge(l),...await bt(t)];Pe(r,{ok:!0,...yt(c),published:s.app!==null,status:l.status,actions:Qp(l.actions,o),warnings:d,next:Xr(l,o).filter(u=>u.step!=="actions")},Ce(...vc(c,l),...Q(d)))}catch(s){i(z(s))}}async function lm(e,t,n,r){let i=am("link",{action:e,object:t});if(!i.ok){Je("appbuilder app actions link",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=n.menu===void 0?[]:[n.menu?"--menu":"--no-menu"],c=Je("appbuilder app actions link",[o,s,...a],n,r),{output:l,fail:d,appArgv:u,apply:f}=c,g=m=>["appbuilder","app","actions","link",o,m.id,...a];try{let m=await $t(n,r,c);if(m===null)return;let p=await Wp(m,{action:o,object:s,...n.menu===void 0?{}:{menu:n.menu}},g);if(!p.ok){d(p);return}let h=p.value,b=[...qe(h.summary),...kc(h)],y=await bt(r),C=[...h.warnings,...y];if(ze(r,h.notices),h.change==="up_to_date"){Pe(l,{ok:!0,applied:!1,dryRun:!1,action:"actions link",...sc(h),status:"up_to_date",notices:h.notices,warnings:C,next:[]},Ce(...b,...Q(C)));return}let S=Ye(n,m.credentials.environment);if(!S.ok){d(S);return}if(S.value.kind==="dry-run"){jn(l,S.value,{action:"actions link",...sc(h),notices:h.notices,warnings:C},f(["actions","link",h.action.apiName,h.object.id,h.includePerformAction===!0?"--menu":"--no-menu"],h.summary.isProduction),Ce(...b,...Q(C)));return}let x=await $o(m,h);if(!x.ok){d(x);return}let v=[...x.value.status==="already_linked"?y:C,...x.value.warnings],k=xc(h,x.value.status);Pe(l,{ok:!0,applied:x.value.status!=="already_linked",dryRun:!1,action:"actions link",...sc(h),status:x.value.status,notices:h.notices,warnings:v,next:[{step:"actions",argv:u(["actions","list"])}]},Ce(k,...b,...Q(v)))}catch(m){d(z(m))}}async function um(e,t,n,r){let i=am("unlink",{action:e,object:t});if(!i.ok){Je("appbuilder app actions unlink",[],n,r).fail(i);return}let{action:o,object:s}=i.value,a=Je("appbuilder app actions unlink",[o,s],n,r),{output:c,fail:l,appArgv:d,apply:u}=a,f=g=>["appbuilder","app","actions","unlink",o,g.id];try{let g=await $t(n,r,a);if(g===null)return;let m=await Jp(g,{action:o,object:s},f);if(!m.ok){l(m);return}let p=m.value,h=Ye(n,g.credentials.environment);if(!h.ok){l(h);return}let b=[...qe(p.summary),...Ac(p)],y=[...p.warnings,...await bt(r)],C={...yt(p.summary),jsAction:{apiName:p.action.apiName,name:p.action.name,hintObjectName:p.action.hintObjectName,inLive:p.action.inLive},object:p.object,associationId:p.associationId,includePerformAction:p.includePerformAction};if(h.value.kind==="dry-run"){jn(c,h.value,{action:"actions unlink",...C,warnings:y},u(["actions","unlink",p.action.apiName,p.object.id],p.summary.isProduction),Ce(...b,...Q(y)));return}let S=await Oo(g,p);if(!S.ok){l(S);return}Pe(c,{ok:!0,applied:!0,dryRun:!1,action:"actions unlink",...C,status:S.value.status,warnings:y,next:[{step:"actions",argv:d(["actions","list"])}]},Ce(Pc(p),...b,...Q(y)))}catch(g){l(z(g))}}function ei(e){let{owner:t,preview:n}=e;return[...qe(e.summary),`Preview: ${t.fullName??t.id} (${t.yours?"yours":t.id}), last updated ${n.updated??"unknown"}`,...n.activeUsersCount===null?[]:[`Active users: ${String(n.activeUsersCount)}`],...n.installedCount===null?[]:[`Installs: ${String(n.installedCount)}`],e.deletesApp?"Delete: this preview, and with it the app":"Delete: this preview"]}var Cc=(e,t)=>{let n=e.summary.name??e.summary.baseApiName;return[`\u2713 Deleted ${e.owner.yours?"your":`${e.owner.fullName??e.owner.id}'s`} preview of ${n}`,...t.appDeleted===!0?[`${n} had no other version, so it was deleted from this business.`]:[],...e.deletesApp&&t.appDeleted===!1?[`${n} has another version now, so it wasn't deleted.`]:[]]},ac=(e,t,n)=>e.code==="preview_changed"?{...e,next:[{step:"preview delete",argv:n(["preview","delete","--owner",t])}]}:e,bx="Kizen reports no last update for this preview, so this dry run can't be pinned to it and has no applyArgv: it can't be applied from this dry run.",Yp=e=>({...yt(e.summary),owner:e.owner,preview:e.preview,deletesApp:e.deletesApp});async function dm(e,t){let n=e.owner===void 0?[]:["--owner",e.owner],r=Je("appbuilder app preview delete",n,e,t),{output:i,fail:o,appArgv:s,apply:a}=r;try{let c=await $t(e,t,r);if(c===null)return;let l=(e.owner??c.credentials.userId).trim(),d=Co(c,{...e.owner!==void 0&&{owner:e.owner},...e.expectUpdated!==void 0&&{expectUpdated:e.expectUpdated}});if(!d.ok){o(ac(d,l,s));return}let u=d.value,f=Ye(e,c.credentials.environment);if(!f.ok){o(f);return}let g=ei(u),m=[...u.warnings,...await bt(t)];if(f.value.kind==="dry-run"){let{updated:C}=u.preview,S=C===null?[bx]:[];ze(t,S),jn(i,f.value,{action:"preview delete",...Yp(u),notices:S,warnings:m},C===null?null:a(["preview","delete","--owner",u.owner.id,"--expect-updated",C,...u.deletesApp?["--delete-app"]:[]],u.summary.isProduction),Ce(...g,...Q(m)));return}let p=Bp(u,e.deleteApp===!0);if(p!==null){o(ac(p,u.owner.id,s));return}let h=await So(c,u,t);if(!h.ok){o(ac(h,u.owner.id,s));return}let b=_o(u,h.value),y=[...b.warnings,...m.slice(u.warnings.length),...h.value.warnings];Pe(i,{ok:!0,applied:!0,dryRun:!1,action:"preview delete",...Yp(b),status:h.value.status,appDeleted:h.value.appDeleted,remembered:h.value.remembered,warnings:y,next:u.owner.yours?[{step:"push",argv:s(["push"])}]:[]},Ce(...Cc(u,h.value),...ei(b),...Q(y)))}catch(c){o(z(c))}}import{useEffect as nP,useState as Lc}from"react";import{Box as Qo,Text as Fc}from"ink";var Fo={credentials:null,credentialNotices:[],warnings:[],notices:[]},pm=e=>t=>e.length===0?t:{...t,notices:[...t.notices,...e]},ni="Loading credentials\u2026",jo="Dry run: nothing was written.";function mm(e){if(e.login===void 0)return e;let{login:t,...n}=e;return{...n,hint:`Sign in with: ${t.argv.map(ge).join(" ")}`}}function Mo({deps:e,setPhase:t,setSession:n,next:r,toView:i=Me,present:o=s=>s}){let s=!1,a=f=>g=>{s||f(g)},c=a(t),l=a(n),d=f=>{s||(e.setExitCode(1),c({type:"error",view:o(f)}))},u=async f=>{c({type:"loading",label:ni});let g=await Nn(f,e);if(s)return;if(!g.ok){if(g.choice==="environment"&&g.choices){c({type:"environment-select",options:f,choices:g.choices});return}d(g);return}let{environment:m,businessId:p}=g.value.credentials;l(h=>({...h,credentials:{environment:m,businessId:p},credentialNotices:g.value.notices})),await r(f,g.value)};return{load:u,pickEnvironment:(f,g)=>u({...f.options,env:g.value}),fail:d,guard:f=>{f().catch(g=>{d(i(g))})},abort:()=>{s=!0},isAborted:()=>s,whileRunning:a}}function fm(e,t){e(),t(130)}function zo(e,t){if(e.dryRun)return"dry-run";if(e.yes){let n=Ye(e,t);if(n.ok&&n.value.kind==="apply")return"apply"}return"confirm"}var wm=e=>e.type==="done"||e.type==="report"||e.type==="error";function wx(e){let t={dryRun:!1,yes:!1,allowProduction:!1,force:!1};switch(e.command){case"versions":case"pull":case"actions list":return t;case"merge":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0};case"push":case"publish":return{dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0,force:e.options.force===!0};case"rollback":case"actions link":case"actions unlink":case"preview delete":return{...t,dryRun:e.options.dryRun===!0,yes:e.options.yes===!0,allowProduction:e.options.allowProduction===!0}}}var vx={dryRun:!1,yes:!1,allowProduction:!1};function kx(e){let t=e.argv??[];if(t[0]!=="appbuilder"||t[1]!=="app")return null;let n=o=>{let s=t.indexOf(o);return s===-1?void 0:t[s+1]},r=n("--release"),i=n("--base");if(t[2]==="push"){let o=n("--base-from-preview");return{command:"push",...o!==void 0&&{baseFromPreview:o}}}return t[2]==="actions"&&t[3]==="link"&&t.length===4?{command:"actions link"}:t[2]==="merge"?{command:"merge",options:{...r!==void 0&&{version:r},...i!==void 0&&{base:i},...t.includes("--accept-live-base")&&{acceptLiveBase:!0}}}:null}var gm=e=>e.replace(/ Only if the user explicitly wants[^:]*: pass --force\./g,""),hm={value:"exit",label:"Exit without publishing",args:[]},Ax={value:"merge",label:"Merge Live into this folder",args:[],argv:["appbuilder","app","merge"]},xx={value:"push",label:"Push this folder as your preview",args:[],argv:["appbuilder","app","push"]},Px={value:"link-actions",label:"Link JS actions now",args:[],argv:["appbuilder","app","actions","link"]},ym={value:"finish",label:"Done",args:[]},Cx=e=>({value:e.id,label:`${e.objectName} (${e.name})`,args:[]}),Sx={linked:"linked",unlinked:"not linked",unknown:"not in Live, links can't be listed"},_x=e=>({value:e.apiName,label:`${e.apiName} (${e.name}): ${Sx[e.status]}`,args:[]});function bm(e,t){if(t===void 0)return I([...e]);let n=To(e,t,()=>[]);if(n.ok)return I([n.value]);if(n.code==="needs_choice"){let r=new Set((n.choices??[]).map(i=>i.value));return I(e.filter(i=>r.has(i.id)))}return n}var Ex=e=>`Conflicted files get git conflict markers: <<<<<<< HEAD is your file and >>>>>>> live is ${e}.`;function vm(e,t,n,r){let i=wx(e),o=e.command==="pull"?Ao(e.version,e.options.preview===!0):null,s=e.command==="publish"?e.options.expectPreview:void 0,a=null,c=Mo({deps:t,setPhase:n,setSession:r,toView:z,present:mm,next:async(E,N)=>{a={credentials:N.credentials,client:N.client},await fr(a)}}),{fail:l}=c,d=c.whileRunning(n),u=c.whileRunning(r),f=()=>!c.isAborted(),g={isAborted:c.isAborted},m=E=>{u(pm(E))},p=E=>{d({type:"loading",label:E})},h=E=>{d({type:"done",outcome:E})},b=(E,N,B)=>{if(Io(B).length===0){d(N);return}d({type:"choose",title:"What next?",message:"",lines:[],above:N,choices:[Px,ym],run:async R=>{if(R.value===ym.value){d(N);return}await P(E,R,null)},dismissed:N})},y=()=>{l({message:"Cancelled."})},C=E=>["appbuilder","app",...E,...Rn(e.options,t.processEnv)].map(ge).join(" "),S=async(E,N)=>{let B=await qr({...E,baseApiName:N},t);return B.ok?(m(B.value.notices),B.value):(l(B),null)},x=async E=>{if(a===null)return null;p("Loading the app\u2026");let N=await qr({...a,baseApiName:E.baseApiName},t);return N.ok?N.value:(l(N),null)},v=async(E,N,B,R)=>{switch(zo(B,E.credentials.environment)){case"dry-run":h({title:jo,tone:"warning",lines:N.lines,warnings:N.warnings,next:null});return;case"apply":await R();return;case"confirm":d({type:"confirm",...N,apply:R})}},k=(E,N,B,R)=>{if(N.code==="base_required"&&N.choices&&N.choices.length>0){d({type:"choose",title:"Choose how to go on",message:gm(N.message),lines:[],choices:N.choices,run:O=>P(E,O,B,R),dismissed:null});return}if(N.code==="publish_conflict"&&N.conflict?.reason!=="preview_replaced"){let{message:O}=N,D=N.conflict?.reason==="base_unknown";d({type:"choose",title:"What next?",message:gm(O),lines:[],choices:[D?xx:Ax,hm],run:async M=>{if(M.value===hm.value){l({message:O});return}await P(E,M,D?B:null)},dismissed:null});return}l(N)},P=async(E,N,B,R)=>{let O=kx(N);if(O===null){l({message:`Can't run "${N.label}" here.`});return}let D=await x(E);if(D!==null){if(O.command==="push"){await A(D,R===void 0?B:R,O.baseFromPreview===void 0?{}:{baseFromPreview:O.baseFromPreview});return}if(O.command==="actions link"){await $e(D,{},vx);return}await T(D,O.options,O.options.acceptLiveBase===!0?B:null)}},w=async(E,N,B,R)=>{if(!f())return;p("Checking the push\u2026");let O=await fo(E,N,{force:i.force,...R},t);if(!O.ok){k(E,O,async()=>{let J=await x(E);J!==null&&await w(J,N,B,{})},B);return}let D=O.value,M=Fn(N.deployable.artifacts.js_action_templates),Y=await it(E,{kind:"version",templates:M}),G=[...Qr(D),...Qe(Y)],Z=[...D.warnings,...Ge(Y)];m([...D.notices,...ot(Y)]),await v(E,{lines:G,warnings:Z,isProduction:D.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)"},i,async()=>{if(!f())return;p(`Saving your preview of ${D.appName}\u2026`);let J=await go(E,N,D,t,g);if(!J.ok){l(J);return}let le=uc(D.appName,J.value);if(B!==null){m([le,...Q([...Z,...J.value.warnings])]),await B();return}p("Checking the JS actions\u2026");let se=await Eo(E,M);m(ot(se)),b(E,{type:"done",outcome:{title:le,tone:"success",lines:[...Qr(D),...Qe(se)],warnings:[...D.warnings,...Ge(se),...J.value.warnings],next:C(["publish"])}},se)})},A=async(E,N,B)=>{if(!f())return;p("Packaging the app\u2026");let R=await mo(t);if(!R.ok){l(R);return}let{issues:O,source:D,deployable:M}=R.value;u(G=>({...G,warnings:O})),m(D.notice===void 0?[]:[D.notice]);let Y="api"in E?E:await S(E,M.api_name);Y!==null&&await w(Y,R.value,N,B)},_=async E=>{if(!f())return;p("Checking for conflicts\u2026");let N=async()=>{let M=await x(E);M!==null&&await _(M)},B=await ho(E,{force:i.force,...s!==void 0&&{expectPreview:s}},t);if(!B.ok){k(E,B,N);return}let R=B.value,O=dc(R),D=await it(E,{kind:"version",templates:Fn(R.jsActionTemplates)});m(ot(D)),await v(E,{lines:[...O,pc(R),...Qe(D)],warnings:[...R.warnings,...Ge(D)],isProduction:R.summary.isProduction,prompt:"Publish? (Y/n)",productionPrompt:"Type y to publish to production (y/N)"},i,async()=>{if(!f())return;p("Publishing\u2026");let M=await yo(E,R,t,g);if(!M.ok){k(E,M,N);return}let Y=await it(E,{kind:"live",version:M.value.liveVersion});m(ot(Y)),b(E,{type:"done",outcome:{title:mc(R,M.value),tone:"success",lines:[...O,...Qe(Y)],warnings:[...R.warnings,...M.value.warnings,...Ge(Y)],next:null}},Y)})},T=async(E,N,B)=>{if(!f())return;p("Planning the merge\u2026");let R=await bo(E,N,t);if(!R.ok){l(R);return}let O=R.value,D=Bo(O.targetVersion,O.targetIsLive),M=O.kind==="merge"&&O.plan.conflicted.length>0;m(O.notices);let Y=async()=>{if(!f())return;p(O.kind==="fallback"?`Extracting ${D}\u2026`:O.kind==="merge"?"Merging\u2026":"Recording the base\u2026");let G=await wo(E,O,t,g);if(!G.ok){l(G);return}let Z=G.value,[J="",...le]=hc(O,Z),se=[...O.warnings,...Z.warnings],Fe=Z.status==="accepted"||Z.status==="up_to_date";if(B!==null&&Fe){m([J,...Q(se)]),await B();return}let Hn={title:J,tone:Z.status==="conflicts"||Z.status==="fallback"?"warning":"success",lines:le,warnings:se,next:Z.status==="accepted"?C(["push"]):null};if(Z.status==="fallback"&&O.kind==="fallback"){d({type:"choose",title:"Choose how to go on",message:fc,lines:[J,...le],choices:O.choices,run:Ns=>P(E,Ns,null),dismissed:{type:"done",outcome:Hn}});return}h(Hn)};if(O.kind==="up_to_date"&&!O.advancesBase){await Y();return}await v(E,{lines:[...qe(O.summary),...gc(O),...M?[Ex(D)]:[]],warnings:O.warnings,isProduction:!1,prompt:O.kind==="merge"?"Merge? (Y/n)":O.kind==="fallback"?"Extract it? (Y/n)":"Record it? (Y/n)",productionPrompt:""},{dryRun:i.dryRun,yes:i.yes||B!==null&&O.kind==="accept",allowProduction:!0},Y)},L=async(E,N)=>{if(!f())return;p(`Preparing v${N}\u2026`);let B=await vo(E,N,t);if(!B.ok){l(B);return}let R=B.value,O=yc(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,prompt:"Restore it? (Y/n)",productionPrompt:"Type y to restore it on production (y/N)"},i,async()=>{if(!f())return;p(`Restoring v${R.version}\u2026`);let D=await ko(E,R,t,g);if(!D.ok){l(D);return}h({title:bc(R),tone:"success",lines:O,warnings:[...R.warnings,...D.value.warnings],next:C(["publish"])})})},$=async(E,N,B)=>{if(!f())return;p(N.kind==="release"?`Downloading v${N.version}\u2026`:"Downloading your preview\u2026");let R=await xo(E,N,B===void 0?{}:{out:B},t);if(!R.ok){l(R);return}let O=R.value;if(!f())return;let D=await Po(E,O,t,g);if(!D.ok){l(D);return}let[M="",...Y]=wc(O,D.value);h({title:M,tone:"success",lines:Y,warnings:[...O.warnings,...D.value.warnings],next:null})},V=async E=>{p("Reading the JS actions\u2026");let N=await No(E);if(!N.ok){l(N);return}let{summary:B,check:R}=N.value;d({type:"report",lines:vc(B,R),warnings:Ge(R)})},X=async E=>{p("Reading the JS actions\u2026");let N=await ec(E);return N.ok?N.value:(l(N),null)},ve=(E,N)=>{d({type:"choose",message:"",lines:[],...E,run:N,dismissed:null})},Re=async(E,N,B,R)=>{let[O]=N;if(B&&O!==void 0&&N.length===1){await R(O);return}if(O===void 0){l({message:"There's no object on this business that you can see."});return}let D=E.hintObjectName===null?null:To(N,E.hintObjectName,()=>[]);ve({title:`Object for ${E.apiName}`,choices:N.map(Cx),...D?.ok===!0&&{initial:D.value.id},searchable:!0},async M=>{let Y=N.find(G=>G.id===M.value);Y!==void 0&&await R(Y)})},$e=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=bm(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0||N.object===void 0,M=async(J,le)=>{if(N.menu!==void 0||!D){await Te(E,R,J,le,N.menu,B);return}let se=J.links.find(Fe=>Fe.objectId===le.id);ve({title:`Show ${J.apiName} in the Perform Action menus of ${le.objectName}?`,choices:[{value:"no",label:"No",args:[]},{value:"yes",label:"Yes",args:[]}],initial:se?.includePerformAction===!0?"yes":"no"},Fe=>Te(E,R,J,le,Fe.value==="yes",B))},Y=J=>Re(J,O.value,N.object!==void 0,le=>M(J,le));if(N.action!==void 0){let J=Ro(E,R,N.action);if(!J.ok){l(J);return}await Y(J.value);return}let{actions:G}=R.check;if(G.length===0){l({message:`${E.baseApiName} has no JS actions to link.`});return}let Z=G.find(J=>J.status!=="linked");ve({title:"JS action to link",choices:G.map(_x),...Z!==void 0&&{initial:Z.apiName},searchable:!0},async J=>{let le=G.find(se=>se.apiName===J.value);le!==void 0&&await Y(le)})},Te=async(E,N,B,R,O,D)=>{if(!f())return;let M=tc(E,N,B,R,{...O!==void 0&&{menu:O}}),Y=[...qe(M.summary),...kc(M)];if(m(M.notices),M.change==="up_to_date"){h({title:"Nothing to change.",tone:"success",lines:Y,warnings:[],next:null});return}let G=M.change==="create";await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:G?"Link it? (Y/n)":"Change it? (Y/n)",productionPrompt:G?"Type y to link it on production (y/N)":"Type y to change it on production (y/N)"},D,async()=>{if(!f())return;p(G?"Linking\u2026":"Changing the link\u2026");let Z=await $o(E,M,g);if(!Z.ok){l(Z);return}h({title:xc(M,Z.value.status),tone:Z.value.status==="already_linked"?"warning":"success",lines:Y,warnings:[...Z.value.status==="already_linked"?[]:M.warnings,...Z.value.warnings],next:C(["actions","list"])})})},gn=async(E,N,B)=>{if(!f())return;let R=await X(E);if(R===null)return;let O=bm(R.objects,N.object);if(!O.ok){l(O);return}let D=N.action===void 0?null:Ro(E,R,N.action);if(D!==null&&!D.ok){l(D);return}if(D!==null&&N.object!==void 0){await Re(D.value,O.value,!0,G=>ct(E,R,D.value,G,B));return}let M=new Set(O.value.map(G=>G.id)),Y=(D===null?R.check.actions:[D.value]).flatMap(G=>G.links.filter(Z=>M.has(Z.objectId)).map(Z=>({action:G,link:Z})));if(Y.length===0){l(D===null?{message:`${E.baseApiName} has no listed JS action links to remove.`}:{message:`${D.value.apiName} isn't linked to any object.`,...!D.value.inLive&&{hint:nc(D.value.apiName)}});return}ve({title:"Link to remove",choices:Y.map(({action:G,link:Z})=>({value:Z.id,label:`${G.apiName} \u2192 ${Z.label} (${Z.objectName})`,args:[]})),searchable:!0},async G=>{let Z=Y.find(({link:Fe})=>Fe.id===G.value);if(Z===void 0)return;let{action:J,link:le}=Z,se=R.objects.find(Fe=>Fe.id===le.objectId)??{id:le.objectId,name:le.objectName,objectName:le.label,entityName:null};await ct(E,R,J,se,B)})},ct=async(E,N,B,R,O)=>{if(!f())return;let D=rc(E,N,B,R);if(!D.ok){l(D);return}let M=D.value,Y=[...qe(M.summary),...Ac(M)];await v(E,{lines:Y,warnings:M.warnings,isProduction:M.summary.isProduction,prompt:"Unlink it? (Y/n)",productionPrompt:"Type y to unlink it on production (y/N)"},O,async()=>{if(!f())return;p("Unlinking\u2026");let G=await Oo(E,M,g);if(!G.ok){l(G);return}h({title:Pc(M),tone:"success",lines:Y,warnings:M.warnings,next:C(["actions","list"])})})},mr=async(E,N)=>{if(!f())return;let B=Co(E,{...N.owner!==void 0&&{owner:N.owner},...N.expectUpdated!==void 0&&{expectUpdated:N.expectUpdated}});if(!B.ok){l(B);return}let R=B.value,O=ei(R);await v(E,{lines:O,warnings:R.warnings,isProduction:R.summary.isProduction,strict:R.deletesApp,prompt:"Delete it? (Y/n)",productionPrompt:R.deletesApp?`Type y to delete the preview and the whole app${R.summary.isProduction?" on production":""} (y/N)`:"Type y to delete it on production (y/N)"},R.deletesApp&&N.deleteApp!==!0?{...i,yes:!1}:i,async()=>{if(!f())return;p("Deleting the preview\u2026");let D=await So(E,R,t,g);if(!D.ok){l(D);return}let[M="",...Y]=Cc(R,D.value),G=_o(R,D.value);h({title:M,tone:"success",lines:[...Y,...ei(G)],warnings:[...G.warnings,...D.value.warnings],next:R.owner.yours?C(["push"]):null})})},fr=async E=>{if(e.command==="push"){let{baseFromPreview:R}=e.options;await A(E,null,R===void 0?{}:{baseFromPreview:R});return}p("Loading the app\u2026");let N;try{N=await t.readManifestApiName(t.cwd)}catch(R){l(z(R));return}let B=await S(E,N);if(B!==null)switch(e.command){case"versions":{let R=await rr(B);if(!R.ok){l(R);return}let O=po(B,R.value),D=await it(B,{kind:"app"});m(ot(D)),b(B,{type:"report",lines:[...lc(O),...Qe(D)],warnings:[...O.warnings,...Ge(D)]},D);return}case"publish":await _(B);return;case"merge":await T(B,{...e.options.release!==void 0&&{version:e.options.release},...e.options.base!==void 0&&{base:e.options.base},...e.options.acceptLiveBase===!0&&{acceptLiveBase:!0}},null);return;case"rollback":await L(B,e.version);return;case"pull":o?.ok===!0&&await $(B,o.value,e.options.out);return;case"actions list":await V(B);return;case"actions link":await $e(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object},...e.options.menu!==void 0&&{menu:e.options.menu}},i);return;case"actions unlink":await gn(B,{...e.action!==void 0&&{action:e.action},...e.object!==void 0&&{object:e.object}},i);return;case"preview delete":await mr(B,e.options)}},{guard:jt}=c;return{start:()=>{if(o?.ok===!1){l(o);return}jt(()=>c.load(e.options))},pickEnvironment:(E,N)=>{jt(()=>c.pickEnvironment(E,N))},accept:E=>{jt(E.apply)},choose:(E,N)=>{jt(()=>E.run(N))},dismiss:E=>{E.dismissed===null?y():d(E.dismissed)},cancel:y,abort:c.abort}}import{useMemo as _c,useState as Am}from"react";import{Box as Ec,Text as Ot,useInput as Ix}from"ink";function Sc(e,t){let n=i=>i.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase(),r=n(t).split(/\s+/).filter(Boolean);return e.flatMap((i,o)=>{let s=n(`${i.label} ${i.description??""}`);return r.every(a=>s.includes(a))?[{item:i,index:o}]:[]})}var Uo=(e,t,n)=>Math.min(Math.max(e,t),n);function Vo(e,t,n,r={}){if(t<=0)return 0;let i=Uo(Math.trunc(e)||0,0,t-1),o=c=>r.disabled?.[c]!==!0;if(n===0)return i;let s=n>0?1:-1;if(Math.abs(n)===1){for(let c=1;c<=t;c++){let l=((i+s*c)%t+t)%t;if(o(l))return l}return i}let a=Uo(i+Math.trunc(n),0,t-1);for(let c=a;c>=0&&c<t;c+=s)if(o(c))return c;for(let c=a-s;c>=0&&c<t;c-=s)if(o(c))return c;return i}function km(e,t,n=10){if(t<=0)return{start:0,end:0};let r=Math.max(1,Math.floor(n));if(t<=r)return{start:0,end:t};let i=Uo(Math.trunc(e)||0,0,t-1),o=Uo(i-Math.floor(r/2),0,t-r);return{start:o,end:o+r}}import{jsx as Dt,jsxs as Tc}from"react/jsx-runtime";var Tx="\u2191/\u2193 to move, Enter to select, Esc to cancel",Nx="Type to filter, \u2191/\u2193 to move, Enter to select, Esc to clear or cancel",Ic=10,xm=(e,t)=>{let n=e.findIndex(o=>o.key===t&&o.disabled!==!0);if(n!==-1)return n;let r=Vo(0,e.length,0);if(e[r]?.disabled!==!0)return r;let i=e.findIndex(o=>o.disabled!==!0);return i===-1?r:i},Lt=({title:e,items:t,onSelect:n,onCancel:r,hint:i,initialKey:o,searchable:s=!1})=>{let[a,c]=Am(""),l=_c(()=>Sc(t,s?a:""),[t,s,a]),d=_c(()=>l.map(({item:C})=>C),[l]),[u,f]=Am(()=>xm(t,o)),g=_c(()=>d.map(C=>C.disabled===!0),[d]),m=Vo(u,d.length,0);Ix((C,S)=>{let x=k=>{f(Vo(m,d.length,k,{disabled:g}))},v=k=>{c(k),f(xm(Sc(t,k).map(({item:P})=>P)))};if(S.upArrow||!s&&C==="k")x(-1);else if(S.downArrow||!s&&C==="j")x(1);else if(S.pageUp)x(-Ic);else if(S.pageDown)x(Ic);else if(S.return){let k=l[m];k!==void 0&&k.item.disabled!==!0&&n(k.item,k.index)}else S.escape?s&&a!==""?v(""):r?.():s&&(S.backspace||S.delete)?v(a.slice(0,-1)):s&&C!==""&&!S.ctrl&&!S.meta&&!S.tab&&v(a+C)});let{start:p,end:h}=km(m,d.length,Ic),b=p,y=d.length-h;return Tc(Ec,{flexDirection:"column",gap:1,children:[Dt(Ot,{bold:!0,children:e}),s&&Dt(Ot,{children:`Filter: ${a}`}),Tc(Ec,{flexDirection:"column",children:[b>0&&Dt(Ot,{dimColor:!0,children:` \u2191 ${String(b)} more`}),s&&d.length===0&&Dt(Ot,{dimColor:!0,children:" No matches"}),d.slice(p,h).map((C,S)=>{let v=p+S===m,k=C.disabled===!0,P=v&&!k;return Tc(Ec,{gap:2,children:[Dt(Ot,{...P&&{color:"cyan"},dimColor:k,children:v?"\u276F":" "}),Dt(Ot,{bold:P,dimColor:k,...P&&{color:"cyan"},children:C.label}),C.description!==void 0&&Dt(Ot,{dimColor:!0,children:C.description})]},C.key)}),y>0&&Dt(Ot,{dimColor:!0,children:` \u2193 ${String(y)} more`})]}),Dt(Ot,{dimColor:!0,children:i??(s?Nx:Tx)})]})};import{jsx as Rx}from"react/jsx-runtime";function or(e,t){return(n,r)=>{let i=e[r];i!==void 0&&t(i)}}function sr({title:e,choices:t,onPick:n,onCancel:r,initial:i,searchable:o=!1}){return Rx(Lt,{title:e,items:t.map(s=>({key:s.value,label:s.label})),onSelect:or(t,n),onCancel:r,...i!==void 0&&{initialKey:i},searchable:o})}import{Text as Pm,useInput as $x}from"ink";import{Fragment as Ox,jsx as Nc,jsxs as Dx}from"react/jsx-runtime";var Rc=({prompt:e,strict:t,onAccept:n,onCancel:r})=>($x((i,o)=>{if(o.ctrl)return;let s=i.toLowerCase();s==="y"||!t&&o.return?n():(t||s==="n"||o.escape)&&r()}),Nc(Pm,{bold:!0,children:e})),Ho=({isProduction:e,strict:t=!1,prompt:n,productionPrompt:r,onAccept:i,onCancel:o})=>Dx(Ox,{children:[e&&Nc(Pm,{color:"red",bold:!0,children:"PRODUCTION"}),Nc(Rc,{prompt:e||t?r:n,strict:e||t,onAccept:i,onCancel:o})]});import{Box as $c,Text as Ko}from"ink";import{Box as Lx,Text as Bx}from"ink";import{jsx as Cm}from"react/jsx-runtime";var Ne=({lines:e,color:t})=>Cm(Lx,{flexDirection:"column",children:e.map((n,r)=>Cm(Bx,{...t&&{color:t},children:n},`${String(r)}-${n}`))});import{jsx as Wo,jsxs as Go}from"react/jsx-runtime";var Jo=({view:e})=>Go($c,{flexDirection:"column",gap:1,children:[Go($c,{gap:1,children:[Wo(Ko,{color:"red",children:"\u2717"}),Wo(Ko,{color:"red",children:e.issues&&e.issues.length>0?We(e.issues):e.message})]}),e.hint!==void 0&&Go(Ko,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&Go($c,{flexDirection:"column",children:[Wo(Ko,{children:"Choices:"}),Wo(Ne,{lines:e.choices.map(t=>` ${t.label}`)})]})]});import{useEffect as Kx}from"react";import{Box as Wx,Text as Em,useApp as Gx,useInput as Jx}from"ink";import{Box as zx,Text as Ux}from"ink";import{Box as Fx,Text as jx}from"ink";import{jsx as Sm}from"react/jsx-runtime";var Mx=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],_m=()=>Sm(Fx,{flexDirection:"column",children:Mx.map((e,t)=>Sm(jx,{color:"cyan",children:e},t))});import{Fragment as Vx,jsx as Oc,jsxs as Hx}from"react/jsx-runtime";var ye=({marginBottom:e=0})=>Hx(Vx,{children:[Oc(_m,{}),Oc(zx,{flexDirection:"column",marginTop:1,marginBottom:e,children:Oc(Ux,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{jsx as qo,jsxs as Im}from"react/jsx-runtime";var Yo=({session:e,children:t})=>Im(Wx,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[qo(ye,{}),e.credentials&&Im(Em,{dimColor:!0,children:["Environment: ",e.credentials.environment," \xB7 Business: ",e.credentials.businessId]}),e.credentialNotices.length>0&&qo(Ne,{lines:e.credentialNotices,color:"yellow"}),e.warnings.length>0&&qo(Em,{dimColor:!0,children:We(e.warnings)}),e.notices.length>0&&qo(Ne,{lines:e.notices}),t]});function Zo(e,t,n){let r=Gx();Kx(()=>{e&&r.exit()},[e,r]),Jx((i,o)=>{o.ctrl&&i==="c"&&!e&&(fm(n,t),r.exit())})}import{Box as Dc,Text as Xo}from"ink";import{jsx as Tm,jsxs as ri}from"react/jsx-runtime";var ar=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return ri(Dc,{flexDirection:"column",marginTop:1,children:[ri(Xo,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...Na(e)].map(([n,r])=>ri(Dc,{flexDirection:"column",marginTop:1,children:[Tm(Xo,{bold:!0,children:n}),r.map((i,o)=>Tm(Dc,{paddingLeft:2,children:ri(Xo,{color:i.severity==="error"?"red":"yellow",children:[i.severity==="error"?"\u2717":"\u26A0"," ",i.message," ",ri(Xo,{dimColor:!0,children:["(",i.rule,")"]})]})},`${i.rule}-${String(o)}`))]},n))]})};import{Box as Qx,Text as eP}from"ink";import{useEffect as qx,useState as Yx}from"react";import{Text as Zx}from"ink";import{jsx as Xx}from"react/jsx-runtime";var Nm=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],wt=()=>{let[e,t]=Yx(0);return qx(()=>{let n=setInterval(()=>{t(r=>(r+1)%Nm.length)},80);return()=>{clearInterval(n)}},[]),Xx(Zx,{color:"cyan",children:Nm[e]??"\u280B"})};import{jsx as Rm,jsxs as tP}from"react/jsx-runtime";var cr=({label:e})=>tP(Qx,{gap:1,children:[Rm(wt,{}),Rm(eP,{dimColor:!0,children:e})]});import{jsx as fe,jsxs as ii}from"react/jsx-runtime";var jc=({warnings:e})=>e.length>0?fe(Ne,{lines:Q(e),color:"yellow"}):null,rP=({outcome:e})=>ii(Qo,{flexDirection:"column",gap:1,children:[fe(Fc,{bold:!0,color:e.tone==="success"?"green":"yellow",children:e.title}),e.lines.length>0&&fe(Ne,{lines:e.lines}),fe(jc,{warnings:e.warnings}),e.next!==null&&ii(Fc,{dimColor:!0,children:["Next: ",e.next]})]}),Bc=({phase:e})=>e.type==="done"?fe(rP,{outcome:e.outcome}):ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:e.lines}),fe(jc,{warnings:e.warnings})]}),iP=({view:e})=>e.issues&&e.issues.length>0?fe(ar,{issues:e.issues}):fe(Jo,{view:e}),$m=({request:e,deps:t})=>{let[n,r]=Lc({type:"loading",label:ni}),[i,o]=Lc(Fo),[s]=Lc(()=>vm(e,t,r,o));nP(()=>{s.start()},[s]),Zo(wm(n),t.setExitCode,s.abort);let a=c=>fe(Yo,{session:i,children:c});switch(n.type){case"loading":return a(fe(cr,{label:n.label}));case"environment-select":return a(fe(sr,{title:"Environment",choices:n.choices,onPick:c=>{s.pickEnvironment(n,c)},onCancel:s.cancel},"environment"));case"report":return a(fe(Bc,{phase:n}));case"confirm":return a(ii(Qo,{flexDirection:"column",gap:1,children:[fe(Ne,{lines:n.lines}),fe(jc,{warnings:n.warnings}),fe(Ho,{isProduction:n.isProduction,strict:n.strict===!0,prompt:n.prompt,productionPrompt:n.productionPrompt,onAccept:()=>{s.accept(n)},onCancel:s.cancel})]}));case"choose":return a(ii(Qo,{flexDirection:"column",gap:1,children:[n.above!==void 0&&fe(Bc,{phase:n.above}),n.lines.length>0&&fe(Ne,{lines:n.lines}),n.message!==""&&fe(Fc,{color:"yellow",children:n.message}),fe(sr,{title:n.title,choices:n.choices,onPick:c=>{s.choose(n,c)},onCancel:()=>{s.dismiss(n)},...n.initial!==void 0&&{initial:n.initial},searchable:n.searchable===!0},[n.title,...n.choices.map(c=>c.value)].join("|"))]}));case"done":return a(fe(Bc,{phase:n}));case"error":return a(fe(iP,{view:n.view}))}};var aP=e=>{console.error(`Error: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1},vt=e=>e.option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)"),kt=e=>e.option("--json","print a JSON result to stdout (always headless)").option("--no-interactive",mt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)"),Mn=(e,t=!0)=>(e.option("--dry-run","show what would change without writing anything").option("--yes","write without asking (without it, the command is a dry run)"),t?e.option("--allow-production","allow writes to go/fmo"):e);async function At(e,t,n){try{let r=sp(process.cwd());if(!pt({json:e.options.json===!0,noInteractive:t})){await n(r);return}let{waitUntilExit:i}=sP(oP($m,{request:e,deps:r}),{exitOnCtrlC:!1});await i()}catch(r){aP(r)}}function cP(e){let t=e.command("actions").description("Link the app's JS actions to objects: list, link and unlink"),n=vt(t.command("list").description("Show the app's JS actions and the objects they're linked to"));kt(n).action(async o=>{let{noInteractive:s,options:a}=Ae(o);await At({command:"actions list",options:a},s,c=>cm(a,c))});let r=vt(t.command("link").description("Link a JS action to an object, or change whether it shows in its menus").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick it)").argument("[object]","the object's api name (like client_client) or id")).option("--menu","show the action in the object's Perform Action menus").option("--no-menu","don't show it there (the default for a new link)");kt(Mn(r)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await At({command:"actions link",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>lm(o,s,l,d))});let i=vt(t.command("unlink").description("Remove a JS action's link to an object").argument("[action]","the JS action's api_name (at a terminal, leave it out to pick a link)").argument("[object]","the object's api name (like client_client) or id"));kt(Mn(i)).action(async(o,s,a)=>{let{noInteractive:c,options:l}=Ae(a);await At({command:"actions unlink",...o!==void 0&&{action:o},...s!==void 0&&{object:s},options:l},c,d=>um(o,s,l,d))})}function lP(e){let t=e.command("preview").description("Manage the app's previews: delete"),n=vt(t.command("delete").description("Delete your preview of the app, or with --owner, another developer's")).option("--owner <userId>","delete this user's preview instead of yours").option("--expect-updated <ts>","delete only if the preview's last update is still <ts> (a dry run prints it)").option("--delete-app","allow deleting the whole app when this preview is its only version (a dry run that says so prints it)");kt(Mn(n)).action(async r=>{let{noInteractive:i,options:o}=Ae(r);await At({command:"preview delete",options:o},i,s=>dm(o,s))})}function Om(e){let t=e.command("app").description("Publish the plugin as a Business App: previews, releases, merges and rollbacks"),n=vt(t.command("versions").description("Show the app's Live, released and preview versions"));kt(n).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"versions",options:d},l,u=>tm(d,u))});let r=vt(t.command("push").description("Save this folder as your preview of the app"));kt(Mn(r).option("--force","push even if files still have merge conflict markers").option("--base-from-preview <id>","take this folder's base from your preview, while it's still source package <id> (a base_required choice prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"push",options:d},l,u=>nm(d,u))});let i=vt(t.command("publish").description("Publish your preview as the next Live version"));kt(Mn(i).option("--force","publish even if Live changed since your preview was based on it, or its base is unknown").option("--expect-preview <id>","publish only if your preview's source package is still <id> (a dry run prints it)")).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"publish",options:d},l,u=>rm(d,u))});let o=vt(t.command("merge").description("Merge the Live version (or --release) into this folder")).option("--release <n>","merge release <n> instead of the Live version").option("--base <n>","the release this folder was copied from, when no base is recorded (a wrong one drops the changes made since)").option("--accept-live-base","record Live (or --release) as this folder's base without merging, after merging by hand");kt(Mn(o,!1)).action(async c=>{let{noInteractive:l,options:d}=Ae(c);await At({command:"merge",options:d},l,u=>im(d,u))});let s=vt(t.command("rollback").description("Restore a released version as your preview").argument("<version>","the released version to restore"));kt(Mn(s)).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await At({command:"rollback",version:c,options:u},d,f=>om(c,u,f))});let a=vt(t.command("pull").description("Download a released version's source, or with --preview your preview's, into a new folder").argument("[version]","the released version to download (or pass --preview instead)")).option("--preview","download your preview instead of a released version").option("--out <dir>","folder to create (default: ../<api_name>-v<version>, or ../<api_name>-preview)");kt(a).action(async(c,l)=>{let{noInteractive:d,options:u}=Ae(l);await At({command:"pull",...c!==void 0&&{version:c},options:u},d,f=>sm(c,u,f))}),cP(t),lP(t)}var uP=async(e,t)=>{let n={json:!0,deps:t},r=i=>Et("appbuilder whoami",[...i.args,...rn(e,t.processEnv)],n);try{let i=bn(e,t.processEnv);if(!i.ok){It(n,me("usage_error",i.message),r);return}let o=await $a(e.env,i.request,{sessions:t.store,connect:(c,l)=>t.identify(t.tokenProvider(c,l===void 0?void 0:{account:l})),processEnv:t.processEnv});if(!o.ok){It(n,o,r);return}let{environment:s,connected:a}=o.value;Pe(n,{ok:!0,environment:s,businessId:a.businessId,businessName:a.businessName??null,userId:a.userId,fullName:a.fullName??null,email:a.email??null},Ri(s,a))}catch(i){It(n,Me(i),r)}},Dm=(e,t)=>e.json===!0?uP(e,t):_u(e,t);import{render as dP}from"ink";import{jsx as pP}from"react/jsx-runtime";var Lm=async(e,t)=>{let n,r=dP(pP(Lt,{title:e,items:t,onSelect:i=>{n=i.key,r.unmount()},onCancel:()=>{r.unmount()}}));return await r.waitUntilExit(),n};var mP=[{name:"login",description:"Sign in to Kizen in the browser, or switch to a saved account, and store the session on this machine",env:"environment to sign in to (default: go)",options:[["--business <id-or-name>","switch to the saved account with this business id, or business name (ignoring case); signs in with the browser if none matches or it expired"],["--user <userId>","with --business, pick the saved account of this user id"],["--list","list the saved accounts for the environment and exit"],["--json","with --list, print the accounts as JSON"],["--no-interactive",mt]],run:Cu},{name:"logout",description:"Remove the stored session from this machine",env:"environment to sign out of (default: the only signed-in one)",options:[["--all","also remove every other saved account for the environment"],["--business <id-or-name>","remove only this saved account, by business id or name (ignoring case)"],["--user <userId>","with --business, remove the saved account of this user id"]],run:Su},{name:"whoami",description:"Show the user and business of the stored session",env:"environment to check (default: the only signed-in one, or with --business the only one where it's saved)",options:[["--business <id-or-name>","check this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)"],["--user <userId>","with --business, check the saved account of this user id (default: $APPBUILDER_USER)"],["--json","print the identity as JSON"]],run:Dm},{name:"auth-header",description:"Print an Authorization header for the stored session as JSON (for a Claude Code MCP headersHelper)",env:"environment to use; must match CLAUDE_CODE_MCP_SERVER_URL when that is set (default: the environment matching it, else the only signed-in one)",options:[["--business <id>","with --user, use this saved account, current or not"],["--user <userId>","with --business, the user id of that account"]],run:Eu}];function Bm(e){for(let{name:t,description:n,env:r,options:i=[],run:o}of mP){let s=e.command(t).description(n).option("--env <env>",r);for(let[a,c]of i)s.option(a,c);s.action(async a=>{let{noInteractive:c,options:l}=Ae(a);await o(l,vu(void 0,Lm,c))})}}import{createElement as IC}from"react";import{render as TC}from"ink";import{PluginValidationError as NC}from"@kizenapps/packager";import{spawn as fP}from"child_process";import{platform as Fm}from"process";function gP(){return Fm==="darwin"?[{cmd:"pbcopy",args:[]}]:Fm==="win32"?[{cmd:"clip",args:[]}]:[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}var hP=2e3;function yP(e,{cmd:t,args:n}){return new Promise(r=>{let i;try{i=fP(t,n,{stdio:["pipe","ignore","ignore"]})}catch{r(!1);return}let o=i,s=!1;function a(l){s||(s=!0,clearTimeout(c),r(l))}let c=setTimeout(()=>{o.kill(),a(!1)},hP);c.unref(),o.on("error",()=>{a(!1)}),o.on("close",l=>{a(l===0)}),o.stdin.on("error",()=>{a(!1)});try{o.stdin.end(e)}catch{a(!1)}})}async function es(e){for(let t of gP())if(await yP(e,t))return!0;return!1}import{BLOCKS_DIRECTORY_NAME as OP,CONFIG_FILE_NAME as DP,MANIFEST_FILE_NAME as LP,sanitizeToAPIName as BP}from"@kizenapps/packager";var ts=["min_w","max_w","min_h","max_h","default_w","default_h"];import{createHash as bP}from"crypto";import{mkdir as wP,readFile as vP,writeFile as kP}from"fs/promises";import{dirname as AP,join as zm}from"path";var Mc="appbuilder:",zn=".kizenapp/pushes.json",xP=["environment","businessId","pluginApiName","blockApiName","dashboardId","dashletId","contentHash","pushedAt"];function zc(e){return typeof e=="number"&&Number.isFinite(e)}function ns(e,t,n){return Math.min(Math.max(e,t),n)}function PP(e){let t={...e};return delete t.custom_object,t}function Um(e,t){return`${Mc}${e}/${t}`}function Vm(e){if(!e.startsWith(Mc))return null;let t=e.slice(Mc.length).split("/");if(t.length!==2)return null;let[n,r]=t;return!n||!r?null:{pluginApiName:n,blockApiName:r}}function Hm(e){let t={};for(let n of ts){let r=e[n];zc(r)&&(t[n]=r)}return t}function Km(e){return typeof e.host_chrome=="boolean"?{host_chrome:e.host_chrome}:{}}var Wm=e=>Object.entries(e).map(([t,n])=>({name:t,script:n}));function CP(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:Wm(e.event_scripts)}}function Vc(e){return e.length>0?{views:e.map(CP)}:{}}function Gm(e,t=[]){return{kind:"custom_code",version:1,name:e.name,script:e.script,styles:e.styles,event_scripts:Wm(e.event_scripts),...Hm(e),...Km(e),...Vc(t)}}function SP(e){return{object_id:e.objectId,entity_type:"static_content",report_type:"html",chart_type:"html",content:e.content,fe_extra_info:{}}}function _P(e){let t=0;for(let n of e){let r=n.layout;if(!F(r))continue;let{y:i,h:o}=r;!zc(i)||!zc(o)||(t=Math.max(t,i+o))}return t}function EP(e,t,n){let r=ns(t.default_w??t.min_w??6,t.min_w??1,t.max_w??12),i=ns(t.default_h??t.min_h??3,t.min_h??1,t.max_h??99);return{i:n,x:0,y:_P(e),w:ns(r,2,12),h:ns(i,1,99)}}function Jm(e){return{name:Um(e.pluginApiName,e.blockApiName),layout:EP(e.dashlets,e.content,e.layoutId),config:SP({content:e.content,objectId:e.objectId})}}function qm(e,t){let n=e.config;return{config:{...PP(F(n)?n:{}),content:t}}}function Ym(e){let t=e.config;return F(t)?t.content:void 0}function lr(e){let t=e.config;if(!F(t)||t.chart_type!=="html")return!1;let n=t.content;return F(n)&&n.kind==="custom_code"}function Zm(e){return e.dashlets.filter(lr)}function rs(e){let t=Ym(e);return F(t)&&typeof t.name=="string"?t.name:e.name}var cn=e=>typeof e=="string"?e:"";function Xm(e){return Array.isArray(e)?e.filter(F).map(t=>({name:cn(t.name),script:cn(t.script)})):F(e)?Object.entries(e).map(([t,n])=>({name:t,script:cn(n)})):[]}function Uc(e){if(Array.isArray(e))return e.map(Uc);if(F(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Uc(e[n]);return t}return e}function Qm(e){return typeof e=="string"?e.trim():typeof e=="number"||typeof e=="boolean"?String(e).trim():""}function IP(e){return Array.isArray(e)?e.filter(F).map(t=>({api_name:cn(t.api_name),name:Qm(t.name),type:cn(t.type),script:cn(t.script),html:cn(t.html),css:cn(t.css),event_scripts:Xm(t.event_scripts)})):[]}function Hc(e){let t=F(e)?e:{},n=IP(t.views),r={name:Qm(t.name),script:typeof t.script=="string"?t.script:"",styles:typeof t.styles=="string"?t.styles:"",event_scripts:Xm(t.event_scripts),...Hm(t),...Km(t),...n.length>0&&{views:n}};return bP("sha256").update(JSON.stringify(Uc(r))).digest("hex")}function ef(e){let{entry:t}=e;if(t?.dashboardId===e.dashboardId){let o=e.dashlets.find(s=>s.id===t.dashletId);if(o&&lr(o))return{kind:"map",dashlet:o,entry:t}}let n=Um(e.pluginApiName,e.blockApiName),r=e.dashlets.filter(o=>o.name===n&&lr(o)),[i]=r;return r.length===1&&i?{kind:"name",dashlet:i}:r.length>1?{kind:"ambiguous",dashlets:r}:{kind:"none"}}function tf(e,t){return t?.dashletId!==e.id?!1:Hc(Ym(e))!==t.contentHash}function Kc(e,t){return e.environment===t.environment&&e.businessId===t.businessId&&e.pluginApiName===t.pluginApiName&&e.blockApiName===t.blockApiName}function Wc(e,t){return e.find(n=>Kc(n,t))}function nf(e,t){let n=e.findIndex(r=>Kc(r,t));return n===-1?[...e,t]:e.map((r,i)=>i===n?t:r)}function rf(e,t){return e.filter(n=>!Kc(n,t))}function TP(e){if(!F(e))return null;for(let n of xP)if(typeof e[n]!="string")return null;let t=e;return{environment:t.environment,businessId:br(t.businessId),pluginApiName:t.pluginApiName,blockApiName:t.blockApiName,dashboardId:t.dashboardId,dashletId:t.dashletId,contentHash:t.contentHash,pushedAt:t.pushedAt}}var jm=e=>Date.parse(e.pushedAt)||0;function NP(e){let t=new Map;for(let n of e){let r=[n.environment,n.businessId,n.pluginApiName,n.blockApiName].join("\0"),i=t.get(r);(i===void 0||jm(n)>jm(i))&&t.set(r,n)}return[...t.values()]}var Mm=e=>e instanceof Error?e.message:String(e);async function of(e){let t;try{t=await vP(zm(e,zn),"utf8")}catch(r){if(tt(r))return[];throw new Error(`Couldn't read ${zn}: ${Mm(r)}. Fix its permissions, or delete it to start a fresh push map.`)}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`${zn} is not valid JSON (${Mm(r)}). Fix it, or delete it to start a fresh push map.`)}if(!Array.isArray(n))throw new Error(`${zn} must contain a JSON array of push entries. Fix it, or delete it to start a fresh push map.`);return NP(n.map(TP).filter(r=>r!==null))}async function sf(e,t){let n=zm(e,zn);await wP(AP(n),{recursive:!0}),await kP(n,`${JSON.stringify(t,null,2)}
|
|
868
|
+
`,"utf8")}var RP={generic_dashboard:"dashboard",homepage:"homepage",chart_group:"chart_group"},$P={dashboard:"generic_dashboard",homepage:"homepage",chart_group:"chart_group"};function Gc(e){return RP[e]}function af(e){return $P[e]}function cf(e){let t=e.appBaseUrl.replace(/\/+$/,""),n=e.dashboardId;return e.surface==="homepage"?`${t}/home/${n}`:e.surface==="chart_group"&&e.customObject?e.customObject.fetchUrl==="client"?`${t}/clients/charts/${n}`:`${t}/custom-objects/${e.customObject.id}/charts/${n}`:`${t}/dashboard/${n}`}var df=["min_w","max_w","min_h","max_h"],pf=[["min_w","max_w"],["min_h","max_h"]],is={default_w:["min_w","max_w"],default_h:["min_h","max_h"]},FP=Object.keys(is),mf=[...ts,"host_chrome"],jP=["\0","{__ref:"],Jc="views",qc=class extends Error{reason;available;field;constructor(t,n,r={}){super(n),this.name="BlockExportError",this.reason=t,this.available=r.available??[],this.field=r.field}};function MP(e){let t=new Set(e.map(n=>n.pluginApiName)).size>1;return e.map(n=>t?`${n.pluginApiName}/${n.apiName}`:n.apiName).join(", ")}function zP(e,t){let n=e.flatMap(s=>s.artifacts.custom_blocks.map(a=>({block:a,pluginApiName:s.api_name}))),r=n.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}));if(n.length===0)return{ok:!1,reason:"no_blocks",available:r};if(t===void 0){let[s]=n;return n.length===1&&s?{ok:!0,...s}:{ok:!1,reason:"ambiguous",available:r}}let i=n.filter(({block:s})=>s.api_name===t),[o]=i;return o?i.length>1?{ok:!1,reason:"ambiguous",available:i.map(({block:s,pluginApiName:a})=>({pluginApiName:a,apiName:s.api_name}))}:{ok:!0,...o}:{ok:!1,reason:"not_found",available:r}}var lf=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,oi=e=>jP.some(t=>e.includes(t));function UP(e){let t=e,{name:n,script:r,styles:i,event_scripts:o}=t;if(typeof r!="string"||!r.trim())return"script";if(n!==void 0&&typeof n!="string")return"name";if(i!==void 0&&typeof i!="string")return"styles";if(o!==void 0){if(!F(o))return"event_scripts";let d=Object.entries(o).find(([u,f])=>typeof f!="string"||oi(u)||oi(f));if(d)return`event_scripts.${d[0]}`}let s=[["name",n],["script",r],["styles",i]].find(([,d])=>typeof d=="string"&&oi(d));if(s)return s[0];let a=df.find(d=>t[d]!==void 0&&!lf(t[d]));if(a)return a;let c=pf.find(([d,u])=>{let f=t[d],g=t[u];return typeof f=="number"&&typeof g=="number"&&f>g});if(c)return c[0];let l=FP.find(d=>{let u=t[d];if(u===void 0)return!1;if(typeof u!="number"||!lf(u))return!0;let[f,g]=is[d],m=t[f],p=t[g];return typeof m=="number"&&u<m||typeof p=="number"&&u>p});if(l)return l;if(t.host_chrome!==void 0&&typeof t.host_chrome!="boolean")return"host_chrome"}var VP=["api_name","name","script","html","css"],uf=e=>typeof e!="string"||oi(e);function HP(e){for(let t of e){let n=t,r=typeof n.api_name=="string"?n.api_name:String(n.api_name),i=VP.find(a=>uf(n[a]));if(i)return{view:r,field:i};let o=n.event_scripts;if(!F(o))return{view:r,field:"event_scripts"};let s=Object.entries(o).find(([a,c])=>oi(a)||uf(c));if(s)return{view:r,field:`event_scripts.${s[0]}`}}}var KP=({view:e,field:t})=>`views.${e}.${t}`,WP=(e,t)=>`Block "${e}" can't carry view ${JSON.stringify(t.view)}: its ${t.field} must be a string without NUL characters or "{__ref:".`,GP=(e,t)=>{if(t==="script")return`Block "${e}" has no script. Add a non-empty script.js to the block directory.`;if(t==="host_chrome")return`Block "${e}" has an invalid host_chrome: it must be true or false.`;let n=pf.find(([r])=>r===t);if(n)return`Block "${e}" has an invalid ${t}: it must be a positive integer no greater than ${n[1]}.`;if(df.includes(t))return`Block "${e}" has an invalid ${t}: it must be a positive integer.`;if(t in is){let[r,i]=is[t];return`Block "${e}" has an invalid ${t}: it must be a positive integer between ${r} and ${i}.`}return`Block "${e}" has an invalid ${t}: it must be a string without NUL characters or "{__ref:".`},JP=({reason:e,available:t},n,r)=>{let i=MP(t);return e==="no_blocks"?"This plugin has no blocks. Scaffold one with `appbuilder create --artifacts block`.":e==="not_found"?`No block with api_name "${n??""}". Available blocks: ${i}`:n===void 0?`This plugin has several blocks; pass the api_name of the one to ${r}: ${i}`:`More than one plugin has a block with api_name "${n}": ${i}`},qP=e=>{try{let t=JSON.parse(e);return F(t)?t:void 0}catch{return}},ff=e=>{let t=e.find(o=>o.path===LP),n=t?JSON.parse(t.content):[],r=Array.isArray(n)?n:[n],i=new Map;for(let o of r)F(o)&&typeof o.api_name=="string"&&typeof o.entry=="string"&&i.set(o.api_name,o.entry);return i},gf=(e,t)=>{let n=Ai(e);return n===""?t:`${n}/${t}`},hf=(e,t,n)=>{let r=`${gf(t,n)}/`,i=new Set,o=[];for(let s of e){if(!s.path.startsWith(r)||s.path.endsWith(".DS_Store"))continue;let[a,c,...l]=s.path.slice(r.length).split("/");if(a&&(i.add(a),c===DP&&l.length===0)){let d=qP(s.content);d&&o.push([a,d])}}return{directories:i,configs:o}},yf=(e,t)=>typeof e.api_name=="string"&&e.api_name!==""?e.api_name:BP(t),YP=(e,t)=>{let n=new Map;for(let[r,i]of hf(e,t,OP).configs){let o=yf(i,r),s={};for(let a of mf)i[a]!==void 0&&(s[a]=i[a]);n.set(o,s)}return n},ZP=(e,t={})=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!mf.includes(r))),...t});function XP(e,t){let n=ff(t);return e.map(r=>{let i=n.get(r.api_name),o=i===void 0?new Map:YP(t,i);return{...r,artifacts:{...r.artifacts,custom_blocks:r.artifacts.custom_blocks.map(s=>ZP(s,o.get(s.api_name)))}}})}var bf=(e,t)=>JSON.stringify([String(e),String(t)]),QP=(e,t)=>{let{directories:n,configs:r}=hf(e,t,Jc),i=new Map(r),o=new Set;for(let s of n){let a=i.get(s)??{};o.add(bf(yf(a,s),a.name||s))}return o},eC=(e,t)=>e.api_name.localeCompare(t.api_name)||String(e.name).localeCompare(String(t.name)),tC="appbuilder/views-unmatched";function nC(e,t){let n=ff(t),r={},i=[];for(let o of e){let s=n.get(o.api_name),a=s===void 0?new Set:QP(t,s),c=o.artifacts.routable_pages.filter(l=>a.has(bf(l.api_name,l.name))).sort(eC);c.length!==a.size&&s!==void 0&&i.push({rule:tC,severity:"warning",message:`Found ${String(a.size)} ${Jc}/ components but matched ${String(c.length)} packaged views; the pushed block carries only the matched ones.`,path:gf(s,Jc),pluginApiName:o.api_name}),r[o.api_name]=c}return{views:r,warnings:i}}function rC(e,t){return Object.hasOwn(e,t)?e[t]??[]:[]}function wf(e){return{...e.block,...Vc(e.views)}}async function Yc(e){let{files:t,deployable:n,issues:r}=await Hr(e),i=nC(n,t);return{deployable:XP(n,t),views:i.views,warnings:[...r.filter(o=>o.severity==="warning"),...i.warnings]}}function Zc({deployable:e,views:t,warnings:n},r,i){let o=zP(e,r);if(!o.ok)return{ok:!1,reason:o.reason,message:JP(o,r,i),available:o.available};let s=UP(o.block);if(s!==void 0)return{ok:!1,reason:"invalid_block",message:GP(o.block.api_name,s),available:[],field:s};let a=rC(t,o.pluginApiName),c=HP(a);return c!==void 0?{ok:!1,reason:"invalid_block",message:WP(o.block.api_name,c),available:[],field:KP(c)}:{ok:!0,value:{block:o.block,pluginApiName:o.pluginApiName,views:a,warnings:n}}}async function vf(e,t){let n=Zc(await Yc(e),t,"export");if(!n.ok)throw new qc(n.reason,n.message,n);return n.value}import{randomUUID as iC}from"crypto";function Qc(e){return{...Qi(e),packageBlocks:Yc,readPushMap:of,writePushMap:sf,ensureGitignore:Ze,staleAgentFileWarnings:t=>Yi(t),randomUUID:iC}}var oC=new Set(["owner","admin","edit"]),sC="Chart groups are not listed here; find them with `appbuilder block targets --object <id> --json` and pass --dashboard <id>.",et=me;function aC(e,t){let n=new Set(t.map(r=>r.pluginApiName)).size>1;return t.map(({pluginApiName:r,apiName:i})=>{let o=e.find(a=>a.api_name===r)?.artifacts.custom_blocks.find(a=>a.api_name===i),s=n?`${r}/${i}`:i;return{value:i,label:`${o?.name??i} (${s})`,args:[i]}})}async function el(e,t){let n=await t.packageBlocks(t.cwd),r=Zc(n,e,"push");if(!r.ok){let{reason:l,message:d,field:u}=r;return l==="no_blocks"||l==="invalid_block"?et("invalid_block",d,u===void 0?{}:{field:u}):et("needs_choice",d,{choice:"block",choices:aC(n.deployable,r.available)})}let{block:i,pluginApiName:o,views:s,warnings:a}=r.value,c=Gm(i,s);return I({block:i,pluginApiName:o,content:c,contentHash:Hc(c),warnings:a})}var kf=e=>e==null?null:oC.has(e.toLowerCase());function si(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:kf(e.employee_access)}}var Af=e=>({id:e.id,objectName:e.object_name,fetchUrl:e.fetch_url}),cC="Contacts";async function tl(e){let[t,n]=await Promise.all([e.listCustomObjects(),e.getClientObjectId().catch(()=>null)]),r=t.map(Af).sort((i,o)=>i.objectName.localeCompare(o.objectName));return n!==null&&n!==""&&!r.some(i=>i.id===n)&&r.push({id:n,objectName:cC,fetchUrl:"client"}),r}async function lC(e,t,n){let{environment:r,businessId:i}=t;try{if(n.object!==void 0){let c=n.object,[l,d]=await Promise.all([e.getCustomObject(c).catch(()=>null),e.listDashboards("chart_group",c)]);return I({ok:!0,environment:r,businessId:i,object:l?Af(l):null,surfaces:{chart_group:d.map(u=>si(u,"chart_group"))}})}let[o,s,a]=await Promise.all([e.listDashboards("generic_dashboard"),e.listDashboards("homepage"),tl(e)]);return I({ok:!0,environment:r,businessId:i,surfaces:{dashboard:o.map(c=>si(c,"dashboard")),homepage:s.map(c=>si(c,"homepage"))},customObjects:a})}catch(o){return Me(o)}}var nl=(e,t)=>t.dashboard===e.id;function ss(e,t){return[...Zm(e).filter(r=>nl(e,r)).map(r=>{let i=Vm(r.name);return{value:r.id,label:rs(r),args:["--dashboard",e.id,"--dashlet",r.id],pushKey:i?r.name:null,isFromThisPlugin:i?.pluginApiName===t.pluginApiName}}),{value:"new",label:"Create a new block",args:["--dashboard",e.id,"--create"]}]}var rl=(e,t)=>ef({dashboardId:t.id,dashlets:t.dashlets,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name,entry:e.entry}),xf=(e,t)=>I({dashboard:e,surface:Gc(e.type),action:"create",dashlet:void 0,resolvedBy:t}),os=(e,t,n)=>I({dashboard:e,surface:Gc(e.type),action:"update",dashlet:t,resolvedBy:n});async function uC(e){let[t,n]=await Promise.all([e.client.listDashboards("generic_dashboard"),e.client.listDashboards("homepage")]),r=i=>o=>({value:o.id,label:o.name,args:["--dashboard",o.id],surface:i,canEdit:kf(o.employee_access)});return et("needs_choice",`Choose where to push; pass --dashboard <id>. ${sC}`,{choice:"dashboard",choices:[...t.map(r("dashboard")),...n.map(r("homepage"))]})}async function dC(e,t,n){let r=await e.client.getDashboard(t);if(n.create)return xf(r,"flag");let i=()=>ss(r,e.block);if(n.dashlet!==void 0){let s=n.dashlet,a=r.dashlets.find(c=>c.id===s&&nl(r,c));return a?lr(a)?os(r,a,"flag"):et("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.`):et("not_found",`Dashlet ${s} is not on dashboard "${r.name}" (${r.id}).`,{choice:"target",choices:i()})}let o=rl(e,r);return o.kind==="map"?os(r,o.dashlet,"push_map"):o.kind==="name"?os(r,o.dashlet,"name"):et("needs_choice",o.kind==="ambiguous"?`Dashboard "${r.name}" has ${String(o.dashlets.length)} blocks pushed from this block; pass --dashlet <id> to pick one, or --create.`:`Choose a block to update on "${r.name}", or create a new one; pass --dashlet <id> or --create.`,{choice:"target",choices:i()})}async function pC(e,t,n){let r;try{r=await e.client.getDashboard(t.dashboardId)}catch(o){if(o instanceof q&&o.kind==="not_found")return et("remembered_target_missing",`The remembered dashboard ${t.dashboardId} no longer exists. Pass --dashboard <id> to choose another, or --forget to clear it.`);throw o}if(n.create)return xf(r,"remembered");let i=r.dashlets.find(o=>o.id===t.dashletId&&nl(r,o));return i&&lr(i)?os(r,i,"remembered"):et("remembered_target_missing",`The remembered block (dashlet ${t.dashletId}) is no longer on "${r.name}". Choose a block to update, or create a new one.`,{choice:"target",choices:ss(r,e.block)})}async function il(e,t){if(t.dashlet!==void 0&&t.create)return et("usage_error","Pass either --dashlet <id> or --create, not both.");if(t.dashlet!==void 0&&t.dashboard===void 0)return et("usage_error","--dashlet <id> needs --dashboard <id>.");try{return t.dashboard!==void 0?await dC(e,t.dashboard,t):e.entry?await pC(e,e.entry,t):await uC(e)}catch(n){return Me(n)}}async function mC(e,t,n){let r=t.custom_object;if(r==null||r==="")return null;if(typeof r!="string"){if(typeof r!="object"||typeof r.id!="string")return null;let{id:i,fetch_url:o}=r;return typeof o=="string"?{id:i,fetchUrl:o}:{id:i}}if(n!=="chart_group")return{id:r};try{let i=await e.getCustomObject(r);return{id:r,fetchUrl:i.fetch_url}}catch{return{id:r}}}async function ol(e,t,n,r){let{credentials:i,block:o}=e,{dashboard:s,surface:a}=t,c=[],l,d;if(t.action==="update"){let{dashlet:f}=t;if(tf(f,e.entry)){let g=`"${rs(f)}" (dashlet ${f.id}) was changed in Kizen since the last push.`;if(!n.force)return et("drift_detected",`${g} Pushing would overwrite those changes; pass --force to overwrite them.`);c.push(`${g} Overwriting it because of --force.`)}l={action:"update",method:"PATCH",path:Ar(s.id,f.id),body:qm(f,o.content),dashletId:f.id},d=`Update "${rs(f)}" (dashlet ${f.id})`}else l={action:"create",method:"POST",path:Ar(s.id),body:Jm({pluginApiName:o.pluginApiName,blockApiName:o.block.api_name,content:o.content,dashlets:s.dashlets,objectId:r.randomUUID(),layoutId:r.randomUUID()}),dashletId:null},d=`Create a new block on "${s.name}"`;let u=cf({appBaseUrl:Ll[i.environment],surface:a,dashboardId:s.id,customObject:await mC(e.client,s,a)});return I({...l,dashboard:{id:s.id,name:s.name,type:a},url:u,resolvedBy:t.resolvedBy,warnings:c,summary:{environment:i.environment,businessId:i.businessId,isProduction:Kn(i.environment),surface:a,dashboardId:s.id,dashboardName:s.name,action:t.action,actionLine:d,dashletId:l.dashletId,blockName:o.block.name,blockApiName:o.block.api_name,pluginApiName:o.pluginApiName,scriptBytes:Buffer.byteLength(o.content.script,"utf8"),stylesBytes:Buffer.byteLength(o.content.styles,"utf8"),...o.content.views&&{viewsBytes:Buffer.byteLength(JSON.stringify(o.content.views),"utf8")}}})}var sl=e=>({environment:e.credentials.environment,businessId:e.credentials.businessId,pluginApiName:e.block.pluginApiName,blockApiName:e.block.block.api_name});async function al(e,t,n){let r;try{if(t.action==="create"){let c=(await e.client.createDashlet(t.dashboard.id,t.body)).id;if(typeof c!="string"||c==="")return et("api_error",`POST ${t.path} succeeded but the response had no dashlet id; check "${t.dashboard.name}" before pushing again.`);r=c}else await e.client.updateDashlet(t.dashboard.id,t.dashletId,t.body),r=t.dashletId}catch(a){return Me(a)}let i=[...t.warnings],o={...sl(e),dashboardId:t.dashboard.id,dashletId:r,contentHash:e.block.contentHash,pushedAt:n.now().toISOString()},s=!1;try{n.ensureGitignore(n.cwd),await n.writePushMap(n.cwd,nf(e.pushMap,o)),s=!0}catch(a){i.push(`The push succeeded, but ${zn} couldn't be written, so this target isn't remembered: ${je(a)}`)}return I({dashletId:r,remembered:s,warnings:i})}var fC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function cl(e){return fC.test(e)?{dashboardId:e,script:`await window.__kizenCustomBlocks?.refresh('${e}')`}:null}async function gC(e,t){let n=sl(e);if(!Wc(e.pushMap,n))return null;let r=rf(e.pushMap,n);return await t.writePushMap(t.cwd,r),r}async function ll(e,t){let{client:n,credentials:r,block:i}=e,o=await t.readPushMap(t.cwd),s=!1;if(e.forget&&e.isAborted?.()!==!0){let a=await gC({credentials:r,block:i,pushMap:o},t);a&&(o=a,s=!0)}return{context:{client:n,credentials:r,block:i,pushMap:o,entry:Wc(o,sl({credentials:r,block:i}))},forgotten:s}}function ai(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 hC=e=>`${e.path===void 0?"":`${e.path}: `}${e.message} (${e.rule})`;async function yC(e){try{return await e.staleAgentFileWarnings(e.cwd)}catch{return[]}}async function Pf(e,t,n){let r={json:t.json===!0,deps:n},i="appbuilder block push",o=e===void 0?[]:[e],s=Rn(t,n.processEnv),a=(d,u)=>u==="environment"?[...o,...d.args,...rn(t,n.processEnv)]:u==="block"?[...d.args,...s]:[...o,...s,...d.args],c=(d,u)=>Et(i,a(d,u),r),l=d=>{It(r,d,c)};try{let d=await Nn(t,n);if(!d.ok){l(d);return}let{credentials:u,client:f,notices:g}=d.value;s=to(t,u),ze(n,g);let m=await el(e,n);if(!m.ok){l(m);return}let p=m.value;o=[p.block.api_name],p.warnings.length>0&&n.writeStderr(`${We(p.warnings)}
|
|
869
|
+
`);let{context:h,forgotten:b}=await ll({client:f,credentials:u,block:p,forget:t.forget===!0},n);b&&n.writeStderr(`Forgot the remembered target for ${p.block.api_name}.
|
|
870
|
+
`);let y=await il(h,t);if(!y.ok){l(y);return}let C=Ye(t,u.environment);if(!C.ok){l(C);return}let S=await ol(h,y.value,t,n);if(!S.ok){l(S);return}let x=S.value,v={pluginApiName:p.pluginApiName,apiName:p.block.api_name,name:p.block.name},k={environment:u.environment,businessId:u.businessId,dashboard:x.dashboard},P=[...p.warnings.map(hC),...await yC(n)],w=C.value;if(w.kind==="dry-run"){let V=[...P,...x.warnings],X=x.summary.isProduction,ve=Et(i,[p.block.api_name,...s,"--dashboard",x.dashboard.id,...x.action==="update"?["--dashlet",x.dashletId]:["--create"],...t.force===!0?["--force"]:[],"--yes",...X?["--allow-production"]:[]],r),Re={ok:!0,applied:!1,dryRun:!0,reason:w.reason,action:x.action,...k,dashletId:x.dashletId,url:x.url,resolvedBy:x.resolvedBy,block:v,method:x.method,path:x.path,body:x.body,warnings:V,...b?{forgotten:!0}:{},applyArgv:ve,requiresProductionConsent:X};Pe(r,Re,[...ai(x.summary),`URL: ${x.url}`,...Q(V),"",`${x.method} ${x.path}`,JSON.stringify(x.body,null,2),""].join(`
|
|
871
|
+
`),[...ai(x.summary),...Q(V),""].join(`
|
|
872
|
+
`)),w.reason==="no_yes"&&n.writeStderr(`${eo}
|
|
873
|
+
`);return}let A=await al(h,x,n);if(!A.ok){l(A);return}let _=A.value,T=[...P,..._.warnings],L=cl(x.dashboard.id),$={ok:!0,applied:!0,dryRun:!1,action:x.action==="create"?"created":"updated",...k,dashletId:_.dashletId,url:x.url,...L?{refresh:L}:{},resolvedBy:x.resolvedBy,block:v,remembered:_.remembered,warnings:T,...b?{forgotten:!0}:{}};Pe(r,$,[`\u2713 ${$.action==="created"?"Created":"Updated"} ${p.block.name} on "${x.dashboard.name}" (dashlet ${_.dashletId})`,...ai(x.summary),`URL: ${x.url}`,...L?[`Refresh an open tab: ${L.script}`]:[],...Q(T),""].join(`
|
|
874
|
+
`))}catch(d){l(Me(d))}}var bC=(e,t)=>e.padEnd(t);function Xc(e,t){if(t.length===0)return[e," (none)"];let n=["NAME","ID","DASHLETS","ACCESS"],r=t.map(s=>[`${s.name}${s.hidden?" (hidden)":""}`,s.id,s.dashletsCount===null?"-":String(s.dashletsCount),`${s.employeeAccess??"-"}${s.canEdit===!1?" (no edit access)":""}`]),i=n.map((s,a)=>Math.max(s.length,...r.map(c=>(c[a]??"").length))),o=s=>` ${s.map((a,c)=>bC(a,i[c]??0)).join(" ")}`.trimEnd();return[e,o(n),...r.map(o)]}function wC(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})`,"",...Xc("Chart groups",e.surfaces.chart_group)):t.push(...Xc("Dashboards",e.surfaces.dashboard),"",...Xc("Homepages",e.surfaces.homepage),"","Custom objects",...e.customObjects.length===0?[" (none)"]:e.customObjects.map(n=>` ${n.objectName} ${n.id}`),"","List an object\u2019s chart groups with `appbuilder block targets --object <id>`."),`${t.join(`
|
|
855
875
|
`)}
|
|
856
|
-
`}async function
|
|
857
|
-
`:wm(h.value))}catch(a){s(Re(a))}}import{useEffect as Da,useState as Gn}from"react";import{Box as de,Text as Y,useApp as $m,useInput as Fa}from"ink";import"@kizenapps/packager";import{Box as Cm,Text as Sm}from"ink";import{Box as vm,Text as xm}from"ink";import{jsx as Ia}from"react/jsx-runtime";var km=[" :::::::: "," :::::: ::::::::::: "," :::::: :::::::::: "," :::::: :::::: ::::::: "," ::::: :::::: ::::::::::::::::: "," ::::: ::::: ::::::::::::::::::: "," ::::: ::::: :::::: ::::: ",":::: ::::: ::: ::::: :: ","::::: :::::: :::::::::: ","::::: :::::: ::::::::::: "," ::::: ::: ::::::: "," ::::::: ::: ::::: "," ::::::::::: :::::: :::::"," :::::::::: :::::: :::::"," :: ::::: ::: ::::: ::::"," ::::: :::::: ::::: ::::: ::: "," ::::::::::::::::::: ::::: ::::: "," ::::::::::::::::: ::::: ::::: "," ::::::::: :::::: :::::: "," :::::::::: :::::: "," ::::::::::: :::::: "," :::::::: "],$a=()=>Ia(vm,{flexDirection:"column",children:km.map((e,t)=>Ia(xm,{color:"cyan",children:e},t))});import{Fragment as Pm,jsx as Ro,jsxs as Em}from"react/jsx-runtime";var G=({marginBottom:e=0})=>Em(Pm,{children:[Ro($a,{}),Ro(Cm,{flexDirection:"column",marginTop:1,marginBottom:e,children:Ro(Sm,{bold:!0,color:"cyan",children:"Kizen App Development Toolkit"})})]});import{useEffect as _m,useState as Am}from"react";import{Text as Tm}from"ink";import{jsx as Im}from"react/jsx-runtime";var Na=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ee=()=>{let[e,t]=Am(0);return _m(()=>{let n=setInterval(()=>{t(r=>(r+1)%Na.length)},80);return()=>{clearInterval(n)}},[]),Im(Tm,{color:"cyan",children:Na[e]??"\u280B"})};import{Fragment as zm,jsx as R,jsxs as J}from"react/jsx-runtime";var Ra=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],Nm={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},Oo="\u2191/\u2193 to move, Enter to select, Esc to go back",Dm="The block was edited in Kizen since your last push. Overwriting discards those edits.",Jn=e=>e.args.includes("--create");function Oa(e,t){let n=e.filter(i=>i.value===t),r=e.filter(Jn),o=e.filter(i=>i.value!==t&&!Jn(i));return n.length>0?[...n,...o,...r]:[...r,...o]}function xt(e,t){return(n,r)=>{let o=e[r];o!==void 0&&t(o)}}function Rm(e,t){if(Jn(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function Om(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function Bm(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,Jn(n)?{...r,create:!0}:{...r,dashlet:n.value}}function Fm(e,t,n,r){let o=f=>{t.setExitCode(1),n({type:"error",view:f})},i=f=>{f().catch(u=>{o(Re(u))})},s=async(f,u)=>{n({type:"applying",plan:u});let w=await To(f,u,t);if(!w.ok){o(w);return}n({type:"done",plan:u,applied:w.value})},a=async(f,u,w)=>{n({type:"loading",label:"Preparing the push\u2026"});let k=await _o(f,u,w,t);if(!k.ok){if(k.code==="drift_detected"){n({type:"confirm",kind:"drift",message:k.message,target:u,options:w,context:f});return}o(k);return}if(w.dryRun){n({type:"done",plan:k.value,applied:null});return}if(w.yes){let _=No(w,f.credentials.environment);if(_.ok&&_.value.kind==="apply"){await s(f,k.value);return}}n({type:"confirm",kind:"push",plan:k.value,options:w,context:f})},c=async(f,u,w)=>{n({type:"loading",label:"Resolving the target\u2026"});let k=await Eo(f,u);if(k.ok){await a(f,k.value,u);return}let _=u.dashboard??f.entry?.dashboardId;if((k.code==="needs_choice"&&k.choice==="target"||k.code==="remembered_target_missing")&&k.choices&&k.choices.length>0&&_!==void 0){n({type:"target-select",dashboardId:_,title:"Choose a block to update, or create a new one",message:k.message,choices:Oa(k.choices,null),matchedId:null,back:w,options:u,context:f});return}o(k)},g=async(f,{credentials:u,client:w},k)=>{let{context:_,forgotten:P}=await $o({client:w,credentials:u,block:k,forget:f.forget===!0},t);if(P&&r(C=>({...C,notices:[...C.notices,`Forgot the remembered target for ${k.block.api_name}.`]})),f.dashboard!==void 0||_.entry){await c(_,f,null);return}n({type:"surface-select",options:f,context:_})},m=async(f,u,w)=>{n({type:"packaging"});let k=await ko(w,t);if(!k.ok){if(k.choice==="block"&&k.choices){n({type:"block-select",options:f,resolved:u,choices:k.choices});return}o(k);return}r(_=>({..._,warnings:k.value.warnings})),await g(f,u,k.value)},h=async f=>{n({type:"loading",label:"Loading credentials\u2026"});let u=await Wn(f,t);if(!u.ok){if(u.choice==="environment"&&u.choices){n({type:"environment-select",options:f,choices:u.choices});return}o(u);return}r(w=>({...w,credentials:u.value.credentials,credentialNotices:u.value.notices})),await m(f,u.value,e)},y=async({options:f,context:u},w,k,_)=>{let P=Nm[w];n({type:"loading",label:`Loading ${P}s\u2026`});let T=(await u.client.listDashboards(Ls(w),k?.id)).map(d=>Wt(d,w)),{environment:v,businessId:l}=u.credentials;if(T.length===0){o({message:`No ${P}s found${k?` on ${k.objectName}`:""} for business ${l} (${v}).`});return}n({type:"dashboard-select",surface:w,objectId:k?.id??null,title:k?`Choose a chart group on ${k.objectName}`:`Choose a ${P}`,rows:T,back:_,options:f,context:u})};return{start:f=>{i(()=>h(f))},pickEnvironment:(f,u)=>{i(()=>h({...f.options,env:u.value}))},pickBlock:(f,u)=>{i(()=>m(f.options,f.resolved,u.value))},pickSurface:(f,u)=>{i(async()=>{if(u!=="chart_group"){await y(f,u,null,f);return}n({type:"loading",label:"Loading custom objects\u2026"});let w=await Co(f.context.client);if(w.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}n({type:"object-select",objects:w,back:f,options:f.options,context:f.context})})},pickObject:(f,u)=>{i(()=>y(f,"chart_group",u,f))},pickDashboard:(f,u)=>{i(async()=>{let{context:w}=f,k={...f.options,dashboard:u.id};if(k.dashlet!==void 0||k.create){await c(w,k,f);return}n({type:"loading",label:`Loading "${u.name}"\u2026`});let _=await w.client.getDashboard(u.id),P=Po(w,_),C=P.kind==="map"||P.kind==="name"?P.dashlet.id:null;n({type:"target-select",dashboardId:_.id,title:`Choose what to push to on "${_.name}"`,message:null,choices:Oa(qn(_,w.block),C),matchedId:C,back:f,options:k,context:w})})},pickTarget:(f,u)=>{i(()=>c(f.context,Bm(f.options,f.dashboardId,u),f))},acceptDrift:f=>{i(()=>a(f.context,f.target,{...f.options,force:!0}))},acceptPush:f=>{i(()=>s(f.context,f.plan))},cancel:()=>{o({message:"Cancelled."})}}}var Ba=({prompt:e,strict:t,onAccept:n,onCancel:r})=>(Fa((o,i)=>{if(i.ctrl)return;let s=o.toLowerCase();s==="y"||!t&&i.return?n():(t||s==="n"||i.escape)&&r()}),R(Y,{bold:!0,children:e})),mt=({lines:e,color:t})=>R(de,{flexDirection:"column",children:e.map((n,r)=>R(Y,{...t&&{color:t},children:n},`${String(r)}-${n}`))}),ja=({plan:e})=>J(de,{flexDirection:"column",children:[R(mt,{lines:qt(e.summary)}),J(Y,{children:["URL: ",e.url]})]}),Bo=({label:e})=>J(de,{gap:1,children:[R(Ee,{}),R(Y,{dimColor:!0,children:e})]}),jm=({view:e})=>J(de,{flexDirection:"column",gap:1,children:[J(de,{gap:1,children:[R(Y,{color:"red",children:"\u2717"}),R(Y,{color:"red",children:e.issues&&e.issues.length>0?De(e.issues):e.message})]}),e.hint!==void 0&&J(Y,{dimColor:!0,children:["Hint: ",e.hint]}),e.choices&&e.choices.length>0&&J(de,{flexDirection:"column",children:[R(Y,{children:"Choices:"}),R(mt,{lines:e.choices.map(t=>` ${t.label}`)})]})]}),Lm=({plan:e,applied:t})=>{let n=Io(e.dashboard.id);return t===null?J(de,{flexDirection:"column",gap:1,children:[R(Y,{color:"yellow",children:"Dry run: nothing was written."}),R(ja,{plan:e}),e.warnings.length>0&&R(mt,{lines:ft(e.warnings),color:"yellow"}),J(de,{flexDirection:"column",children:[J(Y,{bold:!0,children:[e.method," ",e.path]}),R(Y,{children:JSON.stringify(e.body,null,2)})]})]}):J(de,{flexDirection:"column",gap:1,children:[J(de,{gap:1,children:[R(Y,{color:"green",children:"\u2713"}),J(Y,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),J(de,{flexDirection:"column",children:[J(Y,{children:["URL: ",e.url]}),n&&J(Y,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&R(mt,{lines:ft(t.warnings),color:"yellow"})]})},La=({apiName:e,options:t,deps:n})=>{let r=$m(),[o,i]=Gn({type:"loading",label:"Loading credentials\u2026"}),[s,a]=Gn({credentials:null,credentialNotices:[],warnings:[],notices:[]}),[c]=Gn(()=>Fm(e,n,i,a)),[g]=Gn(t);Da(()=>{c.start(g)},[c,g]),Da(()=>{(o.type==="done"||o.type==="error")&&r.exit()},[o,r]),Fa((h,y)=>{y.ctrl&&h==="c"&&o.type!=="done"&&o.type!=="error"&&(n.setExitCode(130),r.exit())});let m=h=>J(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[R(G,{}),s.credentials&&J(Y,{dimColor:!0,children:["Environment: ",s.credentials.environment," \xB7 Business:"," ",s.credentials.businessId]}),s.credentialNotices.length>0&&R(mt,{lines:s.credentialNotices,color:"yellow"}),s.warnings.length>0&&R(Y,{dimColor:!0,children:De(s.warnings)}),s.notices.length>0&&R(mt,{lines:s.notices}),h]});switch(o.type){case"loading":return m(R(Bo,{label:o.label}));case"packaging":return m(R(Bo,{label:"Packaging blocks\u2026"}));case"applying":return m(R(Bo,{label:`Pushing ${o.plan.summary.blockName} to "${o.plan.dashboard.name}"\u2026`}));case"environment-select":return m(R(Ne,{title:"Environment",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:xt(o.choices,h=>{c.pickEnvironment(o,h)}),onCancel:c.cancel},"environment"));case"block-select":return m(R(Ne,{title:"Block to push",items:o.choices.map(h=>({key:h.value,label:h.label})),onSelect:xt(o.choices,h=>{c.pickBlock(o,h)}),onCancel:c.cancel},"block"));case"surface-select":return m(R(Ne,{title:"Where should the block go?",items:Ra,onSelect:xt(Ra,h=>{c.pickSurface(o,h.key)}),onCancel:c.cancel},"surface"));case"object-select":return m(R(Ne,{title:"Custom object",items:o.objects.map(h=>({key:h.id,label:h.objectName})),onSelect:xt(o.objects,h=>{c.pickObject(o,h)}),onCancel:()=>{i(o.back)},hint:Oo},"object"));case"dashboard-select":return m(R(Ne,{title:o.title,items:o.rows.map(Om),onSelect:xt(o.rows,h=>{c.pickDashboard(o,h)}),onCancel:()=>{i(o.back)},hint:Oo},`dashboards-${o.surface}-${o.objectId??""}`));case"target-select":{let{back:h}=o;return m(J(zm,{children:[o.message!==null&&R(Y,{color:"yellow",children:o.message}),R(Ne,{title:o.title,items:o.choices.map(y=>Rm(y,o.matchedId)),onSelect:xt(o.choices,y=>{c.pickTarget(o,y)}),onCancel:h?()=>{i(h)}:c.cancel,...h&&{hint:Oo}},`targets-${o.dashboardId}`)]}))}case"confirm":return o.kind==="drift"?m(J(de,{flexDirection:"column",gap:1,children:[R(Y,{color:"yellow",children:Dm}),R(Y,{dimColor:!0,children:o.message}),R(Ba,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{c.acceptDrift(o)},onCancel:c.cancel},"drift")]})):m(J(de,{flexDirection:"column",gap:1,children:[R(ja,{plan:o.plan}),o.plan.warnings.length>0&&R(mt,{lines:ft(o.plan.warnings),color:"yellow"}),o.plan.summary.isProduction&&R(Y,{color:"red",bold:!0,children:"PRODUCTION"}),R(Ba,{prompt:o.plan.summary.isProduction?"Type y to push to production (y/N)":"Push? (Y/n)",strict:o.plan.summary.isProduction,onAccept:()=>{c.acceptPush(o)},onCancel:c.cancel},"push")]}));case"done":return m(R(Lm,{plan:o.plan,applied:o.applied}));case"error":return m(R(jm,{view:o.view}))}};var Ma=e=>`Error: ${e instanceof Error?e.message:String(e)}`,Km=e=>e instanceof Hm?De(e.issues):Ma(e),za=e=>{console.error(Ma(e)),process.exitCode=1};function Ua(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(n,r)=>{try{let o=await ta(process.cwd(),n),{block:i,warnings:s}=o;s.length>0&&console.error(De(s));let a=JSON.stringify(ea(o),null,2);console.log(a),r.copy&&console.error(await In(a)?`Copied block "${i.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(o){console.error(Km(o)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async(n,r)=>{try{let o=xo(process.cwd());if(!process.stdin.isTTY||!process.stdout.isTTY||r.json===!0){await Aa(n,r,o);return}let{waitUntilExit:i}=Um(Mm(La,{...n!==void 0&&{apiName:n},options:r,deps:o}),{exitOnCtrlC:!1});await i()}catch(o){za(o)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async n=>{try{await Ta(n,xo(process.cwd()))}catch(r){za(r)}})}import{createElement as Gm}from"react";import{render as Jm}from"ink";import{useEffect as Ka,useState as Yt}from"react";import{Box as Xt,Text as kt,useApp as Vm}from"ink";import{PluginValidationError as Wm}from"@kizenapps/packager";function Gt(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Box as Fo,Text as Yn}from"ink";import{jsx as Ha,jsxs as Jt}from"react/jsx-runtime";var Xn=({issues:e})=>{let t=e.filter(n=>n.severity==="error").length;return Jt(Fo,{flexDirection:"column",marginTop:1,children:[Jt(Yn,{color:"red",children:["\u2717 ",t," validation ",t===1?"error":"errors"]}),[...ho(e)].map(([n,r])=>Jt(Fo,{flexDirection:"column",marginTop:1,children:[Ha(Yn,{bold:!0,children:n}),r.map((o,i)=>Ha(Fo,{paddingLeft:2,children:Jt(Yn,{color:o.severity==="error"?"red":"yellow",children:[o.severity==="error"?"\u2717":"\u26A0"," ",o.message," ",Jt(Yn,{dimColor:!0,children:["(",o.rule,")"]})]})},`${o.rule}-${String(i)}`))]},n))]})};import{Fragment as qm,jsx as Ye,jsxs as ht}from"react/jsx-runtime";var Va=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],Zn={"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"},Wa=({outputDir:e,pluginDir:t})=>{let n=Vm(),[r,o]=Yt("creating-dir"),[i,s]=Yt(!1),[a,c]=Yt(null),[g,m]=Yt(null),[h,y]=Yt(null);Ka(()=>{Bn(t,e,o).then(({bundleSize:w})=>{y(w),o("done")}).catch(w=>{w instanceof Wm?c(w.issues):m(w instanceof Error?w.message:String(w)),s(!0),process.exitCode=1})},[e,t]),Ka(()=>{(r==="done"||i)&&n.exit()},[r,i,n]);let f=Va.indexOf(r),u=r==="done";return ht(Xt,{flexDirection:"column",paddingY:1,paddingX:2,children:[Ye(G,{marginBottom:1}),ht(Xt,{flexDirection:"column",gap:0,children:[Va.map((w,k)=>{let _=r===w,P=u||f>k;return Ye(Xt,{gap:1,children:i&&k===f?ht(kt,{color:"red",children:["\u2717 ",Zn[w]]}):P?ht(kt,{color:"green",children:["\u2713 ",Zn[w]]}):_?ht(qm,{children:[Ye(Ee,{}),Ye(kt,{children:Zn[w]})]}):ht(kt,{dimColor:!0,children:[" ",Zn[w]]})},w)}),u&&h!==null&&Ye(Xt,{marginTop:1,gap:1,children:ht(kt,{color:"green",children:["\u2713 bundle \u2014 ",Gt(h)]})}),a!==null&&Ye(Xn,{issues:a}),g!==null&&Ye(Xt,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:Ye(kt,{color:"red",children:g})})]})]})};function qa(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;Pe(t);let{waitUntilExit:r}=Jm(Gm(Wa,{outputDir:n,pluginDir:t}));await r()})}import{createElement as Mh}from"react";import{render as Uh}from"ink";import{useCallback as ir,useState as Ct}from"react";import{Box as V,Text as N,useApp as Oh,useInput as Bh}from"ink";import{join as sr}from"path";import{access as $h,mkdir as er,writeFile as Ho}from"fs/promises";import{dirname as Nh,join as Oe}from"path";var Ga=`{
|
|
876
|
+
`}async function Cf(e,t){let n={json:e.json===!0,deps:t},r="appbuilder block targets",i=e.object===void 0?[]:["--object",e.object],o=a=>Et(r,[...a.args,...rn(e,t.processEnv),...i],n),s=a=>{It(n,a,o)};try{let a=await Nn(e,t);if(!a.ok){s(a);return}let{credentials:c,client:l,notices:d}=a.value;ze(t,d);let u=await lC(l,c,e.object===void 0?{}:{object:e.object});if(!u.ok){s(u);return}t.writeStdout(n.json?`${JSON.stringify(u.value,null,2)}
|
|
877
|
+
`:wC(u.value))}catch(a){s(Me(a))}}import{useEffect as vC,useState as as}from"react";import{Box as ln,Text as at}from"ink";import{Fragment as EC,jsx as ce,jsxs as Ue}from"react/jsx-runtime";var Sf=[{key:"dashboard",label:"Dashboard"},{key:"homepage",label:"Homepage"},{key:"chart_group",label:"Chart group"}],kC={dashboard:"dashboard",homepage:"homepage",chart_group:"chart group"},ul="\u2191/\u2193 to move, Enter to select, Esc to go back",AC="The block was edited in Kizen since your last push. Overwriting discards those edits.",cs=e=>e.args.includes("--create");function _f(e,t){let n=e.filter(o=>o.value===t),r=e.filter(cs),i=e.filter(o=>o.value!==t&&!cs(o));return n.length>0?[...n,...i,...r]:[...r,...i]}function xC(e,t){if(cs(e))return{key:e.value,label:e.label};if(e.value===t)return{key:e.value,label:`Update "${e.label}" (last pushed here)`};let n=e.isFromThisPlugin?"pushed from this plugin":e.pushKey;return{key:e.value,label:`Update "${e.label}"`,...n?{description:n}:{}}}function PC(e){let t=e.dashletsCount===null?e.name:`${e.name} (${String(e.dashletsCount)} dashlets)`;if(e.canEdit===!1)return{key:e.id,label:t,description:"no edit access",disabled:!0};let n=[e.employeeAccess,e.hidden?"hidden":null].filter(r=>r!==null&&r!=="").join(" \xB7 ");return{key:e.id,label:t,...n===""?{}:{description:n}}}function CC(e,t,n){let r={...e,dashboard:t};return delete r.dashlet,delete r.create,cs(n)?{...r,create:!0}:{...r,dashlet:n.value}}function SC(e,t,n,r){let i=Mo({deps:t,setPhase:n,setSession:r,next:(p,h)=>g(p,h,e)}),{fail:o,guard:s}=i,a=i.whileRunning(n),c=i.whileRunning(r),l=async(p,h)=>{if(i.isAborted())return;a({type:"applying",plan:h});let b=await al(p,h,t);if(!b.ok){o(b);return}a({type:"done",plan:h,applied:b.value})},d=async(p,h,b)=>{a({type:"loading",label:"Preparing the push\u2026"});let y=await ol(p,h,b,t);if(!y.ok){if(y.code==="drift_detected"){a({type:"confirm",kind:"drift",message:y.message,target:h,options:b,context:p});return}o(y);return}switch(zo(b,p.credentials.environment)){case"dry-run":a({type:"done",plan:y.value,applied:null});return;case"apply":await l(p,y.value);return;case"confirm":a({type:"confirm",kind:"push",plan:y.value,options:b,context:p})}},u=async(p,h,b)=>{a({type:"loading",label:"Resolving the target\u2026"});let y=await il(p,h);if(y.ok){await d(p,y.value,h);return}let C=h.dashboard??p.entry?.dashboardId;if((y.code==="needs_choice"&&y.choice==="target"||y.code==="remembered_target_missing")&&y.choices&&y.choices.length>0&&C!==void 0){a({type:"target-select",dashboardId:C,title:"Choose a block to update, or create a new one",message:y.message,choices:_f(y.choices,null),matchedId:null,back:b,options:h,context:p});return}o(y)},f=async(p,{credentials:h,client:b},y)=>{if(i.isAborted())return;let{context:C,forgotten:S}=await ll({client:b,credentials:h,block:y,forget:p.forget===!0,isAborted:i.isAborted},t);if(S&&c(x=>({...x,notices:[...x.notices,`Forgot the remembered target for ${y.block.api_name}.`]})),p.dashboard!==void 0||C.entry){await u(C,p,null);return}a({type:"surface-select",options:p,context:C})},g=async(p,h,b)=>{a({type:"packaging"});let y=await el(b,t);if(!y.ok){if(y.choice==="block"&&y.choices){a({type:"block-select",options:p,resolved:h,choices:y.choices});return}o(y);return}c(C=>({...C,warnings:y.value.warnings})),await f(p,h,y.value)},m=async({options:p,context:h},b,y,C)=>{let S=kC[b];a({type:"loading",label:`Loading ${S}s\u2026`});let v=(await h.client.listDashboards(af(b),y?.id)).map(w=>si(w,b)),{environment:k,businessId:P}=h.credentials;if(v.length===0){o({message:`No ${S}s found${y?` on ${y.objectName}`:""} for business ${P} (${k}).`});return}a({type:"dashboard-select",surface:b,objectId:y?.id??null,title:y?`Choose a chart group on ${y.objectName}`:`Choose a ${S}`,rows:v,back:C,options:p,context:h})};return{start:p=>{s(()=>i.load(p))},pickEnvironment:(p,h)=>{s(()=>i.pickEnvironment(p,h))},pickBlock:(p,h)=>{s(()=>g(p.options,p.resolved,h.value))},pickSurface:(p,h)=>{s(async()=>{if(h!=="chart_group"){await m(p,h,null,p);return}a({type:"loading",label:"Loading custom objects\u2026"});let b=await tl(p.context.client);if(b.length===0){o({message:"No custom objects found, so there are no chart groups to push to."});return}a({type:"object-select",objects:b,back:p,options:p.options,context:p.context})})},pickObject:(p,h)=>{s(()=>m(p,"chart_group",h,p))},pickDashboard:(p,h)=>{s(async()=>{let{context:b}=p,y={...p.options,dashboard:h.id};if(y.dashlet!==void 0||y.create){await u(b,y,p);return}a({type:"loading",label:`Loading "${h.name}"\u2026`});let C=await b.client.getDashboard(h.id),S=rl(b,C),x=S.kind==="map"||S.kind==="name"?S.dashlet.id:null;a({type:"target-select",dashboardId:C.id,title:`Choose what to push to on "${C.name}"`,message:null,choices:_f(ss(C,b.block),x),matchedId:x,back:p,options:y,context:b})})},pickTarget:(p,h)=>{s(()=>u(p.context,CC(p.options,p.dashboardId,h),p))},acceptDrift:p=>{s(()=>d(p.context,p.target,{...p.options,force:!0}))},acceptPush:p=>{s(()=>l(p.context,p.plan))},cancel:()=>{o({message:"Cancelled."})},abort:i.abort}}var Ef=({plan:e})=>Ue(ln,{flexDirection:"column",children:[ce(Ne,{lines:ai(e.summary)}),Ue(at,{children:["URL: ",e.url]})]}),_C=({plan:e,applied:t})=>{let n=cl(e.dashboard.id);return t===null?Ue(ln,{flexDirection:"column",gap:1,children:[ce(at,{color:"yellow",children:jo}),ce(Ef,{plan:e}),e.warnings.length>0&&ce(Ne,{lines:Q(e.warnings),color:"yellow"}),Ue(ln,{flexDirection:"column",children:[Ue(at,{bold:!0,children:[e.method," ",e.path]}),ce(at,{children:JSON.stringify(e.body,null,2)})]})]}):Ue(ln,{flexDirection:"column",gap:1,children:[Ue(ln,{gap:1,children:[ce(at,{color:"green",children:"\u2713"}),Ue(at,{bold:!0,children:[e.action==="create"?"Created":"Updated"," ",e.summary.blockName,' on "',e.dashboard.name,'"']})]}),Ue(ln,{flexDirection:"column",children:[Ue(at,{children:["URL: ",e.url]}),n&&Ue(at,{dimColor:!0,children:["Refresh an open tab: ",n.script]})]}),t.warnings.length>0&&ce(Ne,{lines:Q(t.warnings),color:"yellow"})]})},If=({apiName:e,options:t,deps:n})=>{let[r,i]=as({type:"loading",label:ni}),[o,s]=as(Fo),[a]=as(()=>SC(e,n,i,s)),[c]=as(t);vC(()=>{a.start(c)},[a,c]),Zo(r.type==="done"||r.type==="error",n.setExitCode,a.abort);let l=d=>ce(Yo,{session:o,children:d});switch(r.type){case"loading":return l(ce(cr,{label:r.label}));case"packaging":return l(ce(cr,{label:"Packaging blocks\u2026"}));case"applying":return l(ce(cr,{label:`Pushing ${r.plan.summary.blockName} to "${r.plan.dashboard.name}"\u2026`}));case"environment-select":return l(ce(sr,{title:"Environment",choices:r.choices,onPick:d=>{a.pickEnvironment(r,d)},onCancel:a.cancel},"environment"));case"block-select":return l(ce(sr,{title:"Block to push",choices:r.choices,onPick:d=>{a.pickBlock(r,d)},onCancel:a.cancel},"block"));case"surface-select":return l(ce(Lt,{title:"Where should the block go?",items:Sf,onSelect:or(Sf,d=>{a.pickSurface(r,d.key)}),onCancel:a.cancel},"surface"));case"object-select":return l(ce(Lt,{title:"Custom object",items:r.objects.map(d=>({key:d.id,label:d.objectName})),onSelect:or(r.objects,d=>{a.pickObject(r,d)}),onCancel:()=>{i(r.back)},hint:ul},"object"));case"dashboard-select":return l(ce(Lt,{title:r.title,items:r.rows.map(PC),onSelect:or(r.rows,d=>{a.pickDashboard(r,d)}),onCancel:()=>{i(r.back)},hint:ul},`dashboards-${r.surface}-${r.objectId??""}`));case"target-select":{let{back:d}=r;return l(Ue(EC,{children:[r.message!==null&&ce(at,{color:"yellow",children:r.message}),ce(Lt,{title:r.title,items:r.choices.map(u=>xC(u,r.matchedId)),onSelect:or(r.choices,u=>{a.pickTarget(r,u)}),onCancel:d?()=>{i(d)}:a.cancel,...d&&{hint:ul}},`targets-${r.dashboardId}`)]}))}case"confirm":return r.kind==="drift"?l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(at,{color:"yellow",children:AC}),ce(at,{dimColor:!0,children:r.message}),ce(Rc,{prompt:"Type y to overwrite (y/N)",strict:!0,onAccept:()=>{a.acceptDrift(r)},onCancel:a.cancel},"drift")]})):l(Ue(ln,{flexDirection:"column",gap:1,children:[ce(Ef,{plan:r.plan}),r.plan.warnings.length>0&&ce(Ne,{lines:Q(r.plan.warnings),color:"yellow"}),ce(Ho,{isProduction:r.plan.summary.isProduction,prompt:"Push? (Y/n)",productionPrompt:"Type y to push to production (y/N)",onAccept:()=>{a.acceptPush(r)},onCancel:a.cancel},"push")]}));case"done":return l(ce(_C,{plan:r.plan,applied:r.applied}));case"error":return l(ce(Jo,{view:r.view}))}};var Nf=e=>`Error: ${e instanceof Error?e.message:String(e)}`,RC=e=>e instanceof NC?We(e.issues):Nf(e),Tf=e=>{console.error(Nf(e)),process.exitCode=1};function Rf(e){let t=e.command("block").description("Work with plugin content blocks");t.command("export").description("Print one packaged block as JSON for the Custom Block (AI Coded) paste editor").argument("[api_name]","api_name of the block to export (optional when there is only one)").option("--copy","also copy the JSON to the clipboard").action(async(n,r)=>{try{let i=await vf(process.cwd(),n),{block:o,warnings:s}=i;s.length>0&&console.error(We(s));let a=JSON.stringify(wf(i),null,2);console.log(a),r.copy&&console.error(await es(a)?`Copied block "${o.api_name}" to the clipboard.`:"Couldn't copy to the clipboard; use the JSON printed to stdout instead.")}catch(i){console.error(RC(i)),process.exitCode=1}}),t.command("push").description("Push a block to a Kizen dashboard, homepage or chart group dashlet").argument("[api_name]","api_name of the block to push (optional when there is only one)").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--dashboard <id>","dashboard, homepage or chart group to push to").option("--dashlet <id>","existing custom code dashlet to update (needs --dashboard)").option("--create","create a new dashlet instead of updating one").option("--dry-run","show the request without writing anything").option("--yes","write without asking (headless runs are dry runs without it)").option("--allow-production","allow headless writes to go/fmo").option("--force","overwrite even if the block was edited in Kizen since the last push").option("--forget","clear the remembered target for this block first").option("--json","print a JSON result to stdout (always headless)").option("--no-interactive",mt).option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async(n,r)=>{try{let i=Qc(process.cwd()),{noInteractive:o,options:s}=Ae(r);if(!pt({json:s.json===!0,noInteractive:o})){await Pf(n,s,i);return}let{waitUntilExit:a}=TC(IC(If,{...n!==void 0&&{apiName:n},options:s,deps:i}),{exitOnCtrlC:!1});await a()}catch(i){Tf(i)}}),t.command("targets").description("List the dashboards, homepages and chart groups a block can be pushed to").option("-c, --credentials <path>","path to an API-key credentials JSON file (deprecated; replaces the sign-in session)").option("--profile <name>","stored API-key credential profile to use (deprecated; replaces the sign-in session)").option("--object <id>","list the chart groups of this custom object").option("--json","print a JSON result to stdout").option("--env <env>","environment of the `appbuilder login` session to use").option("--business <id-or-name>","use this saved account, by business id or name (ignoring case), instead of the current one (default: $APPBUILDER_BUSINESS)").option("--user <userId>","with --business, use the saved account of this user id (default: $APPBUILDER_USER)").action(async n=>{try{await Cf(n,Qc(process.cwd()))}catch(r){Tf(r)}})}import{createElement as LC}from"react";import{render as BC}from"ink";import{useEffect as $f,useState as li}from"react";import{Box as ui,Text as ur,useApp as $C}from"ink";import{PluginValidationError as OC}from"@kizenapps/packager";function ci(e){return e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}import{Fragment as DC,jsx as un,jsxs as Un}from"react/jsx-runtime";var Of=["creating-dir","reading-files","validating","minifying","packaging","writing-bundle"],ls={"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"},Df=({outputDir:e,pluginDir:t})=>{let n=$C(),[r,i]=li("creating-dir"),[o,s]=li(!1),[a,c]=li(null),[l,d]=li(null),[u,f]=li(null);$f(()=>{io(t,e,i).then(({bundleSize:p})=>{f(p),i("done")}).catch(p=>{p instanceof OC?c(p.issues):d(p instanceof Error?p.message:String(p)),s(!0),process.exitCode=1})},[e,t]),$f(()=>{(r==="done"||o)&&n.exit()},[r,o,n]);let g=Of.indexOf(r),m=r==="done";return Un(ui,{flexDirection:"column",paddingY:1,paddingX:2,children:[un(ye,{marginBottom:1}),Un(ui,{flexDirection:"column",gap:0,children:[Of.map((p,h)=>{let b=r===p,y=m||g>h;return un(ui,{gap:1,children:o&&h===g?Un(ur,{color:"red",children:["\u2717 ",ls[p]]}):y?Un(ur,{color:"green",children:["\u2713 ",ls[p]]}):b?Un(DC,{children:[un(wt,{}),un(ur,{children:ls[p]})]}):Un(ur,{dimColor:!0,children:[" ",ls[p]]})},p)}),m&&u!==null&&un(ui,{marginTop:1,gap:1,children:Un(ur,{color:"green",children:["\u2713 bundle \u2014 ",ci(u)]})}),a!==null&&un(ar,{issues:a}),l!==null&&un(ui,{marginTop:1,borderStyle:"single",borderColor:"red",paddingX:1,children:un(ur,{color:"red",children:l})})]})]})};function Lf(e){e.command("build").description("Bundle the plugin app into .kizenapp directory").action(async()=>{let t=process.cwd(),n=`${t}/.kizenapp`;Ze(t);let{waitUntilExit:r}=BC(LC(Df,{outputDir:n,pluginDir:t}));await r()})}import{createElement as IS}from"react";import{render as TS}from"ink";import{useCallback as ys,useState as dr}from"react";import{Box as de,Text as K,useApp as xS,useInput as PS}from"ink";import{join as bs}from"path";import{access as wS,mkdir as ps,writeFile as gl}from"fs/promises";import{dirname as vS,join as Bt}from"path";var Bf=`{
|
|
858
878
|
"name": "Hello Frame",
|
|
859
879
|
"api_name": "hello_frame",
|
|
860
880
|
"title": "Hello Frame",
|
|
@@ -863,13 +883,13 @@ ${e.stderr}`),ma=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
863
883
|
"height": 320,
|
|
864
884
|
"width": 280
|
|
865
885
|
}
|
|
866
|
-
`;var
|
|
886
|
+
`;var Ff=`this.outputUI(\`
|
|
867
887
|
<div class="hello-frame">
|
|
868
888
|
<h2 class="hello-frame__title">Hello from a floating frame</h2>
|
|
869
889
|
<p class="hello-frame__body">Edit src/floatingFrames/helloFrame/script.js to change this.</p>
|
|
870
890
|
</div>
|
|
871
891
|
\`);
|
|
872
|
-
`;var
|
|
892
|
+
`;var jf=`.hello-frame {
|
|
873
893
|
padding: 16px;
|
|
874
894
|
font-family: system-ui, sans-serif;
|
|
875
895
|
}
|
|
@@ -883,18 +903,18 @@ ${e.stderr}`),ma=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
883
903
|
margin: 0;
|
|
884
904
|
color: #555;
|
|
885
905
|
}
|
|
886
|
-
`;var
|
|
906
|
+
`;var Mf=`{
|
|
887
907
|
"name": "Hello Block",
|
|
888
908
|
"api_name": "hello_block",
|
|
889
909
|
"types": ["dashboards"]
|
|
890
910
|
}
|
|
891
|
-
`;var
|
|
911
|
+
`;var zf=`this.outputUI(\`
|
|
892
912
|
<div class="hello-block">
|
|
893
913
|
<h2 class="hello-block__title">Hello from a block</h2>
|
|
894
914
|
<p class="hello-block__body">Edit src/blocks/helloBlock/script.js to change this.</p>
|
|
895
915
|
</div>
|
|
896
916
|
\`);
|
|
897
|
-
`;var
|
|
917
|
+
`;var Uf=`.hello-block {
|
|
898
918
|
padding: 16px;
|
|
899
919
|
font-family: system-ui, sans-serif;
|
|
900
920
|
background: #f8fafc;
|
|
@@ -910,25 +930,25 @@ ${e.stderr}`),ma=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "
|
|
|
910
930
|
margin: 0;
|
|
911
931
|
color: #555;
|
|
912
932
|
}
|
|
913
|
-
`;var
|
|
933
|
+
`;var Vf=`{
|
|
914
934
|
"icon": "phone",
|
|
915
935
|
"color": "#0ea5e9",
|
|
916
936
|
"tooltip": "Hello adornment",
|
|
917
937
|
"field_type": "phonenumber"
|
|
918
938
|
}
|
|
919
|
-
`;var
|
|
920
|
-
`;var
|
|
939
|
+
`;var Hf=`this.showToast('Hello from a data adornment.', { variant: 'success' });
|
|
940
|
+
`;var Kf=`{
|
|
921
941
|
"name": "Hello Page",
|
|
922
942
|
"api_name": "hello_page"
|
|
923
943
|
}
|
|
924
|
-
`;var
|
|
944
|
+
`;var Wf=`this.outputUI(\`
|
|
925
945
|
<div class="hello-page">
|
|
926
946
|
<p class="hello-page__loading">Loading\u2026</p>
|
|
927
947
|
</div>
|
|
928
948
|
\`);
|
|
929
949
|
|
|
930
950
|
this.runEventScript('greet');
|
|
931
|
-
`;var
|
|
951
|
+
`;var Gf=`.hello-page {
|
|
932
952
|
padding: 24px;
|
|
933
953
|
font-family: system-ui, sans-serif;
|
|
934
954
|
}
|
|
@@ -966,7 +986,7 @@ this.runEventScript('greet');
|
|
|
966
986
|
.hello-page__button:hover {
|
|
967
987
|
background: #cbd5e1;
|
|
968
988
|
}
|
|
969
|
-
`;var
|
|
989
|
+
`;var Jf=`const tone = this.args?.formData?.tone?.[0] ?? 'plain';
|
|
970
990
|
|
|
971
991
|
const greeting = tone === 'cheer' ? 'Hello, and good to see you!' : 'Hello from a routable page.';
|
|
972
992
|
|
|
@@ -989,33 +1009,32 @@ this.outputUI(\`
|
|
|
989
1009
|
</div>
|
|
990
1010
|
</div>
|
|
991
1011
|
\`);
|
|
992
|
-
`;var
|
|
1012
|
+
`;var qf=`{
|
|
993
1013
|
"api_name": "hello_toolbar_item",
|
|
994
1014
|
"label": "Hello Toolbar Item",
|
|
995
1015
|
"icon": "star",
|
|
996
1016
|
"color": "#0ea5e9"
|
|
997
1017
|
}
|
|
998
|
-
`;var
|
|
999
|
-
`;var
|
|
1018
|
+
`;var Yf=`this.showToast('Hello from a toolbar item.', { variant: 'success' });
|
|
1019
|
+
`;var Zf=`{
|
|
1000
1020
|
"api_name": "hello_object_settings_item",
|
|
1001
1021
|
"label": "Hello Object Settings"
|
|
1002
1022
|
}
|
|
1003
|
-
`;var
|
|
1004
|
-
`;var
|
|
1023
|
+
`;var Xf=`this.showToast('Hello from an object settings item.', { variant: 'success' });
|
|
1024
|
+
`;var Qf=`{
|
|
1005
1025
|
"name": "Hello Action",
|
|
1006
1026
|
"api_name": "hello_action",
|
|
1007
1027
|
"hint_object_name": "client_client"
|
|
1008
1028
|
}
|
|
1009
|
-
`;var
|
|
1010
|
-
`;var
|
|
1011
|
-
`,"utf-8"),await er(Oe(e.targetDir,"src"),{recursive:!0}),await er(Oe(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([Uo(e.targetDir,pc(e.artifacts??[])),Uo(e.targetDir,jn()),Uo(e.targetDir,Ln(e.includeLib===!0?["src"]:[])),Ho(Oe(e.targetDir,...Dh.split("/")),mc(e.apiName))]),Pe(e.targetDir)}var Ze=["name","apiName","externalLink","description","developerBusinessId"],rr={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},Vo=["name","apiName","description"],Wo=/^[a-z_][a-z0-9_]+$/,qo="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function or(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function gc(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function yc(e,t){let n=t.trim();if(Vo.includes(e)&&!n)return`${rr[e]} is required`;if(e==="apiName"&&!Wo.test(n))return`${rr[e]} ${qo}`}function bc(e,t){return e==="description"?t:t.trim()}function wc(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),ae.filter(r=>n.has(r))}import{jsx as I,jsxs as B}from"react/jsx-runtime";var gt=({text:e})=>I(N,{dimColor:!0,children:e}),vc=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let o=Oh(),[i,s]=Ct({type:"target-select",cursor:0}),[a,c]=Ct("in-place"),[g,m]=Ct(()=>gc(t)),[h,y]=Ct(()=>[...ae]),[f,u]=Ct(""),[w,k]=Ct(e),_=ir((v,l)=>{c(v),u(l.name),s({type:"field-entry",field:0,values:l})},[]),P=ir(async v=>{let l=await Xe(v);if(l!=="ok"){s({type:"precheck-error",targetDir:v,reason:l});return}k(v),_("in-place",g)},[g,_]),C=ir(async(v,l)=>{try{let d=await hc(e,v.apiName);k(d),s({type:"confirm",values:v,artifacts:l})}catch(d){s({type:"error",message:d instanceof Error?d.message:String(d)})}},[e]),T=ir(async(v,l,d)=>{try{await nr({targetDir:l,name:v.name,apiName:v.apiName,externalLink:v.externalLink,description:v.description,developerBusinessId:v.developerBusinessId,developerEnvironment:n,artifacts:d,includeLib:r}),s({type:"done",targetDir:l})}catch(p){s({type:"error",message:p instanceof Error?p.message:String(p)})}},[n,r]);if(Bh((v,l)=>{if(l.ctrl&&v==="c"){o.exit();return}if(i.type==="target-select"){l.upArrow?s({type:"target-select",cursor:0}):l.downArrow?s({type:"target-select",cursor:1}):l.return?i.cursor===0?P(e):_("sub-dir",g):l.escape&&o.exit();return}if(i.type==="precheck-error"){(l.return||l.escape)&&o.exit();return}if(i.type==="field-entry"){let{field:d,values:p}=i,b=Ze[d];if(!b)return;if(l.escape){o.exit();return}if(l.backspace||l.delete){u(x=>x.slice(0,-1));return}if(l.upArrow&&d>0){let x={...p,[b]:f},S=d-1,E=Ze[S];s({type:"field-entry",field:S,values:x}),m(x),u(E?x[E]:"");return}if(l.return||l.tab||l.downArrow){let x=yc(b,f);if(x!==void 0){s({type:"field-entry",field:d,values:p,fieldError:x});return}let S=bc(b,f),E={...p,[b]:S};m(E);let $=d+1;if($>=Ze.length)u(""),s({type:"artifact-select",values:E,cursor:0,selected:h});else{let M=Ze[$],ee=M?E[M]:"",ce=M==="apiName"&&!ee?or(E.name):ee;s({type:"field-entry",field:$,values:E}),u(ce)}return}v&&!l.ctrl&&!l.meta&&u(x=>x+v);return}if(i.type==="artifact-select"){let{cursor:d,selected:p,values:b}=i;if(l.escape){let x=Ze.length-1,S=Ze[x];s({type:"field-entry",field:x,values:b}),u(S?b[S]:"");return}if(l.upArrow){s({...i,cursor:Math.max(0,d-1)});return}if(l.downArrow){s({...i,cursor:Math.min(ae.length-1,d+1)});return}if(v===" "){let x=ae[d];if(x){let S=wc(p,x);y(S),s({...i,selected:S})}return}if(v==="a"){y([...ae]),s({...i,selected:[...ae]});return}if(v==="n"){y([]),s({...i,selected:[]});return}l.return&&(a==="sub-dir"?(s({type:"resolving-target"}),C(b,p)):s({type:"confirm",values:b,artifacts:p}));return}if(i.type==="confirm"){if(l.escape){s({type:"artifact-select",values:i.values,cursor:0,selected:i.artifacts});return}l.return&&(s({type:"writing"}),T(i.values,w,i.artifacts));return}(i.type==="done"||i.type==="error")&&(l.return||l.escape)&&o.exit()}),i.type==="target-select"){let v=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Where should the new plugin live?"}),v.map((l,d)=>{let p=i.cursor===d;return B(V,{gap:2,children:[I(N,{...p&&{color:"cyan"},children:p?"\u276F":" "}),I(N,{bold:p,...p&&{color:"cyan"},children:l.label}),I(N,{dimColor:!0,children:l.desc})]},l.label)})]}),I(gt,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="precheck-error"){let{targetDir:v,reason:l}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I(N,{color:"red",bold:!0,children:"Cannot create plugin"}),B(V,{flexDirection:"column",gap:0,children:[B(N,{children:[v," already contains ",I(N,{bold:!0,children:l==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),I(N,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),I(gt,{text:"Enter or Esc to exit"})]})}if(i.type==="field-entry"){let{field:v,fieldError:l}=i,d=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${w}`;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Plugin details"}),I(N,{dimColor:!0,children:d})]}),l!==void 0&&B(N,{color:"red",children:["Error: ",l]}),I(V,{flexDirection:"column",gap:0,children:Ze.map((p,b)=>{let x=v===b,S=x?f:g[p],E=Vo.includes(p),$=`${rr[p]}${E?"":" (optional)"}`;return B(V,{gap:2,children:[I(V,{width:24,children:I(N,{bold:x,...x&&{color:"cyan"},children:$})}),I(N,{...x&&{color:"cyan"},children:">"}),I(N,{children:S}),x&&I(N,{color:"cyan",children:"\u2588"})]},p)})}),I(gt,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(i.type==="artifact-select"){let{cursor:v,selected:l}=i;return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Which artifacts should we scaffold?"}),I(N,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),I(V,{flexDirection:"column",gap:0,children:ae.map((d,p)=>{let b=v===p,x=l.includes(d);return B(V,{gap:1,children:[I(N,{...b&&{color:"cyan"},children:b?"\u276F":" "}),I(N,{...x&&{color:"green"},children:x?"\u25C9":"\u25EF"}),I(N,{bold:b,...b&&{color:"cyan"},children:jo[d]})]},d)})}),I(gt,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(i.type==="confirm"){let v=Ko({targetDir:w,name:i.values.name,apiName:i.values.apiName,externalLink:i.values.externalLink,description:i.values.description,developerBusinessId:i.values.developerBusinessId,developerEnvironment:n});return B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Ready to create"}),B(N,{dimColor:!0,children:["Target: ",w]})]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"kizen.json preview"}),I(N,{children:JSON.stringify(v,null,2)})]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{bold:!0,children:"Artifacts"}),i.artifacts.length===0?B(N,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):i.artifacts.map(l=>B(N,{dimColor:!0,children:[" ",jo[l]]},l))]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{dimColor:!0,children:"Also creates:"}),B(N,{dimColor:!0,children:[" ",sr(w,"src/")]}),B(N,{dimColor:!0,children:[" ",sr(w,"src/thumbnail.png")," (generated placeholder)"]}),B(N,{dimColor:!0,children:[" ",sr(w,"releaseNotes/")]}),B(N,{dimColor:!0,children:[" ",sr(w,".gitignore")," (adds .kizenapp/)"]})]}),I(gt,{text:"Enter to create \xB7 Esc to go back"})]})}return i.type==="resolving-target"?I(V,{paddingY:1,paddingX:2,children:I(N,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):i.type==="writing"?I(V,{paddingY:1,paddingX:2,children:I(N,{dimColor:!0,children:"Creating plugin\u2026"})}):i.type==="done"?B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),B(N,{color:"green",bold:!0,children:["Plugin created at ",i.targetDir]}),B(V,{flexDirection:"column",gap:0,children:[I(N,{dimColor:!0,children:"Next steps:"}),B(N,{children:[" ","cd ",i.targetDir]}),B(N,{children:[" ","npx --yes @kizenapps/cli dev"]}),B(N,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),I(gt,{text:"Enter or Esc to exit"})]}):B(V,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[I(G,{}),I(N,{color:"red",bold:!0,children:"Failed to create plugin"}),I(N,{children:i.message}),I(gt,{text:"Enter or Esc to exit"})]})};async function xc(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let i=await e.loadGlobalCredentials();return{businessId:i?.businessId??"",environment:i?.environment??"go"}}let n=await jt(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var Fh="A hello-world Kizen plugin.",kc=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function jh(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...ae];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!ae.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${ae.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function Lh(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let o=(e.apiName?.trim()??"")||or(r);if(!Wo.test(o))throw new Error(`api_name "${o}" is invalid: ${qo}. Pass --api-name.`);let i=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=zh(e,t);return{targetDir:n,name:r,apiName:o,externalLink:e.externalLink?.trim()??"",description:i===void 0||i===""?Fh:i,developerBusinessId:s,developerEnvironment:a,artifacts:jh(e.artifacts),includeLib:e.includeLib===!0}}function zh(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!Dt(n))throw new Error(`Unknown environment "${n}". Valid environments: ${W.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function Cc(e,t,n,r){let o;try{o=Lh(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1012
|
-
`),r.setExitCode(1);return}let
|
|
1013
|
-
`),r.setExitCode(1);return}try{await r.createPlugin(
|
|
1014
|
-
`),r.setExitCode(1);return}let s=
|
|
1029
|
+
`;var eg=`this.showToast('Hello from a JS action.', { variant: 'success' });
|
|
1030
|
+
`;var Be=["floatingFrame","block","dataAdornment","page","toolbarItem","objectSettingsItem","jsAction"],dl={floatingFrame:"Floating frame",block:"Block",dataAdornment:"Data adornment",page:"Routable page",toolbarItem:"Toolbar item",objectSettingsItem:"Object settings item",jsAction:"JS action"},nS={floatingFrame:{directory:"floatingFrames",component:"helloFrame",files:{"config.json":Bf,"script.js":Ff,"styles.css":jf}},block:{directory:"blocks",component:"helloBlock",files:{"config.json":Mf,"script.js":zf,"styles.css":Uf}},dataAdornment:{directory:"dataAdornments",component:"helloAdornment",files:{"config.json":Vf,"script.js":Hf}},page:{directory:"pages",component:"helloPage",files:{"config.json":Kf,"script.js":Wf,"styles.css":Gf,"eventScripts/greet.js":Jf}},toolbarItem:{directory:"toolbarItems",component:"helloToolbarItem",files:{"config.json":qf,"script.js":Yf}},objectSettingsItem:{directory:"objectSettingsItems",component:"helloObjectSettingsItem",files:{"config.json":Zf,"script.js":Xf}},jsAction:{directory:"actions",component:"helloAction",files:{"config.json":Qf,"script.js":eg}}};function rS(e,t="src"){let{directory:n,component:r,files:i}=nS[e];return Object.entries(i).map(([o,s])=>({path:`${t}/${n}/${r}/${o}`,content:s}))}function tg(e,t="src"){return[...new Set(e)].flatMap(n=>rS(n,t))}import{deflateSync as iS}from"zlib";var ml=512,oS=150,sS=26,fl=46,ng=.6,aS=fl*.55,cS=.55,lS=.47;function uS(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t}function dS(e){let t=uS(e);return{hue:t%360,quarterTurns:(t>>>16)%4}}function pS(e,t,n){let r=(1-Math.abs(2*n-1))*t,i=e/60,o=r*(1-Math.abs(i%2-1)),s=n-r/2,[a,c,l]=i<1?[r,o,0]:i<2?[o,r,0]:i<3?[0,r,o]:i<4?[0,o,r]:i<5?[o,0,r]:[r,0,o];return[Math.round((a+s)*255),Math.round((c+s)*255),Math.round((l+s)*255)]}function di(e,t,n,r,i){let o=Math.abs(e)-n+i,s=Math.abs(t)-r+i;return Math.hypot(Math.max(o,0),Math.max(s,0))+Math.min(Math.max(o,s),0)-i}function us(e,t,n,r,i){return Math.hypot(e-n,t-r)-i}function mS(e,t){let n=oS,r=fl,i=r*ng,o=aS,s=di(e,t,n,n,sS),a=Math.min(us(e,t,0,-n-i,r),di(e,t+n+i/2,o,i/2+1,0)),c=Math.min(us(e,t,n+i,0,r),di(e-n-i/2,t,i/2+1,o,0));s=Math.min(s,a,c);let l=Math.min(us(e,t,0,n-i,r),di(e,t-n+i/2,o,i/2+1,0)),d=Math.min(us(e,t,-n+i,0,r),di(e+n-i/2,t,i/2+1,o,0));return Math.max(s,-l,-d)}function fS(e){let t=ml,n=new Uint8Array(t*t*4),[r,i,o]=pS(e.hue,cS,lS),s=fl*(1+ng),a=(t-1)/2,c=s/2;for(let l=0;l<t;l+=1)for(let d=0;d<t;d+=1){let u=d-a,f=l-a;for(let h=0;h<e.quarterTurns;h+=1)[u,f]=[-f,u];let g=mS(u+c,f-c),m=Math.min(1,Math.max(0,.5-g));if(m<=0)continue;let p=(l*t+d)*4;n[p]=r,n[p+1]=i,n[p+2]=o,n[p+3]=Math.round(m*255)}return n}var gS=new Uint32Array(256).map((e,t)=>{let n=t;for(let r=0;r<8;r+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function hS(e){let t=4294967295;for(let n of e)t=(gS[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}function pl(e,t){let n=Buffer.from(e,"latin1"),r=Buffer.alloc(4);r.writeUInt32BE(t.length);let i=Buffer.alloc(4);return i.writeUInt32BE(hS(Buffer.concat([n,t]))),Buffer.concat([r,n,t,i])}var yS=Buffer.from([137,80,78,71,13,10,26,10]);function bS(e,t,n){if(n.length!==e*t*4)throw new Error(`encodePng: expected ${String(e*t*4)} bytes of RGBA for ${String(e)}x${String(t)}, got ${String(n.length)}`);let r=Buffer.alloc(13);r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=8,r[9]=6;let i=e*4,o=Buffer.alloc((i+1)*t);for(let s=0;s<t;s+=1)o.set(n.subarray(s*i,(s+1)*i),s*(i+1)+1);return Buffer.concat([yS,pl("IHDR",r),pl("IDAT",iS(o,{level:9})),pl("IEND",new Uint8Array(0))])}function rg(e){return bS(ml,ml,fS(dS(e)))}var kS="src/thumbnail.png",AS=["go","fmo"];async function ms(e){try{return await wS(e),!0}catch{return!1}}async function dn(e){return await ms(Bt(e,"kizen.json"))?"has-manifest":await ms(Bt(e,".kizenapp"))?"has-kizenapp":"ok"}async function ig(e,t){let n=Bt(e,t);if(!await ms(n))return n;for(let r=1;r<1e3;r++){let i=Bt(e,`${t}-${String(r)}`);if(!await ms(i))return i}throw new Error(`Could not find an available directory name for "${t}"`)}function hl(e){let t=e.developerBusinessId.trim(),n=t!==""&&!AS.includes(e.developerEnvironment)?[e.developerEnvironment]:["prod"];return{name:e.name,version:"1.0.0",published:!0,api_name:e.apiName,external_link:e.externalLink,description:e.description,entry:"src/",engine:"1.0.0",release_notes_directory:"releaseNotes/",release_environments:n,config_template:{},base_config:{},...t?{developer_business_id:{[e.developerEnvironment]:t}}:{}}}async function ds(e,t){let n=t.map(i=>({fullPath:Bt(e,...i.path.split("/")),content:i.content})),r=new Set(n.map(i=>vS(i.fullPath)));await Promise.all([...r].map(i=>ps(i,{recursive:!0}))),await Promise.all(n.map(i=>gl(i.fullPath,i.content,"utf-8")))}async function fs(e){await ps(e.targetDir,{recursive:!0});let t=hl(e);await gl(Bt(e.targetDir,"kizen.json"),JSON.stringify(t,null,2)+`
|
|
1031
|
+
`,"utf-8"),await ps(Bt(e.targetDir,"src"),{recursive:!0}),await ps(Bt(e.targetDir,"releaseNotes"),{recursive:!0}),await Promise.all([ds(e.targetDir,tg(e.artifacts??[])),ds(e.targetDir,Ki()),ds(e.targetDir,zd(e.includeLib===!0?["src"]:[])),ds(e.targetDir,Ud()),gl(Bt(e.targetDir,...kS.split("/")),rg(e.apiName))]),Ze(e.targetDir)}var pn=["name","apiName","externalLink","description","developerBusinessId"],gs={name:"Name",apiName:"API name",externalLink:"External link",description:"Description",developerBusinessId:"Business ID"},yl=["name","apiName","description"],bl=/^[a-z_][a-z0-9_]+$/,wl="must start with a letter or underscore and contain only lowercase letters, numbers, or underscores (minimum 2 characters)";function hs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function og(e){return{name:"",apiName:"",externalLink:"",description:"",developerBusinessId:e}}function sg(e,t){let n=t.trim();if(yl.includes(e)&&!n)return`${gs[e]} is required`;if(e==="apiName"&&!bl.test(n))return`${gs[e]} ${wl}`}function ag(e,t){return e==="description"?t:t.trim()}function cg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Be.filter(r=>n.has(r))}import{jsx as U,jsxs as ee}from"react/jsx-runtime";var Vn=({text:e})=>U(K,{dimColor:!0,children:e}),lg=({parentDir:e,defaultBusinessId:t,defaultEnvironment:n,includeLib:r=!1})=>{let i=xS(),[o,s]=dr({type:"target-select",cursor:0}),[a,c]=dr("in-place"),[l,d]=dr(()=>og(t)),[u,f]=dr(()=>[...Be]),[g,m]=dr(""),[p,h]=dr(e),b=ys((x,v)=>{c(x),m(v.name),s({type:"field-entry",field:0,values:v})},[]),y=ys(async x=>{let v=await dn(x);if(v!=="ok"){s({type:"precheck-error",targetDir:x,reason:v});return}h(x),b("in-place",l)},[l,b]),C=ys(async(x,v)=>{try{let k=await ig(e,x.apiName);h(k),s({type:"confirm",values:x,artifacts:v})}catch(k){s({type:"error",message:k instanceof Error?k.message:String(k)})}},[e]),S=ys(async(x,v,k)=>{try{await fs({targetDir:v,name:x.name,apiName:x.apiName,externalLink:x.externalLink,description:x.description,developerBusinessId:x.developerBusinessId,developerEnvironment:n,artifacts:k,includeLib:r}),s({type:"done",targetDir:v})}catch(P){s({type:"error",message:P instanceof Error?P.message:String(P)})}},[n,r]);if(PS((x,v)=>{if(v.ctrl&&x==="c"){i.exit();return}if(o.type==="target-select"){v.upArrow?s({type:"target-select",cursor:0}):v.downArrow?s({type:"target-select",cursor:1}):v.return?o.cursor===0?y(e):b("sub-dir",l):v.escape&&i.exit();return}if(o.type==="precheck-error"){(v.return||v.escape)&&i.exit();return}if(o.type==="field-entry"){let{field:k,values:P}=o,w=pn[k];if(!w)return;if(v.escape){i.exit();return}if(v.backspace||v.delete){m(A=>A.slice(0,-1));return}if(v.upArrow&&k>0){let A={...P,[w]:g},_=k-1,T=pn[_];s({type:"field-entry",field:_,values:A}),d(A),m(T?A[T]:"");return}if(v.return||v.tab||v.downArrow){let A=sg(w,g);if(A!==void 0){s({type:"field-entry",field:k,values:P,fieldError:A});return}let _=ag(w,g),T={...P,[w]:_};d(T);let L=k+1;if(L>=pn.length)m(""),s({type:"artifact-select",values:T,cursor:0,selected:u});else{let $=pn[L],V=$?T[$]:"",X=$==="apiName"&&!V?hs(T.name):V;s({type:"field-entry",field:L,values:T}),m(X)}return}x&&!v.ctrl&&!v.meta&&m(A=>A+x);return}if(o.type==="artifact-select"){let{cursor:k,selected:P,values:w}=o;if(v.escape){let A=pn.length-1,_=pn[A];s({type:"field-entry",field:A,values:w}),m(_?w[_]:"");return}if(v.upArrow){s({...o,cursor:Math.max(0,k-1)});return}if(v.downArrow){s({...o,cursor:Math.min(Be.length-1,k+1)});return}if(x===" "){let A=Be[k];if(A){let _=cg(P,A);f(_),s({...o,selected:_})}return}if(x==="a"){f([...Be]),s({...o,selected:[...Be]});return}if(x==="n"){f([]),s({...o,selected:[]});return}v.return&&(a==="sub-dir"?(s({type:"resolving-target"}),C(w,P)):s({type:"confirm",values:w,artifacts:P}));return}if(o.type==="confirm"){if(v.escape){s({type:"artifact-select",values:o.values,cursor:0,selected:o.artifacts});return}v.return&&(s({type:"writing"}),S(o.values,p,o.artifacts));return}(o.type==="done"||o.type==="error")&&(v.return||v.escape)&&i.exit()}),o.type==="target-select"){let x=[{label:"Use current directory",desc:e},{label:"Create new sub-directory",desc:`${e}/<inferred from API name>`}];return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Where should the new plugin live?"}),x.map((v,k)=>{let P=o.cursor===k;return ee(de,{gap:2,children:[U(K,{...P&&{color:"cyan"},children:P?"\u276F":" "}),U(K,{bold:P,...P&&{color:"cyan"},children:v.label}),U(K,{dimColor:!0,children:v.desc})]},v.label)})]}),U(Vn,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="precheck-error"){let{targetDir:x,reason:v}=o;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Cannot create plugin"}),ee(de,{flexDirection:"column",gap:0,children:[ee(K,{children:[x," already contains ",U(K,{bold:!0,children:v==="has-manifest"?"kizen.json":".kizenapp/"}),"."]}),U(K,{dimColor:!0,children:"Remove the conflicting file/directory or choose a different target to avoid overwriting an existing plugin."})]}),U(Vn,{text:"Enter or Esc to exit"})]})}if(o.type==="field-entry"){let{field:x,fieldError:v}=o,k=a==="sub-dir"?`Target: sub-directory of ${e} (inferred from API name)`:`Target: ${p}`;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Plugin details"}),U(K,{dimColor:!0,children:k})]}),v!==void 0&&ee(K,{color:"red",children:["Error: ",v]}),U(de,{flexDirection:"column",gap:0,children:pn.map((P,w)=>{let A=x===w,_=A?g:l[P],T=yl.includes(P),L=`${gs[P]}${T?"":" (optional)"}`;return ee(de,{gap:2,children:[U(de,{width:24,children:U(K,{bold:A,...A&&{color:"cyan"},children:L})}),U(K,{...A&&{color:"cyan"},children:">"}),U(K,{children:_}),A&&U(K,{color:"cyan",children:"\u2588"})]},P)})}),U(Vn,{text:"Enter/Tab/\u2193 next \xB7 \u2191 previous \xB7 Backspace delete \xB7 Esc cancel"})]})}if(o.type==="artifact-select"){let{cursor:x,selected:v}=o;return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Which artifacts should we scaffold?"}),U(K,{dimColor:!0,children:"Each one gets a directory with a config.json and a script that runs."})]}),U(de,{flexDirection:"column",gap:0,children:Be.map((k,P)=>{let w=x===P,A=v.includes(k);return ee(de,{gap:1,children:[U(K,{...w&&{color:"cyan"},children:w?"\u276F":" "}),U(K,{...A&&{color:"green"},children:A?"\u25C9":"\u25EF"}),U(K,{bold:w,...w&&{color:"cyan"},children:dl[k]})]},k)})}),U(Vn,{text:"\u2191\u2193 move \xB7 Space toggle \xB7 a all \xB7 n none \xB7 Enter continue \xB7 Esc back"})]})}if(o.type==="confirm"){let x=hl({targetDir:p,name:o.values.name,apiName:o.values.apiName,externalLink:o.values.externalLink,description:o.values.description,developerBusinessId:o.values.developerBusinessId,developerEnvironment:n});return ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Ready to create"}),ee(K,{dimColor:!0,children:["Target: ",p]})]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"kizen.json preview"}),U(K,{children:JSON.stringify(x,null,2)})]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{bold:!0,children:"Artifacts"}),o.artifacts.length===0?ee(K,{dimColor:!0,children:[" ","none (src/ will hold only thumbnail.png)"]}):o.artifacts.map(v=>ee(K,{dimColor:!0,children:[" ",dl[v]]},v))]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Also creates:"}),ee(K,{dimColor:!0,children:[" ",bs(p,"src/")]}),ee(K,{dimColor:!0,children:[" ",bs(p,"src/thumbnail.png")," (generated placeholder)"]}),ee(K,{dimColor:!0,children:[" ",bs(p,"releaseNotes/")]}),ee(K,{dimColor:!0,children:[" ",bs(p,".gitignore")," (adds .kizenapp/)"]})]}),U(Vn,{text:"Enter to create \xB7 Esc to go back"})]})}return o.type==="resolving-target"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Finding available sub-directory\u2026"})}):o.type==="writing"?U(de,{paddingY:1,paddingX:2,children:U(K,{dimColor:!0,children:"Creating plugin\u2026"})}):o.type==="done"?ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),ee(K,{color:"green",bold:!0,children:["Plugin created at ",o.targetDir]}),ee(de,{flexDirection:"column",gap:0,children:[U(K,{dimColor:!0,children:"Next steps:"}),ee(K,{children:[" ","cd ",o.targetDir]}),ee(K,{children:[" ","npx --yes @kizenapps/cli dev"]}),ee(K,{dimColor:!0,children:[" ","Replace src/thumbnail.png with real artwork before publishing."]})]}),U(Vn,{text:"Enter or Esc to exit"})]}):ee(de,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[U(ye,{}),U(K,{color:"red",bold:!0,children:"Failed to create plugin"}),U(K,{children:o.message}),U(Vn,{text:"Enter or Esc to exit"})]})};async function ug(e){let t=await e.listSessions().catch(()=>[]);if(t.length===0){let o=await e.loadGlobalCredentials();return{businessId:o?.businessId??"",environment:o?.environment??"go"}}let n=await Cr(e.requestedEnvironment?.trim()||void 0,()=>Promise.resolve(t)),r=n.ok?n.environment:"go";return{businessId:(await e.readSession(r).catch(()=>null))?.businessId??"",environment:r}}var CS="A hello-world Kizen plugin.",dg=e=>Object.entries(e).some(([t,n])=>t!=="includeLib"&&n!==void 0);function SS(e){if(e===void 0||e.trim()===""||e.trim()==="all")return[...Be];if(e.trim()==="none")return[];let t=e.split(",").map(r=>r.trim()).filter(r=>r!==""),n=t.filter(r=>!Be.includes(r));if(n.length>0)throw new Error(`Unknown artifact type(s): ${n.join(", ")}. Valid types: ${Be.join(", ")}, or "all" / "none".`);return[...new Set(t)]}function _S(e,t,n){let r=e.name?.trim()??"";if(r==="")throw new Error("--name is required for a non-interactive run.");let i=(e.apiName?.trim()??"")||hs(r);if(!bl.test(i))throw new Error(`api_name "${i}" is invalid: ${wl}. Pass --api-name.`);let o=e.description?.trim(),s=e.businessId?.trim()??t.businessId,a=ES(e,t);return{targetDir:n,name:r,apiName:i,externalLink:e.externalLink?.trim()??"",description:o===void 0||o===""?CS:o,developerBusinessId:s,developerEnvironment:a,artifacts:SS(e.artifacts),includeLib:e.includeLib===!0}}function ES(e,t){let n=e.environment?.trim();if(n!==void 0&&n!==""){if(!vr(n))throw new Error(`Unknown environment "${n}". Valid environments: ${pe.join(", ")}.`);return n}if(e.businessId!==void 0&&t.businessId==="")throw new Error("--environment is required alongside --business-id when neither a sign-in session nor saved credentials give a default business, so the id is keyed to the environment that issued it.");return t.environment}async function pg(e,t,n,r){let i;try{i=_S(e,t,n)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1032
|
+
`),r.setExitCode(1);return}let o=await r.precheckTargetDir(n);if(o!=="ok"){let a=o==="has-manifest"?"kizen.json":".kizenapp/";r.writeStderr(`Error: ${n} already contains ${a}. Refusing to overwrite an existing plugin.
|
|
1033
|
+
`),r.setExitCode(1);return}try{await r.createPlugin(i)}catch(a){r.writeStderr(`Error: ${a instanceof Error?a.message:String(a)}
|
|
1034
|
+
`),r.setExitCode(1);return}let s=i.artifacts&&i.artifacts.length>0?i.artifacts.join(", "):"none";r.writeStdout(`Created plugin ${i.apiName} at ${n}
|
|
1015
1035
|
`),r.writeStdout(`Artifacts: ${s}
|
|
1016
1036
|
`),r.writeStdout(`Thumbnail: src/thumbnail.png (generated placeholder; replace it before publishing)
|
|
1017
|
-
`),
|
|
1018
|
-
`)}function Sc(e){e.command("create").description("Scaffold a new Kizen plugin project").option("-n, --name <name>","plugin display name (implies a non-interactive run)").option("-a, --api-name <name>","plugin api_name (inferred from --name when omitted)").option("-d, --description <text>","plugin description").option("-l, --external-link <url>","external link shown on the plugin listing").option("-b, --business-id <id>","developer business id (defaults to your sign-in session, else saved API-key credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${W.join(", ")} (defaults to your sign-in session, else saved API-key credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${ae.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").action(async t=>{let n=process.cwd(),r=Ce(),{businessId:o,environment:i}=await xc({listSessions:r.listSessions,readSession:r.readSession,loadGlobalCredentials:se,...t.environment!==void 0&&{requestedEnvironment:t.environment}});if(!process.stdin.isTTY||!process.stdout.isTTY||kc(t)){await Cc(t,{businessId:o,environment:i},n,{precheckTargetDir:Xe,createPlugin:nr,writeStdout:c=>{process.stdout.write(c)},writeStderr:c=>{process.stderr.write(c)},setExitCode:c=>{process.exitCode=c}});return}let{waitUntilExit:a}=Uh(Mh(vc,{parentDir:n,defaultBusinessId:o,defaultEnvironment:i,includeLib:t.includeLib===!0}),{exitOnCtrlC:!1});await a()})}import{createElement as el}from"react";import{render as tl}from"ink";import{useCallback as St,useEffect as fr,useRef as Be,useState as ue}from"react";import{Box as ne,Text as F,useInput as Lg}from"ink";import{PluginValidationError as zg}from"@kizenapps/packager";import{watch as Mg}from"fs";import{createServer as Ug}from"http";import{join as Xc}from"path";import{WebSocketServer as Hg}from"ws";import{createReadStream as Bc,realpathSync as sg}from"fs";import{access as ag,readdir as cg,readFile as lg,realpath as dg,stat as Fc}from"fs/promises";import{dirname as ug,extname as jc,join as rn,resolve as pg,sep as ti}from"path";import{fileURLToPath as fg}from"url";var Hh=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ar(e){let t={};for(let[n,r]of Object.entries(e)){let o=n.toLowerCase();Hh.has(o)||o.startsWith("access-control-")||(t[n]=r)}return t}var Go=10*1024*1024,Kh=6e4,Vh=200,Qt=class extends Error{bytesRead;limit;constructor(t,n){super(`Upstream response exceeded ${String(n)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=n}};async function Jo(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],o=0;for await(let i of n){if(o+=i.length,o>t)throw new Qt(o,t);r.push(i)}return Buffer.concat(r)}async function Pc(e){let t=ar(Object.fromEntries(e.headers)),n=await Jo(e,Go);return{status:e.status,headers:t,body:n}}function Ec(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await Pc(await a()),fromCache:!1}},clear(){}};let r=new Map,o=()=>{t?.(r.size)},i=s=>{r.delete(s)&&o()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<Kh)return c.promise.then(m=>({response:m,fromCache:!0}));i(s)}if(r.size>=Vh){let m=r.keys().next().value;m!==void 0&&i(m)}let g=a().then(Pc).catch(m=>{throw i(s),m});return r.set(s,{insertedAt:Date.now(),promise:g}),o(),g.then(m=>((m.status<200||m.status>=300)&&i(s),{response:m,fromCache:!1}))},clear(){r.clear(),o()}}}var Yo={".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 Xo={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function en(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||Xo.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!==""?Xo.localDev:Xo.dev}import{spawn as $c}from"child_process";import{writeFile as Tc,rm as Qo,mkdtemp as Jh,access as Yh}from"fs/promises";import{join as nn}from"path";import{tmpdir as Xh}from"os";var _c=`awslambdaric
|
|
1037
|
+
`),i.developerBusinessId.trim()===""&&r.writeStderr("Warning: no developer_business_id configured, so this plugin can't be preview-published to the marketplace (plugin-wizard) yet. Business Apps (`appbuilder app push`) don't need it.\n")}function mg(e){e.command("create").description("Scaffold a new Kizen plugin project").option("-n, --name <name>","plugin display name (implies a non-interactive run)").option("-a, --api-name <name>","plugin api_name (inferred from --name when omitted)").option("-d, --description <text>","plugin description").option("-l, --external-link <url>","external link shown on the plugin listing").option("-b, --business-id <id>","developer business id (defaults to your sign-in session, else saved API-key credentials)").option("-e, --environment <env>",`environment the business id belongs to: ${pe.join(", ")} (defaults to your sign-in session, else saved API-key credentials)`).option("--artifacts <list>",`comma-separated artifact types, or "all" / "none" (default: all). Types: ${Be.join(", ")}`).option("--include-lib","also install the Kizen data helper library (src/lib/kizenData.js)").option("--no-interactive",mt).action(async t=>{let{noInteractive:n,options:r}=Ae(t),i=process.cwd(),o=ft(),{businessId:s,environment:a}=await ug({listSessions:o.listSessions,readSession:o.readSession,loadGlobalCredentials:De,...r.environment!==void 0&&{requestedEnvironment:r.environment}});if(!pt({noInteractive:n})||dg(r)){await pg(r,{businessId:s,environment:a},i,{precheckTargetDir:dn,createPlugin:fs,writeStdout:d=>{process.stdout.write(d)},writeStderr:d=>{process.stderr.write(d)},setExitCode:d=>{process.exitCode=d}});return}let{waitUntilExit:l}=TS(IS(lg,{parentDir:i,defaultBusinessId:s,defaultEnvironment:a,includeLib:r.includeLib===!0}),{exitOnCtrlC:!1});await l()})}import{createElement as Vg}from"react";import{render as Hg}from"ink";import{useCallback as pr,useEffect as Cs,useRef as Ft,useState as Ve}from"react";import{Box as Ee,Text as te,useInput as __}from"ink";import{PluginValidationError as E_}from"@kizenapps/packager";import{watch as I_}from"fs";import{createServer as T_}from"http";import{join as Mg}from"path";import{WebSocketServer as N_}from"ws";import{createReadStream as Cg,realpathSync as JS}from"fs";import{access as qS,readdir as YS,readFile as ZS,realpath as XS,stat as Sg}from"fs/promises";import{dirname as QS,extname as _g,join as hi,resolve as e_,sep as _l}from"path";import{fileURLToPath as t_}from"url";var NS=new Set(["set-cookie","strict-transport-security","content-security-policy","content-security-policy-report-only","x-frame-options","content-encoding","content-length"]);function ws(e){let t={};for(let[n,r]of Object.entries(e)){let i=n.toLowerCase();NS.has(i)||i.startsWith("access-control-")||(t[n]=r)}return t}var vl=10*1024*1024,RS=6e4,$S=200,pi=class extends Error{bytesRead;limit;constructor(t,n){super(`Upstream response exceeded ${String(n)} bytes (read ${String(t)}).`),this.name="ProxyResponseTooLargeError",this.bytesRead=t,this.limit=n}};async function kl(e,t){let n=e.body;if(n===null)return Buffer.alloc(0);let r=[],i=0;for await(let o of n){if(i+=o.length,i>t)throw new pi(i,t);r.push(o)}return Buffer.concat(r)}async function fg(e){let t=ws(Object.fromEntries(e.headers)),n=await kl(e,vl);return{status:e.status,headers:t,body:n}}function gg(e={}){let{onChange:t,enabled:n=!0}=e;if(!n)return{async get(s,a){return{response:await fg(await a()),fromCache:!1}},clear(){}};let r=new Map,i=()=>{t?.(r.size)},o=s=>{r.delete(s)&&i()};return{get(s,a){let c=r.get(s);if(c!==void 0){if(Date.now()-c.insertedAt<RS)return c.promise.then(d=>({response:d,fromCache:!0}));o(s)}if(r.size>=$S){let d=r.keys().next().value;d!==void 0&&o(d)}let l=a().then(fg).catch(d=>{throw o(s),d});return r.set(s,{insertedAt:Date.now(),promise:l}),i(),l.then(d=>((d.status<200||d.status>=300)&&o(s),{response:d,fromCache:!1}))},clear(){r.clear(),i()}}}var Al={".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 xl={prod:"https://plugin-wizard.kizen.com",dev:"https://plugin-wizard.kizen.dev",localDev:"http://localhost:9823"};function mi(e){let t=process.env.PLUGIN_WIZARD_URL;return t!==void 0&&t!==""?t:e==="prod"?process.env.PLUGIN_WIZARD_URL_PROD||xl.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!==""?xl.localDev:xl.dev}import{spawn as vg}from"child_process";import{writeFile as bg,rm as Cl,mkdtemp as BS,access as FS}from"fs/promises";import{join as gi}from"path";import{tmpdir as jS}from"os";var hg=`awslambdaric
|
|
1019
1038
|
bcrypt
|
|
1020
1039
|
boto3
|
|
1021
1040
|
fpdf2
|
|
@@ -1033,7 +1052,7 @@ pytz
|
|
|
1033
1052
|
requests
|
|
1034
1053
|
sqlalchemy>=2.0,<2.1
|
|
1035
1054
|
tzdata
|
|
1036
|
-
`;import{AUTOMATION_SCRIPT_RUNTIMES as
|
|
1055
|
+
`;import{AUTOMATION_SCRIPT_RUNTIMES as MS,isSupportedScriptRuntime as zS,scriptRuntimeToApiName as kg}from"@kizenapps/packager";function DS(e){return e==null||e.trim()===""?null:e}function LS(e){return e==null?null:typeof e=="string"?DS(e):typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):typeof e=="function"||typeof e=="symbol"?null:JSON.stringify(e)}function yg(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,LS(n)])):{}}var US=`
|
|
1037
1056
|
import sys, json, os, traceback
|
|
1038
1057
|
|
|
1039
1058
|
# --- Inputs proxy (attribute access) ---
|
|
@@ -1193,29 +1212,29 @@ sys.stdout.write('\\n__KIZEN_RESULT_START__\\n')
|
|
|
1193
1212
|
sys.stdout.write(json.dumps(result, ensure_ascii=False))
|
|
1194
1213
|
sys.stdout.write('\\n__KIZEN_RESULT_END__\\n')
|
|
1195
1214
|
sys.stdout.flush()
|
|
1196
|
-
`.trim(),
|
|
1197
|
-
`);for(;
|
|
1198
|
-
`)}}),c.on("end",()=>{if(
|
|
1199
|
-
`).trim(),m=g.length>0?`: ${g}`:"";o(new Error(`${e} exited with code ${String(c)}${m}`))}})})}var Zo=null;function rg(e,t){if(tn)return t&&Zo?.add(t),tn;let n=new Set;t&&n.add(t),Zo=n;let r=i=>{for(let s of n)s(i)},o=nn(cr,"bin","python");return tn=(async()=>{try{let i=!1;try{await Yh(o);let s=await Sn(o);i=s!==null&&Hr(s,Ut)}catch{i=!1}if(!i){await Qo(cr,{recursive:!0,force:!0}).catch(()=>{});let s=await is(e);await Ic(s,["-m","venv",cr])}return r({kind:"start"}),await Ic(o,["-m","pip","install","--disable-pip-version-check",...Dc],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),o}catch(i){let s=i instanceof Error?i.message:String(i);throw r({kind:"error",message:s}),tn=null,await Qo(cr,{recursive:!0,force:!0}).catch(()=>{}),i}finally{Zo=null}})(),tn}function og(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),o=e.indexOf(n);if(r===-1||o===-1)return{userStdout:e,result:null};let i=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,o).trim();try{let a=JSON.parse(s);return{userStdout:i,result:a}}catch{return{userStdout:e,result:null}}}function ig(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function Rc(e){let t=e.timeout??tg;if(!Qh(e.scriptRuntime))return ig(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${ng.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await rg(Nc(e.scriptRuntime),e.onInstallProgress),o=Date.now(),i;try{i=await Jh(nn(Xh(),"kizen-step-"));let s=nn(i,"wrapper.py"),a=nn(i,"script.py");await Promise.all([Tc(s,eg,"utf-8"),Tc(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:g,stdout:m,stderr:h}=await new Promise(k=>{let _=[],P=[],C=!1,T=$c(r,[s],{env:c,cwd:i,stdio:["ignore","pipe","pipe"]}),v=setTimeout(()=>{T.kill("SIGKILL")},t);T.stdout.on("data",d=>{_.push(d)}),T.stderr.on("data",d=>{P.push(d)});let l=d=>{C||(C=!0,clearTimeout(v),k({exitCode:d??1,stdout:Buffer.concat(_).toString("utf-8"),stderr:Buffer.concat(P).toString("utf-8")}))};T.on("close",l),T.on("error",d=>{C||(C=!0,clearTimeout(v),k({exitCode:1,stdout:"",stderr:d.message}))})}),y=Date.now()-o,{userStdout:f,result:u}=og(m);if(u){let k={success:u.success,outputValues:u.outputValues,logs:u.logs,stdout:f,stderr:h,exitCode:g,durationMs:y};return u.error!==null&&(k.error=u.error),u.httpRequests&&(k.httpRequests=u.httpRequests),k}let w={success:!1,outputValues:{},logs:[],stdout:f,stderr:h,exitCode:g,durationMs:y};return g!==0&&(w.error=`Process exited with code ${String(g)}`),w}finally{i&&Qo(i,{recursive:!0,force:!0})}}var Oc=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 Lc,CRYPTO_VERSION as zc,DEFAULT_AUTOMATION_RUNTIME as mg,deserializeEnvelope as hg,encrypt as gg,scriptRuntimeToApiName as yg,serializeEnvelope as bg}from"@kizenapps/packager";function ei(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",n=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${n}${t}`}var wg=2*1024*1024,vg=new Set([".DS_Store",".gitignore"]);function xg(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 Kc=["kizen.com","kizen.dev"];function kg(e){let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="[::1]"?!0:t.protocol!=="https:"?!1:Kc.some(r=>n===r||n.endsWith("."+r))}function Cg(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return Kc.some(r=>n===r||n.endsWith("."+r))}function Sg(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 Mc(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=pg(e,n);if(r!==e&&!r.startsWith(e+ti))return null;try{let o=await dg(r);return o!==e&&!o.startsWith(e+ti)?null:o}catch{return null}}function Uc(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(ti).some(o=>Rn.has(o))}function Vc(){let e=fg(import.meta.url);return rn(ug(e),"viewer")}function Hc(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function ni(e){try{return await ag(e),!0}catch{return!1}}function Wc(e,t,n,r,o,i,s,a,c,g,m){let h=Ec({onChange:a,enabled:m}),y=sg(g);return(f,u)=>{(async()=>{let w=f.url??"/";try{if(!xg(f.headers.host)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Forbidden"}));return}if((f.method==="POST"||f.method==="PATCH"||f.method==="DELETE")&&!Sg(f.headers.origin)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${w}`),w==="/api/credentials"){u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({credentials:r.current??null,activeProfile:o.current??null}));return}if(w==="/api/credential-profiles"&&f.method==="GET"){let l=await We();u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({profiles:l,active:o.current}));return}if(w==="/api/credentials/switch"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let p=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}").profile,b=p===void 0||p===""?await se():await Ie(p);if(b!==null){r.current=b,o.current=p??void 0;let x=o.current,S=await Se(i);await Je(i,{...S,credentialMode:"global",...x!==void 0&&{activeCredentialProfile:x}}),s({type:"credentials-updated",credentials:b,activeProfile:o.current??null})}u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:b!==null}));return}if(w==="/api/bundle"){let l=rn(process.cwd(),".kizenapp","bundle.json");try{let d=await lg(l,"utf-8");u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(d)}catch{u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end("{}")}return}if(w==="/api/last-path"&&f.method==="POST"){let l=[];for await(let p of f)l.push(p);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.path=="string"){c.current=d.path;let p=await Se(i);await Je(i,{...p,lastPath:d.path})}u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/encryption-target"&&f.method==="GET"){let d=(await Se(i)).encryptionTarget==="dev"?"dev":"prod";u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({target:d}));return}if(w==="/api/encryption-target"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}"),p=d!==null&&typeof d=="object"?d:{};if(p.target!=="dev"&&p.target!=="prod"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let b=await Se(i);await Je(i,{...b,encryptionTarget:p.target}),u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/execute-step"&&f.method==="POST"){let l=[];for await(let x of f)l.push(x);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.script!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required field: script"}));return}let p={script:d.script,scriptRuntime:d.scriptRuntime??yg(mg),inputs:Ac(d.inputs),secrets:d.secrets??{},onInstallProgress:x=>{x.kind==="start"?s({type:"venv-install-start"}):x.kind==="log"?s({type:"venv-install-log",line:x.line,stream:x.stream}):x.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:x.message})}};typeof d.timeout=="number"&&d.timeout>0&&(p.timeout=Math.min(d.timeout,300*1e3));let b=await Rc(p);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify(b));return}if(w==="/api/proxy-cache/clear"){h.clear(),n({kind:"info",message:"Proxy cache cleared"}),u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end('{"ok":true}');return}if(w==="/api/local/encrypt"&&f.method==="POST"){let l=[];for await(let p of f)l.push(p);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.publicKeyPem!="string"||typeof d.value!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let p=gg(d.value,d.publicKeyPem),b=bg(p);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify(b))}catch(p){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:p.message}))}return}if(w==="/api/local/validate"&&f.method==="POST"){let l=[];for await(let E of f)l.push(E);let d=JSON.parse(Buffer.concat(l).toString("utf-8")||"{}");if(typeof d.value!="string"){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing required field: value"}));return}let p,b;try{p=hg(d.value)}catch(E){b=E.message}if(b!==void 0||p===void 0){u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({valid:!1,checks:[],error:b}));return}let x=E=>Buffer.from(E,"base64").length,S=[{label:"Version",expected:String(zc),actual:String(p.v),pass:p.v===zc},{label:"Algorithm",expected:Lc,actual:p.alg,pass:p.alg===Lc},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(x(p.k))} bytes`,pass:x(p.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(x(p.iv))} bytes`,pass:x(p.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(x(p.tag))} bytes`,pass:x(p.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(x(p.ct))} bytes`,pass:x(p.ct)>=1}];u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({valid:S.every(E=>E.pass),checks:S}));return}if(w.startsWith("/api/wizard")){let l=f.headers["x-encryption-target"],p=(Array.isArray(l)?l[0]:l)==="dev"?"dev":"prod",b=en(p);if(!kg(b)){u.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:`Encryption API host is not allowed: ${b}`}));return}let x=w.slice(11)||"/",S=`${b}${x}`,E=f.method??"GET",$=[];for await(let tt of f)$.push(tt);let{host:M,"x-encryption-target":ee,...ce}=f.headers,be=$.length>0?Buffer.concat($):void 0,we=be&&be.length>0?be:void 0,me;try{me=await fetch(S,{method:E,headers:ce,...we!==void 0&&{body:we}})}catch(tt){let wr=tt.code==="ECONNREFUSED"?`plugin-wizard is not running at ${b}`:`Failed to reach plugin-wizard: ${tt.message}`;u.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:wr}));return}let pe=ar(Object.fromEntries(me.headers)),Pt=await me.arrayBuffer();u.writeHead(me.status,pe),u.end(Buffer.from(Pt));return}if(w.startsWith("/api/proxy")){let l=f.headers["x-proxy-target"];if(typeof l!="string"){u.writeHead(400),u.end("Missing x-proxy-target header");return}if(!Cg(l)){u.writeHead(400),u.end("Invalid proxy target");return}let d=w.slice(10)||"/",p=`${l}${d}`,b=f.method??"GET",x=[];for await(let me of f)x.push(me);let{host:S,"x-proxy-target":E,...$}=f.headers;if(b==="GET"){let me=`GET::${p}`,{response:pe,fromCache:Pt}=await h.get(me,()=>fetch(p,{method:"GET",headers:$}));n({kind:"request",method:"GET",status:pe.status,upstreamStatus:Hc(d,pe.headers,pe.body),fromCache:Pt,url:d}),u.writeHead(pe.status,pe.headers),u.end(pe.body);return}let M=x.length>0?Buffer.concat(x):void 0,ee=M&&M.length>0?M:void 0,ce=await fetch(p,{method:b,headers:$,...ee!==void 0&&{body:ee}}),be=ar(Object.fromEntries(ce.headers)),we=await Jo(ce,Go);n({kind:"request",method:b,status:ce.status,upstreamStatus:Hc(d,be,we),fromCache:!1,url:d}),u.writeHead(ce.status,be),u.end(we);return}if(w.startsWith("/api/source/tree")&&f.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"",p=await Mc(y,d);if(p===null){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Invalid path"}));return}if(Uc(y,p)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await cg(p,{withFileTypes:!0}),x=await Promise.all(b.filter(E=>E.isDirectory()?!Rn.has(E.name):E.isFile()?!vg.has(E.name):!1).map(async E=>{let $=E.isDirectory()?"dir":"file",M={name:E.name,kind:$};if($==="file")try{let ee=await Fc(rn(p,E.name));M.size=ee.size}catch{}return M}));x.sort((E,$)=>E.kind!==$.kind?E.kind==="dir"?-1:1:E.name.localeCompare($.name));let S=p===y?"":p.slice(y.length+1);u.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({path:S,entries:x}))}catch(b){let x=b instanceof Error?b.message:String(b);t(`source/tree failed (${d}): ${x}`),u.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not found"}))}return}if(w.startsWith("/api/source/file")&&f.method==="GET"){let d=new URL(w,"http://localhost").searchParams.get("path")??"";if(d===""){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Missing path"}));return}let p=await Mc(y,d);if(p===null){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Invalid path"}));return}if(Uc(y,p)){u.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Path is excluded"}));return}try{let b=await Fc(p);if(!b.isFile()){u.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not a file"}));return}if(b.size>wg){u.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"File too large",size:b.size}));return}let x=jc(p).toLowerCase(),S=Yo[x],E=Oc.has(x),$=S??(E?"text/plain; charset=utf-8":"application/octet-stream");u.writeHead(200,{"Content-Type":$,"Content-Length":String(b.size)}),Bc(p).pipe(u)}catch(b){let x=b instanceof Error?b.message:String(b);t(`source/file failed (${d}): ${x}`),u.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:"Not found"}))}return}let P=rn(e,w==="/"?"/index.html":w),C=await ni(P)?P:rn(e,"index.html"),T=jc(C),v=Yo[T]??"application/octet-stream";u.writeHead(200,{"Content-Type":v}),Bc(C).pipe(u)}catch(k){if(w.startsWith("/api/proxy")){let _=w.slice(10)||"/",P=f.method??"GET";k instanceof Qt?n({kind:"info",message:`${P} ${_} \u2192 502 (response exceeded ${String(k.limit)} bytes)`}):n({kind:"request",method:P,status:502,fromCache:!1,url:_})}else n({kind:"info",message:`Error handling ${w}: ${k instanceof Error?k.message:String(k)}`});u.headersSent||(u.writeHead(502),u.end("Bad Gateway"))}})()}}import{launch as Pg}from"chrome-launcher";import{createRequire as Eg}from"module";import{mkdirSync as _g}from"fs";import{readFile as Ag}from"fs/promises";import{dirname as Tg,join as Ig}from"path";import{fileURLToPath as $g}from"url";var qc=Eg(import.meta.url)("chrome-remote-interface"),Ng=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Jc=["kizen.dev","kizen.com"];function Gc(e){try{let{hostname:t}=new URL(e);return Jc.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function Dg(e){try{let t=Ig(Tg($g(import.meta.url)),"viewer","icon.png"),n=await Ag(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function Yc(e){_g(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await Pg({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,o=null,i=null,s=null,a=null,c=0,g=!1,m=C=>{e.debugLog?.(C)},h=C=>{e.verbose&&e.debugLog?.(C)},y=()=>{i!==null&&(clearInterval(i),i=null)},f=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",u=async C=>{y(),s=null,await Dg(C),await C.Fetch.enable({patterns:Jc.flatMap(v=>[{urlPattern:`*://${v}/*`,requestStage:"Response"},{urlPattern:`*://*.${v}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",v=>{(async()=>{let l=v,{requestId:d,request:p,responseHeaders:b,responseStatusCode:x}=l,S=p.url;h(`Fetch ${String(x??"?")} ${S}`);let E=[],$=!1;for(let M of b??[])if(!Ng.has(M.name.toLowerCase()))if(M.name.toLowerCase()==="set-cookie"&&Gc(S)){let ee=M.value.split(`
|
|
1200
|
-
`).map(
|
|
1201
|
-
`);E.push({name:M.name,value:ee}),$=!0}else E.push(M);$&&h(` rewrote Set-Cookie SameSite on ${S}`);try{let{body:M,base64Encoded:ee}=await C.Fetch.getResponseBody({requestId:d});await C.Fetch.fulfillRequest({requestId:d,responseCode:x??200,responseHeaders:E,body:M,...ee&&{base64Encoded:!0}})}catch(M){h(` fulfillRequest failed (${M.message}), falling through`);try{await C.Fetch.continueRequest({requestId:d})}catch(ee){h(` continueRequest also failed (${ee.message})`)}}})()}),i=setInterval(()=>{(async()=>{try{let{cookies:v}=await C.Network.getAllCookies(),l=0;for(let d of v){if(!Gc(`https://${d.domain??""}`)||d.sameSite==="None")continue;let p=d.domain??"",b=p.startsWith(".")?p.slice(1):p;await C.Network.setCookie({url:`https://${b}`,name:d.name,value:d.value,domain:p,path:d.path??"/",secure:!0,...d.httpOnly!==void 0&&{httpOnly:d.httpOnly},...d.expirationDate!==void 0&&{expires:d.expirationDate},sameSite:"None"}),l++}l>0&&h(`cookie-patch cycle: updated ${String(l)} cookie(s) to SameSite=None`)}catch(v){h(`cookie-patch cycle failed: ${v.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let T=v=>{if(v.type==="page"){if(f(v.url)){m(`closed stray new-tab-page target ${v.targetId}`),s!==null&&C.Target.activateTarget({targetId:s}).catch(()=>{}),C.Target.closeTarget({targetId:v.targetId}).catch(()=>{});return}s===null&&(s=v.targetId,m(`captured main target ${v.targetId} (${v.url})`))}};C.on("Target.targetCreated",v=>{let{targetInfo:l}=v;h(`target +${l.type} ${l.targetId} ${l.url}`),T(l)}),C.on("Target.targetInfoChanged",v=>{let{targetInfo:l}=v;h(`target ~${l.type} ${l.targetId} ${l.url}`),T(l)}),C.on("disconnect",()=>{g||o!==C||(m("CDP disconnected"),o=null,y(),w())})},w=()=>{if(g||a!==null)return;let C=Math.min(1e3*2**c,1e4),T=c+1;c++,m(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(T)})`),a=setTimeout(()=>{a=null,(async()=>{let v;try{v=await qc({port:r})}catch{m(`CDP reconnect attempt #${String(T)} failed`),w();return}if(g){try{await v.close()}catch{}return}o=v;try{await u(v),m(`CDP reconnected after ${String(T)} attempt(s)`),c=0}catch{o===v&&(o=null);try{await v.close()}catch{}m(`CDP reconnect attempt #${String(T)} failed during setup`),w()}})()},C)},k=30,_=300;for(let C=0;C<k;C++){await new Promise(T=>setTimeout(T,_)),m(`CDP connect attempt ${String(C+1)}/${String(k)}`);try{let T=await qc({port:r});o=T,e.path&&T.send("Page.navigate",{url:`${t}${e.path}`});try{await u(T),m("CDP connected")}catch{o===T&&(o=null);try{await T.close()}catch{}m("CDP setup failed after connect")}break}catch{if(C===k-1){let T=`CDP unavailable after ${String(k)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return m(T),e.onWarn?.(T),{kill:()=>{n.kill()}}}}}return o?{kill:()=>{if(m("CDP kill requested \u2014 tearing down"),g=!0,a!==null&&(clearTimeout(a),a=null),y(),o!==null){try{o.close()}catch{}o=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as Rg,useState as Og}from"react";function lr(e){let[t,n]=Og([]),r=Rg(o=>{n(i=>[...i,`${new Date().toLocaleTimeString()}: ${o}`].slice(-e))},[e]);return[t,r]}import{useCallback as dr,useEffect as ri,useState as ur}from"react";import{Box as Q,Text as z,useInput as Bg}from"ink";import{jsx as D,jsxs as te}from"react/jsx-runtime";var Qe=["apiKey","userId","businessId"],Fg={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},on=({text:e})=>D(z,{dimColor:!0,children:e}),pr=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[o,i]=ur(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=ur(""),[c,g]=ur(null),[m,h]=ur(void 0),y=dr(v=>{if(v==="local"){n({mode:"local",credentials:null});return}i({type:"profile-loading"})},[n]),f=dr(async v=>{if(v===null){i({type:"profile-loading"});let p=await We();i({type:"name-entry",nameBuffer:"",existingProfiles:p});return}h(v.isDefault?void 0:v.name),i({type:"loading"});let l=v.isDefault?await se():await Ie(v.name),d=l?Math.max(0,W.indexOf(l.environment)):0;i({type:"creds-entry",field:0,values:l??{},envCursor:d})},[]),u=dr(async(v,l)=>{let d=W[l]??"go",p={...Nt(v),environment:d};i({type:"saving"});try{await Ti(m??Ke,p),n({mode:"global",credentials:p,...m!==void 0&&{profileName:m}})}catch(b){g(b instanceof Error?b.message:String(b)),i({type:"creds-entry",field:0,values:v,envCursor:l})}},[n,m]);Bg((v,l)=>{if(l.ctrl&&v==="c"&&process.exit(0),l.escape){if((o.type==="creds-entry"||o.type==="name-entry")&&e==="global"&&t){i({type:"profile-loading"}),w();return}r?.();return}if(o.type==="mode-select"){if(l.upArrow)i({type:"mode-select",cursor:0});else if(l.downArrow)i({type:"mode-select",cursor:1});else if(l.return){let d=o.cursor===0?"global":"local";y(d)}return}if(o.type==="profile-select"){let{profiles:d,cursor:p}=o,b=d.length,x=d.length+1;if(l.upArrow)i({...o,cursor:(p-1+x)%x});else if(l.downArrow)i({...o,cursor:(p+1)%x});else if(l.return)if(p===b)i({type:"name-entry",nameBuffer:"",existingProfiles:d});else{let S=d[p]??d[0];S&&f(S)}return}if(o.type==="name-entry"){let{nameBuffer:d,existingProfiles:p}=o;if(l.backspace||l.delete)i({type:"name-entry",nameBuffer:d.slice(0,-1),existingProfiles:p});else if(l.return){let b=d.trim();if(!b){i({...o,nameError:"Name cannot be empty"});return}if(b===Ke){i({...o,nameError:`"${Ke}" is reserved`});return}if(p.some(x=>x.name===b)){i({...o,nameError:`Profile "${b}" already exists`});return}h(b),i({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else v&&!l.ctrl&&!l.meta&&i({type:"name-entry",nameBuffer:d+v,existingProfiles:p});return}if(o.type==="creds-entry"){let{field:d,values:p,envCursor:b}=o;if(d===Qe.length){l.leftArrow?i({...o,envCursor:(b-1+W.length)%W.length}):l.rightArrow?i({...o,envCursor:(b+1)%W.length}):l.upArrow?(i({...o,field:d-1}),a(p[Qe[d-1]]??"")):l.return&&u(p,b);return}let S=Qe[d];if(!S)return;if(l.backspace||l.delete)a(E=>E.slice(0,-1));else if(l.upArrow&&d>0){let E={...p,[S]:s},$=d-1;i({...o,field:$,values:E}),a(E[Qe[$]]??"")}else if(l.return||l.tab||l.downArrow){let E={...p,[S]:s},$=d+1;i({...o,field:$,values:E}),$<Qe.length?a(E[Qe[$]]??""):a("")}else v&&!l.ctrl&&!l.meta&&a(E=>E+v)}});let w=dr(async()=>{let v=await We();i({type:"profile-select",profiles:v,cursor:0})},[]);if(ri(()=>{o.type==="profile-loading"&&w()},[o.type,w]),ri(()=>{e==="global"&&!t&&(async()=>{let v=await se(),l=v?Math.max(0,W.indexOf(v.environment)):0;i({type:"creds-entry",field:0,values:v??{},envCursor:l})})()},[]),ri(()=>{o.type==="creds-entry"&&o.field===0&&a(o.values.apiKey??"")},[o.type]),o.type==="loading"||o.type==="saving"||o.type==="profile-loading"){let v=o.type==="saving"?"Saving credentials\u2026":o.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return D(Q,{paddingY:1,paddingX:2,children:D(z,{dimColor:!0,children:v})})}if(o.type==="done")return null;if(o.type==="mode-select")return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{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((l,d)=>{let p=o.cursor===d;return te(Q,{gap:2,children:[D(z,{...p&&{color:"cyan"},children:p?"\u276F":" "}),D(z,{bold:p,...p&&{color:"cyan"},children:l.label}),D(z,{dimColor:!0,children:l.desc})]},l.mode)})]}),D(on,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(o.type==="profile-select"){let{profiles:v,cursor:l}=o,d=v.length;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:"Credential profiles"}),v.map((p,b)=>{let x=l===b;return te(Q,{gap:2,children:[D(z,{...x&&{color:"cyan"},children:x?"\u276F":" "}),D(z,{bold:x,...x&&{color:"cyan"},children:p.isDefault?"Default":p.name}),D(z,{dimColor:!0,children:p.path})]},p.name)}),te(Q,{gap:2,children:[D(z,{...l===d&&{color:"cyan"},children:l===d?"\u276F":" "}),D(z,{bold:l===d,...l===d&&{color:"cyan"},children:"+ Add new profile"})]})]}),D(on,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(o.type==="name-entry"){let{nameBuffer:v,nameError:l}=o;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),D(Q,{flexDirection:"column",gap:0,children:D(z,{bold:!0,children:"New credential profile"})}),l&&te(z,{color:"red",children:["Error: ",l]}),te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:!0,color:"cyan",children:"Profile name"})}),D(z,{color:"cyan",children:">"}),D(z,{children:v}),D(z,{color:"cyan",children:"\u2588"})]}),D(on,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:k,values:_,envCursor:P}=o,C=k===Qe.length,T=m??Ke;return te(Q,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[D(G,{}),te(Q,{flexDirection:"column",gap:0,children:[D(z,{bold:!0,children:m!==void 0?`Profile: ${m}`:"Global credentials"}),te(z,{dimColor:!0,children:["Saved to:"," ",m!==void 0?`~/.kizenappbuilder/${m}.json`:He]})]}),c&&te(z,{color:"red",children:["Error: ",c]}),te(Q,{flexDirection:"column",gap:0,children:[Qe.map((v,l)=>{let d=k===l,p=d?s:_[v]??"";return te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:d,...d&&{color:"cyan"},children:Fg[v]})}),D(z,{...d&&{color:"cyan"},children:">"}),D(z,{children:p}),d&&D(z,{color:"cyan",children:"\u2588"})]},v)}),te(Q,{gap:2,children:[D(Q,{width:12,children:D(z,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),D(z,{...C&&{color:"cyan"},children:">"}),D(Q,{gap:1,children:W.map((v,l)=>{let d=l===P;return C?D(z,{bold:d,...d&&{color:"cyan"},children:d?`[${v}]`:v},v):D(z,{dimColor:!d,bold:d,children:v},v)})})]})]}),C?D(on,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):D(on,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),te(z,{dimColor:!0,children:["Profile: ",T]})]})};import{jsx as j,jsxs as X}from"react/jsx-runtime";var Kg=[".kizenapp",".git"],Zc=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:o,activeCredentialProfile:i,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:g=!0,cacheEnabled:m=!0})=>{let h=Be(r),y=Be(i),f=Be(s),[u,w]=ue("main"),[k,_]=ue(o),[P,C]=ue("starting"),[T,v]=ue(null),[l,d]=lr(50),[p,b]=lr(50),[x,S]=lr(50),[E,$]=ue([]),[M,ee]=ue("pending"),[ce,be]=ue(null),[we,me]=ue(null),[pe,Pt]=ue(null),[tt,wr]=ue(null),[vr,xr]=ue(0),[ai,jl]=ue(0),[Ll,zl]=ue(0),[kr,Ml]=ue(0),Cr=Be(!1),ci=Be(!1),an=Be(null),Et=Be(null),Fe=Be(new Set),cn=Be([]),he=St(A=>{let H=JSON.stringify(A);if(Fe.current.size===0){cn.current=[...cn.current,H].slice(-50);return}let je=!1;for(let ve of Fe.current)if(ve.readyState===1)try{ve.send(H)}catch{Fe.current.delete(ve),je=!0}je&&xr(Fe.current.size)},[]),ln=d,Sr=St(()=>{an.current?.kill(),an.current=null,Yc({port:e,userDataDir:Xc(n,".chrome"),broadcast:he,onWarn:A=>{d(`\u26A0 ${A}`)},...f.current!==void 0&&{path:f.current},...a&&{debugLog:S},...c&&{verbose:!0}}).then(A=>{an.current=A})},[e,n,he,a,c,S,d]);fr(()=>{let A=()=>{an.current?.kill()};return process.on("exit",A),()=>{process.off("exit",A)}},[]),Lg((A,H)=>{(A==="q"||H.ctrl&&A==="c")&&process.exit(0),A==="c"&&w("editing"),A==="v"&&Sr()},{isActive:u==="main"}),fr(()=>{P!=="running"||ci.current||!g||(ci.current=!0,Sr())},[P,g,Sr]);let Ul=St(A=>{h.current=A.credentials,y.current=A.profileName,w("main"),_(A.mode);let H=A.profileName;Je(n,{credentialMode:A.mode,...H!==void 0&&{activeCredentialProfile:H}}),he({type:"credentials-updated",credentials:A.credentials})},[n,he]),li=St(A=>{$(H=>[...H,`${new Date().toLocaleTimeString()}: ${ei(A)}`].slice(-50)),A.kind==="request"&&(A.fromCache?zl(H=>H+1):Ml(H=>H+1)),he({type:"proxy-log",entry:A})},[he]),nt=St(A=>{b(A),he({type:"log",message:A})},[b,he]),Pr=St(()=>{Cr.current||(Cr.current=!0,ee("building"),be(null),me(null),nt("Build started"),Bn(t,n).then(({bundleSize:A})=>{nt(`Build finished \u2014 bundle: ${Gt(A)}`),ee("done"),Pt(new Date),wr(A),nt("Notifying viewers to reload"),he({type:"rebuild"})}).catch(A=>{A instanceof zg?(me(A.issues),be(null)):(be(A instanceof Error?A.message:String(A)),me(null)),ee("error")}).finally(()=>{Cr.current=!1}))},[t,n,nt,he]);if(fr(()=>{Pr();let A=Mg(t,{recursive:!0},(H,je)=>{if(!je)return;let ve=je.replace(/\\/g,"/");Kg.some(dn=>ve.startsWith(dn))||(nt(`File change detected: ${je}`),Et.current!==null&&clearTimeout(Et.current),Et.current=setTimeout(Pr,150))});return A.on("error",H=>{nt(`File watcher error \u2014 rebuilds have stopped: ${H.message}`)}),()=>{A.close(),Et.current!==null&&clearTimeout(Et.current)}},[t,Pr,nt]),fr(()=>{let A=Vc();ni(Xc(A,"index.html")).then(H=>{if(!H){v("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let je=Wc(A,ln,li,h,y,n,he,jl,f,t,m),ve=Ug(je),dn=new Hg({server:ve});return dn.on("connection",rt=>{for(let Kl of cn.current)rt.readyState===1&&rt.send(Kl);cn.current=[],ln("Viewer connected for live reload"),Fe.current.add(rt),xr(Fe.current.size),rt.on("close",()=>{Fe.current.delete(rt),xr(Fe.current.size)})}),ve.listen(e,"127.0.0.1",()=>{C("running"),ln(`Server started on 127.0.0.1:${String(e)}`)}),ve.on("error",rt=>{v(rt.message),C("error")}),()=>{dn.close(),ve.close()}})},[e,ln,li,he,n,t,m]),u==="editing")return j(pr,{...k!==void 0&&{initialMode:k},showProfileManager:k==="global",onComplete:Ul,onCancel:()=>{w("main")}});let Er=pe!==null?Math.round((Date.now()-pe.getTime())/1e3):null,Hl=Er===null?"":Er<5?" (just now)":` (${String(Er)}s ago)`,di=we?.filter(A=>A.severity==="error").length??0;return X(ne,{flexDirection:"column",paddingY:1,paddingX:2,children:[j(G,{marginBottom:1}),X(ne,{flexDirection:"column",children:[X(ne,{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"&&X(ne,{gap:1,children:[j(Ee,{}),j(F,{children:"Building plugin package\u2026"})]}),M==="done"&&X(ne,{gap:1,children:[j(F,{color:"green",children:"\u2713 Built"}),pe!==null&&X(F,{dimColor:!0,children:["at ",pe.toLocaleTimeString(),Hl]}),tt!==null&&X(F,{dimColor:!0,children:["\xB7 bundle: ",Gt(tt)]})]}),M==="error"&&(we!==null?X(F,{color:"red",children:["\u2717 ",di," validation ",di===1?"error":"errors"]}):X(F,{color:"red",children:["\u2717 ",ce??"unknown error"]}))]}),we!==null&&j(Xn,{issues:we}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:p.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Web Server"}),P==="starting"&&j(F,{dimColor:!0,children:"starting\u2026"}),P==="running"&&X(ne,{gap:2,children:[j(F,{color:"green",children:"\u2713 Running"}),X(F,{dimColor:!0,children:["\u25CF ",vr," viewer",vr!==1?"s":""]})]}),P==="error"&&X(F,{color:"red",children:["\u2717 ",T??"Server error"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:l.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"Network Proxy"}),j(F,{color:"green",children:"\u2713 Active"}),j(F,{dimColor:!0,children:m?`\u25CF ${String(ai)} key${ai!==1?"s":""} in the network cache \xB7 ${String(Ll)} hit \xB7 ${String(kr)} miss`:`\u25CF network cache disabled \xB7 ${String(kr)} request${kr!==1?"s":""}`})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:E.length===0?j(F,{dimColor:!0,children:" No requests yet."}):E.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),a&&X(ne,{marginTop:1,flexDirection:"column",children:[X(ne,{gap:2,children:[j(F,{bold:!0,dimColor:!0,children:"CDP Debug"}),X(F,{dimColor:!0,children:["\u25CF ",x.length," event(s)"]})]}),j(ne,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:x.length===0?j(F,{dimColor:!0,children:" No CDP events yet."}):x.slice(-8).map((A,H)=>j(F,{dimColor:!0,wrap:"truncate",children:A},H))})]}),X(ne,{marginTop:1,gap:1,children:[j(F,{dimColor:!0,children:"["}),j(F,{children:"q"}),j(F,{dimColor:!0,children:"] quit ["}),j(F,{children:"c"}),j(F,{dimColor:!0,children:"] credentials ["}),j(F,{children:"v"}),X(F,{dimColor:!0,children:["] ",vr===0?"open viewer":"relaunch viewer"]})]})]})};async function Qc(e){return new Promise(t=>{let n=null,r=i=>{n?.(),t(i)},{unmount:o}=tl(el(pr,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=o})}function nl(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let n=parseInt(t.port,10),r=process.cwd(),o=`${r}/.kizenapp`;Pe(r);let i=null,s,a,{lastPath:c}=await Se(o);if(t.credentials)i=await Ve(t.credentials);else{let u=await Se(o);if(u.credentialMode==="local")s="local";else if(u.credentialMode==="global"){if(s="global",a=u.activeCredentialProfile,a?(i=await Ie(a),i||(i=await se(),a=void 0)):i=await se(),!i){let w=await Qc("global");i=w.credentials,a=w.profileName}}else{let w=await Qc();i=w.credentials,s=w.mode,a=w.profileName;let k=w.profileName;await Je(o,{credentialMode:w.mode,...k!==void 0&&{activeCredentialProfile:k}})}}let g=t.verbose===!0,m=g||t.debug===!0,h=t.viewer!==!1,y=t.cache!==!1,{waitUntilExit:f}=tl(el(Zc,{port:n,pluginDir:r,outputDir:o,credentials:i,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:m,verbose:g,autoViewer:h,cacheEnabled:y}),{exitOnCtrlC:!1});await f()})}import{createElement as ry}from"react";import{render as oy}from"ink";import{useCallback as hr,useEffect as sl,useState as gr}from"react";import{Box as _e,Text as U,useApp as Xg,useInput as Zg}from"ink";import{encrypt as Vg,serializeEnvelope as Wg}from"@kizenapps/packager";function qg(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function rl(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 ol(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(qg(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${pn()==="unavailable"?` ${un}`:""}`)}}async function il(e){let t=await e.text();if(t==="")return{};try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function Gg(e,t,n){let r=en(e.stage),o=await ol(r,"/get-public-key",{method:"POST",headers:rl(t),body:JSON.stringify({api_name:n})}),i=await il(o);if(!o.ok||typeof i.public_key!="string"){let s=typeof i.error=="string"?i.error:`HTTP ${String(o.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return i.public_key}function Jg(e,t){let n=Vg(t,e),r=Wg(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function Yg(e,t,n,r){let o=en(e.stage),i=await ol(o,"/encrypt",{method:"POST",headers:rl(t),body:JSON.stringify({api_name:n,value:r})}),s=await il(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 mr(e,t,n,r,o){if(e.isRemote)return o?.("encrypting"),Yg(e,t,n,r);o?.("fetching-key");let i=await Gg(e,t,n);return o?.("encrypting"),Jg(i,r)}import{Fragment as yr,jsx as L,jsxs as re}from"react/jsx-runtime";var oi=({text:e})=>L(U,{dimColor:!0,children:e}),al=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:o,initialValue:i,onDone:s})=>{let a=Xg(),[c,g]=gr({type:"loading"}),[m,h]=gr(null),[y,f]=gr(r??""),[u,w]=gr(i??""),k=hr(d=>{process.exitCode=1,g({type:"error",message:d instanceof Error?d.message:String(d)})},[]),_=hr(async(d,p,b)=>{try{let x=await mr(e,d,p,b,$=>{g($==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),S=JSON.stringify({encrypted:!0,value:x},null,2);s?.(x);let E=await In(S);g({type:"done",envelope:S,copied:E})}catch(x){k(x)}},[e,k,s]),P=hr((d,p,b)=>{if(p.trim()===""){g({type:"api-name-entry",buffer:o??""});return}if(b===""){g({type:"value-entry",buffer:""});return}_(d,p.trim(),b)},[o,_]),C=hr(async d=>{try{g({type:"loading"});let p=d.isDefault?await se():await Ie(d.name);if(p===null)throw new Error(`Could not load credential profile: ${d.name}`);h(p),P(p,y,u)}catch(p){k(p)}},[y,u,P,k]);sl(()=>{(async()=>{try{if(n!==void 0){let b;try{b=await Ve(n)}catch(x){throw new Error(`Could not load credentials from ${n}: ${x instanceof Error?x.message:String(x)}`)}h(b),P(b,y,u);return}let d=await We();if(d.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[p]=d;if(d.length===1&&p!==void 0){let b=p.isDefault?await se():await Ie(p.name);if(b===null)throw new Error(`Could not load credential profile: ${p.name}`);h(b),P(b,y,u);return}g({type:"profile-select",profiles:d,cursor:0})}catch(d){k(d)}})()},[]),sl(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),Zg((d,p)=>{if(p.ctrl&&d==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:b,cursor:x}=c;if(p.upArrow)g({...c,cursor:(x-1+b.length)%b.length});else if(p.downArrow)g({...c,cursor:(x+1)%b.length});else if(p.return){let S=b[x];S!==void 0&&C(S)}return}if(c.type==="api-name-entry"){let{buffer:b}=c;if(p.backspace||p.delete)g({type:"api-name-entry",buffer:b.slice(0,-1)});else if(p.return){let x=b.trim();if(x===""){g({type:"api-name-entry",buffer:b,error:"api_name cannot be empty"});return}f(x),m?P(m,x,u):k(new Error("Internal error: credentials were not loaded"))}else d&&!p.ctrl&&!p.meta&&g({type:"api-name-entry",buffer:b+d});return}if(c.type==="value-entry"){let{buffer:b}=c;if(p.backspace||p.delete)g({type:"value-entry",buffer:b.slice(0,-1)});else if(p.return){if(b===""){g({type:"value-entry",buffer:b,error:"secret cannot be empty"});return}w(b),m?P(m,y,b):k(new Error("Internal error: credentials were not loaded"))}else d&&!p.ctrl&&!p.meta&&g({type:"value-entry",buffer:b+d});return}});let T=e.isRemote?"remote Kizen API":"on-machine",v=t===!0?`${e.stage} (default)`:e.stage,l=d=>re(_e,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[L(G,{}),re(U,{dimColor:!0,children:["Mode: ",T," Stage: ",v]}),d]});if(c.type==="loading")return l(re(_e,{gap:1,children:[L(Ee,{}),L(U,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:d,cursor:p}=c;return l(re(yr,{children:[L(U,{bold:!0,children:"Credential profile"}),L(_e,{flexDirection:"column",children:d.map((b,x)=>{let S=p===x;return re(_e,{gap:2,children:[L(U,{...S&&{color:"cyan"},children:S?"\u276F":" "}),L(U,{bold:S,...S&&{color:"cyan"},children:b.isDefault?"Default":b.name}),L(U,{dimColor:!0,children:b.path})]},b.name)})}),L(oi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?l(re(yr,{children:[L(U,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(_e,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:c.buffer}),L(U,{color:"cyan",children:"\u2588"})]}),L(oi,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?l(re(yr,{children:[L(U,{bold:!0,children:"Secret value"}),c.error!==void 0&&re(U,{color:"red",children:["Error: ",c.error]}),re(_e,{gap:1,children:[L(U,{color:"cyan",children:">"}),L(U,{children:"\u2022".repeat(c.buffer.length)}),L(U,{color:"cyan",children:"\u2588"})]}),L(oi,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?l(re(_e,{gap:1,children:[L(Ee,{}),re(U,{children:["Fetching ",e.stage," public key for ",L(U,{bold:!0,children:y}),"\u2026"]})]})):c.type==="encrypting"?l(re(_e,{gap:1,children:[L(Ee,{}),L(U,{children:"Encrypting\u2026"})]})):c.type==="error"?l(re(_e,{gap:1,children:[L(U,{color:"red",children:"\u2717"}),L(U,{color:"red",children:c.message})]})):l(re(yr,{children:[re(_e,{gap:1,children:[L(U,{color:"green",children:"\u2713"}),L(U,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?L(U,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):L(U,{dimColor:!0,children:"Paste this into the secret value in your kizen.json (re-run with --out <path> to save it to a file; selecting it here may capture line wraps):"}),L(U,{children:c.envelope})]}))};import{readFile as Qg,writeFile as ey}from"fs/promises";import{join as ty}from"path";function cl(e){return{encrypted:!0,value:e}}function ll(e){return JSON.stringify(cl(e))}async function ii(e,t){await ey(e,`${JSON.stringify(cl(t),null,2)}
|
|
1202
|
-
`,"utf-8")}var
|
|
1203
|
-
`}async function
|
|
1204
|
-
`),a=
|
|
1205
|
-
`),t.out!==void 0)try{await
|
|
1206
|
-
`)}catch(
|
|
1207
|
-
`),
|
|
1208
|
-
`)}catch(
|
|
1209
|
-
${
|
|
1210
|
-
`)}var
|
|
1215
|
+
`.trim(),VS=3e4,vs=gi(process.cwd(),".kizenapp","venv"),HS=MS.map(kg),Ag=Ru(hg);if(Ag.length===0)throw new Error("python-requirements.txt bundled no packages \u2014 check the build output");var fi=null;function wg(e,t,n){return new Promise((r,i)=>{let o=vg(e,t,{stdio:["ignore","pipe","pipe"]}),s=(c,l)=>{let d=[],u="";return c.on("data",f=>{u+=f.toString("utf-8");let g=u.indexOf(`
|
|
1216
|
+
`);for(;g>=0;){let m=u.slice(0,g).replace(/\r$/,"");u=u.slice(g+1),d.push(m),n?.(m,l),g=u.indexOf(`
|
|
1217
|
+
`)}}),c.on("end",()=>{if(u.length>0){let f=u.replace(/\r$/,"");d.push(f),n?.(f,l)}}),d},a=s(o.stderr,"stderr");s(o.stdout,"stdout"),o.on("error",i),o.on("close",c=>{if(c===0)r();else{let l=a.slice(-10).join(`
|
|
1218
|
+
`).trim(),d=l.length>0?`: ${l}`:"";i(new Error(`${e} exited with code ${String(c)}${d}`))}})})}var Pl=null;function KS(e,t){if(fi)return t&&Pl?.add(t),fi;let n=new Set;t&&n.add(t),Pl=n;let r=o=>{for(let s of n)s(o)},i=gi(vs,"bin","python");return fi=(async()=>{try{let o=!1;try{await FS(i);let s=await Oi(i);o=s!==null&&Gs(s,Ir)}catch{o=!1}if(!o){await Cl(vs,{recursive:!0,force:!0}).catch(()=>{});let s=await Ou(e);await wg(s,["-m","venv",vs])}return r({kind:"start"}),await wg(i,["-m","pip","install","--disable-pip-version-check",...Ag],(s,a)=>{r({kind:"log",line:s,stream:a})}),r({kind:"complete"}),i}catch(o){let s=o instanceof Error?o.message:String(o);throw r({kind:"error",message:s}),fi=null,await Cl(vs,{recursive:!0,force:!0}).catch(()=>{}),o}finally{Pl=null}})(),fi}function WS(e){let t="__KIZEN_RESULT_START__",n="__KIZEN_RESULT_END__",r=e.indexOf(t),i=e.indexOf(n);if(r===-1||i===-1)return{userStdout:e,result:null};let o=e.slice(0,r).trimEnd(),s=e.slice(r+t.length,i).trim();try{let a=JSON.parse(s);return{userStdout:o,result:a}}catch{return{userStdout:e,result:null}}}function GS(e){return{success:!1,outputValues:{},logs:[],stdout:"",stderr:"",error:e,exitCode:1,durationMs:0}}async function xg(e){let t=e.timeout??VS;if(!zS(e.scriptRuntime))return GS(`Unsupported runtime "${e.scriptRuntime}". Supported runtimes: ${HS.join(", ")}. Update the step's config.json "runtime" field (e.g. "python 3.13").`);let r=await KS(kg(e.scriptRuntime),e.onInstallProgress),i=Date.now(),o;try{o=await BS(gi(jS(),"kizen-step-"));let s=gi(o,"wrapper.py"),a=gi(o,"script.py");await Promise.all([bg(s,US,"utf-8"),bg(a,e.script,"utf-8")]);let c={...process.env,__KIZEN_INPUTS__:JSON.stringify(e.inputs),__KIZEN_SECRETS__:JSON.stringify(e.secrets),__KIZEN_SCRIPT_PATH__:a},{exitCode:l,stdout:d,stderr:u}=await new Promise(h=>{let b=[],y=[],C=!1,S=vg(r,[s],{env:c,cwd:o,stdio:["ignore","pipe","pipe"]}),x=setTimeout(()=>{S.kill("SIGKILL")},t);S.stdout.on("data",k=>{b.push(k)}),S.stderr.on("data",k=>{y.push(k)});let v=k=>{C||(C=!0,clearTimeout(x),h({exitCode:k??1,stdout:Buffer.concat(b).toString("utf-8"),stderr:Buffer.concat(y).toString("utf-8")}))};S.on("close",v),S.on("error",k=>{C||(C=!0,clearTimeout(x),h({exitCode:1,stdout:"",stderr:k.message}))})}),f=Date.now()-i,{userStdout:g,result:m}=WS(d);if(m){let h={success:m.success,outputValues:m.outputValues,logs:m.logs,stdout:g,stderr:u,exitCode:l,durationMs:f};return m.error!==null&&(h.error=m.error),m.httpRequests&&(h.httpRequests=m.httpRequests),h}let p={success:!1,outputValues:{},logs:[],stdout:g,stderr:u,exitCode:l,durationMs:f};return l!==0&&(p.error=`Process exited with code ${String(l)}`),p}finally{o&&Cl(o,{recursive:!0,force:!0})}}var Pg=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 Eg,CRYPTO_VERSION as Ig,DEFAULT_AUTOMATION_RUNTIME as n_,deserializeEnvelope as r_,encrypt as i_,scriptRuntimeToApiName as o_,serializeEnvelope as s_}from"@kizenapps/packager";function Sl(e){if(e.kind==="info")return e.message;let t=e.fromCache?" [cache]":"",n=e.upstreamStatus!==void 0?` (upstream ${String(e.upstreamStatus)})`:"";return`${e.method} ${e.url} \u2192 ${String(e.status)}${n}${t}`}var a_=2*1024*1024,c_=new Set([".DS_Store",".gitignore"]);function l_(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 $g=["kizen.com","kizen.dev"];function u_(e){let t;try{t=new URL(e)}catch{return!1}let n=t.hostname.toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="[::1]"?!0:t.protocol!=="https:"?!1:$g.some(r=>n===r||n.endsWith("."+r))}function d_(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!=="https:")return!1;let n=t.hostname.toLowerCase();return $g.some(r=>n===r||n.endsWith("."+r))}function p_(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 Tg(e,t){if(t.includes("\0"))return null;let n=t.replace(/^\/+/,""),r=e_(e,n);if(r!==e&&!r.startsWith(e+_l))return null;try{let i=await XS(r);return i!==e&&!i.startsWith(e+_l)?null:i}catch{return null}}function Ng(e,t){let n=t===e?"":t.slice(e.length+1);return n===""?!1:n.split(_l).some(i=>no.has(i))}function Og(){let e=t_(import.meta.url);return hi(QS(e),"viewer")}function Rg(e,t,n){if(e.includes("/external-integrations/proxy")&&t["content-type"]?.includes("application/json"))try{let r=JSON.parse(n.toString("utf8"));return typeof r.status_code=="number"?r.status_code:void 0}catch{return}}async function El(e){try{return await qS(e),!0}catch{return!1}}function Dg(e,t,n,r,i,o,s,a,c,l,d){let u=gg({onChange:a,enabled:d}),f=JS(l);return(g,m)=>{(async()=>{let p=g.url??"/";try{if(!l_(g.headers.host)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Forbidden"}));return}if((g.method==="POST"||g.method==="PATCH"||g.method==="DELETE")&&!p_(g.headers.origin)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Forbidden"}));return}if(t(`Received request: ${p}`),p==="/api/credentials"){m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({credentials:r.current??null,activeProfile:i.current??null}));return}if(p==="/api/credential-profiles"&&g.method==="GET"){let v=await Jt();m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({profiles:v,active:i.current}));return}if(p==="/api/credentials/switch"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let P=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}").profile,w=P===void 0||P===""?await De():await Ct(P);if(w!==null){r.current=w,i.current=P??void 0;let A=i.current,_=await ht(o);await nn(o,{..._,credentialMode:"global",...A!==void 0&&{activeCredentialProfile:A}}),s({type:"credentials-updated",credentials:w,activeProfile:i.current??null})}m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({ok:w!==null}));return}if(p==="/api/bundle"){let v=hi(process.cwd(),".kizenapp","bundle.json");try{let k=await ZS(v,"utf-8");m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(k)}catch{m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end("{}")}return}if(p==="/api/last-path"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.path=="string"){c.current=k.path;let P=await ht(o);await nn(o,{...P,lastPath:k.path})}m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/encryption-target"&&g.method==="GET"){let k=(await ht(o)).encryptionTarget==="dev"?"dev":"prod";m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({target:k}));return}if(p==="/api/encryption-target"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}"),P=k!==null&&typeof k=="object"?k:{};if(P.target!=="dev"&&P.target!=="prod"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"target must be one of: 'dev', 'prod'"}));return}let w=await ht(o);await nn(o,{...w,encryptionTarget:P.target}),m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/execute-step"&&g.method==="POST"){let v=[];for await(let A of g)v.push(A);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.script!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required field: script"}));return}let P={script:k.script,scriptRuntime:k.scriptRuntime??o_(n_),inputs:yg(k.inputs),secrets:k.secrets??{},onInstallProgress:A=>{A.kind==="start"?s({type:"venv-install-start"}):A.kind==="log"?s({type:"venv-install-log",line:A.line,stream:A.stream}):A.kind==="complete"?s({type:"venv-install-complete"}):s({type:"venv-install-error",message:A.message})}};typeof k.timeout=="number"&&k.timeout>0&&(P.timeout=Math.min(k.timeout,300*1e3));let w=await xg(P);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify(w));return}if(p==="/api/proxy-cache/clear"){u.clear(),n({kind:"info",message:"Proxy cache cleared"}),m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end('{"ok":true}');return}if(p==="/api/local/encrypt"&&g.method==="POST"){let v=[];for await(let P of g)v.push(P);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.publicKeyPem!="string"||typeof k.value!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required fields: publicKeyPem, value"}));return}try{let P=i_(k.value,k.publicKeyPem),w=s_(P);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify(w))}catch(P){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:P.message}))}return}if(p==="/api/local/validate"&&g.method==="POST"){let v=[];for await(let T of g)v.push(T);let k=JSON.parse(Buffer.concat(v).toString("utf-8")||"{}");if(typeof k.value!="string"){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing required field: value"}));return}let P,w;try{P=r_(k.value)}catch(T){w=T.message}if(w!==void 0||P===void 0){m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({valid:!1,checks:[],error:w}));return}let A=T=>Buffer.from(T,"base64").length,_=[{label:"Version",expected:String(Ig),actual:String(P.v),pass:P.v===Ig},{label:"Algorithm",expected:Eg,actual:P.alg,pass:P.alg===Eg},{label:"Wrapped key",expected:"384 bytes (RSA-3072)",actual:`${String(A(P.k))} bytes`,pass:A(P.k)===384},{label:"IV",expected:"12 bytes",actual:`${String(A(P.iv))} bytes`,pass:A(P.iv)===12},{label:"Auth tag",expected:"16 bytes",actual:`${String(A(P.tag))} bytes`,pass:A(P.tag)===16},{label:"Ciphertext",expected:"\u2265 1 byte",actual:`${String(A(P.ct))} bytes`,pass:A(P.ct)>=1}];m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({valid:_.every(T=>T.pass),checks:_}));return}if(p.startsWith("/api/wizard")){let v=g.headers["x-encryption-target"],P=(Array.isArray(v)?v[0]:v)==="dev"?"dev":"prod",w=mi(P);if(!u_(w)){m.writeHead(500,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:`Encryption API host is not allowed: ${w}`}));return}let A=p.slice(11)||"/",_=`${w}${A}`,T=g.method??"GET",L=[];for await(let ct of g)L.push(ct);let{host:$,"x-encryption-target":V,...X}=g.headers,ve=L.length>0?Buffer.concat(L):void 0,Re=ve&&ve.length>0?ve:void 0,$e;try{$e=await fetch(_,{method:T,headers:X,...Re!==void 0&&{body:Re}})}catch(ct){let mr=ct.code==="ECONNREFUSED"?`plugin-wizard is not running at ${w}`:`Failed to reach plugin-wizard: ${ct.message}`;m.writeHead(503,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:mr}));return}let Te=ws(Object.fromEntries($e.headers)),gn=await $e.arrayBuffer();m.writeHead($e.status,Te),m.end(Buffer.from(gn));return}if(p.startsWith("/api/proxy")){let v=g.headers["x-proxy-target"];if(typeof v!="string"){m.writeHead(400),m.end("Missing x-proxy-target header");return}if(!d_(v)){m.writeHead(400),m.end("Invalid proxy target");return}let k=p.slice(10)||"/",P=`${v}${k}`,w=g.method??"GET",A=[];for await(let $e of g)A.push($e);let{host:_,"x-proxy-target":T,...L}=g.headers;if(w==="GET"){let $e=`GET::${P}`,{response:Te,fromCache:gn}=await u.get($e,()=>fetch(P,{method:"GET",headers:L}));n({kind:"request",method:"GET",status:Te.status,upstreamStatus:Rg(k,Te.headers,Te.body),fromCache:gn,url:k}),m.writeHead(Te.status,Te.headers),m.end(Te.body);return}let $=A.length>0?Buffer.concat(A):void 0,V=$&&$.length>0?$:void 0,X=await fetch(P,{method:w,headers:L,...V!==void 0&&{body:V}}),ve=ws(Object.fromEntries(X.headers)),Re=await kl(X,vl);n({kind:"request",method:w,status:X.status,upstreamStatus:Rg(k,ve,Re),fromCache:!1,url:k}),m.writeHead(X.status,ve),m.end(Re);return}if(p.startsWith("/api/source/tree")&&g.method==="GET"){let k=new URL(p,"http://localhost").searchParams.get("path")??"",P=await Tg(f,k);if(P===null){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Invalid path"}));return}if(Ng(f,P)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await YS(P,{withFileTypes:!0}),A=await Promise.all(w.filter(T=>T.isDirectory()?!no.has(T.name):T.isFile()?!c_.has(T.name):!1).map(async T=>{let L=T.isDirectory()?"dir":"file",$={name:T.name,kind:L};if(L==="file")try{let V=await Sg(hi(P,T.name));$.size=V.size}catch{}return $}));A.sort((T,L)=>T.kind!==L.kind?T.kind==="dir"?-1:1:T.name.localeCompare(L.name));let _=P===f?"":P.slice(f.length+1);m.writeHead(200,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({path:_,entries:A}))}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/tree failed (${k}): ${A}`),m.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not found"}))}return}if(p.startsWith("/api/source/file")&&g.method==="GET"){let k=new URL(p,"http://localhost").searchParams.get("path")??"";if(k===""){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Missing path"}));return}let P=await Tg(f,k);if(P===null){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Invalid path"}));return}if(Ng(f,P)){m.writeHead(403,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Path is excluded"}));return}try{let w=await Sg(P);if(!w.isFile()){m.writeHead(400,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not a file"}));return}if(w.size>a_){m.writeHead(413,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"File too large",size:w.size}));return}let A=_g(P).toLowerCase(),_=Al[A],T=Pg.has(A),L=_??(T?"text/plain; charset=utf-8":"application/octet-stream");m.writeHead(200,{"Content-Type":L,"Content-Length":String(w.size)}),Cg(P).pipe(m)}catch(w){let A=w instanceof Error?w.message:String(w);t(`source/file failed (${k}): ${A}`),m.writeHead(404,{"Content-Type":"application/json; charset=utf-8"}),m.end(JSON.stringify({error:"Not found"}))}return}let y=hi(e,p==="/"?"/index.html":p),C=await El(y)?y:hi(e,"index.html"),S=_g(C),x=Al[S]??"application/octet-stream";m.writeHead(200,{"Content-Type":x}),Cg(C).pipe(m)}catch(h){if(p.startsWith("/api/proxy")){let b=p.slice(10)||"/",y=g.method??"GET";h instanceof pi?n({kind:"info",message:`${y} ${b} \u2192 502 (response exceeded ${String(h.limit)} bytes)`}):n({kind:"request",method:y,status:502,fromCache:!1,url:b})}else n({kind:"info",message:`Error handling ${p}: ${h instanceof Error?h.message:String(h)}`});m.headersSent||(m.writeHead(502),m.end("Bad Gateway"))}})()}}import{launch as m_}from"chrome-launcher";import{createRequire as f_}from"module";import{mkdirSync as g_}from"fs";import{readFile as h_}from"fs/promises";import{dirname as y_,join as b_}from"path";import{fileURLToPath as w_}from"url";var Lg=f_(import.meta.url)("chrome-remote-interface"),v_=new Set(["content-security-policy","content-security-policy-report-only","x-frame-options"]),Fg=["kizen.dev","kizen.com"];function Bg(e){try{let{hostname:t}=new URL(e);return Fg.some(n=>t===n||t.endsWith("."+n))}catch{return!1}}async function k_(e){try{let t=b_(y_(w_(import.meta.url)),"viewer","icon.png"),n=await h_(t);await e.Browser.setDockTile({image:n.toString("base64")})}catch{}}async function jg(e){g_(e.userDataDir,{recursive:!0});let t=`http://localhost:${String(e.port)}`,n=await m_({startingUrl:t,chromeFlags:[`--app=${t}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-features=DeviceBoundSessions"],userDataDir:e.userDataDir,handleSIGINT:!1,logLevel:"silent"}),r=n.port,i=null,o=null,s=null,a=null,c=0,l=!1,d=C=>{e.debugLog?.(C)},u=C=>{e.verbose&&e.debugLog?.(C)},f=()=>{o!==null&&(clearInterval(o),o=null)},g=C=>C==="chrome://new-tab-page/"||C==="chrome://newtab/",m=async C=>{f(),s=null,await k_(C),await C.Fetch.enable({patterns:Fg.flatMap(x=>[{urlPattern:`*://${x}/*`,requestStage:"Response"},{urlPattern:`*://*.${x}/*`,requestStage:"Response"}])}),C.on("Fetch.requestPaused",x=>{(async()=>{let v=x,{requestId:k,request:P,responseHeaders:w,responseStatusCode:A}=v,_=P.url;u(`Fetch ${String(A??"?")} ${_}`);let T=[],L=!1;for(let $ of w??[])if(!v_.has($.name.toLowerCase()))if($.name.toLowerCase()==="set-cookie"&&Bg(_)){let V=$.value.split(`
|
|
1219
|
+
`).map(X=>/SameSite=/i.test(X)?X.replace(/SameSite=\w+/i,"SameSite=None"):X+"; SameSite=None; Secure").join(`
|
|
1220
|
+
`);T.push({name:$.name,value:V}),L=!0}else T.push($);L&&u(` rewrote Set-Cookie SameSite on ${_}`);try{let{body:$,base64Encoded:V}=await C.Fetch.getResponseBody({requestId:k});await C.Fetch.fulfillRequest({requestId:k,responseCode:A??200,responseHeaders:T,body:$,...V&&{base64Encoded:!0}})}catch($){u(` fulfillRequest failed (${$.message}), falling through`);try{await C.Fetch.continueRequest({requestId:k})}catch(V){u(` continueRequest also failed (${V.message})`)}}})()}),o=setInterval(()=>{(async()=>{try{let{cookies:x}=await C.Network.getAllCookies(),v=0;for(let k of x){if(!Bg(`https://${k.domain??""}`)||k.sameSite==="None")continue;let P=k.domain??"",w=P.startsWith(".")?P.slice(1):P;await C.Network.setCookie({url:`https://${w}`,name:k.name,value:k.value,domain:P,path:k.path??"/",secure:!0,...k.httpOnly!==void 0&&{httpOnly:k.httpOnly},...k.expirationDate!==void 0&&{expires:k.expirationDate},sameSite:"None"}),v++}v>0&&u(`cookie-patch cycle: updated ${String(v)} cookie(s) to SameSite=None`)}catch(x){u(`cookie-patch cycle failed: ${x.message}`)}})()},2e3),await C.Target.setDiscoverTargets({discover:!0});let S=x=>{if(x.type==="page"){if(g(x.url)){d(`closed stray new-tab-page target ${x.targetId}`),s!==null&&C.Target.activateTarget({targetId:s}).catch(()=>{}),C.Target.closeTarget({targetId:x.targetId}).catch(()=>{});return}s===null&&(s=x.targetId,d(`captured main target ${x.targetId} (${x.url})`))}};C.on("Target.targetCreated",x=>{let{targetInfo:v}=x;u(`target +${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("Target.targetInfoChanged",x=>{let{targetInfo:v}=x;u(`target ~${v.type} ${v.targetId} ${v.url}`),S(v)}),C.on("disconnect",()=>{l||i!==C||(d("CDP disconnected"),i=null,f(),p())})},p=()=>{if(l||a!==null)return;let C=Math.min(1e3*2**c,1e4),S=c+1;c++,d(`CDP reconnect scheduled in ${String(C)}ms (attempt #${String(S)})`),a=setTimeout(()=>{a=null,(async()=>{let x;try{x=await Lg({port:r})}catch{d(`CDP reconnect attempt #${String(S)} failed`),p();return}if(l){try{await x.close()}catch{}return}i=x;try{await m(x),d(`CDP reconnected after ${String(S)} attempt(s)`),c=0}catch{i===x&&(i=null);try{await x.close()}catch{}d(`CDP reconnect attempt #${String(S)} failed during setup`),p()}})()},C)},h=30,b=300;for(let C=0;C<h;C++){await new Promise(S=>setTimeout(S,b)),d(`CDP connect attempt ${String(C+1)}/${String(h)}`);try{let S=await Lg({port:r});i=S,e.path&&S.send("Page.navigate",{url:`${t}${e.path}`});try{await m(S),d("CDP connected")}catch{i===S&&(i=null);try{await S.close()}catch{}d("CDP setup failed after connect")}break}catch{if(C===h-1){let S=`CDP unavailable after ${String(h)} attempts \u2014 viewer running without interception (CSP/cookie rewrites disabled)`;return d(S),e.onWarn?.(S),{kill:()=>{n.kill()}}}}}return i?{kill:()=>{if(d("CDP kill requested \u2014 tearing down"),l=!0,a!==null&&(clearTimeout(a),a=null),f(),i!==null){try{i.close()}catch{}i=null}n.kill()}}:{kill:()=>{n.kill()}}}import{useCallback as A_,useState as x_}from"react";function ks(e){let[t,n]=x_([]),r=A_(i=>{n(o=>[...o,`${new Date().toLocaleTimeString()}: ${i}`].slice(-e))},[e]);return[t,r]}import{useCallback as As,useEffect as Il,useState as xs}from"react";import{Box as we,Text as ie,useInput as P_}from"ink";import{jsx as W,jsxs as Se}from"react/jsx-runtime";var mn=["apiKey","userId","businessId"],C_={apiKey:"API Key",userId:"User ID",businessId:"Business ID"},yi=({text:e})=>W(ie,{dimColor:!0,children:e}),Ps=({initialMode:e,showProfileManager:t,onComplete:n,onCancel:r})=>{let[i,o]=xs(e==="global"&&!t?{type:"loading"}:e==="global"&&t?{type:"profile-loading"}:{type:"mode-select",cursor:0}),[s,a]=xs(""),[c,l]=xs(null),[d,u]=xs(void 0),f=As(x=>{if(x==="local"){n({mode:"local",credentials:null});return}o({type:"profile-loading"})},[n]),g=As(async x=>{if(x===null){o({type:"profile-loading"});let P=await Jt();o({type:"name-entry",nameBuffer:"",existingProfiles:P});return}u(x.isDefault?void 0:x.name),o({type:"loading"});let v=x.isDefault?await De():await Ct(x.name),k=v?Math.max(0,pe.indexOf(v.environment)):0;o({type:"creds-entry",field:0,values:v??{},envCursor:k})},[]),m=As(async(x,v)=>{let k=pe[v]??"go",P={...wr(x),environment:k};o({type:"saving"});try{await tu(d??Wt,P),n({mode:"global",credentials:P,...d!==void 0&&{profileName:d}})}catch(w){l(w instanceof Error?w.message:String(w)),o({type:"creds-entry",field:0,values:x,envCursor:v})}},[n,d]);P_((x,v)=>{if(v.ctrl&&x==="c"&&process.exit(0),v.escape){if((i.type==="creds-entry"||i.type==="name-entry")&&e==="global"&&t){o({type:"profile-loading"}),p();return}r?.();return}if(i.type==="mode-select"){if(v.upArrow)o({type:"mode-select",cursor:0});else if(v.downArrow)o({type:"mode-select",cursor:1});else if(v.return){let k=i.cursor===0?"global":"local";f(k)}return}if(i.type==="profile-select"){let{profiles:k,cursor:P}=i,w=k.length,A=k.length+1;if(v.upArrow)o({...i,cursor:(P-1+A)%A});else if(v.downArrow)o({...i,cursor:(P+1)%A});else if(v.return)if(P===w)o({type:"name-entry",nameBuffer:"",existingProfiles:k});else{let _=k[P]??k[0];_&&g(_)}return}if(i.type==="name-entry"){let{nameBuffer:k,existingProfiles:P}=i;if(v.backspace||v.delete)o({type:"name-entry",nameBuffer:k.slice(0,-1),existingProfiles:P});else if(v.return){let w=k.trim();if(!w){o({...i,nameError:"Name cannot be empty"});return}if(w===Wt){o({...i,nameError:`"${Wt}" is reserved`});return}if(P.some(A=>A.name===w)){o({...i,nameError:`Profile "${w}" already exists`});return}u(w),o({type:"creds-entry",field:0,values:{},envCursor:0}),a("")}else x&&!v.ctrl&&!v.meta&&o({type:"name-entry",nameBuffer:k+x,existingProfiles:P});return}if(i.type==="creds-entry"){let{field:k,values:P,envCursor:w}=i;if(k===mn.length){v.leftArrow?o({...i,envCursor:(w-1+pe.length)%pe.length}):v.rightArrow?o({...i,envCursor:(w+1)%pe.length}):v.upArrow?(o({...i,field:k-1}),a(P[mn[k-1]]??"")):v.return&&m(P,w);return}let _=mn[k];if(!_)return;if(v.backspace||v.delete)a(T=>T.slice(0,-1));else if(v.upArrow&&k>0){let T={...P,[_]:s},L=k-1;o({...i,field:L,values:T}),a(T[mn[L]]??"")}else if(v.return||v.tab||v.downArrow){let T={...P,[_]:s},L=k+1;o({...i,field:L,values:T}),L<mn.length?a(T[mn[L]]??""):a("")}else x&&!v.ctrl&&!v.meta&&a(T=>T+x)}});let p=As(async()=>{let x=await Jt();o({type:"profile-select",profiles:x,cursor:0})},[]);if(Il(()=>{i.type==="profile-loading"&&p()},[i.type,p]),Il(()=>{e==="global"&&!t&&(async()=>{let x=await De(),v=x?Math.max(0,pe.indexOf(x.environment)):0;o({type:"creds-entry",field:0,values:x??{},envCursor:v})})()},[]),Il(()=>{i.type==="creds-entry"&&i.field===0&&a(i.values.apiKey??"")},[i.type]),i.type==="loading"||i.type==="saving"||i.type==="profile-loading"){let x=i.type==="saving"?"Saving credentials\u2026":i.type==="profile-loading"?"Loading profiles\u2026":"Loading credentials\u2026";return W(we,{paddingY:1,paddingX:2,children:W(ie,{dimColor:!0,children:x})})}if(i.type==="done")return null;if(i.type==="mode-select")return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{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((v,k)=>{let P=i.cursor===k;return Se(we,{gap:2,children:[W(ie,{...P&&{color:"cyan"},children:P?"\u276F":" "}),W(ie,{bold:P,...P&&{color:"cyan"},children:v.label}),W(ie,{dimColor:!0,children:v.desc})]},v.mode)})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]});if(i.type==="profile-select"){let{profiles:x,cursor:v}=i,k=x.length;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{bold:!0,children:"Credential profiles"}),x.map((P,w)=>{let A=v===w;return Se(we,{gap:2,children:[W(ie,{...A&&{color:"cyan"},children:A?"\u276F":" "}),W(ie,{bold:A,...A&&{color:"cyan"},children:P.isDefault?"Default":P.name}),W(ie,{dimColor:!0,children:P.path})]},P.name)}),Se(we,{gap:2,children:[W(ie,{...v===k&&{color:"cyan"},children:v===k?"\u276F":" "}),W(ie,{bold:v===k,...v===k&&{color:"cyan"},children:"+ Add new profile"})]})]}),W(yi,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Esc to cancel"})]})}if(i.type==="name-entry"){let{nameBuffer:x,nameError:v}=i;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),W(we,{flexDirection:"column",gap:0,children:W(ie,{bold:!0,children:"New credential profile"})}),v&&Se(ie,{color:"red",children:["Error: ",v]}),Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:!0,color:"cyan",children:"Profile name"})}),W(ie,{color:"cyan",children:">"}),W(ie,{children:x}),W(ie,{color:"cyan",children:"\u2588"})]}),W(yi,{text:"Type a name \xB7 Enter to confirm \xB7 Esc to go back"})]})}let{field:h,values:b,envCursor:y}=i,C=h===mn.length,S=d??Wt;return Se(we,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[W(ye,{}),Se(we,{flexDirection:"column",gap:0,children:[W(ie,{bold:!0,children:d!==void 0?`Profile: ${d}`:"Global credentials"}),Se(ie,{dimColor:!0,children:["Saved to:"," ",d!==void 0?`~/.kizenappbuilder/${d}.json`:Kt]})]}),c&&Se(ie,{color:"red",children:["Error: ",c]}),Se(we,{flexDirection:"column",gap:0,children:[mn.map((x,v)=>{let k=h===v,P=k?s:b[x]??"";return Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:k,...k&&{color:"cyan"},children:C_[x]})}),W(ie,{...k&&{color:"cyan"},children:">"}),W(ie,{children:P}),k&&W(ie,{color:"cyan",children:"\u2588"})]},x)}),Se(we,{gap:2,children:[W(we,{width:12,children:W(ie,{bold:C,...C&&{color:"cyan"},children:"Environment"})}),W(ie,{...C&&{color:"cyan"},children:">"}),W(we,{gap:1,children:pe.map((x,v)=>{let k=v===y;return C?W(ie,{bold:k,...k&&{color:"cyan"},children:k?`[${x}]`:x},x):W(ie,{dimColor:!k,bold:k,children:x},x)})})]})]}),C?W(yi,{text:"\u2190\u2192 to select \xB7 \u2191\u2193 to move \xB7 Enter to save \xB7 Esc to cancel"}):W(yi,{text:"\u2191\u2193 to move \xB7 Backspace to delete \xB7 Esc to cancel"}),Se(ie,{dimColor:!0,children:["Profile: ",S]})]})};import{jsx as ne,jsxs as be}from"react/jsx-runtime";var R_=[".kizenapp",".git"],zg=({port:e,pluginDir:t,outputDir:n,credentials:r,credentialMode:i,activeCredentialProfile:o,lastPath:s,debug:a=!1,verbose:c=!1,autoViewer:l=!0,cacheEnabled:d=!0})=>{let u=Ft(r),f=Ft(o),g=Ft(s),[m,p]=Ve("main"),[h,b]=Ve(i),[y,C]=Ve("starting"),[S,x]=Ve(null),[v,k]=ks(50),[P,w]=ks(50),[A,_]=ks(50),[T,L]=Ve([]),[$,V]=Ve("pending"),[X,ve]=Ve(null),[Re,$e]=Ve(null),[Te,gn]=Ve(null),[ct,mr]=Ve(null),[fr,jt]=Ve(0),[E,N]=Ve(0),[B,R]=Ve(0),[O,D]=Ve(0),M=Ft(!1),Y=Ft(!1),G=Ft(null),Z=Ft(null),J=Ft(new Set),le=Ft([]),se=pr(j=>{let ae=JSON.stringify(j);if(J.current.size===0){le.current=[...le.current,ae].slice(-50);return}let Mt=!1;for(let lt of J.current)if(lt.readyState===1)try{lt.send(ae)}catch{J.current.delete(lt),Mt=!0}Mt&&jt(J.current.size)},[]),Fe=k,Hn=pr(()=>{G.current?.kill(),G.current=null,jg({port:e,userDataDir:Mg(n,".chrome"),broadcast:se,onWarn:j=>{k(`\u26A0 ${j}`)},...g.current!==void 0&&{path:g.current},...a&&{debugLog:_},...c&&{verbose:!0}}).then(j=>{G.current=j})},[e,n,se,a,c,_,k]);Cs(()=>{let j=()=>{G.current?.kill()};return process.on("exit",j),()=>{process.off("exit",j)}},[]),__((j,ae)=>{(j==="q"||ae.ctrl&&j==="c")&&process.exit(0),j==="c"&&p("editing"),j==="v"&&Hn()},{isActive:m==="main"}),Cs(()=>{y!=="running"||Y.current||!l||(Y.current=!0,Hn())},[y,l,Hn]);let Ns=pr(j=>{u.current=j.credentials,f.current=j.profileName,p("main"),b(j.mode);let ae=j.profileName;nn(n,{credentialMode:j.mode,...ae!==void 0&&{activeCredentialProfile:ae}}),se({type:"credentials-updated",credentials:j.credentials})},[n,se]),$l=pr(j=>{L(ae=>[...ae,`${new Date().toLocaleTimeString()}: ${Sl(j)}`].slice(-50)),j.kind==="request"&&(j.fromCache?R(ae=>ae+1):D(ae=>ae+1)),se({type:"proxy-log",entry:j})},[se]),hn=pr(j=>{w(j),se({type:"log",message:j})},[w,se]),Rs=pr(()=>{M.current||(M.current=!0,V("building"),ve(null),$e(null),hn("Build started"),io(t,n).then(({bundleSize:j})=>{hn(`Build finished \u2014 bundle: ${ci(j)}`),V("done"),gn(new Date),mr(j),hn("Notifying viewers to reload"),se({type:"rebuild"})}).catch(j=>{j instanceof E_?($e(j.issues),ve(null)):(ve(j instanceof Error?j.message:String(j)),$e(null)),V("error")}).finally(()=>{M.current=!1}))},[t,n,hn,se]);if(Cs(()=>{Rs();let j=I_(t,{recursive:!0},(ae,Mt)=>{if(!Mt)return;let lt=Mt.replace(/\\/g,"/");R_.some(wi=>lt.startsWith(wi))||(hn(`File change detected: ${Mt}`),Z.current!==null&&clearTimeout(Z.current),Z.current=setTimeout(Rs,150))});return j.on("error",ae=>{hn(`File watcher error \u2014 rebuilds have stopped: ${ae.message}`)}),()=>{j.close(),Z.current!==null&&clearTimeout(Z.current)}},[t,Rs,hn]),Cs(()=>{let j=Og();El(Mg(j,"index.html")).then(ae=>{if(!ae){x("Viewer not built. Run 'pnpm build:viewer' first."),C("error");return}let Mt=Dg(j,Fe,$l,u,f,n,se,N,g,t,d),lt=T_(Mt),wi=new N_({server:lt});return wi.on("connection",yn=>{for(let Oh of le.current)yn.readyState===1&&yn.send(Oh);le.current=[],Fe("Viewer connected for live reload"),J.current.add(yn),jt(J.current.size),yn.on("close",()=>{J.current.delete(yn),jt(J.current.size)})}),lt.listen(e,"127.0.0.1",()=>{C("running"),Fe(`Server started on 127.0.0.1:${String(e)}`)}),lt.on("error",yn=>{x(yn.message),C("error")}),()=>{wi.close(),lt.close()}})},[e,Fe,$l,se,n,t,d]),m==="editing")return ne(Ps,{...h!==void 0&&{initialMode:h},showProfileManager:h==="global",onComplete:Ns,onCancel:()=>{p("main")}});let $s=Te!==null?Math.round((Date.now()-Te.getTime())/1e3):null,$h=$s===null?"":$s<5?" (just now)":` (${String($s)}s ago)`,Ol=Re?.filter(j=>j.severity==="error").length??0;return be(Ee,{flexDirection:"column",paddingY:1,paddingX:2,children:[ne(ye,{marginBottom:1}),be(Ee,{flexDirection:"column",children:[be(Ee,{gap:2,marginBottom:0,children:[ne(te,{bold:!0,dimColor:!0,children:"App Build"}),$==="pending"&&ne(te,{dimColor:!0,children:"waiting\u2026"}),$==="building"&&be(Ee,{gap:1,children:[ne(wt,{}),ne(te,{children:"Building plugin package\u2026"})]}),$==="done"&&be(Ee,{gap:1,children:[ne(te,{color:"green",children:"\u2713 Built"}),Te!==null&&be(te,{dimColor:!0,children:["at ",Te.toLocaleTimeString(),$h]}),ct!==null&&be(te,{dimColor:!0,children:["\xB7 bundle: ",ci(ct)]})]}),$==="error"&&(Re!==null?be(te,{color:"red",children:["\u2717 ",Ol," validation ",Ol===1?"error":"errors"]}):be(te,{color:"red",children:["\u2717 ",X??"unknown error"]}))]}),Re!==null&&ne(ar,{issues:Re}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:P.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"Web Server"}),y==="starting"&&ne(te,{dimColor:!0,children:"starting\u2026"}),y==="running"&&be(Ee,{gap:2,children:[ne(te,{color:"green",children:"\u2713 Running"}),be(te,{dimColor:!0,children:["\u25CF ",fr," viewer",fr!==1?"s":""]})]}),y==="error"&&be(te,{color:"red",children:["\u2717 ",S??"Server error"]})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:v.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"Network Proxy"}),ne(te,{color:"green",children:"\u2713 Active"}),ne(te,{dimColor:!0,children:d?`\u25CF ${String(E)} key${E!==1?"s":""} in the network cache \xB7 ${String(B)} hit \xB7 ${String(O)} miss`:`\u25CF network cache disabled \xB7 ${String(O)} request${O!==1?"s":""}`})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:T.length===0?ne(te,{dimColor:!0,children:" No requests yet."}):T.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),a&&be(Ee,{marginTop:1,flexDirection:"column",children:[be(Ee,{gap:2,children:[ne(te,{bold:!0,dimColor:!0,children:"CDP Debug"}),be(te,{dimColor:!0,children:["\u25CF ",A.length," event(s)"]})]}),ne(Ee,{flexDirection:"column",height:10,borderStyle:"single",borderColor:"gray",overflow:"hidden",children:A.length===0?ne(te,{dimColor:!0,children:" No CDP events yet."}):A.slice(-8).map((j,ae)=>ne(te,{dimColor:!0,wrap:"truncate",children:j},ae))})]}),be(Ee,{marginTop:1,gap:1,children:[ne(te,{dimColor:!0,children:"["}),ne(te,{children:"q"}),ne(te,{dimColor:!0,children:"] quit ["}),ne(te,{children:"c"}),ne(te,{dimColor:!0,children:"] credentials ["}),ne(te,{children:"v"}),be(te,{dimColor:!0,children:["] ",fr===0?"open viewer":"relaunch viewer"]})]})]})};async function Ug(e){return new Promise(t=>{let n=null,r=o=>{n?.(),t(o)},{unmount:i}=Hg(Vg(Ps,{...e!==void 0&&{initialMode:e},onComplete:r}),{exitOnCtrlC:!1});n=i})}function Kg(e){e.command("dev").description("Start the plugin viewer dev server").option("-p, --port <port>","port to listen on","3121").option("-c, --credentials <path>","path to an API-key credentials JSON file (dev still uses API keys; sign-in support is planned)").option("-d, --debug","Enable CDP lifecycle logs in the TUI").option("-v, --verbose","Log every CDP event and handled error (implies --debug)").option("--no-viewer","Don't auto-launch the viewer on startup (press [v] to launch manually)").option("--no-cache","Disable the network proxy cache (always fetch upstream)").action(async t=>{let n=parseInt(t.port,10),r=process.cwd(),i=`${r}/.kizenapp`;Ze(r);let o=null,s,a,{lastPath:c}=await ht(i);if(t.credentials)o=await Gt(t.credentials);else{let m=await ht(i);if(m.credentialMode==="local")s="local";else if(m.credentialMode==="global"){if(s="global",a=m.activeCredentialProfile,a?(o=await Ct(a),o||(o=await De(),a=void 0)):o=await De(),!o){let p=await Ug("global");o=p.credentials,a=p.profileName}}else{let p=await Ug();o=p.credentials,s=p.mode,a=p.profileName;let h=p.profileName;await nn(i,{credentialMode:p.mode,...h!==void 0&&{activeCredentialProfile:h}})}}let l=t.verbose===!0,d=l||t.debug===!0,u=t.viewer!==!1,f=t.cache!==!1,{waitUntilExit:g}=Hg(Vg(zg,{port:n,pluginDir:r,outputDir:i,credentials:o,...s!==void 0&&{credentialMode:s},...a!==void 0&&{activeCredentialProfile:a},...c!==void 0&&{lastPath:c},debug:d,verbose:l,autoViewer:u,cacheEnabled:f}),{exitOnCtrlC:!1});await g()})}import{createElement as K_}from"react";import{render as W_}from"ink";import{useCallback as _s,useEffect as qg,useState as Es}from"react";import{Box as xt,Text as oe,useApp as j_,useInput as M_}from"ink";import{encrypt as $_,serializeEnvelope as O_}from"@kizenapps/packager";function D_(e){let t=e;return t.code==="ECONNREFUSED"||t.cause?.code==="ECONNREFUSED"}function Wg(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 Gg(e,t,n){try{return await fetch(`${e}${t}`,n)}catch(r){throw new Error(D_(r)?`Plugin-wizard is not running at ${e}`:`Failed to reach plugin-wizard: ${r.message}${ki()==="unavailable"?` ${vi}`:""}`)}}async function Jg(e){let t=await e.text();if(t==="")return{};try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}async function L_(e,t,n){let r=mi(e.stage),i=await Gg(r,"/get-public-key",{method:"POST",headers:Wg(t),body:JSON.stringify({api_name:n})}),o=await Jg(i);if(!i.ok||typeof o.public_key!="string"){let s=typeof o.error=="string"?o.error:`HTTP ${String(i.status)}`;throw new Error(`Failed to fetch public key: ${s}`)}return o.public_key}function B_(e,t){let n=$_(t,e),r=O_(n);if(typeof r.value!="string")throw new Error("Unexpected serialized envelope shape from @kizenapps/packager");return r.value}async function F_(e,t,n,r){let i=mi(e.stage),o=await Gg(i,"/encrypt",{method:"POST",headers:Wg(t),body:JSON.stringify({api_name:n,value:r})}),s=await Jg(o);if(!o.ok||s.encrypted!==!0||typeof s.value!="string"){let a=typeof s.error=="string"?s.error:`HTTP ${String(o.status)}`;throw new Error(`Encryption via plugin-wizard failed: ${a}`)}return s.value}async function Ss(e,t,n,r,i){if(e.isRemote)return i?.("encrypting"),F_(e,t,n,r);i?.("fetching-key");let o=await L_(e,t,n);return i?.("encrypting"),B_(o,r)}import{Fragment as Is,jsx as re,jsxs as Ie}from"react/jsx-runtime";var Tl=({text:e})=>re(oe,{dimColor:!0,children:e}),Yg=({ctx:e,stageDefaulted:t,credentialsPath:n,initialApiName:r,defaultApiName:i,initialValue:o,onDone:s})=>{let a=j_(),[c,l]=Es({type:"loading"}),[d,u]=Es(null),[f,g]=Es(r??""),[m,p]=Es(o??""),h=_s(k=>{process.exitCode=1,l({type:"error",message:k instanceof Error?k.message:String(k)})},[]),b=_s(async(k,P,w)=>{try{let A=await Ss(e,k,P,w,L=>{l(L==="fetching-key"?{type:"fetching-key"}:{type:"encrypting"})}),_=JSON.stringify({encrypted:!0,value:A},null,2);s?.(A);let T=await es(_);l({type:"done",envelope:_,copied:T})}catch(A){h(A)}},[e,h,s]),y=_s((k,P,w)=>{if(P.trim()===""){l({type:"api-name-entry",buffer:i??""});return}if(w===""){l({type:"value-entry",buffer:""});return}b(k,P.trim(),w)},[i,b]),C=_s(async k=>{try{l({type:"loading"});let P=k.isDefault?await De():await Ct(k.name);if(P===null)throw new Error(`Could not load credential profile: ${k.name}`);u(P),y(P,f,m)}catch(P){h(P)}},[f,m,y,h]);qg(()=>{(async()=>{try{if(n!==void 0){let w;try{w=await Gt(n)}catch(A){throw new Error(`Could not load credentials from ${n}: ${A instanceof Error?A.message:String(A)}`)}u(w),y(w,f,m);return}let k=await Jt();if(k.length===0)throw new Error("No credential profiles found. Create ~/.kizenappbuilder/credentials.json first.");let[P]=k;if(k.length===1&&P!==void 0){let w=P.isDefault?await De():await Ct(P.name);if(w===null)throw new Error(`Could not load credential profile: ${P.name}`);u(w),y(w,f,m);return}l({type:"profile-select",profiles:k,cursor:0})}catch(k){h(k)}})()},[]),qg(()=>{(c.type==="done"||c.type==="error")&&a.exit()},[c,a]),M_((k,P)=>{if(P.ctrl&&k==="c"){process.exitCode=130,a.exit();return}if(c.type==="profile-select"){let{profiles:w,cursor:A}=c;if(P.upArrow)l({...c,cursor:(A-1+w.length)%w.length});else if(P.downArrow)l({...c,cursor:(A+1)%w.length});else if(P.return){let _=w[A];_!==void 0&&C(_)}return}if(c.type==="api-name-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"api-name-entry",buffer:w.slice(0,-1)});else if(P.return){let A=w.trim();if(A===""){l({type:"api-name-entry",buffer:w,error:"api_name cannot be empty"});return}g(A),d?y(d,A,m):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"api-name-entry",buffer:w+k});return}if(c.type==="value-entry"){let{buffer:w}=c;if(P.backspace||P.delete)l({type:"value-entry",buffer:w.slice(0,-1)});else if(P.return){if(w===""){l({type:"value-entry",buffer:w,error:"secret cannot be empty"});return}p(w),d?y(d,f,w):h(new Error("Internal error: credentials were not loaded"))}else k&&!P.ctrl&&!P.meta&&l({type:"value-entry",buffer:w+k});return}});let S=e.isRemote?"remote Kizen API":"on-machine",x=t===!0?`${e.stage} (default)`:e.stage,v=k=>Ie(xt,{flexDirection:"column",paddingY:1,paddingX:2,gap:1,children:[re(ye,{}),Ie(oe,{dimColor:!0,children:["Mode: ",S," Stage: ",x]}),k]});if(c.type==="loading")return v(Ie(xt,{gap:1,children:[re(wt,{}),re(oe,{dimColor:!0,children:"Loading credentials\u2026"})]}));if(c.type==="profile-select"){let{profiles:k,cursor:P}=c;return v(Ie(Is,{children:[re(oe,{bold:!0,children:"Credential profile"}),re(xt,{flexDirection:"column",children:k.map((w,A)=>{let _=P===A;return Ie(xt,{gap:2,children:[re(oe,{..._&&{color:"cyan"},children:_?"\u276F":" "}),re(oe,{bold:_,..._&&{color:"cyan"},children:w.isDefault?"Default":w.name}),re(oe,{dimColor:!0,children:w.path})]},w.name)})}),re(Tl,{text:"\u2191\u2193 to move \xB7 Enter to select \xB7 Ctrl+C to quit"})]}))}return c.type==="api-name-entry"?v(Ie(Is,{children:[re(oe,{bold:!0,children:"Plugin api_name"}),c.error!==void 0&&Ie(oe,{color:"red",children:["Error: ",c.error]}),Ie(xt,{gap:1,children:[re(oe,{color:"cyan",children:">"}),re(oe,{children:c.buffer}),re(oe,{color:"cyan",children:"\u2588"})]}),re(Tl,{text:"Type the api_name \xB7 Enter to confirm \xB7 Ctrl+C to quit"})]})):c.type==="value-entry"?v(Ie(Is,{children:[re(oe,{bold:!0,children:"Secret value"}),c.error!==void 0&&Ie(oe,{color:"red",children:["Error: ",c.error]}),Ie(xt,{gap:1,children:[re(oe,{color:"cyan",children:">"}),re(oe,{children:"\u2022".repeat(c.buffer.length)}),re(oe,{color:"cyan",children:"\u2588"})]}),re(Tl,{text:"Input hidden \xB7 Enter to encrypt \xB7 Ctrl+C to quit"})]})):c.type==="fetching-key"?v(Ie(xt,{gap:1,children:[re(wt,{}),Ie(oe,{children:["Fetching ",e.stage," public key for ",re(oe,{bold:!0,children:f}),"\u2026"]})]})):c.type==="encrypting"?v(Ie(xt,{gap:1,children:[re(wt,{}),re(oe,{children:"Encrypting\u2026"})]})):c.type==="error"?v(Ie(xt,{gap:1,children:[re(oe,{color:"red",children:"\u2717"}),re(oe,{color:"red",children:c.message})]})):v(Ie(Is,{children:[Ie(xt,{gap:1,children:[re(oe,{color:"green",children:"\u2713"}),re(oe,{bold:!0,children:"Encrypted secret ready"})]}),c.copied?re(oe,{color:"green",children:"\u2713 Copied to clipboard \u2014 paste it into the secret value in your kizen.json."}):re(oe,{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):"}),re(oe,{children:c.envelope})]}))};import{readFile as z_,writeFile as U_}from"fs/promises";import{join as V_}from"path";function Zg(e){return{encrypted:!0,value:e}}function Xg(e){return JSON.stringify(Zg(e))}async function Nl(e,t){await U_(e,`${JSON.stringify(Zg(t),null,2)}
|
|
1221
|
+
`,"utf-8")}var H_="prod";function Qg(e){return e==="dev"||e==="prod"}function eh(e){return`Error: --stage must be "dev" or "prod" (got: "${e}")`}function th(e){return{stage:e==="dev"||e==="prod"?e:H_,wasDefaulted:e===void 0}}function nh(e){return`No --stage given; defaulting to ${e} encryption keys (pass --stage dev to override)
|
|
1222
|
+
`}async function rh(e=process.cwd()){try{let t=await z_(V_(e,"kizen.json"),"utf-8"),n=JSON.parse(t),r=Array.isArray(n)?n[0]:n,i=typeof r.api_name=="string"&&r.api_name!==""?r.api_name:void 0;return{...i!==void 0&&{apiName:i}}}catch{}return{}}function ih(e){return e.replace(/[\r\n]+$/,"")}async function oh(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf-8")}async function sh(e,t,n,r,i){let o=t.credentials!==void 0?await i.loadCredentialsFromFile(t.credentials):await i.loadGlobalCredentials();if(o===null)throw new Error("No credentials found. Pass --credentials or create ~/.kizenappbuilder/credentials.json.");let s=t.apiName??n.apiName;if(s===void 0||s.trim()==="")throw new Error("api_name is required in non-interactive mode. Pass --api-name or run inside a plugin directory.");r&&i.writeStderr(nh(e.stage));let a=t.value;if(a===void 0){if(i.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`).');i.writeStderr(`Reading secret from stdin (pass --value to skip)\u2026
|
|
1223
|
+
`),a=ih(await i.readStdin())}if(a==="")throw new Error("A secret value is required. Pass --value or pipe it via stdin.");let c=await i.encryptSecret(e,o,s.trim(),a);if(i.writeStdout(`${Xg(c)}
|
|
1224
|
+
`),t.out!==void 0)try{await i.writeEnvelopeFile(t.out,c),i.writeStderr(`Wrote encrypted envelope to ${t.out}
|
|
1225
|
+
`)}catch(l){i.writeStderr(`Error writing ${t.out}: ${l instanceof Error?l.message:String(l)}
|
|
1226
|
+
`),i.setExitCode(1)}}function ah(e){e.command("encrypt").description("Encrypt a secret for a plugin against its encryption keys").option("--remote","encrypt via the plugin-wizard's remote API instead of on-machine").option("-c, --credentials <path>","path to an API-key credentials JSON file (encrypt still uses API keys until plugin-wizard accepts sign-in sessions)").option("-a, --api-name <name>","plugin api_name the secret belongs to").option("-v, --value <value>","plaintext secret value to encrypt").option("-s, --stage <stage>","which encryption API to use: dev or prod (default: prod)").option("-o, --out <path>","also write the encrypted envelope to a file").option("--no-interactive",mt).action(async t=>{let{noInteractive:n,options:r}=Ae(t);r.stage!==void 0&&!Qg(r.stage)&&(console.error(eh(r.stage)),process.exit(1));let o=r.apiName===void 0?await rh():{},{stage:s,wasDefaulted:a}=th(r.stage),c={isRemote:r.remote===!0,stage:s};if(!pt({noInteractive:n})){try{await sh(c,r,o,a,{loadCredentialsFromFile:Gt,loadGlobalCredentials:De,encryptSecret:Ss,readStdin:oh,stdinIsTTY:()=>process.stdin.isTTY,writeStdout:u=>{process.stdout.write(u)},writeStderr:u=>{process.stderr.write(u)},writeEnvelopeFile:Nl,setExitCode:u=>{process.exitCode=u}})}catch(u){console.error(`Error: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}return}let l,{waitUntilExit:d}=W_(K_(Yg,{ctx:c,stageDefaulted:a,onDone:u=>{l=u},...r.credentials!==void 0&&{credentialsPath:r.credentials},...r.apiName!==void 0&&{initialApiName:r.apiName},...o.apiName!==void 0&&{defaultApiName:o.apiName},...r.value!==void 0&&{initialValue:r.value}}),{exitOnCtrlC:!1});if(await d(),l!==void 0&&r.out!==void 0)try{await Nl(r.out,l),process.stderr.write(`Wrote encrypted envelope to ${r.out}
|
|
1227
|
+
`)}catch(u){console.error(`Error writing ${r.out}: ${u instanceof Error?u.message:String(u)}`),process.exitCode=1}})}var G_=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","circle-check","arrow-progress","puzzle-piece","code"]),J_=[...G_].sort(),q_=new Set(["kizen-k","form-entity"]),ch=[...J_,...[...q_].sort()];function lh(e){e.command("icons").description("List all valid icon names accepted by toolbar items, pages, and adornments").action(()=>{for(let t of ch)console.log(t)})}import{mkdir as rE,writeFile as vh,readFile as iE}from"fs/promises";import{join as Ts}from"path";var Y_=new Set(["developer_business_id"]);function Z_(e){return Array.isArray(e)?e.map(t=>{if(typeof t!="object"||t===null)return t;let n=t;if(typeof n.auth_credentials!="object"||n.auth_credentials===null)return n;let r=Object.fromEntries(Object.keys(n.auth_credentials).map(i=>[i,"*****"]));return{...n,auth_credentials:r}}):e}function dh(e){let t={name:"",children:new Map,isFile:!1,filePath:""};for(let n of e){let r=n.path.split("/"),i=t;r.forEach((o,s)=>{i.children.has(o)||i.children.set(o,{name:o,children:new Map,isFile:s===r.length-1,filePath:r.slice(0,s+1).join("/")});let a=i.children.get(o);a&&(i=a)})}return t}function ph(e){return[...e.children.values()].sort((t,n)=>t.isFile!==n.isFile?t.isFile?1:-1:t.name.localeCompare(n.name))}function Rl(e){return"file-"+e.replace(/[^a-zA-Z0-9]/g,"-")}function Pt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function mh(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}var X_={".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 Q_(e){return X_[mh(e)]??""}function uh(e){let t=[...e.matchAll(/`+/g)].reduce((n,r)=>Math.max(n,r[0].length),0);return"`".repeat(Math.max(3,t+1))}function fh(e,t=""){let n=ph(e);return n.map((r,i)=>{let o=i===n.length-1,s=o?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",a=o?" ":"\u2502 ";return r.isFile?`${t}${s}${r.name}`:`${t}${s}${r.name}/
|
|
1228
|
+
${fh(r,t+a)}`}).join(`
|
|
1229
|
+
`)}var eE=/(^|\/)licen[cs]e(\.md|\.txt)?$/i;function gh(e){return e.filter(t=>t.path!=="kizen.json"&&t.path!=="plugin-report.html"&&!eE.test(t.path))}function hh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!Y_.has(t)).map(([t,n])=>[t,t==="services"?Z_(n):n]))}var tE={".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function yh(e){return`<ul>${ph(e).map(r=>r.isFile?`<li class="tf"><a href="#${Rl(r.filePath)}" data-id="${Rl(r.filePath)}">${Pt(r.name)}</a></li>`:`<li class="td"><span class="dn">${Pt(r.name)}/</span>${yh(r)}</li>`).join("")}</ul>`}function nE(e){let t;return e.base64Image!==void 0?t=`<img src="data:${tE[mh(e.path)]??"image/png"};base64,${e.base64Image}" alt="${Pt(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>${Pt(e.content)}</code></pre>`,`<section id="${Rl(e.path)}"><h2 class="fp">${Pt(e.path)}</h2><div class="fb">${t}</div></section>`}function bh(e,t){let n=hh(e),r=typeof e.name=="string"?e.name:"Plugin",i=typeof e.version=="string"?e.version:"",o=typeof e.description=="string"?e.description:"",s=gh(t),a=[];a.push(`# ${r}${i?` v${i}`:""}`),o&&a.push("",o);let c=JSON.stringify(n,null,2),l=uh(c);a.push("","## Configuration (`kizen.json`)","",`${l}json`,c,l),a.push("","## File Tree","","```",fh(dh(s)),"```"),a.push("","## Files");for(let d of s)if(a.push("",`### \`${d.path}\``,""),d.base64Image!==void 0)a.push(`[Image file: ${d.path}]`);else if(d.binaryData!==void 0)a.push(`[Binary file: ${String(d.binaryData.length)} bytes]`);else{let u=uh(d.content);a.push(`${u}${Q_(d.path)}`,d.content,u)}return a.join(`
|
|
1211
1230
|
`)+`
|
|
1212
|
-
`}function
|
|
1231
|
+
`}function wh(e,t){let n=hh(e),r=typeof e.name=="string"?e.name:"Plugin",i=typeof e.version=="string"?e.version:"",o=typeof e.description=="string"?e.description:"",s=gh(t),a=yh(dh(s)),c=s.map(nE).join(`
|
|
1213
1232
|
`);return`<!DOCTYPE html>
|
|
1214
1233
|
<html lang="en">
|
|
1215
1234
|
<head>
|
|
1216
1235
|
<meta charset="UTF-8">
|
|
1217
1236
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1218
|
-
<title>${
|
|
1237
|
+
<title>${Pt(r)} \u2014 Plugin Report</title>
|
|
1219
1238
|
<style>
|
|
1220
1239
|
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
|
|
1221
1240
|
:root{
|
|
@@ -1252,8 +1271,8 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1252
1271
|
</head>
|
|
1253
1272
|
<body>
|
|
1254
1273
|
<header>
|
|
1255
|
-
<h1>${
|
|
1256
|
-
${
|
|
1274
|
+
<h1>${Pt(r)}${i?` <span style="color:var(--mu);font-size:.8em">v${Pt(i)}</span>`:""}</h1>
|
|
1275
|
+
${o?`<p>${Pt(o)}</p>`:""}
|
|
1257
1276
|
</header>
|
|
1258
1277
|
<div class="layout">
|
|
1259
1278
|
<nav>
|
|
@@ -1261,7 +1280,7 @@ img{border:1px solid var(--bd);border-radius:4px}
|
|
|
1261
1280
|
${a}
|
|
1262
1281
|
</nav>
|
|
1263
1282
|
<main>
|
|
1264
|
-
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${
|
|
1283
|
+
<section id="config"><h2 class="fp">kizen.json \u2014 Plugin Configuration</h2><div class="fb"><pre><code>${Pt(JSON.stringify(n,null,2))}</code></pre></div></section>
|
|
1265
1284
|
${c}
|
|
1266
1285
|
</main>
|
|
1267
1286
|
</div>
|
|
@@ -1275,9 +1294,10 @@ ${c}
|
|
|
1275
1294
|
})();
|
|
1276
1295
|
</script>
|
|
1277
1296
|
</body>
|
|
1278
|
-
</html>`}var
|
|
1279
|
-
${
|
|
1280
|
-
${s}`)})}
|
|
1297
|
+
</html>`}var kh=Ts(nt,"examples");function Ah(e){e.command("report").description("Generate a self-contained HTML report of the plugin").option("-o, --output <path>",`output file path (default: ${kh}/<api_name>.html)`).action(async t=>{let n=process.cwd(),r;try{let c=await iE(Ts(n,"kizen.json"),"utf-8"),l=JSON.parse(c);r=Array.isArray(l)?l[0]:l}catch{console.error("Error: kizen.json not found. Run this command from a plugin directory."),process.exit(1)}let i=typeof r.api_name=="string"?r.api_name:"plugin",o=t.output??Ts(kh,`${i}.html`),s=o.replace(/\.html$/,".md"),a=await ro(n,{detectBinaryByContent:!0});await rE(Ts(o,".."),{recursive:!0}),await Promise.all([vh(o,wh(r,a),"utf-8"),vh(s,bh(r,a),"utf-8")]),console.log(`Plugin report written to:
|
|
1298
|
+
${o}
|
|
1299
|
+
${s}`)})}import{spawn as oE}from"child_process";var DL=Ke.claude.staleWarning,sE=gt;var aE="@kizenapps/cli",cE=6e4,lE=(e,t)=>new Promise((n,r)=>{let i=oE(e,[...t],{stdio:["ignore","pipe","pipe"],timeout:cE}),o="",s="";i.stdout.setEncoding("utf-8"),i.stderr.setEncoding("utf-8"),i.stdout.on("data",a=>{o+=a}),i.stderr.on("data",a=>{s+=a}),i.on("error",r),i.on("close",a=>{n({code:a,stdout:o,stderr:s})})}),Ph=e=>({run:lE,hasOAuthSession:async t=>await ft().readSession(t)!==null,cliVersion:e,fs:sE,log:t=>{console.log(t)},error:t=>{console.error(t)},setExitCode:t=>{process.exitCode=t}});function uE(e,t){let n=`kizen-${e}`,r=`${Ut(e)}/api/mcp`,i=JSON.stringify({type:"http",url:r,headersHelper:`npx -y ${aE}@${t} auth-header`}),o=["mcp","add-json","--scope","user",n,i];return{environment:e,name:n,url:r,addArgs:o,addCommand:["claude",...o].map(ge).join(" ")}}function dE(e){return e.mcp!==!0&&(e.env!==void 0||e.force===!0)?"--env and --force only apply with --mcp.":e.mcp===!0&&e.includeLib===!0?"--mcp and --include-lib can't be combined. Run `appbuilder setup-claude --include-lib` and `appbuilder setup-claude --mcp` separately.":e.env===void 0?void 0:wn(e.env).message}var pE=e=>/already\s+exists/i.test(`${e.stdout}
|
|
1300
|
+
${e.stderr}`),xh=e=>{let t=(e.stderr.trim()||e.stdout.trim()).replace(/\s+/g," "),n=e.code===null?"was stopped (timed out?)":`exited ${String(e.code)}`;return t===""?n:`${n}: ${t}`};async function mE(e,t,n){let r=uE(e,n.cliVersion),{name:i}=r,o=!1,s=a=>{n.error(`Error: couldn't register the MCP server ${i}: ${a}`),o&&(n.error(`The old ${i} registration was already removed, so Claude Code has no ${i} server now. Re-run \`appbuilder setup-claude --mcp --env ${e}\`, or run:`),n.error(` ${r.addCommand}`)),n.setExitCode(1)};if(t.dryRun){n.log(`Dry run: would register the MCP server ${r.name} with: ${r.addCommand}`);return}try{let a=await n.run("claude",r.addArgs);if(a.code!==0&&pE(a)){if(!t.force){n.log(`MCP server ${r.name} already exists in Claude Code; left unchanged. Pass --force to replace it.`);return}let c=await n.run("claude",["mcp","remove","--scope","user",r.name]);if(c.code!==0){s(`claude mcp remove --scope user ${xh(c)}`);return}o=!0,a=await n.run("claude",r.addArgs)}if(a.code!==0){s(`claude mcp add-json ${xh(a)}`);return}}catch(a){if(!o&&He(a,"ENOENT")){n.log("Claude Code's `claude` command wasn't found. To register the MCP server, run (in a POSIX shell such as bash or zsh):"),n.log(` ${r.addCommand}`);return}s(ke(a));return}n.log(`Registered the MCP server ${r.name} (${r.url}) in Claude Code at user scope.`);try{await n.hasOAuthSession(e)||n.log(`You're not signed in to ${e} yet. Run \`${ut(e)}\` before using ${r.name}.`)}catch(a){n.log(ke(a))}}async function Ch(e,t,n){let r=dE(t);if(r!==void 0){n.error(`Error: ${r}`),n.setExitCode(1);return}let i=t.dryRun===!0;if(t.mcp===!0){await mE((t.env===void 0?void 0:wn(t.env).environment)??Ht,{dryRun:i,force:t.force===!0},n);return}await Zi(e,"claude",{dryRun:i,includeLib:t.includeLib===!0,notFoundHint:", or pass --mcp to only register the MCP server"},n)}function Sh(e,t){e.command("setup-claude").description("Install or refresh the Claude Code files in a plugin, or with --mcp only register the Kizen MCP server").option("--dry-run","report what would change without writing files").option("--include-lib","also install the Kizen data helper library (<entry>/lib/kizenData.js)").option("--mcp","only register the Kizen MCP server in Claude Code (user scope); writes no files, so it works in any directory").option("--env <env>","environment of the MCP server to register (with --mcp; default: go)").option("--force","replace an existing Kizen MCP server registration (with --mcp)").action(async n=>{await Ch(process.cwd(),n,Ph(t))})}var VL=`${Ke.codex.skillsDir}/kizen-custom-block/SKILL.md`,HL=Ke.codex.staleWarning,_h=()=>({fs:gt,log:e=>{console.log(e)},error:e=>{console.error(e)},setExitCode:e=>{process.exitCode=e}});async function Eh(e,t,n){await Zi(e,"codex",{dryRun:t.dryRun===!0,includeLib:t.includeLib===!0},n)}function Ih(e){e.command("setup-codex").description("Install or refresh the Codex skills (.agents/skills) in a plugin").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 Eh(process.cwd(),t,_h())})}async function Th(e,t={}){if(await dn(e)!=="has-manifest")throw new Error(`No kizen.json found in ${e}`);let n=t.dryRun===!0,r=await Gi(e,Ki(),{dryRun:n});return n||Ze(e),{files:r}}function Nh(e){e.command("setup-copilot").description("Add or refresh the Copilot code-review setup in an existing plugin repo").option("--dry-run","report what would change without writing anything").action(async t=>{let n=process.cwd();if(await dn(n)!=="has-manifest"){console.error(`No kizen.json found in ${n} \u2014 run "appbuilder setup-copilot" from the root of a plugin repo.`),process.exitCode=1;return}let r=t.dryRun===!0;try{let i=await Th(n,{dryRun:r});for(let o of i.files)console.log(Ji(o));if(r){console.log(`
|
|
1281
1301
|
Dry run \u2014 no files and no .gitignore entries were written.`);return}console.log(`
|
|
1282
|
-
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(
|
|
1302
|
+
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(i){console.error(`Error: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}})}function wE(){let e=hE(gE(yE(import.meta.url)),"..","package.json");return JSON.parse(fE(e,"utf-8")).version}function Rh(){let e=new bE,t=wE();return e.name("appbuilder").description("Kizen plugin app builder").version(t),mg(e),Sh(e,t),Ih(e),Nh(e),Lf(e),Kg(e),ah(e),Ah(e),lh(e),Rf(e),Om(e),Bm(e),Uu(e),e}Dl({env:process.env,http:vE});Rh().parse();
|
|
1283
1303
|
//# sourceMappingURL=index.js.map
|