@kizenapps/cli 1.19.0-f84db71 → 1.19.1-e3a10e9
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 +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/viewer/assets/{CodeStepsPage-D_a3dij6.js → CodeStepsPage-CTfZK03G.js} +1 -1
- package/dist/viewer/assets/{ConfigurationPage-DUiOAiMK.js → ConfigurationPage-CLLy6iFh.js} +1 -1
- package/dist/viewer/assets/CredentialsContext-BMg90DV1.js +1 -0
- package/dist/viewer/assets/{DevSidebar-CkLpkWSy.js → DevSidebar-DuVuRTJu.js} +1 -1
- package/dist/viewer/assets/{SandboxPage-B-KoJu8j.js → SandboxPage-BIG6-7Fa.js} +1 -1
- package/dist/viewer/assets/{SecretsPage-CQVPedWl.js → SecretsPage-BWbgZ1eZ.js} +1 -1
- package/dist/viewer/assets/{WhenBadge-CV5t88Iv.js → WhenBadge-DIPCKp0g.js} +1 -1
- package/dist/viewer/assets/{api-C4R44YCL.js → api-CW7z0-aU.js} +1 -1
- package/dist/viewer/assets/{bootstrapQuery-WnoB2iya.js → bootstrapQuery-CCNB4wuD.js} +1 -1
- package/dist/viewer/assets/{index-CiPj7LCo.js → index-vb4au6lQ.js} +3 -3
- package/dist/viewer/assets/{useCompleteSetup-BgC9V-FN.js → useCompleteSetup-Cmw-h_Vn.js} +1 -1
- package/dist/viewer/assets/{usePluginConfig-mg5WevIz.js → usePluginConfig-Co8lbaWp.js} +1 -1
- package/dist/viewer/index.html +4 -4
- package/package.json +1 -1
- package/dist/viewer/assets/CredentialsContext-p3i8s7a6.js +0 -1
package/README.md
CHANGED
|
@@ -72,7 +72,7 @@ It then asks which artifacts to scaffold — Floating frame, Block, Data adornme
|
|
|
72
72
|
| API Key | An API key issued for your Kizen user, from the Kizen app. |
|
|
73
73
|
| User ID | The UUID of your Kizen user. |
|
|
74
74
|
| Business ID | The UUID of the Kizen business you are developing against. |
|
|
75
|
-
| Environment | One of `go`, `fmo`, `staging`, `integration`, `test1` — which Kizen deployment the above belong to. |
|
|
75
|
+
| Environment | One of `go`, `fmo`, `staging`, `e2e-staging`, `integration`, `e2e-integration`, `test1`, `perf` — which Kizen deployment the above belong to. |
|
|
76
76
|
|
|
77
77
|
They are sent as `X-API-KEY` / `X-USER-ID` / `X-BUSINESS-ID` headers on every proxied request, so they must all belong to the same environment.
|
|
78
78
|
|
|
@@ -284,7 +284,7 @@ It runs headless when stdin or stdout is not a TTY, under a coding agent or CI,
|
|
|
284
284
|
| `--business <id or name>` | `$APPBUILDER_BUSINESS`, else the current account | Saved account to use, matched as for [`login --business`](#saved-accounts). Not with `-c` or `--profile`. |
|
|
285
285
|
| `--user <user id>` | `$APPBUILDER_USER` | With `--business`, the user id of that saved account. Not with `-c` or `--profile`. |
|
|
286
286
|
|
|
287
|
-
**Credentials.** Without `-c` or `--profile`, the push uses your [`appbuilder login`](#appbuilder-login-logout-whoami-and-auth-header) session for `--env`, or for the only environment you're signed in to. If you're signed in to several environments and pass no `--env`, the run is `needs_choice` with `choice: "environment"`. It uses that environment's current account, unless `--business` (and `--user`), or `APPBUILDER_BUSINESS` (and `APPBUILDER_USER`), names another saved account; then the environment without `--env` is the only one where that name matches a saved account, whether or not any account there is current, and several such environments are `needs_choice` the same way (see [Saved accounts](#saved-accounts)). If you're signed out, it fails with `not_signed_in`, whose `login.argv` is the `appbuilder login` command to run; it never falls back to an API key. API keys (deprecated) are used only with `-c <path>` or `--profile <name>`, and never touch the session; `--env`, `--business` or `--user` with either is a `usage_error`, and `APPBUILDER_BUSINESS` and `APPBUILDER_USER` are ignored. The credentials file must name a valid `environment` (`go`, `fmo`, `staging`, `integration`, `test1`); a missing or invalid one is refused with `credentials_invalid` rather than defaulting to production. Empty `apiKey`, `userId` or `businessId` are refused the same way. A `.kizenapp/config.json` `activeCredentialProfile` no longer selects an API key: the push uses the session and prints a one-line notice to stderr, so `--json` output stays clean. `credentialMode: "local"` doesn't affect block commands.
|
|
287
|
+
**Credentials.** Without `-c` or `--profile`, the push uses your [`appbuilder login`](#appbuilder-login-logout-whoami-and-auth-header) session for `--env`, or for the only environment you're signed in to. If you're signed in to several environments and pass no `--env`, the run is `needs_choice` with `choice: "environment"`. It uses that environment's current account, unless `--business` (and `--user`), or `APPBUILDER_BUSINESS` (and `APPBUILDER_USER`), names another saved account; then the environment without `--env` is the only one where that name matches a saved account, whether or not any account there is current, and several such environments are `needs_choice` the same way (see [Saved accounts](#saved-accounts)). If you're signed out, it fails with `not_signed_in`, whose `login.argv` is the `appbuilder login` command to run; it never falls back to an API key. API keys (deprecated) are used only with `-c <path>` or `--profile <name>`, and never touch the session; `--env`, `--business` or `--user` with either is a `usage_error`, and `APPBUILDER_BUSINESS` and `APPBUILDER_USER` are ignored. The credentials file must name a valid `environment` (`go`, `fmo`, `staging`, `e2e-staging`, `integration`, `e2e-integration`, `test1`, `perf`); a missing or invalid one is refused with `credentials_invalid` rather than defaulting to production. Empty `apiKey`, `userId` or `businessId` are refused the same way. A `.kizenapp/config.json` `activeCredentialProfile` no longer selects an API key: the push uses the session and prints a one-line notice to stderr, so `--json` output stays clean. `credentialMode: "local"` doesn't affect block commands.
|
|
288
288
|
|
|
289
289
|
**Write gating (headless).** `--dry-run` is always a dry run. Without `--yes` the run is a dry run too, and stderr says `Dry run only: pass --yes to write.` With `--yes`, `go` and `fmo` also need `--allow-production` (else `production_requires_flag`). A dry run's `applyArgv` is the command that writes what it showed: the same push with `--yes`, pinned to its dashboard and dashlet (`--dashboard` plus `--dashlet` or `--create`) and to the account the run signed in as, with `--allow-production` only on production, where `requiresProductionConsent` is `true` so an agent asks the user first. If the target dashlet was pushed from here before and its content has since been changed in Kizen, both dry runs and writes stop with `drift_detected` unless `--force` is passed.
|
|
290
290
|
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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=`
|
|
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","e2e-staging":"https://app.e2e-staging.kizen.com/api",integration:"https://integration.kizen.dev/api","e2e-integration":"https://e2e-integration.kizen.dev/api",test1:"https://app.test1.kizen.dev/api",perf:"https://app.perf.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","e2e-staging":"https://e2e-staging.kizen.com",integration:"https://v2.integration.kizen.dev","e2e-integration":"https://v2.e2e-integration.kizen.dev",test1:"https://test1.kizen.dev",perf:"https://perf.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,7 +82,7 @@ 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 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}
|
|
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","e2e-staging","integration","e2e-integration","test1","perf"];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
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
88
|
Business: ${Ni(t.businessName,t.businessId)}
|