@cognite/cli 1.9.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/cli.js CHANGED
@@ -1,26 +1,17 @@
1
1
  #!/usr/bin/env node
2
- var ws=Object.defineProperty;var er=e=>{throw TypeError(e)};var o=(e,t)=>ws(e,"name",{value:t,configurable:!0});var tr=(e,t,n)=>t.has(e)||er("Cannot "+n);var Ke=(e,t,n)=>(tr(e,t,"read from private field"),n?n.call(e):t.get(e)),nr=(e,t,n)=>t.has(e)?er("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),rr=(e,t,n,r)=>(tr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as gm}from"fs";import{Command as ym}from"commander";var _t=class _t extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let r=this.deriveDefaults(n);this.hint=n.hint??r.hint,this.helpUrl=n.helpUrl??r.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:Es(t.cause)}}};o(_t,"HintedError");var f=_t;function ir(e){return e instanceof f}o(ir,"isHintedError");var or="https://docs.cognite.com/cdf/access/",vs="https://status.cognite.com";function As(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:or};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:or};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:vs};default:return{}}}o(As,"defaultHintForStatus");var Ut=class Ut extends f{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,r=As(n),i=super.deriveDefaults(t);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(Ut,"HintedHttpError");var pe=Ut;function sr(e){return e instanceof pe}o(sr,"isHintedHttpError");function Cs(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Cs,"hintForErrno");function Es(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,i=Cs(r.code,r);if(i!==void 0)return i;t=r.cause}}o(Es,"hintForCause");function E(e=process.env){return e.COGNITE_ALPHA_ENABLE_SESSION_AUTH?.trim().toLowerCase()==="true"}o(E,"isSessionAuthEnabled");import{existsSync as ma,readFileSync as fa}from"fs";import{join as ga,resolve as Qe}from"path";import{verifyBundle as ya}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as ha}from"jose";import Kt from"enquirer";import{email as bs,pipe as ks,safeParse as Ps,string as xs}from"valibot";var Ds=ks(xs(),bs());function Se(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Ps(Ds,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(Se,"parseEmail");function we(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}o(we,"parseExpiryMonths");import{execFileSync as Be}from"child_process";import{execFileSync as Is}from"child_process";function je(e={}){let{execFileSync:t=Is}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(je,"isGitInstalled");function q(e={}){if(!je(e))throw new f("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}o(q,"throwIfGitMissing");function Ve(e,t={}){let{execFileSync:n=Be}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ve,"isInsideGitRepo");function ar(e,t={}){let{execFileSync:n=Be}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(ar,"gitInitAndCommit");function pr(e={}){let{execFileSync:t=Be}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(pr,"gitUserName");function cr(e={}){let{execFileSync:t=Be}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(cr,"gitUserEmail");import{inspect as Ts}from"util";var Lt="[REDACTED]",ce,Ge=class Ge{constructor(t){nr(this,ce);rr(this,ce,t)}toString(){return Lt}toJSON(){return Lt}[Ts.custom](){return Lt}expose(){return Ke(this,ce)}equals(t){return Ke(this,ce)===Ke(t,ce)}static from(t){return new Ge(t)}};ce=new WeakMap,o(Ge,"SensitiveString");var C=Ge;var Ye=3,lr="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",dr=`Key expiry in months (${1}-${12})`,ur="Email address for the registry entry",mr=`Passphrase for the encrypted private key (min ${15} chars)`,fr="Confirm passphrase",gr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),yr=o(e=>`Passphrases do not match (attempt ${e}/${Ye}).
3
- `,"passphraseMismatchMsg"),hr=`Passphrase confirmation failed after ${Ye} attempts`,Sr=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),wr="How would you like to submit your key registration?",vr="Open in browser",Ar="Copy link to clipboard";async function qe(e){return Kt.prompt(e)}o(qe,"defaultPrompt");function jt(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(jt,"parserAsValidator");var Fs=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function de(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!Fs.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}o(de,"parseKid");async function Cr(e={}){let{prompt:t=qe}=e,{kid:n}=await t({type:"input",name:"kid",message:lr,validate:jt(de)});return de(n)}o(Cr,"promptKid");async function Er(e={}){let{prompt:t=o(r=>Kt.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:wr,choices:[{name:"browser",message:vr},{name:"clipboard",message:Ar}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}o(Er,"promptZendeskAction");async function br(e={}){let{prompt:t=qe}=e,{months:n}=await t({type:"input",name:"months",message:dr,initial:String(6),validate:jt(r=>we(r,"expiry"))});return we(n,"expiry")}o(br,"promptExpiryMonths");async function kr(e={}){let{prompt:t=qe,gitUserEmail:n=cr}=e,{email:r}=await t({type:"input",name:"email",message:ur,initial:n(),validate:jt(i=>Se(i,"email"))});return Se(r,"email")}o(kr,"promptEmail");async function Pr(e={}){let{prompt:t=qe,stderr:n=process.stderr}=e;for(let r=1;r<=Ye;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:mr,validate:o(a=>a.length>=15?!0:gr(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:fr});if(i===s)return C.from(i);n.write(yr(r))}throw new Error(hr)}o(Pr,"promptPassphrase");async function xr(e,t={}){let{prompt:n=o(i=>Kt.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:Sr(e),initial:!1});return r}o(xr,"promptConfirmOverwrite");import{existsSync as Gs,readdirSync as Ys,readFileSync as qs}from"fs";import{join as Gt}from"path";import{execFile as Ms}from"child_process";import{promisify as _s}from"util";import{execFileSync as Dr}from"child_process";import{platform as $s}from"os";import Os from"path";function N(e,t={}){let{platform:n=$s}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(N,"isOS");function Ir(e,t={}){let{exec:n=Dr,log:r=console.log}=t,[i,s]=N("macos",t)?["open",[e]]:N("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{return n(i,s),!0}catch{return r(`Could not open browser \u2014 open manually:
4
- ${e}`),!1}}o(Ir,"openInBrowser");function Tr(e,t={}){let{exec:n=Dr,log:r=console.log}=t,[i,s]=N("macos",t)?["open",["-R",e]]:N("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Os.dirname(e)]];try{n(i,s)}catch{r(`Could not open file manager \u2014 files are at:
5
- ${e}`)}}o(Tr,"revealInFileManager");var Rr="cognite-flows",Us=_s(Ms),Fr=o((e,t)=>Us(e,t),"defaultExecFile"),Ls=-25300,Ns=Ls&255;function Hs(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Ns)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Hs,"isKeychainNotFoundError");async function $r(e,t,n={}){let r=t.expose();if(!N("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=Fr}=n;await i("security",["add-generic-password","-a",e,"-s",Rr,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}o($r,"storeKeyInKeychain");async function ze(e,t={}){if(!N("macos",t))return null;let{execFile:n=Fr}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Rr,"-w"]);return C.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(Hs(r))return null;throw r}}o(ze,"readKeyFromKeychain");var Mr="cognite-cli-signing",Ks="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",js="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",Or="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function Bs(e){if(!(e instanceof Error))return Or;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?Ks:t.includes("ambiguous")?js:Or}o(Bs,"hintFor");function _r(e,t,n){return new f(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:Bs(n),shouldReport:!1})}o(_r,"wrapKeyringError");async function Ur(e,t){let{Entry:n}=await import("@napi-rs/keyring"),r=new n(e,t);return{setPassword:o(i=>r.setPassword(i),"setPassword"),getPassword:o(()=>r.getPassword(),"getPassword"),deleteCredential:o(()=>r.deleteCredential(),"deleteCredential")}}o(Ur,"defaultCreateEntry");async function Lr(e,t,n={}){let{createEntry:r=Ur}=n,i=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(Mr,e)).setPassword(i)}catch(s){throw _r("store",e,s)}}o(Lr,"storeSigningKey");async function We(e,t={}){let{createEntry:n=Ur}=t;try{let i=(await n(Mr,e)).getPassword();return i===null?null:C.from(Buffer.from(i,"base64").toString("utf-8"))}catch(r){throw _r("read",e,r)}}o(We,"readSigningKey");import{homedir as Vs}from"os";import{join as Vt}from"path";function P(e={}){let{env:t=process.env,homedir:n=Vs}=e,r=t.COGNITE_CLI_HOME?.trim()||Vt(n(),".cognite-cli");return{home:r,keysDir:Vt(r,"keys"),sessionFile:Vt(r,"session.json")}}o(P,"getConfig");var ee=".pub.pem",Yt=".key.jwe",qt=".meta.json";function Je(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(Je,"formatLocalKeySource");function zs(e){return{existsSync:e.existsSync??Gs,readdirSync:e.readdirSync??Ys,readFileSync:e.readFileSync??((t,n)=>qs(t,n)),isOS:e.isOS??(t=>N(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>ze(t)),readSigningKey:e.readSigningKey??(t=>We(t))}}o(zs,"resolveDeps");function Ws(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(Ws,"readEmailFromMeta");function Js(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(ee)):[]}o(Js,"publicKeyEntries");function Xs(e){return e.slice(0,-ee.length)}o(Xs,"kidFromPublicKeyFilename");async function Zs(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let r=Gt(t,`${e}${Yt}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}o(Zs,"resolveSource");async function Xe(e=P().keysDir,t={}){let n=zs(t),r=new Set,i=Js(e,n).flatMap(s=>{let a=Xs(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await Zs(s,e,n),c=Gt(e,`${s}${qt}`),l;try{l=Ws(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:Gt(e,a),email:l}}))}o(Xe,"discoverLocalKeys");import{createReadStream as Qs}from"fs";function Ze(e){let t=Qs(e);return new ReadableStream({start(n){t.on("data",r=>{let i=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}o(Ze,"createWebStreamFromFile");import ea from"path";var Nr=".cognite-bundles";function Hr(e,t){return`${e}-${t}.zip`}o(Hr,"bundleFileName");function j(e,t,n){return ea.join(e,Nr,Hr(t,n))}o(j,"bundlePath");import{existsSync as la,readFileSync as da}from"fs";import{resolve as ua}from"path";import{array as Kr,boolean as ta,check as ve,forward as Ae,literal as na,maxLength as ra,minLength as oa,nonEmpty as te,object as jr,optional as X,picklist as ia,pipe as z,safeParse as sa,string as B,url as Br}from"valibot";var zt=z(B(),te("must not be empty")),Wt=z(B(),te("must not be empty"),ra(256,"must be 256 characters or fewer")),Jt=z(B(),te("must not be empty"),Br("must be a valid URL")),aa=z(B(),te("must not be empty"),Br("must be a valid URL")),Xt=z(B(),te("must not be empty")),Zt=z(B(),te("must not be empty")),pa=z(jr({org:Xt,project:Zt,baseUrl:Jt,deployClientId:X(B(),""),deploySecretName:X(B(),""),published:X(ta(),!1),idpType:X(ia(["cdf","entra_id","oauth"]),"cdf"),tenantId:X(B()),scopes:X(Kr(z(B(),te("must not be empty")))),tokenUrl:X(aa)}),Ae(ve(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Ae(ve(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),Ae(ve(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),Ae(ve(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),Ae(ve(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),Ae(ve(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),ca=jr({name:zt,externalId:Wt,versionTag:z(B(),te("must not be empty")),description:X(B(),""),deployments:z(Kr(pa),oa(1,"must contain at least one deployment")),infra:X(na("appsApi"))});function Qt(e){let t=sa(ca,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",i=r?`"${r}" `:"";throw new Error(`app.json: ${i}${n.message}`)}o(Qt,"validateAppConfig");function b(e,t={}){let{validator:n=Qt,existsSync:r=la,readFileSync:i=da}=t,s=ua(e,"app.json");if(!r(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}o(b,"loadAppConfig");var Vr=[".dev.sig",".cert.sig",".sig"];function Sa(e){return{existsSync:e.existsSync??ma,readFileSync:e.readFileSync??((t,n)=>fa(t,n)),createBundleStream:e.createBundleStream??Ze,verifyBundle:e.verifyBundle??ya,loadAppConfig:e.loadAppConfig??b,defaultKeyDir:e.defaultKeyDir??(()=>P().keysDir)}}o(Sa,"resolveDeps");function wa(e,t){return Vr.map(n=>`${e}${n}`).find(n=>t(n))}o(wa,"findSiblingSignature");function va(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}o(va,"isCompactJws");function Aa(e){try{let t=ha(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}o(Aa,"readKidFromToken");function Ca(e,t,n){let{existsSync:r,readFileSync:i}=n;try{de(e)}catch(a){throw new f(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!r(t))throw new f(`Key directory not found: ${t}`,{shouldReport:!1});let s=ga(t,`${e}${ee}`);if(!r(s))throw new f(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return i(s,"utf-8")}catch(a){throw new f(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}o(Ca,"resolvePublicKeyForKid");function Ea(e,t){let{payload:n,kid:r}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${r}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let i=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(n,null,2))}o(Ea,"printResult");async function Gr(e,t,n={},r=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=Sa(n),d;if(e)d=Qe(r,e);else{let m;try{m=a(r)}catch(h){let S=h instanceof Error?h.message:String(h);throw new f(S,{cause:h,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=j(r,m.externalId,m.versionTag)}if(!i(d)){let m=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new f(`Bundle not found: ${d}`,{hint:m,shouldReport:!1})}let u=t.sig?Qe(r,t.sig):wa(d,i);if(!u)throw new f("No signature file found.",{hint:`Pass --sig <path> or place one of ${Vr.map(m=>`${d}${m}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i(u))throw new f(`Signature file not found: ${u}`,{shouldReport:!1});let g;try{g=s(u,"utf-8").trim()}catch(m){throw new f(`Failed to read signature file: ${u}`,{cause:m,shouldReport:!1})}if(!va(g))throw new f(`Malformed JWS in ${u}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let y;if(t.key){let m=Qe(r,t.key);if(!i(m))throw new f(`Public key not found: ${m}`,{shouldReport:!1});try{y=s(m,"utf-8")}catch(h){throw new f(`Failed to read public key file: ${m}`,{cause:h,shouldReport:!1})}}else{let m=t.keyDir?Qe(r,t.keyDir):l(),h=Aa(g);if(!h)throw new f("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});y=Ca(h,m,{existsSync:i,readFileSync:s})}try{let m=await c({token:g,publicKeyPem:y,bundleStream:p(d)});Ea(m,t.verbose??!1)}catch(m){let h=m instanceof Error?m.message:String(m);throw new f(`Bundle rejected: ${h}`,{shouldReport:!1})}}o(Gr,"handleVerify");function Yr(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
6
- Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
7
-
8
- Examples:
9
- cognite apps verify Verify default bundle (path from app.json)
10
- cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
11
- cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
12
- cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,r)=>Gr(n,r,t))}o(Yr,"registerVerifyCommand");var qr="https://docs.cognite.com/cdf/access/";function H(e){return e!==null&&typeof e=="object"}o(H,"isRecord");function ue(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(ue,"isHttpError");function ba(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
- See: ${qr}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
- See: ${qr}`;default:return}}o(ba,"httpStatusHint");function W(e){let t=e instanceof Error?e:new Error(String(e));if(!ue(t))return null;let n=ba(t.status);return n?Object.assign(new Error(`${t.message}
15
- ${n}`),{cause:t}):null}o(W,"enrichedHttpError");function ka(e){if(!H(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(H(n)){let r=n.error;if(H(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(ka,"findMissingArray");function Pa(e,t){if(!ue(e)||e.status!==400)return!1;let n=ka(e);return n?n.some(r=>H(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(Pa,"isMissingExternalIdError");function et(e,t){return ue(e)&&e.status===404||Pa(e,t)}o(et,"isNotFoundError");var Wr=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Jr=["ACTIVE","PREVIEW"],en=class en extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(en,"AppVersionNotFoundError");var V=en,tn=class tn extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};o(tn,"AppNotFoundError");var Ce=tn;function tt(e,t){return e.includes(t)}o(tt,"includesValue");function xa(e){return tt(Wr,e)}o(xa,"isAppVersionLifecycleState");function Da(e){return tt(Jr,e)}o(Da,"isAppVersionAlias");function Ia(e){return typeof e.version=="string"&&xa(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Da(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Ia,"isAppVersion");function zr(e){if(!H(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Ia(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}o(zr,"parseAppVersion");function Ta(e){if(!H(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:r}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof r=="string"?r:void 0}}o(Ta,"parseAppMetadata");var nn=class nn{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(i){throw W(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw W(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return Ta(r.data)}catch(r){throw et(r,[t])?new Ce(t):W(r)??r}}async uploadVersion(t,n,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",n),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate();if(!l)throw new f("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=C.from(l),u=`${this.client.getBaseUrl()}${c}`,g=new AbortController,y=setTimeout(()=>g.abort(),300*1e3),m;try{m=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:g.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new f("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new f(`Failed to upload version to ${u}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(y)}if(!m.ok){let h=await m.text(),S;try{S=JSON.parse(h)}catch{}let A=h;if(H(S)){let G=S.error;if(typeof G=="string")A=G;else if(H(G)){let x=G.message,k=G.code;A=typeof x=="string"?x:k!=null?`Unknown error (code: ${k})`:h}else{let x=S.message;A=typeof x=="string"?x:h}}let v=m.headers.get("x-request-id"),w=v?` | X-Request-ID: ${v}`:"",D=H(S)?S:h;throw new pe(`Upload failed: ${m.status} \u2014 ${A}${w}`,{httpStatusCode:m.status,requestUrl:u,responseBody:D})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return zr(a.data)}catch(a){throw et(a,[t,n])?new V(t,n):W(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!H(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return zr(s[0])}catch(i){if(et(i,[t]))return null;throw W(i)??i}}async deleteVersions(t,n){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/delete`;try{await this.client.post(i,{data:{items:n.map(s=>({version:s}))}})}catch(s){throw W(s)??s}}async updateVersions(t,n){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw W(s)??s}}async submitSignatures(t,n,r){let i=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw W(p)??p}}async listSignatures(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return $a(a.data)}catch(a){throw W(a)??a}}};o(nn,"AppHostingApi");var nt=nn,Ra=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],Fa=["developer","certifier"];function $a(e){if(!H(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let r=Oa(n);return r?[r]:[]})}o($a,"parseStoredSignatures");function Oa(e){if(!H(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!tt(Fa,n)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!tt(Ra,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Oa,"parseStoredSignature");function rn(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let r=e.description??"";return r!==t.description&&n.push({field:"description",remote:r,local:t.description}),n}o(rn,"diffAppMetadata");function Ma(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:r,local:i}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${r}" \u2192 "${i}"`)}return t.join(`
16
- `)}o(Ma,"formatMetadataDriftError");var on=class on{constructor(t){this.api=new nt(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,i,s){return this.api.uploadVersion(t,n,r,i,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(i){if(ue(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,r);return}throw i}}async checkMetadataDrift(t,n,r){let i;try{i=await this.getApp(t)}catch{return}let s=rn(i,{name:n,description:r});if(s.length!==0)throw new f(Ma(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,r){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(t,n,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,r),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async deleteVersion(t,n){await this.api.deleteVersions(t,[n])}async deprecateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"ARCHIVED"}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let i=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,r,i,s,a,p=!1){console.log(`
17
- \u{1F680} Deploying application via App Hosting API...
18
- `),await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
19
- \u2705 Deployment successful!`)}};o(on,"AppHostingClient");var I=on;import{CogniteClient as Oo}from"@cognite/sdk";import za from"open";import{buildAuthorizationUrl as Wa,calculatePKCECodeChallenge as Ja,discovery as Xa,None as Za,randomPKCECodeVerifier as Qa,randomState as ep}from"openid-client";import Xr from"mixpanel";var _a="5c4d853e7c3b77b1eb4468d5329b278c",Ua="api-eu.mixpanel.com",xe="cognite-cli",La=2e3,Zr={env:process.env,init:Xr.init.bind(Xr)},Na={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function sn(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(sn,"isTelemetryDisabled");function Ha(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}o(Ha,"detectCiEnvironment");function Ka(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Ka,"isDebug");function rt(e={}){let t=e.env??Zr.env,n=e.init??Zr.init,r=e.packageName,i=e.cliVersion,s=Ka(t),a=Ha(t);if(sn(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
20
- `),Na;let p,c=new Set;function l(){if(p)return p;try{return p=n(_a,{geolocate:!1,keepAlive:!1,host:Ua}),p}catch{return}}return o(l,"getClient"),{track(d,u={}){let g=l();if(!g)return;let y={...u,applicationId:xe,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(y)}
21
- `);let m=o(()=>{},"finish"),h=new Promise(S=>{m=S});c.add(h);try{g.track(d,y,m)}catch{m()}h.finally(()=>c.delete(h))},async flush(d=La){if(c.size===0)return;let u,g=new Promise(y=>{u=setTimeout(y,d),u.unref?.()});try{await Promise.race([Promise.allSettled([...c]),g])}finally{u&&clearTimeout(u)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
22
- `)}}}o(rt,"createTelemetry");var ot={min:3100,max:3110},ja=`${ot.min}-${ot.max}`,De=`3000, or ${ja}`;function it(e){return Number.isInteger(e)?e===3e3||e>=ot.min&&e<=ot.max:!1}o(it,"isAllowedCallbackPort");function st(e){return`Unsupported callback port ${typeof e=="string"?`"${e}"`:e} \u2014 only ${De} are supported.`}o(st,"formatUnsupportedCallbackPort");import Va from"http";import{authorizationCodeGrant as Ga}from"openid-client";function Qr(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Qr,"escapeHtml");function an(e,t,n){let r=Qr(t),i=Qr(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
23
- <h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
2
+ var El=Object.defineProperty;var _r=e=>{throw TypeError(e)};var r=(e,t)=>El(e,"name",{value:t,configurable:!0});var jr=(e,t,n)=>t.has(e)||_r("Cannot "+n);var bt=(e,t,n)=>(jr(e,t,"read from private field"),n?n.call(e):t.get(e)),Hr=(e,t,n)=>t.has(e)?_r("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Br=(e,t,n,o)=>(jr(e,t,"write to private field"),o?o.call(e,n):t.set(e,n),n);import{writeSync as RS}from"fs";import{Command as IS}from"commander";var Bn=class Bn extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let o=this.deriveDefaults(n);this.hint=n.hint??o.hint,this.helpUrl=n.helpUrl??o.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:Pl(t.cause)}}};r(Bn,"HintedError");var m=Bn;function ue(e){return e instanceof m}r(ue,"isHintedError");var Kr="https://docs.cognite.com/cdf/access/",bl="https://status.cognite.com";function xl(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Kr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Kr};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:bl};default:return{}}}r(xl,"defaultHintForStatus");var Kn=class Kn extends m{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,o=xl(n),i=super.deriveDefaults(t);return{hint:o.hint??i.hint,helpUrl:o.helpUrl}}};r(Kn,"HintedHttpError");var de=Kn;function xt(e){return e instanceof de}r(xt,"isHintedHttpError");function kl(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}r(kl,"hintForErrno");function Pl(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let o=t,i=kl(o.code,o);if(i!==void 0)return i;t=o.cause}}r(Pl,"hintForCause");import{Command as Tl,Option as kt}from"commander";var Vr=Object.freeze({interactive:new kt("--interactive","Use browser-based authentication instead of env-var credentials").default(!1),baseUrl:new kt("--base-url <url>","CDF base URL (only with --interactive)"),project:new kt("--project <project>","CDF project name (only with --interactive)"),org:new kt("--org <org>","Organization hint for login (only with --interactive)")}),US=Object.values(Vr).map(e=>e.long),Tt=class Tt extends Tl{constructor(t){super(t);for(let n of Object.values(Vr))this.addOption(n)}createCommand(t){return new Tt(t)}};r(Tt,"BaseCommand");var Ee=Tt,Vn=class Vn extends Ee{constructor(t){super(t),this.configure()}};r(Vn,"CommandGroup");var Pt=Vn;import{performance as qr}from"perf_hooks";import{existsSync as Nl,readFileSync as _l}from"fs";import{resolve as jl}from"path";import{array as Gr,boolean as Rl,check as Ye,forward as ze,literal as Il,maxLength as Dl,minLength as $l,nonEmpty as Re,object as Yr,optional as be,picklist as Ol,pipe as me,safeParse as Fl,string as te,url as zr}from"valibot";var Gn=me(te(),Re("must not be empty")),Yn=me(te(),Re("must not be empty"),Dl(256,"must be 256 characters or fewer")),zn=me(te(),Re("must not be empty"),zr("must be a valid URL")),Ll=me(te(),Re("must not be empty"),zr("must be a valid URL")),qn=me(te(),Re("must not be empty")),Jn=me(te(),Re("must not be empty")),Ml=me(Yr({org:qn,project:Jn,baseUrl:zn,deployClientId:be(te(),""),deploySecretName:be(te(),""),published:be(Rl(),!1),idpType:be(Ol(["cdf","entra_id","oauth"]),"cdf"),tenantId:be(te()),scopes:be(Gr(me(te(),Re("must not be empty")))),tokenUrl:be(Ll)}),ze(Ye(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),ze(Ye(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),ze(Ye(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),ze(Ye(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Ul=Yr({name:Gn,externalId:Yn,versionTag:me(te(),Re("must not be empty")),description:be(te(),""),deployments:me(Gr(Ml),$l(1,"must contain at least one deployment")),infra:be(Il("appsApi"))});function Wn(e){let t=Fl(Ul,e);if(t.success)return t.output;let n=t.issues[0],o=n.path?.map(s=>s.key).join(".")??"",i=o?`"${o}" `:"";throw new Error(`app.json: ${i}${n.message}`)}r(Wn,"validateAppConfig");function k(e,t={}){let{validator:n=Wn,existsSync:o=Nl,readFileSync:i=_l}=t,s=jl(e,"app.json");if(!o(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),c;try{c=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(c)}r(k,"loadAppConfig");var qe=1e3,Rt;function Hl(){Rt=qr.now()}r(Hl,"markActionStart");function Bl(){Rt=void 0}r(Bl,"resetActionStart");function Zn(){if(Rt!==void 0)return Math.max(0,Math.round(qr.now()-Rt))}r(Zn,"snapshotActionDurationMs");function Jr(){let e=Zn();return Bl(),{...e!==void 0&&{actionDurationMs:e}}}r(Jr,"takePerformanceFields");var Kl=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description","externalId"]);function Xn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Kl.has(t)?[t,n]:[t,"[REDACTED]"]))}r(Xn,"sanitizeOptions");function Vl(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}r(Vl,"getCommandPath");function Wr(e){try{let t=e(process.cwd()),n=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...n&&{cogniteOrg:n.org,cogniteProject:n.project}}}catch{return{}}}r(Wr,"tryLoadAppConfig");function Qn(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}r(Qn,"commandFromArgv");function Zr(e,t,n=k){e.hook("preAction",()=>{Hl()}),e.hook("postAction",async(o,i)=>{try{let s={command:Vl(i),options:Xn(i.opts()),success:!0,...Wr(n),...Jr()};t.track("Flows.CLI.Command",{...s}),await t.flush(qe)}catch{}})}r(Zr,"instrument");async function Xr(e,t,n=k){try{let o={command:Qn(t),options:{},success:!1,...Wr(n),...Jr()};e.track("Flows.CLI.Command",{...o}),await e.flush(qe)}catch{}}r(Xr,"trackFailure");var Gl=Object.freeze({create:"Flows.CLI.Agents.Create",push:"Flows.CLI.Agents.Push",open:"Flows.CLI.Agents.Open",publish:"Flows.CLI.Agents.Publish",unpublish:"Flows.CLI.Agents.Unpublish",pull:"Flows.CLI.Agents.Pull",list:"Flows.CLI.Agents.List",status:"Flows.CLI.Agents.Status",eval:"Flows.CLI.Agents.Eval"});async function Qr(e,t){if(!e||t.name()==="eval")return;let n=Gl[t.name()];if(n)try{e.track(n,{command:t.name(),options:Xn(t.optsWithGlobals()),success:!0}),await e.flush(qe)}catch{}}r(Qr,"trackAgentsCommand");import{existsSync as as}from"fs";import{cp as ou,mkdir as cs,readFile as ko,writeFile as nn}from"fs/promises";import{basename as Po,dirname as ru,join as he,resolve as To}from"path";import{fileURLToPath as iu}from"url";import{Option as Be}from"commander";import Yl,{Chalk as zl}from"chalk";var rt=new zl({level:0});function P(e){return e.isTTY?Yl:rt}r(P,"chalkForStream");var ql="ERR_USE_AFTER_CLOSE";function ti(e){return e instanceof Error&&"code"in e&&e.code===ql}r(ti,"isReadlineClosedError");function Jl(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}r(Jl,"isPlainObject");function eo(e){return e==null||ti(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Jl(e)&&Object.keys(e).length===0)}r(eo,"isPromptCancel");var ei=!1;function It(){ei||(ei=!0,process.on("uncaughtException",e=>{ti(e)&&(console.error(`
3
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{eo(e)&&(console.error(`
4
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}r(It,"installCancelHandler");import{readdir as Wl,readFile as Zl}from"fs/promises";import{basename as ii,join as si}from"path";import{array as it,looseObject as ai,nullable as Xl,object as ci,optional as se,parse as li,record as Ql,string as K,unknown as ep}from"valibot";import{parse as tp,stringify as np}from"yaml";var A=Object.freeze({configSuffix:".agent.yaml",configGlob:"*.agent.yaml",readme:"README.md",readmeTemplate:"README_TEMPLATE.md",agentsMd:"AGENTS.md",agentsMdTemplate:"AGENTS_TEMPLATE.md",evalDir:"eval",evalCases:"eval.yaml",evalCasesTemplate:"EVAL_CASES_TEMPLATE.yaml"});function Ie(e){return`${e.replace(/[^A-Za-z0-9._-]/g,"_")}${A.configSuffix}`}r(Ie,"agentConfigFileName");var Me=`${A.evalDir}/${A.evalCases}`,ni={dirName:"my-agent"},oi=[".cursor/skills",".claude/skills"];var ri="cdf_industrial_v4";var op=ci({agentExternalId:K()}),rp=ci({question:K()}),ip=ai({name:K(),type:K(),description:K(),instructions:se(K()),configuration:se(Xl(Ql(K(),ep())))}),pi=ai({externalId:K(),name:K(),description:se(K()),instructions:se(K()),model:se(K()),runtimeVersion:se(K()),labels:se(it(K())),exampleQuestions:se(it(rp)),skills:se(it(K())),subagents:se(it(op)),tools:se(it(ip),[])});function sp(e){let t=tp(e);return li(pi,t)}r(sp,"parseAgentYaml");function ge(e){let t=li(pi,e);return np(t,{lineWidth:0})}r(ge,"serializeAgentYaml");async function st(e){let t;try{t=await Wl(e,{withFileTypes:!0})}catch{return[]}let n=A.configSuffix.toLowerCase();return t.filter(o=>o.name.toLowerCase().endsWith(n)&&!o.isDirectory()).map(o=>o.name).sort()}r(st,"findAgentYamlNames");async function ap(e){let t=await st(e);if(t.length===0)throw new m(`No ${A.configGlob} found in:
5
+ ${e}`,{hint:"Run this command from an agent project directory, or pass the directory as an argument.",shouldReport:!1});if(t.length===1)return si(e,t[0]);let n=Ie(ii(e)).toLowerCase(),o=t.find(i=>i.toLowerCase()===n);if(o!==void 0)return si(e,o);throw new m(`Found multiple ${A.configGlob} files in:
6
+ ${e}
7
+ ${t.map(i=>` - ${i}`).join(`
8
+ `)}`,{hint:`Each agent needs its own directory. Move the extra definitions elsewhere, or name the one you want after its folder (${Ie(ii(e))}).`,shouldReport:!1})}r(ap,"resolveAgentYamlPath");async function De(e){return(await at(e)).agent}r(De,"readAgentYaml");async function at(e){let t=await ap(e),n=await Zl(t,"utf8");return{path:t,agent:sp(n)}}r(at,"loadAgentYaml");function Ue(e){let{createdTime:t,lastUpdatedTime:n,ownerId:o,...i}=e;return i}r(Ue,"toAgentCreate");import di from"enquirer";var to=class to{constructor(t,n,o,i=[],s=di.prompt.bind(di)){this.dirArg=t;this.flags=n;this.isInteractive=o;this.availableModels=i;this.promptFn=s}async resolve(){let t=await this.getDirName();return{dirName:t,externalId:this.flags.externalId?.trim()||t,name:await this.getDisplayName(t),description:await this.getDescription(),model:await this.getModel(),instructions:await this.getInstructions(),runtimeVersion:this.flags.runtimeVersion?.trim()||void 0}}async getDirName(){return this.dirArg?this.dirArg:this.isInteractive?ct(this.promptFn,{message:"Agent name (used as directory and externalId)",initial:"my-agent",validate:ui("Agent name")}):ni.dirName}async getDisplayName(t){let n=this.flags.displayName?.trim();return n||(this.isInteractive?ct(this.promptFn,{message:"Display name",initial:t,validate:ui("Display name")}):t)}async getDescription(){let t=this.flags.description?.trim();if(t)return t;if(this.isInteractive){let n=await ct(this.promptFn,{message:"Description (optional)",initial:"",validate:r(()=>!0,"validate")});if(n)return n}}async getModel(){let t=this.flags.model?.trim();if(t)return t;if(this.isInteractive&&this.availableModels.length>0)return ct(this.promptFn,{message:"Model",choices:this.availableModels,initial:0})}async getInstructions(){let t=this.flags.instructions?.trim();if(t)return t;if(this.isInteractive){let n=await ct(this.promptFn,{message:"Agent instructions (custom behavior; built-in platform guidance applies automatically)",initial:"",validate:r(()=>!0,"validate")});if(n)return n}return cp}};r(to,"AgentCreateResolver");var Dt=to,cp=["Help users explore and understand the data in this project.","Use the available tools to retrieve data before answering.","When the data is insufficient, say so rather than guessing."].join(`
9
+ `);function ui(e){return r(function(n){return n.trim()?!0:`${e} is required`},"_requiredInner")}r(ui,"required");async function ct(e,t){if("choices"in t){let{value:o}=await e({type:"select",name:"value",...t});return o.trim()}let{value:n}=await e({type:"input",name:"value",...t});return n.trim()}r(ct,"ask");var $t={"cdf-version":"beta"};function ne(e){async function t(l){let p=c(e.project).concat("/ai/agents");return(await e.post(p,{data:{items:[l]},headers:$t})).data.items[0]}r(t,"upsert");async function n(l){let p=c(e.project).concat("/ai/agents/byids"),d;try{d=await e.post(p,{data:{items:[{externalId:l}]},headers:$t})}catch(g){throw o(g)&&g.status===422?new m(`Agent "${l}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1}):g}let u=d.data?.items??[];if(!u.length)throw new m(`Agent "${l}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1});return u[0]}r(n,"getByExternalId");function o(l){return typeof l=="object"&&l!==null&&"status"in l&&typeof l.status=="number"}r(o,"isHttpError");async function i(){let l=c(e.project).concat("/ai/agents");return(await e.get(l,{headers:$t})).data}r(i,"list");async function s(){let l=c(e.project).concat("/ai/availability");return(await e.get(l,{headers:$t})).data}r(s,"getServiceAvailability");async function a(){return(await s()).items.find(d=>d.path==="/ai/agents")?.supportedLanguageModels??[]}r(a,"getAvailableModels");function c(l){return`/api/v1/projects/${encodeURIComponent(l)}`}return r(c,"getBaseUrl"),{upsert:t,getByExternalId:n,list:i,getServiceAvailability:s,getAvailableModels:a}}r(ne,"getAgentsService");import{CogniteClient as Qd}from"@cognite/sdk";import{existsSync as gp,mkdirSync as fp,readFileSync as hp,renameSync as yp,rmSync as Sp,writeFileSync as wp}from"fs";import{dirname as vp}from"path";import{isoTimestamp as Cp,literal as Ap,nonEmpty as yi,object as Ep,pipe as Si,safeParse as bp,string as wi}from"valibot";import{homedir as lp}from"os";import{join as no}from"path";function D(e={}){let{env:t=process.env,homedir:n=lp}=e,o=t.COGNITE_CLI_HOME?.trim()||no(n(),".cognite-cli");return{home:o,keysDir:no(o,"keys"),sessionFile:no(o,"session.json")}}r(D,"getConfig");import{inspect as pp}from"util";var oo="[REDACTED]",Ne,Ot=class Ot{constructor(t){Hr(this,Ne);Br(this,Ne,t)}toString(){return oo}toJSON(){return oo}[pp.custom](){return oo}expose(){return bt(this,Ne)}equals(t){return bt(this,Ne)===bt(t,Ne)}static from(t){return new Ot(t)}};Ne=new WeakMap,r(Ot,"SensitiveString");var b=Ot;var _e="cognite-cli-session",dp=1280,up=process.platform==="win32"?dp:1/0,ro="cognite-session/chunks=";function Ft(e,t){return`${e}/chunk/${t}`}r(Ft,"chunkAccount");function io(e){if(!e.startsWith(ro))return null;let t=Number(e.slice(ro.length));return Number.isFinite(t)&&t>0?t:null}r(io,"parseChunkCount");async function mp(e,t){let{Entry:n}=await import("@napi-rs/keyring"),o=new n(e,t);return{setPassword:r(i=>o.setPassword(i),"setPassword"),getPassword:r(()=>o.getPassword(),"getPassword"),deleteCredential:r(()=>o.deleteCredential(),"deleteCredential")}}r(mp,"defaultCreateEntry");function so(e){return{createEntry:e.createEntry??mp,chunkSize:e.chunkSize??up}}r(so,"resolveDeps");async function mi(e,t,n={}){let{createEntry:o,chunkSize:i}=so(n),s=await o(_e,e),a=s.getPassword();if(a!==null){let p=io(a);if(p!==null)for(let d=0;d<p;d++)(await o(_e,Ft(e,d))).deleteCredential()}let c=t.expose();if(c.length<=i){s.setPassword(c);return}let l=[];for(let p=0;p<c.length;p+=i)l.push(c.slice(p,p+i));s.setPassword(`${ro}${l.length}`);for(let p=0;p<l.length;p++)(await o(_e,Ft(e,p))).setPassword(l[p])}r(mi,"storeSessionToken");async function gi(e,t={}){let{createEntry:n}=so(t),o=(await n(_e,e)).getPassword();if(o===null)return null;let i=io(o);if(i===null)return b.from(o);let s=[];for(let a=0;a<i;a++){let c=(await n(_e,Ft(e,a))).getPassword();if(c===null)return null;s.push(c)}return b.from(s.join(""))}r(gi,"readSessionToken");async function fi(e,t={}){let{createEntry:n}=so(t),o=await n(_e,e),i=o.getPassword();if(i!==null){let s=io(i);if(s!==null)for(let a=0;a<s;a++)(await n(_e,Ft(e,a))).deleteCredential()}o.deleteCredential()}r(fi,"deleteSessionToken");var Lt=1,co=r(e=>`${e}/accessToken`,"accessTokenAccount"),lo=r(e=>`${e}/refreshToken`,"refreshTokenAccount"),hi=Si(wi(),yi("must not be empty"),Cp("must be an ISO 8601 timestamp")),xp=Ep({version:Ap(Lt),org:Si(wi(),yi("must not be empty")),accessTokenExpiresAt:hi,refreshTokenExpiresAt:hi});function Mt(e){return{sessionFile:e.sessionFile??D().sessionFile,existsSync:e.existsSync??gp,readFileSync:e.readFileSync??hp,writeFileSync:e.writeFileSync??wp,mkdirSync:e.mkdirSync??fp,renameSync:e.renameSync??yp,rmSync:e.rmSync??Sp,storeSecret:e.storeSecret??mi,readSecret:e.readSecret??gi,deleteSecret:e.deleteSecret??fi}}r(Mt,"resolveDeps");var ao="Run `npx @cognite/cli auth logout` to clear it, then `npx @cognite/cli auth login` to sign in again.";function xe(e={}){let t=Mt(e);if(!t.existsSync(t.sessionFile))return null;let n=t.readFileSync(t.sessionFile,"utf-8"),o;try{o=JSON.parse(n)}catch{throw new Error(`Session file at ${t.sessionFile} is not valid JSON. ${ao}`)}let i=bp(xp,o);if(!i.success){let s=i.issues[0],a=s.path?.map(l=>l.key).join(".")??"",c=a?`"${a}" `:"";throw new Error(`Session file is invalid: ${c}${s.message}. ${ao}`)}return i.output}r(xe,"readSessionMetadata");async function lt(e={}){let t=Mt(e),n=xe(e);if(!n)return null;let[o,i]=await Promise.all([t.readSecret(co(n.org)),t.readSecret(lo(n.org))]);if(!o||!i)throw new Error(`Session metadata exists but its tokens are missing from the keychain. ${ao}`);return{...n,accessToken:o,refreshToken:i}}r(lt,"readSession");async function Ut(e,t={}){let n=Mt(t);await n.storeSecret(co(e.org),e.accessToken),await n.storeSecret(lo(e.org),e.refreshToken);let o={version:Lt,org:e.org,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshTokenExpiresAt:e.refreshTokenExpiresAt};n.mkdirSync(vp(n.sessionFile),{recursive:!0,mode:448});let i=`${n.sessionFile}.tmp`;n.writeFileSync(i,`${JSON.stringify(o,null,2)}
10
+ `,{mode:384});try{n.renameSync(i,n.sessionFile)}catch(s){throw n.rmSync(i,{force:!0}),s}}r(Ut,"writeSession");function kp(e){if(!e.existsSync(e.sessionFile))return null;try{let t=JSON.parse(e.readFileSync(e.sessionFile,"utf-8"));if(t&&typeof t=="object"&&"org"in t){let n=t.org;return typeof n=="string"&&n.length>0?n:null}}catch{}return null}r(kp,"readOrgLoosely");async function Nt(e={}){let t=Mt(e),n=kp(t);t.rmSync(t.sessionFile,{force:!0}),n&&(await t.deleteSecret(co(n)),await t.deleteSecret(lo(n)))}r(Nt,"clearSession");var Pp=300*1e3;function je(e,t=new Date){let n=t.getTime();return Date.parse(e.refreshTokenExpiresAt)<=n?"EXPIRED":Date.parse(e.accessTokenExpiresAt)-n<=Pp?"EXPIRING":"VALID"}r(je,"tokenState");import ud from"path";import{lock as md}from"proper-lockfile";import{None as td,discovery as nd,tokenRevocation as od,refreshTokenGrant as rd}from"openid-client";import{buildAuthorizationUrl as Yp,calculatePKCECodeChallenge as zp,discovery as qp,None as Jp,randomPKCECodeVerifier as Wp,randomState as Zp}from"openid-client";import vi from"mixpanel";var Tp="5c4d853e7c3b77b1eb4468d5329b278c",Rp="api-eu.mixpanel.com",pt="cognite-cli",Ip=2e3,Ci={env:process.env,init:vi.init.bind(vi)},Dp={track:r(()=>{},"track"),flush:r(async()=>{},"flush")};function po(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}r(po,"isTelemetryDisabled");function $p(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}r($p,"detectCiEnvironment");function Op(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}r(Op,"isDebug");function _t(e={}){let t=e.env??Ci.env,n=e.init??Ci.init,o=e.packageName,i=e.cliVersion,s=Op(t),a=$p(t);if(po(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
11
+ `),Dp;let c,l=new Set;function p(){if(c)return c;try{return c=n(Tp,{geolocate:!1,keepAlive:!1,host:Rp}),c}catch{return}}return r(p,"getClient"),{track(d,u={}){let g=p();if(!g)return;let h={...u,applicationId:pt,...o&&{packageName:o},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(h)}
12
+ `);let f=r(()=>{},"finish"),y=new Promise(S=>{f=S});l.add(y);try{g.track(d,h,f)}catch{f()}y.finally(()=>l.delete(y))},async flush(d=Ip){if(l.size===0)return;let u,g=new Promise(h=>{u=setTimeout(h,d),u.unref?.()});try{await Promise.race([Promise.allSettled([...l]),g])}finally{u&&clearTimeout(u)}s&&process.stderr.write(`[telemetry] flush done (${l.size} still pending)
13
+ `)}}}r(_t,"createTelemetry");var jt={min:3100,max:3110},Fp=`${jt.min}-${jt.max}`,dt=`3000, or ${Fp}`;function Ht(e){return Number.isInteger(e)?e===3e3||e>=jt.min&&e<=jt.max:!1}r(Ht,"isAllowedCallbackPort");function Bt(e){return`Unsupported callback port ${typeof e=="string"?`"${e}"`:e} \u2014 only ${dt} are supported.`}r(Bt,"formatUnsupportedCallbackPort");import Mp from"http";import{authorizationCodeGrant as Up}from"openid-client";function Ai(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}r(Ai,"escapeHtml");function uo(e,t,n){let o=Ai(t),i=Ai(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
14
+ <h1>${o}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
24
15
  @keyframes checkmark {
25
16
  0% { transform: scale(0); }
26
17
  50% { transform: scale(1.2); }
@@ -28,49 +19,178 @@ Examples:
28
19
  }
29
20
  h1 { animation: checkmark 0.5s ease-out; }
30
21
  </style>`:""}
31
- </body></html>`}o(an,"generateHtml");import Ba from"net";function eo(e,t){return new Promise(n=>{let r=new Ba.Socket,i=o(s=>{r.removeAllListeners(),r.destroy(),n(s)},"done");r.setTimeout(500),r.once("connect",()=>i(!1)),r.once("timeout",()=>i(!0)),r.once("error",()=>i(!0)),r.connect(e,t)})}o(eo,"isHostPortFree");function at(e){return`Port ${e} is already in use. Pin another callback port with --port <port> \u2014 supported ports are ${De}.`}o(at,"freePortHint");async function to(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([eo(e,"127.0.0.1"),eo(e,"::1")])).every(Boolean)}o(to,"isPortFree");async function Ya(e,t,n,r,i,s){let{authorizationCodeGrant:a,logger:p}=s,c=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`);if(c.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{p.log("\u{1F504} Exchanging authorization code for tokens...");let l=await a(n,c,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),t.end(an("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:l}}catch(l){let d=l instanceof Error?l:new Error(String(l));return t.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),t.end(an("error","Authentication Error",d.message)),{shouldClose:!0,error:d}}}o(Ya,"handleCallback");function qa(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(qa,"formatTimeoutMinutes");function no(e,t,n,r,i={createServer:Va.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Ga,logger:console}){let{createServer:s,setTimeout:a,clearTimeout:p,logger:c}=i;return new Promise((l,d)=>{let u=s(async(m,h)=>{try{let S=await Ya(m,h,t,n,r,i);S.shouldClose&&(y(),S.error?d(S.error):S.tokens?l(S.tokens):d(new Error("No tokens received")))}catch(S){y(),d(S instanceof Error?S:new Error(String(S)))}}),g=a(()=>{y(),d(new Error(`Login timeout - no response received within ${qa(e.loginTimeout)}`))},e.loginTimeout);function y(){p(g),u.close(),u.closeIdleConnections?.()}o(y,"cleanup"),u.on("error",m=>{y(),m.code==="EADDRINUSE"||m.code==="EACCES"?d(new f(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:at(e.port)})):d(new f(`Login callback server failed: ${m.message}`,{cause:m}))}),u.listen(e.port,"127.0.0.1",()=>{c.log(`\u{1F310} Local HTTP server started on http://localhost:${e.port}`)})})}o(no,"startCallbackServer");var pn="openid profile email";function cn(e){return`http://localhost:${e}/`}o(cn,"callbackRedirectUri");var ln={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:cn(3e3),port:3e3,loginTimeout:300*1e3},tp={open:za,startCallbackServer:no,isPortFree:to,discovery:Xa,buildAuthorizationUrl:Wa,randomPKCECodeVerifier:Qa,calculatePKCECodeChallenge:Ja,randomState:ep,logger:console,telemetry:rt()};async function Ie(e,t=ln,n){return n===void 0?oo(e,t,tp):oo(e,t,n)}o(Ie,"login");async function np(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,Za())}catch(r){throw new f(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}o(np,"fetchOpenIdConfig");async function oo(e,t,n){let{isPortFree:r,telemetry:i,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:p,randomState:c,buildAuthorizationUrl:l,open:d,startCallbackServer:u}=n;if(!await r(t.port))throw i?.track("Flows.CLI.PortInUse",{port:t.port}),new f(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:at(t.port)});s.log(`\u{1F510} Starting CDF login flow...
32
- `),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let y=await np(n,t),m=a(),h=await p(m),S=c(),A={redirect_uri:t.redirectUri,scope:t.scope??pn,code_challenge:h,code_challenge_method:"S256",state:S};e&&(A.organization_hint=e);let v=l(y,A).toString();e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
33
- `);try{await d(v)}catch(w){let D=w instanceof Error?w.message:String(w);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${D}`),s.error(`Please open this URL manually:
34
- `),s.error(v),s.error("")}return u(t,y,m,S)}o(oo,"loginImpl");import rp from"enquirer";function op(e){return`${e.org}/${e.project}`}o(op,"targetLabel");var pt=o(async function(e,t,n,r={isTTY:process.stdin.isTTY??!1,confirm:o(i=>rp.prompt({type:"confirm",name:"confirmed",message:i,initial:!1}),"confirm")}){let{isTTY:i,confirm:s}=r,a=op(e);if(t.confirmActionTarget!==void 0){if(t.confirmActionTarget===a)return;throw new f(`--confirm-action-target "${t.confirmActionTarget}" does not match the deployment this command resolved to ("${a}").`,{shouldReport:!1,hint:`Pass --confirm-action-target ${a} to ${n}.`})}if(console.warn(`
35
- Using session credentials \u2014 your token has access to all projects in the "${e.org}" organization.`),!i)throw new f("Session credentials detected but no TTY available for confirmation.",{shouldReport:!1,hint:"Pass --confirm-action-target <org/project> to skip the prompt, or configure deployClientId and deploySecretName in app.json."});let{confirmed:p}=await s(`Confirm ${n} to ${a}?`);if(!p)throw new f("Aborted.",{shouldReport:!1})},"confirmActionTarget");import ip from"enquirer";var sp=o(e=>ip.prompt(e),"defaultPrompt");function ap(e){switch(e.method){case"client-credentials":return"Use client credentials from app.json";case"session":return`Reuse existing session for ${e.org}`;case"browser":return"One-off sign-in via browser (does not save a session; use `cognite auth login` for that)"}}o(ap,"choiceLabel");async function ct(e,t=sp){if(e.length===0)throw new f("No valid authentication method available.",{hint:"Run `cognite auth login` and authenticate to the correct organization, or set deployClientId/deploySecretName in app.json."});let n=e.map(a=>a.method);if(new Set(n).size!==n.length)throw new Error(`Cannot present a selection with duplicate method names (${n.join(", ")}).`);let r=Array.from(new Set(n)).join("|"),{choice:i}=await t({type:"select",name:"choice",message:`Multiple valid authentication methods detected (skip with --auth-method <${r}>). Authenticate with`,choices:e.map(a=>({name:a.method,message:ap(a)}))}),s=e.find(a=>a.method===i);if(!s)throw new f(`Selected authentication method "${i}" was not offered.`,{hint:"Pass --auth-method to choose one of the offered methods explicitly."});return s}o(ct,"promptAuthMethod");async function io(e,t,n,r={confirmActionTarget:pt,promptAuthMethod:ct,isTTY:process.stdin.isTTY??!1}){let{valid:i}=e;if(i.length===0)throw pp(e,t);let s;if(n.authMethod){let a=i.find(p=>p.method===n.authMethod);if(!a)throw new f(`Pass --auth-method ${i.map(p=>p.method).join(" or --auth-method ")} \u2014 "${n.authMethod}" is not currently valid for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login` for a session, set deployClientId/deploySecretName in app.json for client credentials, or pass --interactive for browser login."});s=a}else if(i.length===1)[s]=i;else if(r.isTTY)s=await r.promptAuthMethod(i);else throw new f(`Pass --auth-method ${i.map(a=>a.method).join("|")} to choose non-interactively \u2014 several are valid for ${t.project} @ ${t.baseUrl} and there is no TTY to prompt.`,{shouldReport:!1,hint:"Or re-run in an interactive terminal to pick from the prompt."});if(s.method==="session"&&n.action&&!n.interactive)await r.confirmActionTarget(t,{confirmActionTarget:n.confirmActionTarget},n.action);else if(n.confirmActionTarget!==void 0&&s.method!=="session")throw new f(`Remove --confirm-action-target \u2014 it only guards session credentials and is never validated against the selected deployment with ${s.method} authentication.`,{shouldReport:!1,hint:"Pass --auth-method session (or pick the session option at the prompt) if you meant to acknowledge a session target."});return s}o(io,"chooseAuthMethod");function pp(e,t){let{invalidSession:n}=e;if(!n)return new f(`No credentials available for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login`, set deployClientId/deploySecretName in app.json, or pass --interactive."});let r=`Run \`cognite auth login\` for "${t.org}", or pass --interactive.`;return n.reason==="SESSION_EXPIRED"?new f(`Your session for organization "${n.org}" has expired.`,{hint:r}):new f(`Your active session is for organization "${n.org}", but this command targets "${t.org}".`,{hint:r})}o(pp,"createNoCredentialsError");import{existsSync as up,mkdirSync as mp,readFileSync as fp,renameSync as gp,rmSync as yp,writeFileSync as hp}from"fs";import{dirname as Sp}from"path";import{isoTimestamp as wp,literal as vp,nonEmpty as lo,object as Ap,pipe as uo,safeParse as Cp,string as mo}from"valibot";var me="cognite-cli-session",cp=1280,lp=process.platform==="win32"?cp:1/0,dn="cognite-session/chunks=";function lt(e,t){return`${e}/chunk/${t}`}o(lt,"chunkAccount");function un(e){if(!e.startsWith(dn))return null;let t=Number(e.slice(dn.length));return Number.isFinite(t)&&t>0?t:null}o(un,"parseChunkCount");async function dp(e,t){let{Entry:n}=await import("@napi-rs/keyring"),r=new n(e,t);return{setPassword:o(i=>r.setPassword(i),"setPassword"),getPassword:o(()=>r.getPassword(),"getPassword"),deleteCredential:o(()=>r.deleteCredential(),"deleteCredential")}}o(dp,"defaultCreateEntry");function mn(e){return{createEntry:e.createEntry??dp,chunkSize:e.chunkSize??lp}}o(mn,"resolveDeps");async function so(e,t,n={}){let{createEntry:r,chunkSize:i}=mn(n),s=await r(me,e),a=s.getPassword();if(a!==null){let l=un(a);if(l!==null)for(let d=0;d<l;d++)(await r(me,lt(e,d))).deleteCredential()}let p=t.expose();if(p.length<=i){s.setPassword(p);return}let c=[];for(let l=0;l<p.length;l+=i)c.push(p.slice(l,l+i));s.setPassword(`${dn}${c.length}`);for(let l=0;l<c.length;l++)(await r(me,lt(e,l))).setPassword(c[l])}o(so,"storeSessionToken");async function ao(e,t={}){let{createEntry:n}=mn(t),r=(await n(me,e)).getPassword();if(r===null)return null;let i=un(r);if(i===null)return C.from(r);let s=[];for(let a=0;a<i;a++){let p=(await n(me,lt(e,a))).getPassword();if(p===null)return null;s.push(p)}return C.from(s.join(""))}o(ao,"readSessionToken");async function po(e,t={}){let{createEntry:n}=mn(t),r=await n(me,e),i=r.getPassword();if(i!==null){let s=un(i);if(s!==null)for(let a=0;a<s;a++)(await n(me,lt(e,a))).deleteCredential()}r.deleteCredential()}o(po,"deleteSessionToken");var dt=1,gn=o(e=>`${e}/accessToken`,"accessTokenAccount"),yn=o(e=>`${e}/refreshToken`,"refreshTokenAccount"),co=uo(mo(),lo("must not be empty"),wp("must be an ISO 8601 timestamp")),Ep=Ap({version:vp(dt),org:uo(mo(),lo("must not be empty")),accessTokenExpiresAt:co,refreshTokenExpiresAt:co});function ut(e){return{sessionFile:e.sessionFile??P().sessionFile,existsSync:e.existsSync??up,readFileSync:e.readFileSync??fp,writeFileSync:e.writeFileSync??hp,mkdirSync:e.mkdirSync??mp,renameSync:e.renameSync??gp,rmSync:e.rmSync??yp,storeSecret:e.storeSecret??so,readSecret:e.readSecret??ao,deleteSecret:e.deleteSecret??po}}o(ut,"resolveDeps");var fn="Run `npx @cognite/cli auth logout` to clear it, then `npx @cognite/cli auth login` to sign in again.";function fe(e={}){let t=ut(e);if(!t.existsSync(t.sessionFile))return null;let n=t.readFileSync(t.sessionFile,"utf-8"),r;try{r=JSON.parse(n)}catch{throw new Error(`Session file at ${t.sessionFile} is not valid JSON. ${fn}`)}let i=Cp(Ep,r);if(!i.success){let s=i.issues[0],a=s.path?.map(c=>c.key).join(".")??"",p=a?`"${a}" `:"";throw new Error(`Session file is invalid: ${p}${s.message}. ${fn}`)}return i.output}o(fe,"readSessionMetadata");async function Te(e={}){let t=ut(e),n=fe(e);if(!n)return null;let[r,i]=await Promise.all([t.readSecret(gn(n.org)),t.readSecret(yn(n.org))]);if(!r||!i)throw new Error(`Session metadata exists but its tokens are missing from the keychain. ${fn}`);return{...n,accessToken:r,refreshToken:i}}o(Te,"readSession");async function mt(e,t={}){let n=ut(t);await n.storeSecret(gn(e.org),e.accessToken),await n.storeSecret(yn(e.org),e.refreshToken);let r={version:dt,org:e.org,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshTokenExpiresAt:e.refreshTokenExpiresAt};n.mkdirSync(Sp(n.sessionFile),{recursive:!0,mode:448});let i=`${n.sessionFile}.tmp`;n.writeFileSync(i,`${JSON.stringify(r,null,2)}
36
- `,{mode:384});try{n.renameSync(i,n.sessionFile)}catch(s){throw n.rmSync(i,{force:!0}),s}}o(mt,"writeSession");function bp(e){if(!e.existsSync(e.sessionFile))return null;try{let t=JSON.parse(e.readFileSync(e.sessionFile,"utf-8"));if(t&&typeof t=="object"&&"org"in t){let n=t.org;return typeof n=="string"&&n.length>0?n:null}}catch{}return null}o(bp,"readOrgLoosely");async function ft(e={}){let t=ut(e),n=bp(t);t.rmSync(t.sessionFile,{force:!0}),n&&(await t.deleteSecret(gn(n)),await t.deleteSecret(yn(n)))}o(ft,"clearSession");var kp=300*1e3;function ge(e,t=new Date){let n=t.getTime();return Date.parse(e.refreshTokenExpiresAt)<=n?"EXPIRED":Date.parse(e.accessTokenExpiresAt)-n<=kp?"EXPIRING":"VALID"}o(ge,"tokenState");import Lp from"path";import{lock as Np}from"proper-lockfile";import{None as Pp,discovery as xp,tokenRevocation as Dp,refreshTokenGrant as Ip}from"openid-client";var gt={...ln,scope:`${pn} offline_access`},Tp=3600,Rp=1500*60;function go(e){return xp(new URL(e.authority),e.clientId,void 0,Pp())}o(go,"discoverDefault");function fo(e){let t=typeof e=="string"?Number(e):e;return typeof t=="number"&&Number.isFinite(t)?t:void 0}o(fo,"asSeconds");function yo(e,t,n=new Date,r={}){let i=t.access_token?C.from(t.access_token):null;if(!i)throw new f("Login succeeded but no access token was returned.",{hint:"The identity provider did not return an access token. Please try logging in again."});let s=t.refresh_token?C.from(t.refresh_token):r.previousRefreshToken;if(!s)throw new f("Login succeeded but no refresh token was returned.",{hint:"The identity provider may not support the `offline_access` scope, which is required for persisted sessions."});let a=n.getTime(),p=(fo(t.expires_in)??Tp)*1e3,c=(fo(t.refresh_expires_in)??Rp)*1e3;return{version:dt,org:e.org,accessToken:i,refreshToken:s,accessTokenExpiresAt:new Date(a+p).toISOString(),refreshTokenExpiresAt:new Date(a+c).toISOString()}}o(yo,"buildSession");async function ho(e,t={}){if(e.port!==void 0&&!it(e.port))throw new f(st(e.port));let{login:n=o((a,p)=>Ie(a,p),"login"),now:r=o(()=>new Date,"now")}=t,i=e.port===void 0?gt:{...gt,port:e.port,redirectUri:cn(e.port)},s=await n(e.org,i);return yo(e,s,r())}o(ho,"loginForSession");async function So(e,t={}){let{discovery:n=go,tokenRevocation:r=o((s,a)=>Dp(s,a.expose()),"tokenRevocation")}=t,i=await n(gt);await r(i,e)}o(So,"revokeRefreshToken");async function wo(e,t={}){let n=t.discovery??go,r=t.refreshTokenGrant??((p,c)=>Ip(p,c.expose())),i=t.now??(()=>new Date),s=await n(gt),a=await r(s,e.refreshToken);return yo({org:e.org},a,i(),{previousRefreshToken:e.refreshToken})}o(wo,"refreshSession");function vo(e){if(typeof e!="object"||e===null)return!1;if("error"in e&&typeof e.error=="string"&&e.error==="invalid_grant")return!0;if(e instanceof Error)return/invalid_grant/i.test(e.message);let t="message"in e&&typeof e.message=="string"?e.message:"";return/invalid_grant/i.test(t)}o(vo,"isInvalidGrant");var Fp="https://auth.cognite.com",hn=class hn extends Error{constructor(n,r,i){super(r,i);this.kind=n;this.name="SessionVerificationError"}};o(hn,"SessionVerificationError");var Ee=hn;function $p(e){return e instanceof Error?"cause"in e&&e.cause instanceof Error?e.cause.message:e.message:String(e)}o($p,"describeTransportError");function Op(e){return!(typeof e!="object"||e===null||"sub"in e&&typeof e.sub!="string"||"email"in e&&typeof e.email!="string"||"name"in e&&typeof e.name!="string"||"preferred_username"in e&&typeof e.preferred_username!="string")}o(Op,"isJwtClaims");function Mp(e){try{let t=e.expose().split(".");if(t.length!==3)return{};let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));return Op(n)?n:{}}catch{return{}}}o(Mp,"decodeJwtClaims");function _p(e){return typeof e!="object"||e===null?!1:"items"in e?Array.isArray(e.items)?e.items.every(t=>typeof t=="object"&&t!==null&&"name"in t&&typeof t.name=="string"):!1:!0}o(_p,"isCogIdpProjectsResponse");function Up(e){if(e)try{return new URL(e).host}catch{return}}o(Up,"clusterFromApiUrl");async function Ao(e,t={}){let n=t.fetch??globalThis.fetch,r=`${Fp}/api/v0/orgs/${encodeURIComponent(e.org)}/projects`,i;try{i=await n(r,{headers:{Authorization:`Bearer ${e.accessToken.expose()}`}})}catch(l){throw new Ee("unreachable",$p(l),{cause:l})}if(!i.ok)throw new Ee("rejected",`CogIdP rejected the token: ${i.status} ${i.statusText}`);let s=await i.json(),p=((_p(s)?s:{}).items??[]).map(l=>({name:l.name,cluster:Up(l.apiUrl),...l.isDefault?{isDefault:!0}:{}})),c=Mp(e.accessToken);return{sub:c.sub??"unknown",email:c.email,name:c.name,preferredUsername:c.preferred_username,projects:p}}o(Ao,"fetchSessionUserInfo");var Hp=3e4,Sn=class Sn extends f{constructor(t){super("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,...t===void 0?{}:{cause:t}}),this.name="SessionExpiredError"}};o(Sn,"SessionExpiredError");var Re=Sn;function yt(e){return new Re(e)}o(yt,"expiredError");async function Kp(e,t,n){let r=await e(Lp.dirname(t),{stale:Hp,retries:{retries:10,factor:1.5,minTimeout:100,maxTimeout:1e3}});try{return await n()}finally{await r()}}o(Kp,"withSessionLock");async function ht(e={}){let t=e.readSession??(()=>Te()),n=e.now??(()=>new Date),r=e.sessionFile??P().sessionFile,i=e.lock??Np,s=await t();if(!s)return;let a=ge(s,n());if(a==="EXPIRED")throw yt();return a==="VALID"?s:Kp(i,r,async()=>{let p=await t()??s,c=ge(p,n());if(c==="EXPIRED")throw yt();return c==="VALID"?p:jp(p,e)})}o(ht,"ensureFreshSession");async function jp(e,t){let n=t.readSession??(()=>Te()),r=t.writeSession??(s=>mt(s)),i=t.refreshSession??(s=>wo(s));try{let s=await i(e);return await r(s),s}catch(s){if(!vo(s))throw s;let a=await n();if(a&&!a.refreshToken.equals(e.refreshToken))try{let p=await i(a);return await r(p),p}catch(p){throw yt(p)}throw yt(s)}}o(jp,"refreshAndPersist");function Co(e,t,n){return e?t.org&&e.org!==t.org?{reason:"DIFFERENT_ORG",org:void 0}:ge(e,n)==="EXPIRED"?{reason:"SESSION_EXPIRED",org:void 0}:{org:e.org,reason:"VALID"}:{reason:"SESSION_MISSING",org:void 0}}o(Co,"getSessionOrgIfValid");function Eo(e,t,n){let r=[];e.deployClientId&&r.push({method:"client-credentials",org:e.org});let i=n.readSessionMetadata(),s=Co(i,e,n.now());return s.reason==="VALID"&&r.push({method:"session",org:s.org}),t.interactive&&r.push({method:"browser"}),i&&(s.reason==="SESSION_EXPIRED"||s.reason==="DIFFERENT_ORG")?{valid:r,invalidSession:{reason:s.reason,org:i.org}}:{valid:r}}o(Eo,"validAuthMethods");import{CogniteClient as Zp}from"@cognite/sdk";function Bp(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Bp,"exponentialBackoffWithJitter");function Vp(e){return new Promise(t=>setTimeout(t,e))}o(Vp,"sleep");async function bo(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Bp;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!r(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await Vp(p),s++}}o(bo,"retryAsync");var Gp="https://auth.cognite.com/oauth2/token",Yp=o(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function ko({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let i;try{i=await bo(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new f(`Failed to fetch access token from ${t}`,{cause:p})}if(!i.ok){let p=await i.text();throw new pe(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:p})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new f(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!Yp(a))throw new f(`No access token in ${e} authentication response`,{hint:r});return C.from(a.access_token)}o(ko,"fetchOAuthToken");var qp=o(e=>{let t=e.DEPLOYMENT_SECRETS;if(!t)return{};try{let n=JSON.parse(t),r={};for(let[i,s]of Object.entries(n))if(typeof s=="string"){let a=i.toLowerCase().replace(/_/g,"-");r[a]=s}return r}catch(n){return console.error("Error parsing DEPLOYMENT_SECRETS:",n),{}}},"loadSecretsFromEnv"),zp=o((e,t)=>{let n;if(t.DEPLOYMENT_SECRET&&(n=t.DEPLOYMENT_SECRET),n||(n=qp(t)[e]),n||(n=t[e]),!n)throw new f(`Set the ${e} environment variable (named by deploySecretName in app.json) to your deploy client secret, e.g. in a .env file.`,{shouldReport:!1,hint:E(t)?"Alternatively, run `cognite auth login` to use your session, or pass --interactive for a one-off browser login.":"Alternatively, pass --interactive for a one-off browser login."});return C.from(n)},"getSecretFromEnv"),Wp=o((e,t)=>{let n=t.expose();return ko({idp:"CDF",tokenUrl:Gp,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${n}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),Po=o(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:i,missingTokenHint:s})=>ko({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Jp=o((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),Xp=o((e,t,n,r,i)=>Po({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[Jp(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),wn=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return C.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=zp(r,t);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Po({idp:"OAuth",tokenUrl:c,clientId:n,clientSecret:l.expose(),scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Xp(n,l,s,a,p)}return Wp(n,l)},"getToken");async function ye(e,t,n=process.env,r){let i=await wn(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Zp(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(ye,"getSdk");async function be(e,t,n,r){let i=r({appId:t,project:e.project,baseUrl:e.baseUrl,oidcTokenProvider:o(async()=>n.expose(),"oidcTokenProvider")});return await i.authenticate(),i}o(be,"buildAuthenticatedClient");async function xo(e,t,n){let{loginFn:r,createClient:i}=n,s=t.orgHint||e.org||void 0,a=await r(s);return be(e,t.appId,C.from(a.access_token),i)}o(xo,"resolveViaBrowser");import{HttpError as Qp}from"@cognite/sdk";import{array as Do,number as ec,object as Io,optional as tc,safeParse as nc,string as rc}from"valibot";var oc=Io({projects:tc(Do(Io({projectUrlName:rc(),groups:Do(ec())})))});function ic(e,t){switch(e){case 401:return"Run `cognite auth login` to log in.";case 403:return"The token is valid but lacks access to this project. Ask your CDF admin to grant its service account access.";default:return e>=500?`${t} returned a server error \u2014 this is usually transient, so try again shortly.`:"Check that the deployment base URL and project in app.json are correct."}}o(ic,"hintForStatus");var To=o(async function(e){let t=e.getBaseUrl(),n;try{({data:n}=await e.get("/api/v1/token/inspect"))}catch(i){throw i instanceof Qp?new f(`Could not verify project access against ${t} (${i.status}).`,{hint:ic(i.status,t),cause:i}):new f(`Could not connect to ${t} to verify project access.`,{hint:"Check your network connection and verify that the base URL is correct.",cause:i})}let r=nc(oc,n);if(!r.success)throw new f(`Unexpected response from ${t}/api/v1/token/inspect.`,{hint:"Retry; if it persists, your CLI may be out of date or a proxy is altering responses.",cause:new Error(JSON.stringify(r.issues))});return r.output},"inspectDeploymentToken");async function Ro(e,t,n,r){if(!((await(r?.inspectToken||To)(e)).projects??[]).some(p=>p.projectUrlName===t.project&&p.groups.length>0))throw new f(`Your session for organization "${n}" doesn't have access to project "${t.project}" on ${t.baseUrl}.`,{hint:`Check you signed in to the right organization, or have access to the project "${t.project}" within "${n}" organization; \`@cognite/cli auth status\` lists the projects you can reach within your already logged in session token.`})}o(Ro,"assertProjectAccess");async function Fo(e,t,n,r){let i=await r.ensureFreshSession();if(!i)throw new f(`No credentials available for ${e.project} @ ${e.baseUrl}.`,{hint:"Run `cognite auth login` to login."});let s=await be(e,t,i.accessToken,r.createClient);return await Ro(s,e,n),s}o(Fo,"resolveViaSession");async function $o(e,t,n,r){switch(e.method){case"client-credentials":return r.getSdkFn(t,n.appId);case"session":return Fo(t,n.appId,e.org,r);case"browser":return xo(t,n,r)}}o($o,"buildClientForAuthMethod");async function K(e,t,n={}){let{isSessionAuthEnabled:r=E}=n;return r()?ac(e,t,n):sc(e,t,n)}o(K,"buildAppHostingApiClient");var sc=o(async(e,t,n={})=>{let{login:r=Ie,getSdk:i=ye,createClient:s=o(a=>new Oo(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a);return be(e,t.appId,C.from(p.access_token),s)}return i(e,t.appId)},"buildAppHostingApiClientWithoutSessionSupport");async function St(e,t,n={}){let r=await K(e,t,n);return new I(r)}o(St,"buildAppHostingClient");async function ac(e,t,n={}){let{login:r=Ie,getSdk:i=ye,createClient:s=o(m=>new Oo(m),"createClient"),readSessionMetadata:a=fe,ensureFreshSession:p=ht,promptAuthMethod:c=ct,confirmActionTarget:l=pt,isTTY:d=process.stdin.isTTY??!1,now:u=o(()=>new Date,"now")}=n,g=Eo(e,t,{readSessionMetadata:a,now:u}),y=await io(g,e,t,{promptAuthMethod:c,confirmActionTarget:l,isTTY:d});return $o(y,e,t,{loginFn:r,getSdkFn:i,createClient:s,ensureFreshSession:p})}o(ac,"buildAppHostingClientWithSessionSupport");import Mo from"enquirer";var _o="Enter custom target...";function Uo(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
22
+ </body></html>`}r(uo,"generateHtml");import Lp from"net";function Ei(e,t){return new Promise(n=>{let o=new Lp.Socket,i=r(s=>{o.removeAllListeners(),o.destroy(),n(s)},"done");o.setTimeout(500),o.once("connect",()=>i(!1)),o.once("timeout",()=>i(!0)),o.once("error",()=>i(!0)),o.connect(e,t)})}r(Ei,"isHostPortFree");function Kt(e){return`Port ${e} is already in use. Pin another callback port with --port <port> \u2014 supported ports are ${dt}.`}r(Kt,"freePortHint");async function bi(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([Ei(e,"127.0.0.1"),Ei(e,"::1")])).every(Boolean)}r(bi,"isPortFree");async function Np(e,t,n,o,i,s){let{authorizationCodeGrant:a,logger:c}=s,l=new URL(e.url??"/",`http://${e.headers.host??"localhost"}`);if(l.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{c.log("\u{1F504} Exchanging authorization code for tokens...");let p=await a(n,l,{pkceCodeVerifier:o,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),t.end(uo("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let d=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),t.end(uo("error","Authentication Error",d.message)),{shouldClose:!0,error:d}}}r(Np,"handleCallback");function _p(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}r(_p,"formatTimeoutMinutes");function xi(e,t,n,o,i={createServer:Mp.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Up,logger:console}){let{createServer:s,setTimeout:a,clearTimeout:c,logger:l}=i;return new Promise((p,d)=>{let u=s(async(f,y)=>{try{let S=await Np(f,y,t,n,o,i);S.shouldClose&&(h(),S.error?d(S.error):S.tokens?p(S.tokens):d(new Error("No tokens received")))}catch(S){h(),d(S instanceof Error?S:new Error(String(S)))}}),g=a(()=>{h(),d(new Error(`Login timeout - no response received within ${_p(e.loginTimeout)}`))},e.loginTimeout);function h(){c(g),u.close(),u.closeIdleConnections?.()}r(h,"cleanup"),u.on("error",f=>{h(),f.code==="EADDRINUSE"||f.code==="EACCES"?d(new m(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:f,hint:Kt(e.port)})):d(new m(`Login callback server failed: ${f.message}`,{cause:f}))}),u.listen(e.port,"127.0.0.1",()=>{l.log(`\u{1F310} Local HTTP server started on http://localhost:${e.port}`)})})}r(xi,"startCallbackServer");import{spawn as Hp}from"child_process";import Bp from"open";import{parseArgsStringToArgv as Kp}from"string-argv";function jp(e){try{return new URL(e),!0}catch{return!1}}r(jp,"isValidUrl");function ki(e,t="url"){if(!jp(e))throw new Error(`${t} must be a valid URL, got: ${e}`);return e}r(ki,"parseUrl");var Vp=5e3;async function Pi(e,t={}){let{open:n=Bp,spawn:o=r((p,d)=>{let u=Hp(p,d,{stdio:"ignore",detached:!0});return u.unref(),u},"spawn"),platform:i=process.platform,env:s=process.env,setTimeout:a=globalThis.setTimeout,clearTimeout:c=globalThis.clearTimeout}=t,l=s.BROWSER?.trim();if(i==="win32"&&l){let[p,...d]=Kp(l);if(!p){await n(e);return}ki(e,"openBrowser target"),await Gp(o,p,[...d,e],a,c);return}await n(e)}r(Pi,"openBrowser");function Gp(e,t,n,o,i){return new Promise((s,a)=>{let c=e(t,n),l=o(()=>{a(new Error(`Timed out waiting for "${t}" to spawn`))},Vp);c.once("error",p=>{i(l),a(p)}),c.once("spawn",()=>{i(l),s()})})}r(Gp,"spawnBrowser");var mo="openid profile email";function go(e){return`http://localhost:${e}/`}r(go,"callbackRedirectUri");function Xp(e=process.env){let t=e.COGNITE_IDP_BASE_URL?.trim();return t?t.replace(/\/+$/,""):"https://auth.cognite.com"}r(Xp,"resolveIdpBaseUrl");var fo=Xp(),ho={authority:fo,clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:go(3e3),port:3e3,loginTimeout:300*1e3},Qp={open:Pi,startCallbackServer:xi,isPortFree:bi,discovery:qp,buildAuthorizationUrl:Yp,randomPKCECodeVerifier:Wp,calculatePKCECodeChallenge:zp,randomState:Zp,logger:console,telemetry:_t()};async function Vt(e,t=ho,n){return n===void 0?Ri(e,t,Qp):Ri(e,t,n)}r(Vt,"login");async function ed(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,Jp())}catch(o){throw new m(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:o})}}r(ed,"fetchOpenIdConfig");async function Ri(e,t,n){let{isPortFree:o,telemetry:i,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:c,randomState:l,buildAuthorizationUrl:p,open:d,startCallbackServer:u}=n;if(!await o(t.port))throw i?.track("Flows.CLI.PortInUse",{port:t.port}),new m(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:Kt(t.port)});s.log(`\u{1F510} Starting CDF login flow...
23
+ `),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let h=await ed(n,t),f=a(),y=await c(f),S=l(),w={redirect_uri:t.redirectUri,scope:t.scope??mo,code_challenge:y,code_challenge_method:"S256",state:S};e&&(w.organization_hint=e);let v=p(h,w).toString();e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
24
+ `);try{await d(v)}catch(C){let x=C instanceof Error?C.message:String(C);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${x}`),s.error(`Please open this URL manually:
25
+ `),s.error(v),s.error("")}return u(t,h,f,S)}r(Ri,"loginImpl");var Gt={...ho,scope:`${mo} offline_access`},id=3600,sd=1500*60;function Di(e){return nd(new URL(e.authority),e.clientId,void 0,td())}r(Di,"discoverDefault");function Ii(e){let t=typeof e=="string"?Number(e):e;return typeof t=="number"&&Number.isFinite(t)?t:void 0}r(Ii,"asSeconds");function $i(e,t,n=new Date,o={}){let i=t.access_token?b.from(t.access_token):null;if(!i)throw new m("Login succeeded but no access token was returned.",{hint:"The identity provider did not return an access token. Please try logging in again."});let s=t.refresh_token?b.from(t.refresh_token):o.previousRefreshToken;if(!s)throw new m("Login succeeded but no refresh token was returned.",{hint:"The identity provider may not support the `offline_access` scope, which is required for persisted sessions."});let a=n.getTime(),c=(Ii(t.expires_in)??id)*1e3,l=(Ii(t.refresh_expires_in)??sd)*1e3;return{version:Lt,org:e.org,accessToken:i,refreshToken:s,accessTokenExpiresAt:new Date(a+c).toISOString(),refreshTokenExpiresAt:new Date(a+l).toISOString()}}r($i,"buildSession");async function Oi(e,t={}){if(e.port!==void 0&&!Ht(e.port))throw new m(Bt(e.port));let{login:n=r((a,c)=>Vt(a,c),"login"),now:o=r(()=>new Date,"now")}=t,i=e.port===void 0?Gt:{...Gt,port:e.port,redirectUri:go(e.port)},s=await n(e.org,i);return $i(e,s,o())}r(Oi,"loginForSession");async function Fi(e,t={}){let{discovery:n=Di,tokenRevocation:o=r((s,a)=>od(s,a.expose()),"tokenRevocation")}=t,i=await n(Gt);await o(i,e)}r(Fi,"revokeRefreshToken");async function Li(e,t={}){let n=t.discovery??Di,o=t.refreshTokenGrant??((c,l)=>rd(c,l.expose())),i=t.now??(()=>new Date),s=await n(Gt),a=await o(s,e.refreshToken);return $i({org:e.org},a,i(),{previousRefreshToken:e.refreshToken})}r(Li,"refreshSession");function Mi(e){if(typeof e!="object"||e===null)return!1;if("error"in e&&typeof e.error=="string"&&e.error==="invalid_grant")return!0;if(e instanceof Error)return/invalid_grant/i.test(e.message);let t="message"in e&&typeof e.message=="string"?e.message:"";return/invalid_grant/i.test(t)}r(Mi,"isInvalidGrant");var yo=class yo extends Error{constructor(n,o,i){super(o,i);this.kind=n;this.name="SessionVerificationError"}};r(yo,"SessionVerificationError");var Je=yo;function ad(e){return e instanceof Error?"cause"in e&&e.cause instanceof Error?e.cause.message:e.message:String(e)}r(ad,"describeTransportError");function cd(e){return!(typeof e!="object"||e===null||"sub"in e&&typeof e.sub!="string"||"email"in e&&typeof e.email!="string"||"name"in e&&typeof e.name!="string"||"preferred_username"in e&&typeof e.preferred_username!="string")}r(cd,"isJwtClaims");function ld(e){try{let t=e.expose().split(".");if(t.length!==3)return{};let n=JSON.parse(Buffer.from(t[1],"base64url").toString("utf-8"));return cd(n)?n:{}}catch{return{}}}r(ld,"decodeJwtClaims");function pd(e){return typeof e!="object"||e===null?!1:"items"in e?Array.isArray(e.items)?e.items.every(t=>typeof t=="object"&&t!==null&&"name"in t&&typeof t.name=="string"):!1:!0}r(pd,"isCogIdpProjectsResponse");function dd(e){if(e)try{return new URL(e).host}catch{return}}r(dd,"clusterFromApiUrl");async function Yt(e,t={}){let n=t.fetch??globalThis.fetch,o=`${fo}/api/v0/orgs/${encodeURIComponent(e.org)}/projects`,i;try{i=await n(o,{headers:{Authorization:`Bearer ${e.accessToken.expose()}`}})}catch(p){throw new Je("unreachable",ad(p),{cause:p})}if(!i.ok)throw new Je("rejected",`CogIdP rejected the token: ${i.status} ${i.statusText}`);let s=await i.json(),c=((pd(s)?s:{}).items??[]).map(p=>({name:p.name,cluster:dd(p.apiUrl),...p.isDefault?{isDefault:!0}:{}})),l=ld(e.accessToken);return{sub:l.sub??"unknown",email:l.email,name:l.name,preferredUsername:l.preferred_username,projects:c}}r(Yt,"fetchSessionUserInfo");var gd=3e4,So=class So extends m{constructor(t){super("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,...t===void 0?{}:{cause:t}}),this.name="SessionExpiredError"}};r(So,"SessionExpiredError");var He=So;function zt(e){return new He(e)}r(zt,"expiredError");async function fd(e,t,n){let o=await e(ud.dirname(t),{stale:gd,retries:{retries:10,factor:1.5,minTimeout:100,maxTimeout:1e3}});try{return await n()}finally{await o()}}r(fd,"withSessionLock");async function We(e={}){let t=e.readSession??(()=>lt()),n=e.now??(()=>new Date),o=e.sessionFile??D().sessionFile,i=e.lock??md,s=await t();if(!s)return;let a=je(s,n());if(a==="EXPIRED")throw zt();return a==="VALID"?s:fd(i,o,async()=>{let c=await t()??s,l=je(c,n());if(l==="EXPIRED")throw zt();return l==="VALID"?c:hd(c,e)})}r(We,"ensureFreshSession");async function hd(e,t){let n=t.readSession??(()=>lt()),o=t.writeSession??(s=>Ut(s)),i=t.refreshSession??(s=>Li(s));try{let s=await i(e);return await o(s),s}catch(s){if(!Mi(s))throw s;let a=await n();if(a&&!a.refreshToken.equals(e.refreshToken))try{let c=await i(a);return await o(c),c}catch(c){throw zt(c)}throw zt(s)}}r(hd,"refreshAndPersist");import{CogniteClient as Xd}from"@cognite/sdk";var Ui="https://docs.cognite.com/cdf/access/";function V(e){return e!==null&&typeof e=="object"}r(V,"isRecord");function ae(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}r(ae,"isHttpError");function wo(e){return V(e.data)?e.data:void 0}r(wo,"httpErrorResponseBody");function Ni(e){let t=wo(e);if(!t)return;let n=t.error;if(V(n)&&typeof n.message=="string")return n.message;if(typeof t.message=="string")return t.message}r(Ni,"cdfApiErrorMessage");function yd(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
26
+ See: ${Ui}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
27
+ See: ${Ui}`;default:return}}r(yd,"httpStatusHint");function fe(e){let t=e instanceof Error?e:new Error(String(e));if(!ae(t))return null;let n=yd(t.status);return n?Object.assign(new Error(`${t.message}
28
+ ${n}`),{cause:t}):null}r(fe,"enrichedHttpError");function Sd(e){if(!V(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(V(n)){let o=n.error;if(V(o)&&Array.isArray(o.missing))return o.missing;if(Array.isArray(n.missing))return n.missing}return null}r(Sd,"findMissingArray");function wd(e,t){if(!ae(e)||e.status!==400)return!1;let n=Sd(e);return n?n.some(o=>V(o)&&typeof o.externalId=="string"&&t.includes(o.externalId)):!1}r(wd,"isMissingExternalIdError");function qt(e,t){return ae(e)&&e.status===404||wd(e,t)}r(qt,"isNotFoundError");var ji=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Hi=["ACTIVE","PREVIEW"],vo=class vo extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};r(vo,"AppVersionNotFoundError");var oe=vo,Co=class Co extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};r(Co,"AppNotFoundError");var Ze=Co;function Jt(e,t){return e.includes(t)}r(Jt,"includesValue");function vd(e){return Jt(ji,e)}r(vd,"isAppVersionLifecycleState");function Cd(e){return Jt(Hi,e)}r(Cd,"isAppVersionAlias");function Ad(e){return typeof e.version=="string"&&vd(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Cd(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}r(Ad,"isAppVersion");function _i(e){if(!V(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Ad(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}r(_i,"parseAppVersion");function Ed(e){if(!V(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:o}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(o!=null&&typeof o!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof o=="string"?o:void 0}}r(Ed,"parseAppMetadata");var Ao=class Ao{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,o){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:o}]}})}catch(i){throw fe(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw fe(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let o=await this.client.get(n);return Ed(o.data)}catch(o){throw qt(o,[t])?new Ze(t):fe(o)??o}}async uploadVersion(t,n,o,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(o)]),i),a.append("version",n),a.append("entryPath",s);let c=encodeURIComponent(t),l=`${this.appsBasePath}/${c}/versions`,p=await this.client.authenticate();if(!p)throw new m("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=b.from(p),u=`${this.client.getBaseUrl()}${l}`,g=new AbortController,h=setTimeout(()=>g.abort(),300*1e3),f;try{f=await fetch(u,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:g.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new m("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new m(`Failed to upload version to ${u}`,{cause:y,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(h)}if(!f.ok){let y=await f.text(),S;try{S=JSON.parse(y)}catch{}let w=y;if(V(S)){let L=S.error;if(typeof L=="string")w=L;else if(V(L)){let B=L.message,R=L.code;w=typeof B=="string"?B:R!=null?`Unknown error (code: ${R})`:y}else{let B=S.message;w=typeof B=="string"?B:y}}let v=f.headers.get("x-request-id"),C=v?` | X-Request-ID: ${v}`:"",x=V(S)?S:y;throw new de(`Upload failed: ${f.status} \u2014 ${w}${C}`,{httpStatusCode:f.status,requestUrl:u,responseBody:x})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let o=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${o}/versions/${i}`;try{let a=await this.client.get(s);return _i(a.data)}catch(a){throw qt(a,[t,n])?new oe(t,n):fe(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),o=`${this.appsBasePath}/${n}/versions/list`;try{let i=await this.client.post(o,{data:{filter:{aliases:["ACTIVE"]}}});if(!V(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return _i(s[0])}catch(i){if(qt(i,[t]))return null;throw fe(i)??i}}async deleteVersions(t,n){let o=encodeURIComponent(t),i=`${this.appsBasePath}/${o}/versions/delete`;try{await this.client.post(i,{data:{items:n.map(s=>({version:s}))}})}catch(s){throw fe(s)??s}}async updateVersions(t,n){let o=encodeURIComponent(t),i=`${this.appsBasePath}/${o}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw fe(s)??s}}async submitSignatures(t,n,o){let i=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:o}})}catch(c){throw fe(c)??c}}async listSignatures(t,n){let o=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${o}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return kd(a.data)}catch(a){throw fe(a)??a}}};r(Ao,"AppHostingApi");var Wt=Ao,bd=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],xd=["developer","certifier"];function kd(e){if(!V(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let o=Pd(n);return o?[o]:[]})}r(kd,"parseStoredSignatures");function Pd(e){if(!V(e))return null;let{signerKid:t,signerRole:n,signatureIat:o,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Jt(xd,n)||typeof o!="number"||typeof i!="number"||typeof s!="number"||!Jt(bd,a)?null:{signerKid:t,signerRole:n,signatureIat:o,receivedAt:i,createdTime:s,status:a}}r(Pd,"parseStoredSignature");function Eo(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let o=e.description??"";return o!==t.description&&n.push({field:"description",remote:o,local:t.description}),n}r(Eo,"diffAppMetadata");function Td(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:o,local:i}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${o}" \u2192 "${i}"`)}return t.join(`
29
+ `)}r(Td,"formatMetadataDriftError");var bo=class bo{constructor(t){this.api=new Wt(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,o,i,s){return this.api.uploadVersion(t,n,o,i,s)}async ensureApp(t,n,o){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,o),console.log(`\u2705 App '${t}' created`)}catch(i){if(ae(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,o);return}throw i}}async checkMetadataDrift(t,n,o){let i;try{i=await this.getApp(t)}catch{return}let s=Eo(i,{name:n,description:o});if(s.length!==0)throw new m(Td(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,o){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:o?{set:o}:{setNull:!0}}}])}async submitSignatures(t,n,o){o.length!==0&&(console.log(`\u{1F50F} Submitting ${o.length} signature${o.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,o),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async deleteVersion(t,n){await this.api.deleteVersions(t,[n])}async deprecateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"ARCHIVED"}}}])}async activateVersion(t,n){let o=null;try{o=await this.api.getActiveVersion(t)}catch{o=null}let i=o&&o.version!==n?o.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,o,i,s,a,c=!1){console.log(`
30
+ \u{1F680} Deploying application via App Hosting API...
31
+ `),await this.ensureApp(t,n,o),await this.uploadVersion(t,i,s,a),c&&await this.publishAndActivate(t,i),console.log(`
32
+ \u2705 Deployment successful!`)}};r(bo,"AppHostingClient");var M=bo;import Rd from"enquirer";function Id(e){return`${e.org}/${e.project}`}r(Id,"targetLabel");var Zt=r(async function(e,t,n,o={isTTY:process.stdin.isTTY??!1,confirm:r(i=>Rd.prompt({type:"confirm",name:"confirmed",message:i,initial:!1}),"confirm")}){let{isTTY:i,confirm:s}=o,a=Id(e);if(t.confirmActionTarget!==void 0){if(t.confirmActionTarget===a)return;throw new m(`--confirm-action-target "${t.confirmActionTarget}" does not match the deployment this command resolved to ("${a}").`,{shouldReport:!1,hint:`Pass --confirm-action-target ${a} to ${n}.`})}if(console.warn(`
33
+ Using session credentials \u2014 your token has access to all projects in the "${e.org}" organization.`),!i)throw new m("Session credentials detected but no TTY available for confirmation.",{shouldReport:!1,hint:"Pass --confirm-action-target <org/project> to skip the prompt, or configure deployClientId and deploySecretName in app.json."});let{confirmed:c}=await s(`Confirm ${n} to ${a}?`);if(!c)throw new m("Aborted.",{shouldReport:!1})},"confirmActionTarget");import Dd from"enquirer";var $d=r(e=>Dd.prompt(e),"defaultPrompt");function Od(e){switch(e.method){case"client-credentials":return"Use client credentials from app.json";case"session":return`Reuse existing session for ${e.org}`;case"browser":return"One-off sign-in via browser (does not save a session; use `cognite auth login` for that)"}}r(Od,"choiceLabel");async function Xt(e,t=$d){if(e.length===0)throw new m("No valid authentication method available.",{hint:"Run `cognite auth login` and authenticate to the correct organization, or set deployClientId/deploySecretName in app.json."});let n=e.map(a=>a.method);if(new Set(n).size!==n.length)throw new Error(`Cannot present a selection with duplicate method names (${n.join(", ")}).`);let o=Array.from(new Set(n)).join("|"),{choice:i}=await t({type:"select",name:"choice",message:`Multiple valid authentication methods detected (skip with --auth-method <${o}>). Authenticate with`,choices:e.map(a=>({name:a.method,message:Od(a)}))}),s=e.find(a=>a.method===i);if(!s)throw new m(`Selected authentication method "${i}" was not offered.`,{hint:"Pass --auth-method to choose one of the offered methods explicitly."});return s}r(Xt,"promptAuthMethod");async function Bi(e,t,n,o={confirmActionTarget:Zt,promptAuthMethod:Xt,isTTY:process.stdin.isTTY??!1}){let{valid:i}=e;if(i.length===0)throw Fd(e,t);let s;if(n.authMethod){let a=i.find(c=>c.method===n.authMethod);if(!a)throw new m(`Pass --auth-method ${i.map(c=>c.method).join(" or --auth-method ")} \u2014 "${n.authMethod}" is not currently valid for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login` for a session, set deployClientId/deploySecretName in app.json for client credentials, or pass --interactive for browser login."});s=a}else if(i.length===1)[s]=i;else if(o.isTTY)s=await o.promptAuthMethod(i);else throw new m(`Pass --auth-method ${i.map(a=>a.method).join("|")} to choose non-interactively \u2014 several are valid for ${t.project} @ ${t.baseUrl} and there is no TTY to prompt.`,{shouldReport:!1,hint:"Or re-run in an interactive terminal to pick from the prompt."});if(s.method==="session"&&n.action&&!n.interactive)await o.confirmActionTarget(t,{confirmActionTarget:n.confirmActionTarget},n.action);else if(n.confirmActionTarget!==void 0&&s.method!=="session")throw new m(`Remove --confirm-action-target \u2014 it only guards session credentials and is never validated against the selected deployment with ${s.method} authentication.`,{shouldReport:!1,hint:"Pass --auth-method session (or pick the session option at the prompt) if you meant to acknowledge a session target."});return s}r(Bi,"chooseAuthMethod");function Fd(e,t){let{invalidSession:n}=e;if(!n)return new m(`No credentials available for ${t.project} @ ${t.baseUrl}.`,{hint:"Run `cognite auth login`, set deployClientId/deploySecretName in app.json, or pass --interactive."});let o=`Run \`cognite auth login\` for "${t.org}", or pass --interactive.`;return n.reason==="SESSION_EXPIRED"?new m(`Your session for organization "${n.org}" has expired.`,{hint:o}):new m(`Your active session is for organization "${n.org}", but this command targets "${t.org}".`,{hint:o})}r(Fd,"createNoCredentialsError");function Ki(e,t,n){return e?t.org&&e.org!==t.org?{reason:"DIFFERENT_ORG",org:void 0}:je(e,n)==="EXPIRED"?{reason:"SESSION_EXPIRED",org:void 0}:{org:e.org,reason:"VALID"}:{reason:"SESSION_MISSING",org:void 0}}r(Ki,"getSessionOrgIfValid");function Vi(e,t,n){let o=[];e.deployClientId&&o.push({method:"client-credentials",org:e.org});let i=n.readSessionMetadata(),s=Ki(i,e,n.now());return s.reason==="VALID"&&o.push({method:"session",org:s.org}),t.interactive&&o.push({method:"browser"}),i&&(s.reason==="SESSION_EXPIRED"||s.reason==="DIFFERENT_ORG")?{valid:o,invalidSession:{reason:s.reason,org:i.org}}:{valid:o}}r(Vi,"validAuthMethods");import{CogniteClient as Vd}from"@cognite/sdk";function Ld(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}r(Ld,"exponentialBackoffWithJitter");function Md(e){return new Promise(t=>setTimeout(t,e))}r(Md,"sleep");async function Gi(e,t={}){let n=t.maxAttempts??5,o=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Ld;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!o(a))throw a;let c=i(s);t.onAttemptFail?.(a,s,c),await Md(c),s++}}r(Gi,"retryAsync");var Ud="https://auth.cognite.com/oauth2/token",Nd=r(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Yi({idp:e,tokenUrl:t,init:n,missingTokenHint:o}){let i;try{i=await Gi(()=>fetch(t,n),{maxAttempts:3})}catch(c){throw new m(`Failed to fetch access token from ${t}`,{cause:c})}if(!i.ok){let c=await i.text();throw new de(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new m(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:o})}if(!Nd(a))throw new m(`No access token in ${e} authentication response`,{hint:o});return b.from(a.access_token)}r(Yi,"fetchOAuthToken");var _d=r(e=>{let t=e.DEPLOYMENT_SECRETS;if(!t)return{};try{let n=JSON.parse(t),o={};for(let[i,s]of Object.entries(n))if(typeof s=="string"){let a=i.toLowerCase().replace(/_/g,"-");o[a]=s}return o}catch(n){return console.error("Error parsing DEPLOYMENT_SECRETS:",n),{}}},"loadSecretsFromEnv"),jd=r((e,t)=>{let n;if(t.DEPLOYMENT_SECRET&&(n=t.DEPLOYMENT_SECRET),n||(n=_d(t)[e]),n||(n=t[e]),!n)throw new m(`Set the ${e} environment variable (named by deploySecretName in app.json) to your deploy client secret, e.g. in a .env file.`,{shouldReport:!1,hint:"Alternatively, run `cognite auth login` to use your session, or pass --interactive for a one-off browser login."});return b.from(n)},"getSecretFromEnv"),Hd=r((e,t)=>{let n=t.expose();return Yi({idp:"CDF",tokenUrl:Ud,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${n}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),zi=r(({idp:e,tokenUrl:t,clientId:n,clientSecret:o,scopes:i,missingTokenHint:s})=>Yi({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:o,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Bd=r((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),Kd=r((e,t,n,o,i)=>zi({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[Bd(o)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),xo=r(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return b.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:o,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:l}=e,p=jd(o,t);if(i==="oauth"){if(!l)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return zi({idp:"OAuth",tokenUrl:l,clientId:n,clientSecret:p.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Kd(n,p,s,a,c)}return Hd(n,p)},"getToken");async function Qt(e,t,n=process.env,o){let i=await xo(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(o??(c=>new Vd(c)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:r(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}r(Qt,"getSdk");async function en(e,t,n,o){let i=o({appId:t,project:e.project,baseUrl:e.baseUrl,oidcTokenProvider:r(async()=>n.expose(),"oidcTokenProvider")});return await i.authenticate(),i}r(en,"buildAuthenticatedClient");async function qi(e,t,n){let{loginFn:o,createClient:i}=n,s=t.orgHint||e.org||void 0,a=await o(s);return en(e,t.appId,b.from(a.access_token),i)}r(qi,"resolveViaBrowser");import{HttpError as Gd}from"@cognite/sdk";import{array as Ji,number as Yd,object as Wi,optional as zd,safeParse as qd,string as Jd}from"valibot";var Wd=Wi({projects:zd(Ji(Wi({projectUrlName:Jd(),groups:Ji(Yd())})))});function Zd(e,t){switch(e){case 401:return"Run `cognite auth login` to log in.";case 403:return"The token is valid but lacks access to this project. Ask your CDF admin to grant its service account access.";default:return e>=500?`${t} returned a server error \u2014 this is usually transient, so try again shortly.`:"Check that the deployment base URL and project in app.json are correct."}}r(Zd,"hintForStatus");var Zi=r(async function(e){let t=e.getBaseUrl(),n;try{({data:n}=await e.get("/api/v1/token/inspect"))}catch(i){throw i instanceof Gd?new m(`Could not verify project access against ${t} (${i.status}).`,{hint:Zd(i.status,t),cause:i}):new m(`Could not connect to ${t} to verify project access.`,{hint:"Check your network connection and verify that the base URL is correct.",cause:i})}let o=qd(Wd,n);if(!o.success)throw new m(`Unexpected response from ${t}/api/v1/token/inspect.`,{hint:"Retry; if it persists, your CLI may be out of date or a proxy is altering responses.",cause:new Error(JSON.stringify(o.issues))});return o.output},"inspectDeploymentToken");async function Xi(e,t,n,o){if(!((await(o?.inspectToken||Zi)(e)).projects??[]).some(c=>c.projectUrlName===t.project&&c.groups.length>0))throw new m(`Your session for organization "${n}" doesn't have access to project "${t.project}" on ${t.baseUrl}.`,{hint:`Check you signed in to the right organization, or have access to the project "${t.project}" within "${n}" organization; \`@cognite/cli auth status\` lists the projects you can reach within your already logged in session token.`})}r(Xi,"assertProjectAccess");async function Qi(e,t,n,o){let i=await o.ensureFreshSession();if(!i)throw new m(`No credentials available for ${e.project} @ ${e.baseUrl}.`,{hint:"Run `cognite auth login` to login."});let s=await en(e,t,i.accessToken,o.createClient);return await Xi(s,e,n),s}r(Qi,"resolveViaSession");async function es(e,t,n,o){switch(e.method){case"client-credentials":return o.getSdkFn(t,n.appId);case"session":return Qi(t,n.appId,e.org,o);case"browser":return qi(t,n,o)}}r(es,"buildClientForAuthMethod");async function _(e,t,n={}){let{login:o=Vt,getSdk:i=Qt,createClient:s=r(f=>new Xd(f),"createClient"),readSessionMetadata:a=xe,ensureFreshSession:c=We,promptAuthMethod:l=Xt,confirmActionTarget:p=Zt,isTTY:d=process.stdin?.isTTY??!1,now:u=r(()=>new Date,"now")}=n,g=Vi(e,t,{readSessionMetadata:a,now:u}),h=await Bi(g,e,t,{promptAuthMethod:l,confirmActionTarget:p,isTTY:d});return es(h,e,t,{loginFn:o,getSdkFn:i,createClient:s,ensureFreshSession:c})}r(_,"buildAppHostingApiClient");async function tn(e,t,n={}){let o=await _(e,t,n);return new M(o)}r(tn,"buildAppHostingClient");import ts from"enquirer";var ns="Enter custom target...";function os(e,t){let n=t.map((o,i)=>` ${i}: ${o.org}/${o.project}`).join(`
37
34
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
38
- ${n}`)}o(Uo,"deploymentNotFoundError");function T(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;Uo(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Uo(t,e)}o(T,"findDeployment");function F(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(F,"getMissingCredentials");async function $(e,t){if(t.confirmActionTarget!==void 0)throw new f("Pass -d/--deployment <target> to choose a target non-interactively \u2014 --confirm-action-target cannot be combined with --interactive.",{shouldReport:!1,hint:"--interactive already prompts for the target, so there is nothing for --confirm-action-target to acknowledge."});if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return T(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),_o],{selected:r}=await Mo.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==_o){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await Mo.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o($,"resolveDeployment");import{existsSync as pc}from"fs";import{resolve as cc}from"path";import{config as lc}from"dotenv";function O(e,t={existsSync:pc,config:lc}){let n=cc(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(O,"loadEnvFile");function M(e){e.infra!=="appsApi"&&(console.error(`
35
+ ${n}`)}r(os,"deploymentNotFoundError");function $(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let o=e[Number.parseInt(t)];if(o)return o;os(t,e)}let n=e.find(o=>o.project===t||`${o.org}/${o.project}`===t);if(n)return n;os(t,e)}r($,"findDeployment");async function F(e,t){if(t.confirmActionTarget!==void 0)throw new m("Pass -d/--deployment <target> to choose a target non-interactively \u2014 --confirm-action-target cannot be combined with --interactive.",{shouldReport:!1,hint:"--interactive already prompts for the target, so there is nothing for --confirm-action-target to acknowledge."});if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return $(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),ns],{selected:o}=await ts.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(o!==ns){let s=e.deployments.find(a=>`${a.org}/${a.project}`===o);if(s)return s;throw new Error(`Deployment "${o}" could not be resolved from app.json.`)}let i=await ts.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:r(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}r(F,"resolveDeployment");function rs(e,t=process.cwd(),n={}){let o=n.readSessionMetadata??xe,i=n.loadAppConfig??k;if(e.org)return e.org;let s=o();if(s?.org)return s.org;try{let a=i(t),c=$(a.deployments,void 0);if(c.org)return c.org}catch{}throw new m("Could not determine org.",{hint:"Pass --org <org>, run `cognite auth login`, or run from an agent directory with app.json.",shouldReport:!1})}r(rs,"resolveOrg");function T(e,t=1){return" ".repeat(t).concat(e)}r(T,"indent");async function Y(e,t=process.cwd(),n={}){let o=n.ensureFreshSession??We,i=n.fetchUserInfo??Yt,s=n.loadAppConfig??k,a=n.createClient??(l=>new Qd(l));if(e.interactive&&e.baseUrl&&e.project)return await _(nu(e),{interactive:!0,appId:"cognite-cli",orgHint:e.org},n.getClient);let c=await eu(e,o,i,a);if(c)return c;try{let l=s(t),p=e.interactive?await F(l,e):$(l.deployments,void 0);return await _(p,{interactive:e.interactive,appId:"cognite-cli",orgHint:e.org},n.getClient)}catch{}throw new m("Not signed in.",{hint:"Run `cognite auth login` to start a session, or pass --interactive --base-url <url> --project <project>.",shouldReport:!1})}r(Y,"getAgentClient");async function eu(e,t,n,o){let i;try{i=await t()}catch(p){if(p instanceof He)throw new m("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,cause:p});return null}if(!i)return null;let s=await n(i),a=tu(e.project,s.projects),c=`https://${a.cluster}`,l=o({appId:"cognite-cli",project:a.name,baseUrl:c,oidcTokenProvider:r(async()=>((await t())?.accessToken??i.accessToken).expose(),"oidcTokenProvider")});return await l.authenticate(),l}r(eu,"trySessionClient");function tu(e,t){if(e){let o=t.find(i=>i.name===e);if(!o?.cluster)throw new m(`Project "${e}" not found in your session.`,{hint:t.length?`Available projects: ${t.map(i=>i.name).join(", ")}`:"Your session has no reachable projects. Check your org and permissions.",shouldReport:!1});return{...o,cluster:o.cluster}}let n=t.find(o=>o.isDefault);if(n?.cluster)return{...n,cluster:n.cluster};if(t.length===1&&t[0].cluster)return{...t[0],cluster:t[0].cluster};throw t.length===0?new m("No reachable projects found in your session.",{hint:"Check your org and permissions, or pass --project <project>.",shouldReport:!1}):new m("Multiple projects available \u2014 specify which one to use.",{hint:`Pass --project <name>. Available: ${t.map(o=>o.name).join(", ")}`,shouldReport:!1})}r(tu,"resolveSessionProject");function nu(e){return{org:e.org??"",project:e.project??"",baseUrl:e.baseUrl??"",deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}r(nu,"getDeployment");var Ro=class Ro extends Ee{constructor(){super("create");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=s.prompt;a&&It();let c={externalId:s.externalId,displayName:s.displayName,description:s.description,model:s.model,instructions:s.instructions,runtimeVersion:s.runtimeVersion},l=n==="."||n==="./",p=cu(n,l),d=[];if(a&&!c.model?.trim())try{let h=await Y(s);d=await ne(h).getAvailableModels()}catch{}let u=await new Dt(p,c,a,d).resolve(),g=lu(l,u.dirName);await pu(g,l,u.dirName),await nn(he(g,Ie(Po(g))),this.buildAgentYaml(u)),await this.scaffoldEvalCases(g,u),await nn(he(g,A.readme),await this.buildReadme(u)),await this.scaffoldAgentsMd(g),await this.scaffoldSkills(g),this.printSummary(u)},"handle");this.buildAgentYaml=r(({dirName:n,...o})=>ge(o),"buildAgentYaml");this.buildReadme=r(async n=>{let o=await ko(he(on,"agents","create",A.readmeTemplate),"utf8");return ss(o,{displayName:n.name})},"buildReadme");this.scaffoldAgentsMd=r(async n=>{let o=await ko(he(on,"agents","create",A.agentsMdTemplate),"utf8");await nn(he(n,A.agentsMd),o)},"scaffoldAgentsMd");this.scaffoldSkills=r(async n=>{let o=he(on,"agents","create","skills");for(let i of oi){let s=he(n,i);await ou(o,s,{recursive:!0})}},"scaffoldSkills");this.scaffoldEvalCases=r(async(n,o)=>{let i=he(n,A.evalDir);await cs(i,{recursive:!0});let s=await ko(he(on,"agents","create",A.evalCasesTemplate),"utf8"),a=ss(s,{displayName:o.name});await nn(he(i,A.evalCases),a)},"scaffoldEvalCases");this.printSummary=r(n=>{let o=P(process.stdout),i=n.dirName;console.log(),console.log(o.green(`Created agent project at ${i}/`)),console.log(),console.log(T(`directory: ${i}/`)),console.log(T(`externalId: ${n.externalId}`)),console.log(T(`display name: ${n.name}`)),n.model&&console.log(T(`model: ${n.model}`)),console.log(),console.log("Next steps:"),console.log(T(`1. Edit ${i}/${Ie(Po(i))} \u2014 add tools and refine instructions`)),console.log(T(`2. cognite agents push ${i}`)),console.log(T(`3. cognite agents open ${i}`)),console.log(T(`4. Edit ${i}/${Me} and run: cognite agents eval ${i}`)),console.log()},"printSummary");this.description("Scaffold a new agent project").argument("[dir]","Agent name / directory").addHelpText("after",su);for(let n of Object.values(ls))this.addOption(n);this.action(this.handle)}};r(Ro,"CreateCommand");var rn=Ro,ls=Object.freeze({externalId:new Be("--external-id <id>","Agent externalId"),displayName:new Be("--display-name <name>","Agent display name"),description:new Be("--description <text>","Agent description"),model:new Be("--model <model>","Language model (e.g. azure/gpt-4.1)"),instructions:new Be("--instructions <text>","Agent instructions"),runtimeVersion:new Be("--runtime-version <version>","Agent runtime version"),noPrompt:new Be("--no-prompt","Skip interactive prompts, use defaults")}),UA=Object.values(ls).map(e=>e.long),su=`
36
+ Examples:
37
+ cognite agents create Interactive scaffold
38
+ cognite agents create my-agent Scaffold with name "my-agent"
39
+ cognite agents create my-agent \\
40
+ --description "Helps with maintenance" \\
41
+ --model azure/gpt-4.1 \\
42
+ --no-prompt Fully non-interactive
43
+ `,ps=ru(iu(import.meta.url)),is=To(ps,"..","..","_templates"),au=To(ps,"..","..","..","_templates"),on=as(is)?is:au;function cu(e,t){return t?Po(process.cwd()):e}r(cu,"normalizeDirArg");function lu(e,t){return e?process.cwd():To(process.cwd(),t)}r(lu,"resolveTargetDir");async function pu(e,t,n){if(t){let o=await st(e);if(o.length>0){let i=o.length===1?"an agent definition":"agent definitions";throw new m(`This directory already contains ${i}:
44
+ ${o.map(s=>` - ${s}`).join(`
45
+ `)}`,{hint:"Scaffold into a new directory instead, or use `cognite agents pull <external-id> --force` to overwrite.",shouldReport:!1})}return}if(as(e))throw new m(`An agent folder named "${n}" already exists at:
46
+ ${e}`,{hint:"Use a different agent name or remove the existing directory.",shouldReport:!1});await cs(e)}r(pu,"ensureTargetDir");function ss(e,t){return e.replace(/\{\{(\w+)\}\}/g,(n,o)=>t[o]??"")}r(ss,"renderTemplate");import{resolve as Qs}from"path";import{isDeepStrictEqual as Sm}from"util";import{Option as ve}from"commander";function ye(e){return e.invokeError??e.scoreError?!1:e.evalCase.expectPass!==!1?e.passed:!e.passed}r(ye,"caseVerdictPassed");function Io(e){return e.some(t=>!ye(t))}r(Io,"hasCaseVerdictFailures");function ut(e){return e.filter(t=>!ye(t)).length}r(ut,"countCaseVerdictFailures");function mt(e){return e.filter(ye).length}r(mt,"countCaseVerdictPasses");function gt(e){return e.filter(t=>t.evalCase.expectPass===!1&&!t.invokeError&&!t.scoreError&&t.passed).length}r(gt,"countUnexpectedPasses");import{readFile as Cu}from"fs/promises";import{join as $o}from"path";import{safeParse as fs}from"valibot";import{parse as Au}from"yaml";import{array as we,boolean as du,literal as sn,minLength as Xe,nonEmpty as z,object as ce,optional as Se,pipe as O,string as q,variant as uu}from"valibot";var mu=ce({type:sn("correctness"),criteria:O(q(),z("must not be empty"))}),gu=ce({type:sn("faithfulness"),groundTruth:O(q(),z("must not be empty"))}),fu=ce({name:O(q(),z("must not be empty")),description:O(q(),z("must not be empty"))}),ft=Se(O(we(fu),Xe(1,"must contain at least one tool"))),hu=ce({type:sn("toolSelection"),tools:ft}),yu=ce({type:sn("toolInvocation"),tools:ft}),Su=uu("type",[mu,gu,hu,yu]),ds=["correctness","faithfulness","toolSelection","toolInvocation"],wu=ce({input:O(q(),z("must not be empty")),scorers:Se(O(we(Su),Xe(1,"must contain at least one scorer")))}),vu=ce({space:O(q(),z("must not be empty")),externalId:O(q(),z("must not be empty")),version:O(q(),z("must not be empty"))}),Do=ce({dataModels:Se(O(we(vu),Xe(1,"must contain at least one data model"))),instanceSpaces:Se(O(we(O(q(),z("must not be empty"))),Xe(1,"must contain at least one instance space"))),appContext:Se(O(q(),z("must not be empty")))}),us=ce({id:O(q(),z("must not be empty")),tags:Se(we(O(q(),z("tag must not be empty")))),expectPass:Se(du(),!0),turns:O(we(wu),Xe(1,"must contain at least one turn")),...Do.entries,tools:ft}),ms=ce({include:Se(we(O(q(),z("include path must not be empty")))),cases:Se(we(us)),...Do.entries,tools:ft}),gs=ce({tags:Se(we(O(q(),z("tag must not be empty")))),cases:O(we(us),Xe(1,"must contain at least one case")),...Do.entries,tools:ft});function hs(e,t){let n=e,{caseFilter:o,tagFilter:i}=t??{};if(o&&o.length>0&&(n=n.filter(s=>o.includes(s.id))),i&&i.length>0){let s=new Set(i);n=n.filter(a=>a.tags?.some(c=>s.has(c)))}if(n.length===0)throw new m("No eval cases matched the filter.",{hint:`Check the --case and --tag flag values against ${Me}.`,shouldReport:!1});return n}r(hs,"filterEvalCases");async function ys(e){let t=$o(e,A.evalDir),n=$o(t,A.evalCases),{cases:o,include:i,rootContext:s,rootTools:a}=await Eu(n),c=await bu(i,t,s,a),l=[...o,...c];if(l.length===0)throw new m("No eval cases found.",{hint:`Add a cases list or an include field to ${Me}.`,shouldReport:!1});return Pu(l),Tu(l),l}r(ys,"loadEvalCases");async function Eu(e){let t=await Ss(e,{missingFileHint:`Create ${Me} in your agent project directory.`}),n=fs(ms,t);if(!n.success)throw new m(`Invalid ${e}: ${ws(n.issues)}`,{shouldReport:!1});let{include:o,cases:i,tools:s,...a}=n.output;return{cases:(i??[]).map(l=>vs(l,Me,a,s)),include:o,rootContext:a,rootTools:s}}r(Eu,"loadRootCasesFile");async function bu(e,t,n,o){return!e||e.length===0?[]:(await Promise.all(e.map(async s=>{let a=$o(t,s),c=`eval/${s}`,l=await Ss(a),p=fs(gs,l);if(!p.success)throw new m(`Invalid ${a}: ${ws(p.issues)}`,{shouldReport:!1});let{tags:d,cases:u,tools:g,...h}=p.output;return u.map(f=>vs(f,c,n,o,{fileContext:h,fileTags:d,fileTools:g}))}))).flat()}r(bu,"loadIncludedFiles");async function Ss(e,t){let n;try{n=await Cu(e,"utf8")}catch{throw new m(`Eval file not found:
47
+ ${e}`,{hint:t?.missingFileHint,shouldReport:!1})}try{return Au(n)}catch(o){throw new m(`Failed to parse ${e}: ${o instanceof Error?o.message:String(o)}`,{hint:"Check the YAML syntax of the file.",shouldReport:!1})}}r(Ss,"readAndParseYaml");function ws(e){return e.map(t=>{let n=t.path?.map(o=>String(o.key)).join(".")??"";return n?`${n}: ${t.message}`:t.message}).join("; ")}r(ws,"formatValidationIssues");function xu(e,t,n){let o=n?.dataModels??t?.dataModels??e.dataModels,i=n?.instanceSpaces??t?.instanceSpaces??e.instanceSpaces,s=n?.appContext??t?.appContext??e.appContext;if(!o&&!i&&!s)return;let a={};return o&&(a.dataModels=o),i&&(a.instanceSpaces=i),s&&(a.appContext=s),a}r(xu,"mergeSessionContext");function ku(e,t){if(t){if(t.dataModels&&!t.instanceSpaces)throw new m(`Case "${e}" declares dataModels without instanceSpaces`,{hint:"Add instanceSpaces alongside dataModels in your session context.",shouldReport:!1});if(t.instanceSpaces&&!t.dataModels)throw new m(`Case "${e}" declares instanceSpaces without dataModels`,{hint:"Add dataModels alongside instanceSpaces in your session context.",shouldReport:!1})}}r(ku,"assertDataModelScopePairing");function vs(e,t,n,o,i){let{id:s,turns:a,tags:c,expectPass:l,dataModels:p,instanceSpaces:d,appContext:u,tools:g}=e,h=i?.fileTags&&i.fileTags.length>0?[...new Set([...i.fileTags,...c??[]])]:c,f=xu(n,i?.fileContext,{dataModels:p,instanceSpaces:d,appContext:u});ku(s,f);let y=g??i?.fileTools??o;return{id:s,turns:a,expectPass:l,...h?{tags:h}:{},source:t,contextInformation:f,...y?{tools:y}:{}}}r(vs,"buildEvalCase");function Pu(e){let t=new Map;for(let{id:n,source:o}of e){let i=t.get(n)??[];i.push(o),t.set(n,i)}for(let[n,o]of t){if(o.length<=1)continue;let s=[...new Set(o)].map(a=>` - ${a}`).join(`
48
+ `);throw new m(`Duplicate case id "${n}"
49
+ Defined in:
50
+ ${s}`,{hint:"Each case must have a unique id.",shouldReport:!1})}}r(Pu,"assertUniqueCaseIds");function Tu(e){for(let t of e)if(!t.turns.some(o=>o.scorers&&o.scorers.length>0))throw new m(`Case "${t.id}" (${t.source}) has no scored turns`,{hint:"Add scorers to at least one turn in each case.",shouldReport:!1})}r(Tu,"assertCaseHasScoredTurn");function $e(e){if(e===null||typeof e!="object")return JSON.stringify(e);let t=e.toJSON;if(typeof t=="function")return $e(t.call(e));if(Array.isArray(e))return`[${e.map($e).join(",")}]`;let n=e;return`{${Object.keys(n).filter(i=>n[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${$e(n[i])}`).join(",")}}`}r($e,"stableStringify");function Oo(e){try{return $e(e)}catch{return String(e)}}r(Oo,"safeStableStringify");var Ru=["name","description","instructions","model","runtimeVersion"],Iu=["labels","tools","skills","subagents","exampleQuestions"];function bs(e,t){let n=Ue(e),o=Ue(t),i=[];for(let s of Ru){let a=n[s],c=o[s];Du(a,c)||i.push({field:s,local:Cs(a),remote:Cs(c)})}for(let s of Iu){let a=n[s],c=o[s];$u(s,a,c)||i.push({field:s,local:As(s,a),remote:As(s,c)})}return i}r(bs,"detectDrift");function xs(e,t){let n=e.map(i=>i.field).join(", "),o=[`Warning: local ${A.configGlob} differs from deployed config.`,` Fields: ${n}`];if(t?.verbose)for(let{field:i,remote:s,local:a}of e){let c=`${i}:`.padEnd(18);o.push(` ${c}"${s}" \u2192 "${a}"`)}return o.push(" Run with --upsert to push local changes before evaluating."),o.join(`
51
+ `)}r(xs,"formatAgentDriftWarning");function Du(e,t){return Fo(e)===Fo(t)}r(Du,"scalarValuesEqual");function $u(e,t,n){return Mo(Lo(t),e)===Mo(Lo(n),e)}r($u,"arrayValuesEqual");function Fo(e){return e??""}r(Fo,"normalizeOptionalString");function Cs(e){return Fo(e)}r(Cs,"formatScalarValue");function As(e,t){return Mo(Lo(t),e)}r(As,"formatArrayValue");function Lo(e){return e??[]}r(Lo,"normalizeArray");function Mo(e,t){let n=[...e].sort((o,i)=>Es(t,o).localeCompare(Es(t,i)));return $e(n)}r(Mo,"stableArrayStringify");function Es(e,t){if(typeof t!="object"||t===null)return $e(t);let n=t;switch(e){case"tools":return String(n.name??"");case"subagents":return String(n.agentExternalId??"");case"exampleQuestions":return String(n.question??"");default:return $e(t)}}r(Es,"arrayItemSortKey");async function ks(e,t){if(e)try{e.track("Flows.CLI.Agents.Eval",{...t}),await e.flush(qe)}catch{}}r(ks,"trackAgentsEval");function Ou(e){return typeof e=="object"&&e!==null&&e.type==="result"&&Array.isArray(e.messages)}r(Ou,"isSessionResult");function Uo(e){let t=e.content?.text;if(typeof t=="string"&&t.length>0)return t;let n=[];for(let o of e.reasoning??[])for(let i of o.content??[])typeof i.text=="string"&&i.text.length>0&&n.push(i.text);return n.join(`
52
+ `).trim()}r(Uo,"messageText");function an(e){return e.map(t=>t.name).join(", ")}r(an,"formatToolNameList");var Qe=500;function Ps(e,t){return e.length<=t?e:`${e.slice(0,t)}\u2026 (${e.length-t} more chars)`}r(Ps,"truncate");function No(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}r(No,"safeJsonEncode");function et(e,t=1/0){if(e.input===void 0||e.input===null)return`${e.name}()`;let n;if(typeof e.input=="object"&&!Array.isArray(e.input)){let o=Object.entries(e.input);if(o.length===0)return`${e.name}()`;n=o.map(([i,s])=>`${i}=${No(s)}`).join(", ")}else n=No(e.input);return`${e.name}(${Ps(n,t)})`}r(et,"formatToolInvocation");function cn(e,t=Qe){let n=typeof e=="string"?e:No(e);return n=n.replace(/\s+/g," ").trim(),Ps(n,t)}r(cn,"formatToolResultPreview");function Fu(e){let t=[];for(let n of e)for(let o of n.reasoning??[])for(let i of o.data??[]){let s=i.toolCall;typeof s?.name=="string"&&s.name.length>0&&t.push({name:s.name,input:s.input,result:s.result})}return t}r(Fu,"extractToolCalls");function Lu(e){let t=[];for(let n of e){let o=!1;for(let i of n.reasoning??[]){for(let s of i.data??[]){let a=s.toolCall;if(typeof a?.name=="string"&&a.name.length>0){o=!0;break}}if(o)break}if(!o)for(let i of n.actions??[]){let s=i.toolConfirmation;typeof s?.toolName=="string"&&s.toolName.length>0&&t.push({name:s.toolName,input:s.toolArguments,synthesized:!0})}}return t}r(Lu,"synthesizeToolConfirmationCalls");function Ts(e,t){for(let n of t){if(n.synthesized){e.push(n);continue}let o=e.findIndex(i=>i.synthesized===!0&&i.name===n.name&&Oo(i.input)===Oo(n.input));o!==-1?e[o]=n:e.push(n)}}r(Ts,"mergeToolCalls");function Rs(e){let t=e.response;if(!Ou(t))throw new Error("Unexpected agent chat response shape");let n=t.messages,o=n[n.length-1];if(!o)throw new Error("Agent returned no messages");let i=[...Fu(n),...Lu(n)],s=o.actions?.find(c=>c.type==="toolConfirmation");if(s){let c=s.actionId??s.id;if(!c)throw new Error("Tool confirmation action missing actionId (both actionId and id are absent)");return{output:Uo(o),toolCalls:i,cursor:t.cursor,pendingToolConfirmation:{actionId:c,toolName:s.toolConfirmation?.toolName}}}let a=o.actions?.find(c=>c.type==="userSession");if(a){let c=a.actionId??a.id;if(!c)throw new Error("User session action missing actionId (both actionId and id are absent)");return{output:Uo(o),toolCalls:i,cursor:t.cursor,pendingUserSession:{actionId:c}}}return{output:Uo(o),toolCalls:i,cursor:t.cursor}}r(Rs,"extractAgentTurn");function Ds(e){let{modelId:t,service:n,verbose:o}=e;return{specificationVersion:"v2",provider:"cdf",modelId:t,supportedUrls:{},async doGenerate(i){return Mu(i,{modelId:t,service:n,verbose:o})},async doStream(i){throw new Error("CDF chat completions judge does not support streaming")}}}r(Ds,"createCdfChatCompletionsModel");async function Mu(e,t){let{modelId:n,service:o,verbose:i}=t,s=Uu(e.responseFormat),a=Nu(e.prompt,s),c={model:n,messages:a,stream:!1,temperature:e.temperature,maxTokens:e.maxOutputTokens};i?.logJson("chat/completions request",c),i?.log("judge POST /ai/chat/completions");let l=performance.now(),p=await o.postChatCompletions(c);i?.log(`judge chat/completions HTTP 200 in ${((performance.now()-l)/1e3).toFixed(1)}s`),i?.logJson("chat/completions response",p);let d=p.choices[0]?.message?.content??"",u=p.choices[0]?.finishReason??"stop";return{content:[{type:"text",text:d}],finishReason:_u(u),usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{body:c},response:{modelId:p.model??n,body:p}}}r(Mu,"generateWithCdf");function Uu(e){if(!e||e.type==="text")return;let t=e.schema?JSON.stringify(e.schema):'{"label":"string","explanation":"string"}',n=e.name?` (${e.name})`:"";return`Respond with a single valid JSON object only. No markdown code fences or extra text.${e.description?`
53
+ ${e.description}`:""}
54
+ The JSON must conform to this schema${n}: ${t}`}r(Uu,"jsonResponseInstruction");function Nu(e,t){let n=[];t&&n.push({role:"system",content:t});for(let o of e){if(o.role==="system"){n.push({role:"system",content:o.content});continue}if(o.role==="user"){let i=Is(o.content);i&&n.push({role:"user",content:i});continue}if(o.role==="assistant"){let i=Is(o.content);i&&n.push({role:"assistant",content:i})}}return n}r(Nu,"toCdfMessages");function Is(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
55
+ `)}r(Is,"extractTextParts");function _u(e){switch(e){case"stop":return"stop";case"length":return"length";case"content_filter":case"content-filter":return"content-filter";case"tool_calls":case"tool-calls":return"tool-calls";default:return"other"}}r(_u,"mapFinishReason");var ju="azure/gpt-5";function _o(e={}){return e.cliModelId?.trim()||process.env.EVAL_JUDGE_MODEL?.trim()||e.agentModelFallback?.trim()||ju}r(_o,"resolveJudgeModelId");function $s(e){let t=e.modelId??_o({cliModelId:e.cliModelId,agentModelFallback:e.agentModelFallback});return Ds({modelId:t,service:e.service,verbose:e.verbose})}r($s,"createJudgeModel");import{mkdir as Wu,writeFile as Zu}from"fs/promises";import{join as Us}from"path";var Ke="report.json",jo="report.md";var ln="eval-report";function pn(e){let t={name:e.name,message:e.message};ue(e)&&(e.hint&&(t.hint=e.hint),e.helpUrl&&(t.helpUrl=e.helpUrl)),xt(e)&&(t.http={status:e.httpStatusCode,...e.requestUrl!==void 0&&{url:e.requestUrl},...e.responseBody!==void 0&&{responseBody:e.responseBody}});let n=e.cause;return n instanceof Error&&(t.cause=pn(n)),t}r(pn,"serializeError");function Ho(e,t,n){return{version:1,meta:n,summary:{totalCases:e.totalCases,passedCases:e.passedCases,failedCases:e.failedCases,skippedCases:e.skippedCases,metExpectations:mt(e.results),verdictFailures:ut(e.results),unexpectedPassCount:gt(e.results)},cases:e.results.map(Fs),traces:t}}r(Ho,"buildEvalReportDocument");function Fs(e){let t=e.evalCase;return{id:t.id,source:t.source,...t.tags!==void 0&&t.tags.length>0&&{tags:t.tags},expectPass:t.expectPass!==!1,scorersPassed:e.passed,verdictPassed:ye(e),...t.contextInformation!==void 0&&{contextInformation:t.contextInformation},...e.run&&{turns:e.run.turns.map(n=>({input:n.input,output:n.output,toolCalls:n.toolCalls.map(o=>({name:o.name,...o.input!==void 0&&{input:o.input},...o.result!==void 0&&{result:o.result}})),apiRoundTrips:n.apiRoundTrips}))},scores:e.scores.map(n=>({turnIndex:n.turnIndex,scorerType:n.scorerType,score:n.score,...n.label!==void 0&&{label:n.label},...n.explanation!==void 0&&{explanation:n.explanation},passed:n.passed})),...e.invokeError&&{invokeError:pn(e.invokeError)},...e.scoreError&&{scoreError:pn(e.scoreError)}}}r(Fs,"serializeCaseResult");function Ko(e){let t=e.summary.skippedCases>0?` (${e.summary.skippedCases} skipped)`:"";return qu(`
56
+ # Agent eval report
57
+
58
+ - Agent: \`${e.meta.agentExternalId}\`
59
+ - Judge model: \`${e.meta.judgeModelId}\`
60
+ - Chat route: \`${e.meta.route}\`
61
+ - Summary: **${e.summary.metExpectations}/${e.cases.length}** cases met expectations${t}
62
+ - Full verbose-equivalent traces: \`${Ke}\` (${e.traces.length} event(s))
63
+
64
+ ${e.cases.map(Hu).join(`
65
+ `)}
66
+ ${Gu(e.traces)}
67
+ `)}r(Ko,"formatEvalReportMarkdown");function Hu(e){let t=e.verdictPassed?"PASS":"FAIL",n=e.expectPass===!1?" (expected fail)":"",o=e.tags&&e.tags.length>0?`- Tags: ${e.tags.map(i=>`\`${i}\``).join(", ")}
68
+ `:"";return`
69
+ ## ${t}: \`${e.id}\`${n}
70
+
71
+ - Source: \`${e.source}\`
72
+ - Verdict: ${e.verdictPassed?"met expectations":"did not meet expectations"}
73
+ - Scorers: ${e.scorersPassed?"all passed":"failed or missing"}
74
+ ${o}
75
+ ${e.invokeError?Ls("Invoke error",e.invokeError):""}${e.scoreError?Ls("Score error",e.scoreError):""}${Bu(e)}
76
+ `}r(Hu,"formatCaseMarkdown");function Bu(e){return e.turns?e.turns.map((t,n)=>Ku(t,n,e)).join(`
77
+ `):e.scores.length>0?Ms(e.scores,{showTurnIndex:!0}):""}r(Bu,"formatCaseBodyMarkdown");function Ku(e,t,n){let i=(n.turns?.length??0)>1?`### Turn ${t+1}`:"### Turn",s=n.scores.filter(a=>a.turnIndex===t);return`
78
+ ${i}
79
+
80
+ **Prompt**
81
+
82
+ ${Bo(e.input)}
83
+
84
+ **Response**
85
+
86
+ ${Bo(e.output||"(empty)")}
87
+
88
+ ${Vu(e.toolCalls)}${s.length>0?Ms(s):""}
89
+ `}r(Ku,"formatTurnMarkdown");function Vu(e){return e.length===0?"":`
90
+ **Tool calls**
91
+
92
+ ${e.map(n=>{let o=et(n,Qe),i=n.result!==void 0?` \u2192 ${cn(n.result,Qe)}`:"";return`- ${Ju(`${o}${i}`)}`}).join(`
93
+ `)}
94
+ `}r(Vu,"formatToolCallsMarkdown");function Ms(e,t={}){return`
95
+ **Scorers**
96
+
97
+ ${e.map(o=>{let i=t.showTurnIndex===!0?` (turn ${o.turnIndex+1})`:"",s=[o.label?`label=${o.label}`:void 0,`score=${o.score}`].filter(Boolean).join(", "),a=o.explanation?`
98
+ - ${o.explanation}`:"";return`- \`${o.scorerType}\`${i}: **${o.passed?"pass":"fail"}** (${s})${a}`}).join(`
99
+ `)}
100
+ `}r(Ms,"formatScoresMarkdown");function Gu(e){if(e.length===0)return"";let t=e.slice(0,40),n=t.map(i=>i.type==="log"?`- ${i.message}`:`- JSON: ${i.label}`).join(`
101
+ `),o=e.length>t.length?`
102
+ - \u2026 ${e.length-t.length} more event(s) in \`${Ke}\``:"";return`
103
+ ## Debug traces (summary)
104
+
105
+ Captured ${e.length} verbose-equivalent event(s). See \`${Ke}\` for full payloads (agent chat request/response, judge inputs, chat/completions I/O).
106
+
107
+ ${n}${o}
108
+ `}r(Gu,"formatTracesMarkdown");function Ls(e,t){return`
109
+ ### ${e}
110
+
111
+ ${Vo(`- Message: ${t.message}`,t.hint&&`- Hint: ${t.hint}`,t.helpUrl&&`- Help: ${t.helpUrl}`,t.http&&Yu(t.http),t.cause&&zu(t.cause))}
112
+ `}r(Ls,"formatErrorMarkdown");function Yu(e){let t=e.responseBody===void 0?void 0:`- Response body:
113
+
114
+ ${Bo(typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody,null,2))}`;return Vo(`- HTTP status: \`${e.status}\``,e.url&&`- URL: \`${e.url}\``,t)}r(Yu,"formatHttpErrorMarkdown");function zu(e){return Vo(`- Cause: ${e.name}: ${e.message}`,e.http&&` - HTTP status: \`${e.http.status}\``,e.http?.url&&` - URL: \`${e.http.url}\``)}r(zu,"formatCauseMarkdown");function Vo(...e){return e.filter(t=>!!t).join(`
115
+ `)}r(Vo,"lines");function qu(e){return`${e.replace(/^\n+/,"").replace(/\n{3,}/g,`
116
+
117
+ `).trimEnd()}
118
+ `}r(qu,"trimBlankLines");function Bo(e){return`\`\`\`
119
+ ${e.replace(/```/g,"``\\`")}
120
+ \`\`\``}r(Bo,"fence");function Ju(e){let t=Math.max(0,...(e.match(/`+/g)??[]).map(i=>i.length)),n="`".repeat(t+1),o=e.startsWith("`")||e.endsWith("`")||e.startsWith(" ")||e.endsWith(" ")?" ":"";return`${n}${o}${e}${o}${n}`}r(Ju,"inlineCode");async function Ns(e){let t=e.mkdir??Wu,n=e.writeFile??Zu,o=e.reportDir;await t(o,{recursive:!0});let i=Ho(e.summary,e.traces,{...e.meta,reportDir:o}),s=Us(o,Ke),a=Us(o,jo);return await n(s,`${JSON.stringify(i,null,2)}
121
+ `,"utf8"),await n(a,Ko(i),"utf8"),{jsonPath:s,mdPath:a}}r(Ns,"writeEvalReport");async function _s(e,t,n){let o=(e.externalId!==void 0?e.externalId.trim():void 0)??(e.systemAgent?ri:void 0);if(e.externalId!==void 0&&o==="")throw new m("--external-id cannot be empty.",{hint:`Provide a valid agent external ID, or omit the flag to read from ${A.configGlob}.`,shouldReport:!1});if(o!==void 0)return{externalId:o,agentYaml:void 0};let i=await n(t);if(!i.externalId)throw new m("No agent specified.",{hint:`Provide --external-id, --system-agent, or run from a directory with ${A.configGlob}.`,shouldReport:!1});return{externalId:i.externalId,agentYaml:i}}r(_s,"resolveAgentIdentity");function js(){let e=process.env.AGENT_CHAT_ROUTE?.trim().toLowerCase();return e==="public"||e==="agents"?"public":e==="internal"||e==="fusion"?"internal":"public"}r(js,"resolveAgentChatRoute");function Hs(e,t){let n=t==="internal"?"internal/agents/chat":"agents/chat";return`/api/v1/projects/${encodeURIComponent(e)}/ai/${n}`}r(Hs,"formatAgentChatPath");function Bs(e){return`/api/v1/projects/${encodeURIComponent(e)}/ai/chat/completions`}r(Bs,"formatChatCompletionsPath");function Xu(e){return{...e,messages:e.messages.map(t=>t.role==="action"&&t.type==="userSession"?{...t,nonce:"<redacted>"}:t)}}r(Xu,"redactNonces");async function Ks(e){let t=e.allowToolConfirmation!==!1,n=e.maxTurns??8,o=e.verbose;o?.log(`agentExternalId=${e.agentExternalId} | auto-allow tools=${t}`);let i=e.cursor,s,a,c,l,p=[],d="",u=0;for(let g=0;g<n;g+=1){u+=1;let h=`turn ${u}/${n}`,f;a&&c&&i?(f={agentExternalId:e.agentExternalId,cursor:i,messages:[{role:"action",type:"userSession",actionId:a,nonce:c}]},a=void 0,c=void 0):s&&i?(f={agentExternalId:e.agentExternalId,cursor:i,messages:[{role:"action",type:"toolConfirmation",actionId:s,status:"ALLOW"}]},s=void 0):f={agentExternalId:e.agentExternalId,...e.contextInformation?{contextInformation:e.contextInformation}:{},...i?{cursor:i}:{},messages:[{role:"user",content:{type:"text",text:e.input}}]},o?.log(`${h}: sending chat request\u2026`),o?.logJson(`${h} request body`,Xu(f)),l=await e.service.postAgentChat(f),o?.logJson(`${h} response`,l);let y;try{y=Rs(l)}catch(S){throw new m(`Failed to parse agent response on turn ${u}/${n}`,{hint:"The CDF agent API returned an unexpected response shape. Run with --verbose to see the raw response.",cause:S})}if(Ts(p,y.toolCalls),o?.log(`${h}: extracted output length=${y.output.length}, tools=[${an(y.toolCalls)}]`),y.output&&(d=y.output),y.pendingToolConfirmation){if(o?.log(`${h}: tool confirmation requested \u2014 tool=${y.pendingToolConfirmation.toolName??"?"} actionId=${y.pendingToolConfirmation.actionId}`),!t)throw new m(`Agent requested tool confirmation (${y.pendingToolConfirmation.toolName??"unknown"}) but allowToolConfirmation is false`,{hint:"Re-run with tool confirmation enabled, or adjust the agent to avoid confirmation prompts."});if(!y.cursor||!y.pendingToolConfirmation.actionId)throw new m("Tool confirmation missing cursor or actionId",{hint:"The agent API returned an incomplete tool-confirmation action. This may be an API bug \u2014 retry or report to CDF support."});i=y.cursor,s=y.pendingToolConfirmation.actionId,o?.log(`${h}: auto-ALLOW, continuing with cursor\u2026`);continue}if(y.pendingUserSession){if(o?.log(`${h}: userSession requested \u2014 actionId=${y.pendingUserSession.actionId}, creating nonce\u2026`),!y.cursor||!y.pendingUserSession.actionId)throw new m("User session missing cursor or actionId",{hint:"The agent API returned an incomplete user-session action. This may be an API bug \u2014 retry or report to CDF support."});let S=await e.service.createSessionNonce();i=y.cursor,a=y.pendingUserSession.actionId,c=S,o?.log(`${h}: created nonce, continuing with cursor\u2026`);continue}return o?.log(`${h}: conversation complete`),{output:d,toolCalls:p,turns:u,cursor:y.cursor??i,lastResponse:l}}throw new m(`Agent chat exceeded ${n} turns (action loop?)`,{hint:"The agent may be stuck in a tool-confirmation or user-session loop. Increase maxTurns or inspect the agent configuration."})}r(Ks,"invokeAgentCase");import{createCorrectnessEvaluator as rm}from"@arizeai/phoenix-evals/llm/createCorrectnessEvaluator";import{createFaithfulnessEvaluator as im}from"@arizeai/phoenix-evals/llm/createFaithfulnessEvaluator";import{createToolInvocationEvaluator as sm}from"@arizeai/phoenix-evals/llm/createToolInvocationEvaluator";import{createToolSelectionEvaluator as am}from"@arizeai/phoenix-evals/llm/createToolSelectionEvaluator";function Vs(e){return{log(t){e(t)},logJson(t,n,o=6e3){e(`${t}:
122
+ ${Qu(n,o)}`)}}}r(Vs,"createEvalLogger");function Gs(){let e=[];return{events:e,logger:{log(t){e.push({type:"log",message:t})},logJson(t,n){e.push({type:"json",label:t,value:em(n)})}}}}r(Gs,"createTraceCapture");function Ys(e,t){return{log(n){e.log(n),t.log(n)},logJson(n,o,i){e.logJson(n,o,i),t.logJson(n,o,i)}}}r(Ys,"teeEvalLogger");function Qu(e,t=6e3){let n;try{n=JSON.stringify(e,null,2)??String(e)}catch{n=String(e)}return n.length<=t?n:`${n.slice(0,t)}
123
+ \u2026 (${n.length-t} more chars)`}r(Qu,"formatJson");function zs(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}r(zs,"formatDurationMs");function em(e){try{return JSON.parse(JSON.stringify(e)??"null")}catch{return String(e)}}r(em,"cloneForTrace");var tm=.5,nm={correctness:{pass:"correct",fail:"incorrect"},faithfulness:{pass:"faithful",fail:"unfaithful"},toolSelection:{pass:"correct",fail:"incorrect"},toolInvocation:{pass:"correct",fail:"incorrect"}};function om(e,t){let n=nm[e];if(n){if(t.label===n.pass)return!0;if(t.label===n.fail)return!1}return(t.score??0)>=tm}r(om,"scorerPassed");async function ht(e,t,n,o,i,s){s?.log(`scoring ${n.type} (Phoenix + CDF /ai/chat/completions)\u2026`),s?.logJson(`${n.type} judge input`,i);let a=performance.now(),c;try{c=await o.evaluate(i)}catch(d){if(ue(d))throw d;let u=d instanceof Error?d.message:String(d);throw new m(`Phoenix ${n.type} judge failed (${u}). Judge uses CDF POST .../ai/chat/completions.`,{cause:d})}s?.log(`${n.type} judge finished in ${zs(performance.now()-a)}`),s?.logJson(`${n.type} judge result`,c);let l=om(n.type,c),p=typeof c.score=="number"?c.score:l?1:0;return{caseId:e,turnIndex:t,scorerType:n.type,score:p,label:c.label,explanation:c.explanation,passed:l}}r(ht,"runPhoenixLlmScorer");function qs(e=[]){return e.map(t=>`${t.name}: ${t.description}`).join(`
124
+ `)}r(qs,"formatAvailableTools");function cm(e){return e.length>0?an(e):"No tools called"}r(cm,"formatToolSelection");function lm(e){return e.length>0?e.map(t=>et(t)).join(`
125
+ `):"No tools called"}r(lm,"formatToolInvocations");function pm(e){let t=e.map(n=>`"${n}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}r(pm,"formatScorerTypeList");function dm(e,t){let n=e.turns.slice(0,t);return n.length===0?"":`Conversation so far:
126
+ `+n.map(o=>`User: ${o.input}
127
+ Assistant: ${o.output}`).join(`
128
+ `)+`
129
+
130
+ `}r(dm,"conversationContext");async function um(e,t,n,o,i,s){let a=o.turns[t];if(!a)throw new m(`No agent response recorded for turn ${t+1} of case "${e.id}" (${e.source}).`,{hint:"This is an internal mismatch between scored turns and executed turns."});let c=dm(o,t),l=s?.verbose;if(n.type==="correctness"){let d=rm({model:i});return ht(e.id,t,n,d,{input:`${c}User question:
131
+ ${a.input}
132
+
133
+ Criteria:
134
+ ${n.criteria}`,output:a.output},l)}if(n.type==="faithfulness"){let d=im({model:i});return ht(e.id,t,n,d,{input:c?`${c}Current question:
135
+ ${a.input}`:a.input,output:a.output,context:n.groundTruth},l)}if(n.type==="toolSelection"||n.type==="toolInvocation"){let d=n.tools??e.tools??s?.tools??[];if(d.length===0){let g=s?.tools===void 0?`Add a tools field to the scorer, case, or eval.yaml root (${A.configGlob} is not used with --external-id/--system-agent).`:`Add a tools field to the scorer, case, or eval.yaml root, or declare tools in ${A.configGlob}.`,h=`Warning: Skipping ${n.type} scorer on case "${e.id}": no tools available.`;return l?.log(h),s?.warn?.(h,g),null}if(n.type==="toolSelection"){let g=am({model:i});return ht(e.id,t,n,g,{input:c?`${c}Current question:
136
+ ${a.input}`:a.input,availableTools:qs(d),toolSelection:cm(a.toolCalls)},l)}let u=sm({model:i});return ht(e.id,t,n,u,{input:c?`${c}Current question:
137
+ ${a.input}`:a.input,availableTools:qs(d),toolSelection:lm(a.toolCalls)},l)}let p=n;throw new m(`Scorer type "${p.type}" is not supported yet.`,{hint:`The CLI eval schema currently supports only ${pm(ds)} scorers.`,shouldReport:!1})}r(um,"evaluateScorer");async function mm(e,t,n,o,i){let s=e.turns[t]?.scorers??[];return(await Promise.all(s.map(c=>um(e,t,c,n,o,i)))).filter(c=>c!==null)}r(mm,"scoreTurn");async function Js(e,t,n,o){return(await Promise.all(e.turns.map((s,a)=>mm(e,a,t,n,o)))).flat()}r(Js,"scoreCase");function gm(e){return e.length>0&&e.every(t=>t.passed)}r(gm,"casePassed");function fm(e,t,n){if(n<=1)return e;let o=e instanceof Error?e.message:String(e);return new m(`turn ${t+1}/${n}: ${o}`,{hint:ue(e)?e.hint:void 0,helpUrl:ue(e)?e.helpUrl:void 0,shouldReport:ue(e)?e.shouldReport:void 0,cause:e})}r(fm,"annotateTurnFailure");async function hm(e,t){let{service:n,agentExternalId:o,judgeModel:i,verbose:s}=t;s?.log(`--- case "${e.id}" (${e.source}) invoke ---`);let a;try{let c=[],l;for(let[p,d]of e.turns.entries()){s?.log(` turn ${p+1}/${e.turns.length}: "${d.input}"`);let u;try{u=await Ks({service:n,agentExternalId:o,input:d.input,cursor:l,contextInformation:e.contextInformation,allowToolConfirmation:t.allowToolConfirmation,verbose:s})}catch(g){throw fm(g,p,e.turns.length)}l=u.cursor,c.push({input:d.input,output:u.output,toolCalls:u.toolCalls,apiRoundTrips:u.turns})}a={caseId:e.id,turns:c}}catch(c){return{evalCase:e,scores:[],passed:!1,invokeError:c instanceof Error?c:new Error(String(c))}}s?.log(`--- case "${e.id}" (${e.source}) score (Phoenix) ---`);try{let c=await Js(e,a,i,{verbose:s,tools:t.tools,warn:t.warn});return{evalCase:e,run:a,scores:c,passed:gm(c)}}catch(c){return{evalCase:e,run:a,scores:[],passed:!1,scoreError:c instanceof Error?c:new Error(String(c))}}}r(hm,"runCase");async function Ws(e){let{cases:t,verbose:n}=e,o=[];for(let s of t){let a=await hm(s,e);if(o.push(a),e.failFast&&!ye(a)){n?.log(`--- fail-fast: stopping after failed case "${s.id}" (${s.source}) ---`);break}}let i=o.filter(s=>s.passed).length;return{totalCases:t.length,passedCases:i,failedCases:o.length-i,skippedCases:t.length-o.length,results:o}}r(Ws,"runEval");var Zs={"cdf-version":"20230101-alpha"};function Xs(e,t){let n=Hs(e.project,t),o=Bs(e.project);async function i(l){try{return(await e.post(n,{data:l,headers:Zs})).data}catch(p){let d=t==="internal"&&ae(p)&&p.status===404?" Try the public route: set AGENT_CHAT_ROUTE=public.":"";throw Go(p,"Agent chat",n,d||void 0)}}r(i,"postAgentChat");async function s(l){try{return(await e.post(o,{data:l,headers:Zs})).data}catch(p){throw Go(p,"Chat completions",o)}}r(s,"postChatCompletions");async function a(){let l=`/api/v1/projects/${encodeURIComponent(e.project)}/sessions`;try{return await c({oneshotTokenExchange:!0},l)}catch(p){if(ym(p))return await c({tokenExchange:!0},l);throw p}}r(a,"createSessionNonce");async function c(l,p){try{let d=await e.sessions.create([l]),u=d?.[0]?.nonce;if(!u)throw new m("Session creation returned no nonce",{hint:"The Sessions API returned an empty items list. Retry, or check IdP configuration for this project.",cause:new Error(`Response items: ${JSON.stringify(d)}`)});return u}catch(d){throw d instanceof m?d:Go(d,"Session creation",p)}}return r(c,"requestSessionNonce"),{postAgentChat:i,postChatCompletions:s,createSessionNonce:a}}r(Xs,"getEvalService");function ym(e){let t=e instanceof de?e.httpStatusCode:ae(e)?e.status:void 0;return t===400||t===401||t===403}r(ym,"isSessionTypeRejected");function Go(e,t,n,o){if(!ae(e))return e instanceof Error?e:new Error(String(e));let i=Ni(e),s=i?`: ${i}`:"",a=o??"";return new de(`${t} failed (${e.status})${s}${a}`,{httpStatusCode:e.status,requestUrl:n,responseBody:wo(e),cause:e})}r(Go,"wrapCdfApiError");function ta(e){if(!e)return"(none)";let t=[],n=e.dataModels?.length??0,o=e.instanceSpaces?.length??0;return(n>0||o>0)&&t.push(`${n} data model(s), ${o} space(s)`),e.appContext&&t.push("app context"),t.length>0?t.join(", "):"(none)"}r(ta,"formatSessionContextSummary");function wm(e){let t=e.filter(s=>s.contextInformation!==void 0);if(t.length===0)return;let n=t.map(s=>s.contextInformation),o=n[0];return t.length===e.length&&n.every(s=>Sm(s,o))?ta(o):`varies by case (${t.length}/${e.length})`}r(wm,"summarizeSessionContextForStdout");function ea(e,t){return t?[...t,e]:[e]}r(ea,"collectRepeatableValues");var Yo=Object.freeze({case:new ve("--case <id>","Run only cases with this id (repeatable)").argParser(ea),tag:new ve("--tag <tag>","Run only cases with this tag (repeatable)").argParser(ea),judgeModel:new ve("--judge-model <model>","LLM model for scoring eval cases (e.g. azure/gpt-5)"),externalId:new ve("--external-id <id>",`Agent external ID (alternative to reading from ${A.configGlob})`).conflicts("systemAgent"),systemAgent:new ve("--system-agent","Evaluate the Cognite system agent (currently cdf_industrial_v4)").conflicts("externalId"),upsert:new ve("--upsert",`Push the local ${A.configGlob} to CDF before running evals`).conflicts("externalId").conflicts("systemAgent"),failFast:new ve("--fail-fast","Stop after the first failing case; skip the rest"),verbose:new ve("-v, --verbose","Log request/response traces to stderr"),failOnToolConfirmation:new ve("--fail-on-tool-confirmation","Fail a case instead of auto-approving when the agent requests tool confirmation"),reportDir:new ve("--report-dir [path]",`Write structured eval reports (report.json + report.md); defaults to ${ln} when the path is omitted`).preset(ln)}),Vb=Object.values(Yo).map(e=>e.long).filter(e=>e!=null);function vm(e,t){return e.expectPass===!1?t.dim(" (expected fail)"):""}r(vm,"formatExpectedFailSuffix");function Cm(e,t,n,o,i){if(e.length!==0){t(T(n.dim("toolsCalled:"),o));for(let s of e){let a=et(s,Qe);!i||s.result===void 0||s.result===null?t(T(a,o+1)):t(T(`${a} ${n.dim(`\u2192 ${cn(s.result)}`)}`,o+1))}}}r(Cm,"formatToolCalls");function Am(e,t,n,o,i){let a=ye(e)?n.green("\u2713"):n.red("\u2717"),c=vm(e.evalCase,n),l=o&&e.evalCase.source?`${e.evalCase.id} (${e.evalCase.source})`:e.evalCase.id;if(t(`${a} ${l}${c}`),e.invokeError){t(T(n.red("invoke: fail"))),t(T(e.invokeError.message,2)),e.invokeError instanceof m&&e.invokeError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.invokeError.hint}`),2));return}e.scoreError&&(t(T(n.red("score: fail"))),t(T(e.scoreError.message,2)),e.scoreError instanceof m&&e.scoreError.hint&&t(T(n.yellow(`\u{1F4A1} ${e.scoreError.hint}`),2)));let p=e.run?.turns.length??0,d=[...new Set([...Array.from({length:p},(g,h)=>h),...e.scores.map(g=>g.turnIndex)])].sort((g,h)=>g-h),u=d.length>1;for(let g of d){let h=u?2:1;u&&t(T(n.dim(`turn ${g+1}`)));let f=e.run?.turns[g];f&&Cm(f.toolCalls,t,n,h,i);for(let y of e.scores.filter(S=>S.turnIndex===g)){let S=y.passed?n.green("pass"):n.red("fail");t(T(`${y.scorerType}: ${S}`,h)),y.explanation&&t(T(n.dim(y.explanation),h+1))}}}r(Am,"formatCaseResult");async function Em(e,t,n,o){if(n.upsert){await t.upsert(Ue(e)),o.writeStdout(o.c.green(`Pushed agent "${e.externalId}" to project "${o.project}"`));return}try{let i=await t.getByExternalId(e.externalId),s=bs(e,i);s.length>0&&o.writeStderr(o.c.yellow(xs(s,{verbose:n.verbose})))}catch(i){if(i instanceof m&&i.message.includes("not found"))o.writeStderr(o.c.yellow(`Warning: agent "${e.externalId}" is not deployed in CDF. Run with --upsert to push local config before evaluating.`));else{let s=i instanceof Error?i.message:String(i);o.writeStderr(o.c.yellow(`Warning: failed to fetch deployed agent "${e.externalId}": ${s}`))}}}r(Em,"ensureAgentConfigBeforeEval");async function na(e,t,n={}){let o=n.readAgentYaml??De,i=n.loadEvalCases??ys,s=n.writeStdout??(E=>console.log(E)),a=n.writeStderr??(E=>console.error(E)),c=n.chalk??P(process.stdout),l=n.getAgentClient??Y,p=n.getAgentsService??ne,d=n.getEvalService??Xs,u=n.runEval??Ws,g=n.writeEvalReport??Ns,h=Qs(e??"."),{externalId:f,agentYaml:y}=await _s(t,h,o);if(t.upsert&&y===void 0)throw new m(`--upsert requires a local ${A.configGlob} to push.`,{hint:`Remove --upsert, or add an agent definition (${A.configGlob}) to this directory.`,shouldReport:!1});let S=await i(h),w=hs(S,{caseFilter:t.case,tagFilter:t.tag}),v=[...new Set(S.map(E=>E.source))],C=v.length>1,x=await l(t,h),L=p(x);y!==void 0&&await Em(y,L,t,{project:x.project,writeStdout:s,writeStderr:a,c});let B=js(),R=d(x,B),Z=t.reportDir!==void 0&&t.reportDir.length>0?Qs(t.reportDir):void 0,Q=Z!==void 0?Gs():void 0,I=t.verbose?Vs(E=>a(E)):void 0,N=Q&&I?Ys(I,Q.logger):Q?.logger??I,ie=_o({cliModelId:t.judgeModel,agentModelFallback:y?.model});C&&s(`Matched ${w.length} of ${S.length} case(s) across ${v.length} file(s)`);let le=wm(w);le!==void 0&&s(`Session context: ${le}`),s(`Judge model: ${c.cyan(ie)}`),N?.log(`Agent: ${f}`);for(let E of w)N?.log(` ${E.id}: ${ta(E.contextInformation)}`);for(let E of v){let pe=S.filter(Hn=>Hn.source===E).length;N?.log(` ${E} (${pe} case(s))`)}N?.log(`Loaded ${w.length} case(s): ${w.map(E=>E.id).join(", ")}`),N?.log(`judge model: ${ie} (source: ${t.judgeModel?"--judge-model flag":process.env.EVAL_JUDGE_MODEL?"EVAL_JUDGE_MODEL env":y?.model?`${A.configGlob} model fallback`:"default"})`),N?.log(`agent chat route: ${B}`);let G=$s({cliModelId:t.judgeModel,agentModelFallback:y?.model,service:R,verbose:N}),ee=await u({cases:w,service:R,agentExternalId:f,judgeModel:G,verbose:N,tools:y?.tools,warn:r((E,pe)=>{a(c.yellow(pe?`${E}
138
+ hint: ${pe}`:E))},"warn"),allowToolConfirmation:!t.failOnToolConfirmation,failFast:t.failFast});for(let E of ee.results)Am(E,s,c,C,t.verbose??!1),E.evalCase.expectPass===!1&&!E.invokeError&&!E.scoreError&&E.passed&&a(c.yellow(`Warning: case "${E.evalCase.id}" expected scorers to fail but they passed.`));let jn=Io(ee.results),Mr=mt(ee.results),Ur=`${Mr}/${ee.results.length} cases met expectations`,Cl=jn?c.bold(c.red(Ur)):c.bold(c.green(Ur));if(s(`
139
+ ${Cl}`),ee.skippedCases>0&&s(c.yellow(`Stopped early (--fail-fast): ${ee.skippedCases} case(s) not run.`)),Z!==void 0&&Q!==void 0)try{let{jsonPath:E,mdPath:pe}=await g({reportDir:Z,summary:ee,traces:Q.events,meta:{agentExternalId:f,judgeModelId:ie,route:B}});s(`Wrote eval report: ${E}`),s(`Wrote eval report: ${pe}`)}catch(E){let pe=E instanceof Error?E.message:String(E);a(c.yellow(`Warning: failed to write eval report: ${pe}`))}jn&&(process.exitCode=1);let Al=Array.from(new Set(w.flatMap(E=>E.turns.flatMap(pe=>pe.scorers?.map(Hn=>Hn.type)??[])))),Nr=Zn();await ks(n.telemetry,{caseCount:ee.totalCases,passCount:Mr,failCount:ut(ee.results),unexpectedPassCount:gt(ee.results),scorersUsed:Al,success:!jn,...Nr!==void 0&&{actionDurationMs:Nr}})}r(na,"handleAgentsEval");import{Option as Pm}from"commander";function dn(e,t){return e.map((n,o)=>Math.max(n.length,...t.map(i=>i[o].length)))}r(dn,"computeColumnWidths");function yt(e,t,n=e){return e.map((o,i)=>n[i]+" ".repeat(Math.max(0,t[i]-o.length))).join(" ").trimEnd()}r(yt,"formatTableRow");import{writeFile as oa}from"fs/promises";import{resolve as xm}from"path";import{resolve as bm}from"path";async function Ce(e,t,n={}){let o=n.readAgentYaml??De,i=n.getAgentClient??Y,s=n.getAgentsService??ne,a=bm(e??"."),c=await o(a),l=await i(t,a);await s(l).upsert(Ue(c));let d=P(process.stdout);return console.log(d.green(`Pushed agent "${c.externalId}" to project "${l.project}"`)),{client:l,agentYaml:c}}r(Ce,"handleAgentsPush");var ke="published",zo=class zo extends Ee{constructor(){super("publish");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=xm(n??"."),{path:c,agent:l}=await at(a),p=l.labels??[];if(p.includes(ke))await Ce(n,s);else{let u={...l,labels:[...p,ke]};await oa(c,ge(u));try{await Ce(n,s)}catch(g){throw await oa(c,ge(l)),g}}let d=P(process.stdout);console.log(d.green(`Published agent "${l.externalId}"`))},"handle");this.description("Promote a draft agent to production").argument("[dir]","Agent project directory").addHelpText("after",km),this.action(this.handle)}};r(zo,"PublishCommand");var un=zo,km=`
140
+ Examples:
141
+ cognite agents publish Publish agent in current directory
142
+ cognite agents publish ./my-agent Publish agent in my-agent directory
143
+ `;var ra=Object.freeze({json:new Pm("--json","Output as JSON")});async function ia(e,t={}){let n=t.getAgentClient??Y,o=t.getAgentsService??ne,i=await n(e,process.cwd()),c=(await o(i).list()).items;if(e.json){console.log(JSON.stringify(c,null,2));return}if(c.length===0){console.log(`No agents found in project "${i.project}".`);return}let l=P(process.stdout),p=c.map(w=>({externalId:w.externalId,name:w.name,status:w.labels?.includes(ke)?"published":"draft",model:w.model,updated:qo(w.lastUpdatedTime)})),d=["externalId","name","status","model","updated"],u=["External ID","Name","Status","Model","Updated"],g=p.map(w=>d.map(v=>w[v])),h=dn(u,g);console.log(),console.log(l.bold(yt(u,h))),console.log(l.dim(h.map(w=>"\u2500".repeat(w)).join(" ")));for(let w of p){let v=w.status==="published"?l.green(w.status):l.yellow(w.status),C=d.map(L=>w[L]),x=d.map(L=>L==="status"?v:w[L]);console.log(yt(C,h,x))}console.log();let f=p.filter(w=>w.status==="published").length,y=p.length-f,S=[`${p.length} agent${p.length===1?"":"s"}`];f>0&&S.push(`${f} published`),y>0&&S.push(`${y} draft`),console.log(S.join(", "))}r(ia,"handleAgentsList");function qo(e,t=Date.now()){let n=t-e;if(n<0)return"just now";let o=Math.floor(n/1e3);if(o<60)return"just now";let i=Math.floor(o/60);if(i<60)return`${i}m ago`;let s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}r(qo,"formatRelativeTime");import{resolve as Im}from"path";import{Option as Dm}from"commander";function sa(e,t){let{org:n,project:o,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:c}=t,l=new URLSearchParams({cluster:s,customAppVersion:c,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${o}/flows-apps/app/${encodeURIComponent(a)}?${l}`}r(sa,"generateFusionUrl");function aa(e){let{org:t,project:n,cluster:o,agentExternalId:i}=e,s=new URLSearchParams({cluster:o,atlasOverride:i});return`https://${t}.fusion.cognite.com/${n}?${s}`}r(aa,"generateAtlasAgentUrl");import{execFileSync as ca}from"child_process";import{platform as Tm}from"os";import Rm from"path";function X(e,t={}){let{platform:n=Tm}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}r(X,"isOS");function mn(e,t={}){let{exec:n=ca,log:o=console.log}=t,[i,s]=X("macos",t)?["open",[e]]:X("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{return n(i,s),!0}catch{return o(`Could not open browser \u2014 open manually:
144
+ ${e}`),!1}}r(mn,"openInBrowser");function la(e,t={}){let{exec:n=ca,log:o=console.log}=t,[i,s]=X("macos",t)?["open",["-R",e]]:X("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Rm.dirname(e)]];try{n(i,s)}catch{o(`Could not open file manager \u2014 files are at:
145
+ ${e}`)}}r(la,"revealInFileManager");var Jo=Object.freeze({upsert:new Dm("--upsert","Push the agent to CDF before opening (upsert draft)").default(!1)}),Lx=Object.values(Jo).map(e=>e.long).filter(e=>e!=null);function $m(e){try{return new URL(e.getBaseUrl()).hostname}catch{throw new m("Could not determine cluster from client base URL.",{hint:"Check your --base-url or session project configuration.",shouldReport:!1})}}r($m,"clusterFromBaseUrl");async function pa(e,t,n={}){let o=n.handleAgentsPush??Ce,i=n.readAgentYaml??De,s=n.getAgentClient??Y,a=n.resolveOrg??rs,c=n.openInBrowser??mn,l=Im(e??"."),{client:p,agentYaml:d}=t.upsert?await o(e,t):{agentYaml:await i(l),client:await s(t,l)},u=a(t,l),g=p.project,h=$m(p),f=aa({org:u,project:g,cluster:h,agentExternalId:d.externalId}),y=P(process.stdout);console.log(y.cyan(`Opening ${f}`)),c(f)}r(pa,"handleAgentsOpen");import{mkdir as Om,writeFile as Fm}from"fs/promises";import{basename as Lm,join as Mm,resolve as Um}from"path";import{Option as Nm}from"commander";async function da(e,t,n,o={getAgentClient:{}}){let i=await Y(n,process.cwd(),o.getAgentClient),s=await ne(i).getByExternalId(e),a=Um(t??"."),c=Ie(Lm(a)),l=(await st(a)).find(u=>u.toLowerCase()===c.toLowerCase()),p=Mm(a,l??c);if(l!==void 0&&!n.force)throw new m(`${l} already exists at:
146
+ ${p}`,{hint:"Use --force to overwrite the existing file.",shouldReport:!1});await Om(a,{recursive:!0}),await Fm(p,ge(s));let d=P(process.stdout);console.log(d.green(`Pulled agent "${s.name}" (${e}) to ${p}`))}r(da,"handleAgentsPull");var St=Object.freeze({externalId:{name:"external-id",description:"externalId of the agent to pull"},dir:{name:"dir",description:"Agent project directory"}}),Wo=Object.freeze({force:new Nm("--force","Overwrite the existing agent definition without prompting")}),zx=Object.values(Wo).map(e=>e.long).filter(e=>e!=null);import{resolve as _m}from"path";import{Option as ua}from"commander";var ma=Object.freeze({externalId:new ua("--external-id <id>",`Agent external ID (alternative to reading from ${A.configGlob})`),json:new ua("--json","Output as JSON")});function jm(e){return e.labels?.includes(ke)?"published":"draft"}r(jm,"describeAgentStatus");function Hm(e,t=Date.now()){return e==null||isNaN(e)?"unknown":`${new Date(e).toISOString()} (${qo(e,t)})`}r(Hm,"formatUpdatedAt");function Bm(e){let t=e.tools??[];if(t.length===0)return["Tools: none"];let n=[`Tools (${t.length}):`];for(let o of t)n.push(T(`- ${o.type}: ${o.description}`));return n}r(Bm,"formatTools");function Km(e){let t=e.skills??[];if(t.length===0)return["Skills: none"];let n=[`Skills (${t.length}):`];for(let o of t)n.push(T(`- ${o}`));return n}r(Km,"formatSkills");function Vm(e){let t=e.subagents??[];if(t.length===0)return["Sub-agents: none"];let n=[`Sub-agents (${t.length}):`];for(let o of t)n.push(T(`- ${o.agentExternalId}`));return n}r(Vm,"formatSubagents");function Gm(e,t,n=Date.now()){let o=jm(e);return["",`Agent: ${t.bold(e.name)} (${t.dim(e.externalId)})`,`Status: ${o==="published"?t.green(o):t.yellow(o)}`,`Model: ${e.model}`,`Updated: ${t.dim(Hm(e.lastUpdatedTime,n))}`,"",...Bm(e),"",...Km(e),"",...Vm(e),...o==="draft"?["","Run `npx @cognite/cli agents publish .` to publish this agent."]:[]]}r(Gm,"renderAgentStatus");async function ga(e,t,n={}){let o=n.readAgentYaml??De,i=n.getAgentClient??Y,s=n.getAgentsService??ne,a=_m(e??"."),c;if(t.externalId!==void 0){let g=t.externalId.trim();if(!g)throw new m("--external-id cannot be empty.",{hint:`Provide a valid agent external ID, or omit the flag to read from ${A.configGlob}.`,shouldReport:!1});c=g}else c=(await o(a)).externalId;let l=await i(t,a),d=await s(l).getByExternalId(c);if(t.json){console.log(JSON.stringify(d,null,2));return}let u=Gm(d,P(process.stdout));for(let g of u)console.log(g)}r(ga,"handleAgentsStatus");import{writeFile as fa}from"fs/promises";import{resolve as Ym}from"path";var Zo=class Zo extends Ee{constructor(){super("unpublish");this.handle=r(async(n,o,i)=>{let s=i.optsWithGlobals(),a=Ym(n??"."),{path:c,agent:l}=await at(a),p=l.labels??[];if(p.includes(ke)){let u={...l,labels:p.filter(g=>g!==ke)};await fa(c,ge(u));try{await Ce(n,s)}catch(g){throw await fa(c,ge(l)),g}}else await Ce(n,s);let d=P(process.stdout);console.log(d.green(`Unpublished agent "${l.externalId}"`))},"handle");this.description("Retract a published agent back to draft").argument("[dir]","Agent project directory").addHelpText("after",zm),this.action(this.handle)}};r(Zo,"UnpublishCommand");var gn=Zo,zm=`
147
+ Examples:
148
+ cognite agents unpublish Unpublish agent in current directory
149
+ cognite agents unpublish ./my-agent Unpublish agent in my-agent directory
150
+ `;var Qo=class Qo extends Pt{constructor(t,n){super(t),this.telemetry=n}configure(){this.description("Manage Atlas agents \u2014 create, iterate, and publish agents to Cognite Data Fusion"),this.hook("postAction",(t,n)=>Qr(this.telemetry,n)),this.create(),this.push(),this.open(),this.publish(),this.unpublish(),this.pull(),this.list(),this.status(),this.eval()}create(){let t=new rn;return this.addCommand(t),t}push(){return this.command("push").description("Push a draft agent to CDF for interactive testing").argument("[dir]","Agent project directory").action(async(t,n,o)=>{await Ce(t,o.optsWithGlobals())})}open(){let t=this.command("open").description("Open the agent in Fusion for interactive testing").argument("[dir]","Agent project directory");for(let n of Object.values(Jo))t.addOption(n);return t.action((n,o,i)=>pa(n,i.optsWithGlobals()))}publish(){let t=new un;return this.addCommand(t),t}unpublish(){let t=new gn;return this.addCommand(t),t}pull(){let t=this.command("pull").description("Pull an existing agent from CDF into the local project").argument(`<${St.externalId.name}>`,St.externalId.description).argument(`[${St.dir.name}]`,St.dir.description);for(let n of Object.values(Wo))t.addOption(n);return t.action((n,o,i,s)=>da(n,o,s.optsWithGlobals()))}list(){let t=this.command("list").description("List agents in the CDF project");for(let n of Object.values(ra))t.addOption(n);return t.action((n,o)=>ia(o.optsWithGlobals()))}status(){let t=this.command("status").description("Show the current status of the agent in CDF").argument("[dir]","Agent project directory");for(let n of Object.values(ma))t.addOption(n);return t.action(async(n,o,i)=>ga(n,i.optsWithGlobals()))}eval(){let t=this.command("eval").description("Run eval cases for an agent").argument("[dir]","Agent directory");for(let n of Object.values(Yo))t.addOption(n);return t.action((n,o,i)=>na(n,i.optsWithGlobals(),{telemetry:this.telemetry}))}};r(Qo,"AgentsCommand");var Xo=Qo;function ha(e,t={}){let n=new Xo("agents",t.telemetry);return e.addCommand(n),n}r(ha,"registerAgentsCommand");import{existsSync as vg,readFileSync as Cg}from"fs";import{join as Ag,resolve as bn}from"path";import{verifyBundle as Eg}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as bg}from"jose";import er from"enquirer";import{email as qm,pipe as Jm,safeParse as Wm,string as Zm}from"valibot";var Xm=Jm(Zm(),qm());function tt(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Wm(Xm,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}r(tt,"parseEmail");import{execFileSync as hn}from"child_process";import{execFileSync as Qm}from"child_process";function fn(e={}){let{execFileSync:t=Qm}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}r(fn,"isGitInstalled");function Ae(e={}){if(!fn(e))throw new m("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}r(Ae,"throwIfGitMissing");function yn(e,t={}){let{execFileSync:n=hn}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}r(yn,"isInsideGitRepo");function ya(e,t={}){let{execFileSync:n=hn}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}r(ya,"gitInitAndCommit");function Sa(e={}){let{execFileSync:t=hn}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}r(Sa,"gitUserName");function wa(e={}){let{execFileSync:t=hn}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}r(wa,"gitUserEmail");var Sn=3,va="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Ca="Email address for the registry entry",Aa=`Passphrase for the encrypted private key (min ${15} chars)`,Ea="Confirm passphrase",ba=r(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),xa=r(e=>`Passphrases do not match (attempt ${e}/${Sn}).
151
+ `,"passphraseMismatchMsg"),ka=`Passphrase confirmation failed after ${Sn} attempts`,Pa=r(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Ta="How would you like to submit your key registration?",Ra="Open in browser",Ia="Copy link to clipboard";async function tr(e){return er.prompt(e)}r(tr,"defaultPrompt");function Da(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}r(Da,"parserAsValidator");var eg=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function Ge(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!eg.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}r(Ge,"parseKid");async function $a(e={}){let{prompt:t=tr}=e,{kid:n}=await t({type:"input",name:"kid",message:va,validate:Da(Ge)});return Ge(n)}r($a,"promptKid");async function Oa(e={}){let{prompt:t=r(o=>er.prompt(o),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Ta,choices:[{name:"browser",message:Ra},{name:"clipboard",message:Ia}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}r(Oa,"promptZendeskAction");async function Fa(e={}){let{prompt:t=tr,gitUserEmail:n=wa}=e,{email:o}=await t({type:"input",name:"email",message:Ca,initial:n(),validate:Da(i=>tt(i,"email"))});return tt(o,"email")}r(Fa,"promptEmail");async function La(e={}){let{prompt:t=tr,stderr:n=process.stderr}=e;for(let o=1;o<=Sn;o+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Aa,validate:r(a=>a.length>=15?!0:ba(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Ea});if(i===s)return b.from(i);n.write(xa(o))}throw new Error(ka)}r(La,"promptPassphrase");async function Ma(e,t={}){let{prompt:n=r(i=>er.prompt(i),"prompt")}=t,{confirmed:o}=await n({type:"confirm",name:"confirmed",message:Pa(e),initial:!1});return o}r(Ma,"promptConfirmOverwrite");import{existsSync as pg,readdirSync as dg,readFileSync as ug}from"fs";import{join as or}from"path";import{execFile as tg}from"child_process";import{promisify as ng}from"util";var Ua="cognite-flows",og=ng(tg),Na=r((e,t)=>og(e,t),"defaultExecFile"),rg=-25300,ig=rg&255;function sg(e){if(!(e instanceof Error)||!("code"in e)||e.code!==ig)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}r(sg,"isKeychainNotFoundError");async function _a(e,t,n={}){let o=t.expose();if(!X("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=Na}=n;await i("security",["add-generic-password","-a",e,"-s",Ua,"-w",Buffer.from(o,"utf-8").toString("base64"),"-U"])}r(_a,"storeKeyInKeychain");async function wn(e,t={}){if(!X("macos",t))return null;let{execFile:n=Na}=t;try{let{stdout:o}=await n("security",["find-generic-password","-a",e,"-s",Ua,"-w"]);return b.from(Buffer.from(o.trim(),"base64").toString("utf-8"))}catch(o){if(sg(o))return null;throw o}}r(wn,"readKeyFromKeychain");var Ha="cognite-cli-signing",ag="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",cg="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",ja="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function lg(e){if(!(e instanceof Error))return ja;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?ag:t.includes("ambiguous")?cg:ja}r(lg,"hintFor");function Ba(e,t,n){return new m(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:lg(n),shouldReport:!1})}r(Ba,"wrapKeyringError");async function Ka(e,t){let{Entry:n}=await import("@napi-rs/keyring"),o=new n(e,t);return{setPassword:r(i=>o.setPassword(i),"setPassword"),getPassword:r(()=>o.getPassword(),"getPassword"),deleteCredential:r(()=>o.deleteCredential(),"deleteCredential")}}r(Ka,"defaultCreateEntry");async function Va(e,t,n={}){let{createEntry:o=Ka}=n,i=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await o(Ha,e)).setPassword(i)}catch(s){throw Ba("store",e,s)}}r(Va,"storeSigningKey");async function vn(e,t={}){let{createEntry:n=Ka}=t;try{let i=(await n(Ha,e)).getPassword();return i===null?null:b.from(Buffer.from(i,"base64").toString("utf-8"))}catch(o){throw Ba("read",e,o)}}r(vn,"readSigningKey");var Oe=".pub.pem",rr=".key.jwe",ir=".meta.json";function Cn(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}r(Cn,"formatLocalKeySource");function mg(e){return{existsSync:e.existsSync??pg,readdirSync:e.readdirSync??dg,readFileSync:e.readFileSync??((t,n)=>ug(t,n)),isOS:e.isOS??(t=>X(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>wn(t)),readSigningKey:e.readSigningKey??(t=>vn(t))}}r(mg,"resolveDeps");function gg(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}r(gg,"readEmailFromMeta");function fg(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Oe)):[]}r(fg,"publicKeyEntries");function hg(e){return e.slice(0,-Oe.length)}r(hg,"kidFromPublicKeyFilename");async function yg(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let o=or(t,`${e}${rr}`);return n.existsSync(o)?{kind:"encrypted-file",path:o}:{kind:"public-only"}}r(yg,"resolveSource");async function An(e=D().keysDir,t={}){let n=mg(t),o=new Set,i=fg(e,n).flatMap(s=>{let a=hg(s);return!a||o.has(a)?[]:(o.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let c=await yg(s,e,n),l=or(e,`${s}${ir}`),p;try{p=gg(n.readFileSync(l,"utf8"))}catch{}return{kid:s,source:c,publicKeyPath:or(e,a),email:p}}))}r(An,"discoverLocalKeys");import{createReadStream as Sg}from"fs";function En(e){let t=Sg(e);return new ReadableStream({start(n){t.on("data",o=>{let i=typeof o=="string"?Buffer.from(o):o;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",o=>n.error(o))},cancel(){t.destroy()}})}r(En,"createWebStreamFromFile");import wg from"path";var Ga=".cognite-bundles";function Ya(e,t){return`${e}-${t}.zip`}r(Ya,"bundleFileName");function re(e,t,n){return wg.join(e,Ga,Ya(t,n))}r(re,"bundlePath");var za=[".dev.sig",".cert.sig",".sig"];function xg(e){return{existsSync:e.existsSync??vg,readFileSync:e.readFileSync??((t,n)=>Cg(t,n)),createBundleStream:e.createBundleStream??En,verifyBundle:e.verifyBundle??Eg,loadAppConfig:e.loadAppConfig??k,defaultKeyDir:e.defaultKeyDir??(()=>D().keysDir)}}r(xg,"resolveDeps");function kg(e,t){return za.map(n=>`${e}${n}`).find(n=>t(n))}r(kg,"findSiblingSignature");function Pg(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}r(Pg,"isCompactJws");function Tg(e){try{let t=bg(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}r(Tg,"readKidFromToken");function Rg(e,t,n){let{existsSync:o,readFileSync:i}=n;try{Ge(e)}catch(a){throw new m(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!o(t))throw new m(`Key directory not found: ${t}`,{shouldReport:!1});let s=Ag(t,`${e}${Oe}`);if(!o(s))throw new m(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return i(s,"utf-8")}catch(a){throw new m(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}r(Rg,"resolvePublicKeyForKid");function Ig(e,t){let{payload:n,kid:o}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${o}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let i=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${i}`)}t&&console.log(JSON.stringify(n,null,2))}r(Ig,"printResult");async function qa(e,t,n={},o=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:c,verifyBundle:l,defaultKeyDir:p}=xg(n),d;if(e)d=bn(o,e);else{let f;try{f=a(o)}catch(y){let S=y instanceof Error?y.message:String(y);throw new m(S,{cause:y,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=re(o,f.externalId,f.versionTag)}if(!i(d)){let f=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new m(`Bundle not found: ${d}`,{hint:f,shouldReport:!1})}let u=t.sig?bn(o,t.sig):kg(d,i);if(!u)throw new m("No signature file found.",{hint:`Pass --sig <path> or place one of ${za.map(f=>`${d}${f}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!i(u))throw new m(`Signature file not found: ${u}`,{shouldReport:!1});let g;try{g=s(u,"utf-8").trim()}catch(f){throw new m(`Failed to read signature file: ${u}`,{cause:f,shouldReport:!1})}if(!Pg(g))throw new m(`Malformed JWS in ${u}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let h;if(t.key){let f=bn(o,t.key);if(!i(f))throw new m(`Public key not found: ${f}`,{shouldReport:!1});try{h=s(f,"utf-8")}catch(y){throw new m(`Failed to read public key file: ${f}`,{cause:y,shouldReport:!1})}}else{let f=t.keyDir?bn(o,t.keyDir):p(),y=Tg(g);if(!y)throw new m("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});h=Rg(y,f,{existsSync:i,readFileSync:s})}try{let f=await l({token:g,publicKeyPem:h,bundleStream:c(d)});Ig(f,t.verbose??!1)}catch(f){let y=f instanceof Error?f.message:String(f);throw new m(`Bundle rejected: ${y}`,{shouldReport:!1})}}r(qa,"handleVerify");function Ja(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
152
+ Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
153
+
154
+ Examples:
155
+ cognite apps verify Verify default bundle (path from app.json)
156
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
157
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
158
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,o)=>qa(n,o,t))}r(Ja,"registerVerifyCommand");import{existsSync as Dg}from"fs";import{resolve as $g}from"path";import{config as Og}from"dotenv";function j(e,t={existsSync:Dg,config:Og}){let n=$g(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}r(j,"loadEnvFile");function H(e){e.infra!=="appsApi"&&(console.error(`
39
159
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
40
160
 
41
161
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
42
162
  the old CDF Application Registry. This deploy path has been removed.
43
163
 
44
164
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
45
- `),process.exit(1))}o(M,"assertAppHostingInfra");import{Option as Lo}from"commander";var dc={"client-credentials":!0,session:!0,browser:!0};function vn(){return new Lo("--auth-method <method>","Authentication method to use when several are valid, skipping the selection prompt").choices(Object.keys(dc))}o(vn,"authMethodOption");function uc(){return new Lo("--confirm-action-target <target>","Acknowledge the org/project this command will act on, skipping the interactive prompt (value must match the resolved target)")}o(uc,"confirmActionTargetOption");function U(){return[uc(),vn()]}o(U,"sessionAuthOptions");async function mc(e,t,n){let r=await K(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"activate"});return new I(r)}o(mc,"defaultBuildApiClient");async function fc(e,t={}){let{loadEnvFile:n=O,loadAppConfig:r=b,getApiClient:i=mc,isSessionAuthEnabled:s=E}=t,a=process.cwd();n(a);let p=r(a);M(p);let c=e.interactive?await $(p,e):T(p.deployments,e.deployment);if(!e.interactive&&!s()){let m=F(c);if(m.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${m.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p.externalId),{externalId:d,versionTag:u}=p,g;try{g=await l.getVersion(d,u)}catch(m){throw m instanceof V?new Error(`Version ${u} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):m}if(g.alias==="ACTIVE"){console.log(` ${d} @ ${u} is already ACTIVE \u2014 nothing to do.`);return}if(g.lifecycleState==="DEPRECATED"||g.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${d} @ ${u}: version is ${g.lifecycleState} (terminal).`);g.lifecycleState==="DRAFT"&&(await l.publishVersion(d,u),console.log(`\u2713 Published ${d} @ ${u} is now PUBLISHED`));let{supersededVersion:y}=await l.activateVersion(d,u);console.log(`\u2713 Activated ${d} @ ${u} is now ACTIVE`),y&&console.log(` Superseded ${y} \u2192 PUBLISHED`)}o(fc,"handleActivate");function No(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return n()&&U().forEach(i=>r.addOption(i)),r.addHelpText("after",`
165
+ `),process.exit(1))}r(H,"assertAppHostingInfra");import{Option as Wa}from"commander";var Fg={"client-credentials":!0,session:!0,browser:!0};function sr(){return new Wa("--auth-method <method>","Authentication method to use when several are valid, skipping the selection prompt").choices(Object.keys(Fg))}r(sr,"authMethodOption");function Lg(){return new Wa("--confirm-action-target <target>","Acknowledge the org/project this command will act on, skipping the interactive prompt (value must match the resolved target)")}r(Lg,"confirmActionTargetOption");function J(){return[Lg(),sr()]}r(J,"sessionAuthOptions");async function Mg(e,t,n){let o=await _(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"activate"});return new M(o)}r(Mg,"defaultBuildApiClient");async function Ug(e,t={}){let{loadEnvFile:n=j,loadAppConfig:o=k,getApiClient:i=Mg}=t,s=process.cwd();n(s);let a=o(s);H(a);let c=e.interactive?await F(a,e):$(a.deployments,e.deployment),l=await i(c,e,a.externalId),{externalId:p,versionTag:d}=a,u;try{u=await l.getVersion(p,d)}catch(h){throw h instanceof oe?new Error(`Version ${d} of ${p} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):h}if(u.alias==="ACTIVE"){console.log(` ${p} @ ${d} is already ACTIVE \u2014 nothing to do.`);return}if(u.lifecycleState==="DEPRECATED"||u.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${p} @ ${d}: version is ${u.lifecycleState} (terminal).`);u.lifecycleState==="DRAFT"&&(await l.publishVersion(p,d),console.log(`\u2713 Published ${p} @ ${d} is now PUBLISHED`));let{supersededVersion:g}=await l.activateVersion(p,d);console.log(`\u2713 Activated ${p} @ ${d} is now ACTIVE`),g&&console.log(` Superseded ${g} \u2192 PUBLISHED`)}r(Ug,"handleActivate");function Za(e){let t=e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return J().forEach(n=>t.addOption(n)),t.addHelpText("after",`
46
166
  Examples:
47
167
  npx @cognite/cli apps activate . Activate using env-var auth
48
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((i,s)=>fc(s))}o(No,"registerActivateCommand");import{basename as ti,dirname as Wc,normalize as Jc,resolve as Et}from"path";import{fileURLToPath as Xc,pathToFileURL as Zc}from"url";import{Logger as Qc,runner as el}from"hygen";import{safeParse as gc}from"valibot";function Fe(e,t){return n=>{let r=gc(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(Fe,"toPromptValidator");var Ho={name:Fe("App name",Wt),displayName:Fe("Display name",zt),baseUrl:Fe("Base URL",Jt),org:Fe("Org",Xt),project:Fe("Project",Zt)};function yc(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(yc,"composeValidators");function wt(e){return e.map(t=>{if(!(t.name in Ho))return t;let n=Ho[t.name];return{...t,validate:yc(t.validate,n)}})}o(wt,"applySchemaValidators");import{basename as Ko}from"path";import jo from"enquirer";function An(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(An,"kebabCase");var hc={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code, Cursor, or GitHub Copilot. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
49
- `),initial:!1};async function Sc(e,t,n){return e!==void 0?e:t?!!(await n([hc])).useSpecKit:!1}o(Sc,"resolveSpecKit");function wc(e){return typeof e=="function"}o(wc,"isFunctionInitial");function Bo(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(Bo,"normalizeCluster");function Vo({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=jo.prompt.bind(jo)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(k=>k[1]!==void 0)),l=Object.keys(c).length>0,d=e?Ko(process.cwd()):t?Ko(t):null,u=l&&d!==null,g=!u&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,y=wt(g),m=u&&d?{...c,name:d}:c,h=new Set(Object.keys(m)),S=y.filter(k=>!h.has(k.name)),A=S.findIndex(k=>k.name==="baseUrl"),v;if(u){let k=Bo(m.cluster),J=o(_=>wc(_.initial)?_.initial():_.initial,"resolveInitial"),ie=o(_=>{if(_.name==="baseUrl")return`https://${k}.cognitedata.com`;let se=J(_);if(se===void 0)throw new Error(`Non-interactive mode: --${An(_.name)} has no default. Pass it as a flag.`);return se},"deriveValue");v=Object.fromEntries(S.map(_=>[_.name,ie(_)]))}else if(A!==-1){let k=S.filter(ae=>ae.name!=="baseUrl"),J=k.length>0?await a(k):{},ie=typeof J.cluster=="string"?J.cluster:"",se=`https://${Bo(ie||m.cluster)}.cognitedata.com`,he=S[A],He=await a([{...he,initial:se}]);v={...J,...He}}else v=S.length>0?await a(S):{};let w={...m,...v},D=typeof w.name=="string"?w.name:"";D&&n(D);let x=await Sc(s,!u&&S.length>0,a);return r?.(x),{...w,name:D,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:x}},"prompt")})}o(Vo,"createAppPrompter");async function Go(e,t,n){let r=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&r.push({key:s,value:a,label:`--${An(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(Go,"validatePresets");import{cpSync as qo,existsSync as zo,mkdirSync as At,readdirSync as kc,readFileSync as Pc,writeFileSync as Cn}from"fs";import{basename as xc,dirname as En,posix as Dc,resolve as R}from"path";import{fileURLToPath as Wo}from"url";import{copyFileSync as vc,symlinkSync as Ac}from"fs";import{dirname as Cc,join as Ec}from"path";function bc(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(bc,"errno");function Yo(e){return e instanceof Error?e.message:String(e)}o(Yo,"messageOf");function vt({target:e,linkPath:t,label:n,symlink:r=Ac,copyFile:i=vc}){try{return r(e,t),!0}catch(s){let a=bc(s);if(a==="EEXIST")return!0;let p=Yo(s);if(a==="EPERM"||a==="EACCES")try{let c=Ec(Cc(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${p} (copy fallback also failed: ${Yo(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o(vt,"linkOrCopyOrWarn");var Ic=R(En(Wo(import.meta.url)),"..","..","_vendor","spec-kit"),Tc=R(En(Wo(import.meta.url)),"..","..","_cognite-spec-extensions"),Rc=["claude-code","cursor","github-copilot"],Fc={branch_numbering:"sequential"};function Jo({appDir:e,vendorDir:t=Ic,cogniteExtensionsDir:n=Tc,agents:r=Rc}){let i=R(e,".specify"),s=R(i,"memory"),a=new Set(r),p=`prepare spec-kit install for appDir=${e}`,l=[{srcRoot:t,from:"templates",to:".specify/templates"},{srcRoot:t,from:"scripts/bash",to:".specify/scripts/bash"},{srcRoot:t,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:t,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:n,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"templates",to:".specify/templates"}].filter(({agent:d})=>!d||a.has(d));try{for(let{srcRoot:u,from:g,to:y}of l){let m=R(e,y);p=`copy ${xc(u)}/${g} to ${y}`,At(En(m),{recursive:!0}),qo(R(u,g),m,{recursive:!0})}if(a.has("github-copilot")){let u=R(e,".github","agents"),g=R(e,".github","prompts");p="create .github/agents and .github/prompts dirs",At(u,{recursive:!0}),At(g,{recursive:!0});for(let y of[R(t,"commands"),R(n,"commands")])if(zo(y))for(let m of kc(y)){if(!m.endsWith(".md"))continue;let h=m.slice(0,-3);p=`copy ${m} to .github/agents/${h}.agent.md`,Cn(R(u,`${h}.agent.md`),Pc(R(y,m))),p=`write .github/prompts/${h}.prompt.md`,Cn(R(g,`${h}.prompt.md`),`---
50
- agent: ${h}
168
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((n,o)=>Ug(o))}r(Za,"registerActivateCommand");import{basename as mc,dirname as wf,normalize as vf,resolve as Rn}from"path";import{fileURLToPath as Cf,pathToFileURL as Af}from"url";import{Logger as Ef,runner as bf}from"hygen";import{safeParse as Ng}from"valibot";function wt(e,t){return n=>{let o=Ng(t,n);return o.success?!0:`${e} ${o.issues[0].message}`}}r(wt,"toPromptValidator");var Xa={name:wt("App name",Yn),displayName:wt("Display name",Gn),baseUrl:wt("Base URL",zn),org:wt("Org",qn),project:wt("Project",Jn)};function _g(e,t){return e?async n=>{let o=t(n);return o===!0?e(n):o}:t}r(_g,"composeValidators");function xn(e){return e.map(t=>{if(!(t.name in Xa))return t;let n=Xa[t.name];return{...t,validate:_g(t.validate,n)}})}r(xn,"applySchemaValidators");import{basename as Qa}from"path";import ec from"enquirer";function ar(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}r(ar,"kebabCase");var jg={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code, Cursor, or GitHub Copilot. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
169
+ `),initial:!1};async function Hg(e,t,n){return e!==void 0?e:t?!!(await n([jg])).useSpecKit:!1}r(Hg,"resolveSpecKit");function Bg(e){return typeof e=="function"}r(Bg,"isFunctionInitial");function tc(e){return(e??"").trim().replace(/\/+$/,"")||"api"}r(tc,"normalizeCluster");function nc({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:o,presets:i={},specKit:s,prompt:a=ec.prompt.bind(ec)}){return()=>({prompt:r(async c=>{if(!Array.isArray(c))return a([c]);let l=Object.fromEntries(Object.entries(i).filter(R=>R[1]!==void 0)),p=Object.keys(l).length>0,d=e?Qa(process.cwd()):t?Qa(t):null,u=p&&d!==null,g=!u&&d?c.map(R=>R.name==="name"?{...R,initial:d}:R):c,h=xn(g),f=u&&d?{...l,name:d}:l,y=new Set(Object.keys(f)),S=h.filter(R=>!y.has(R.name)),w=S.findIndex(R=>R.name==="baseUrl"),v;if(u){let R=tc(f.cluster),Z=r(I=>Bg(I.initial)?I.initial():I.initial,"resolveInitial"),Q=r(I=>{if(I.name==="baseUrl")return`https://${R}.cognitedata.com`;let N=Z(I);if(N===void 0)throw new Error(`Non-interactive mode: --${ar(I.name)} has no default. Pass it as a flag.`);return N},"deriveValue");v=Object.fromEntries(S.map(I=>[I.name,Q(I)]))}else if(w!==-1){let R=S.filter(G=>G.name!=="baseUrl"),Z=R.length>0?await a(R):{},Q=typeof Z.cluster=="string"?Z.cluster:"",N=`https://${tc(Q||f.cluster)}.cognitedata.com`,ie=S[w],le=await a([{...ie,initial:N}]);v={...Z,...le}}else v=S.length>0?await a(S):{};let C={...f,...v},x=typeof C.name=="string"?C.name:"";x&&n(x);let B=await Hg(s,!u&&S.length>0,a);return o?.(B),{...C,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:B}},"prompt")})}r(nc,"createAppPrompter");async function oc(e,t,n){let o=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&o.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&o.push({key:s,value:a,label:`--${ar(s)}`});for(let{key:s,value:a,label:c}of o){let l=e.find(d=>d.name===s)?.validate;if(!l)continue;let p=await l(a);if(p!==!0)throw new Error(`Invalid ${c}: ${p}`)}}r(oc,"validatePresets");import{cpSync as ic,existsSync as sc,mkdirSync as Pn,readdirSync as qg,readFileSync as Jg,writeFileSync as cr}from"fs";import{basename as Wg,dirname as lr,posix as Zg,resolve as U}from"path";import{fileURLToPath as ac}from"url";import{copyFileSync as Kg,symlinkSync as Vg}from"fs";import{dirname as Gg,join as Yg}from"path";function zg(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}r(zg,"errno");function rc(e){return e instanceof Error?e.message:String(e)}r(rc,"messageOf");function kn({target:e,linkPath:t,label:n,symlink:o=Vg,copyFile:i=Kg}){try{return o(e,t),!0}catch(s){let a=zg(s);if(a==="EEXIST")return!0;let c=rc(s);if(a==="EPERM"||a==="EACCES")try{let l=Yg(Gg(t),e);return i(l,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(l){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${c} (copy fallback also failed: ${rc(l)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,c),!1}}r(kn,"linkOrCopyOrWarn");var Xg=U(lr(ac(import.meta.url)),"..","..","_vendor","spec-kit"),Qg=U(lr(ac(import.meta.url)),"..","..","_cognite-spec-extensions"),ef=["claude-code","cursor","github-copilot"],tf={branch_numbering:"sequential"};function cc({appDir:e,vendorDir:t=Xg,cogniteExtensionsDir:n=Qg,agents:o=ef}){let i=U(e,".specify"),s=U(i,"memory"),a=new Set(o),c=`prepare spec-kit install for appDir=${e}`,p=[{srcRoot:t,from:"templates",to:".specify/templates"},{srcRoot:t,from:"scripts/bash",to:".specify/scripts/bash"},{srcRoot:t,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:t,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:n,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"templates",to:".specify/templates"}].filter(({agent:d})=>!d||a.has(d));try{for(let{srcRoot:u,from:g,to:h}of p){let f=U(e,h);c=`copy ${Wg(u)}/${g} to ${h}`,Pn(lr(f),{recursive:!0}),ic(U(u,g),f,{recursive:!0})}if(a.has("github-copilot")){let u=U(e,".github","agents"),g=U(e,".github","prompts");c="create .github/agents and .github/prompts dirs",Pn(u,{recursive:!0}),Pn(g,{recursive:!0});for(let h of[U(t,"commands"),U(n,"commands")])if(sc(h))for(let f of qg(h)){if(!f.endsWith(".md"))continue;let y=f.slice(0,-3);c=`copy ${f} to .github/agents/${y}.agent.md`,cr(U(u,`${y}.agent.md`),Jg(U(h,f))),c=`write .github/prompts/${y}.prompt.md`,cr(U(g,`${y}.prompt.md`),`---
170
+ agent: ${y}
51
171
  ---
52
- `)}}let d=R(i,"extensions.yml");zo(d)||(p="write .specify/extensions.yml",qo(R(n,"extensions.yml"),d)),p=`write init-options.json under specifyDir=${i}`,Cn(R(i,"init-options.json"),`${JSON.stringify(Fc,null,2)}
53
- `),p=`link .specify/memory/constitution.md in specifyDir=${i}`,At(s,{recursive:!0}),vt({target:Dc.join("..","..","AGENTS.md"),linkPath:R(s,"constitution.md"),label:".specify/memory/constitution.md"})}catch(d){let u=d instanceof Error?d.message:String(d);throw new Error(`installSpecKit failed while ${p} (appDir=${e}, vendorDir=${t}): ${u}`,{cause:d})}}o(Jo,"installSpecKit");import{execFileSync as Ct}from"child_process";import{mkdtempSync as $c,readdirSync as Oc,rmSync as Mc}from"fs";import{createRequire as _c}from"module";import{tmpdir as Uc}from"os";import{join as Lc,resolve as Xo}from"path";import{InvalidArgumentError as Nc}from"commander";import Hc from"enquirer";var Zo="cognitedata/builder-skills",bn=["claude-code","cursor","github-copilot","opencode","codex"],Kc=_c(import.meta.url).resolve("skills/bin/cli.mjs");function kn(e,t={}){try{Ct(process.execPath,[Kc,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw q(),new f(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and try again."})}}o(kn,"execSkillsCli");function jc(){return bn.map(e=>["add",Zo,"-a",e,"--skill","*","-y"])}o(jc,"pullAllArgsPerAgent");var Bc=1e4;async function Qo(e,t={}){let n=t.exec??kn;q();let r=t.timeout??Bc,i=t.readdir??(p=>Oc(p));for(let p of jc())try{n(p,{cwd:e,timeout:r,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[Xo(e,".claude","skills"),Xo(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(Qo,"pullAllSkillsInto");function Vc(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Nc("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Vc,"validateSource");function Gc(e){let t=$c(Lc(Uc(),"skills-"));try{try{Ct("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(r){throw q(),new f(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:r})}let n;try{n=Ct("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Ct("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{Mc(t,{recursive:!0,force:!0})}}o(Gc,"listRemoteSkills");async function Yc(e,t={}){let n=o(p=>Hc.prompt(p),"defaultPrompt"),{listSkills:r=Gc,prompt:i=n}=t,s=r(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(Yc,"pickSkillsInteractive");function qc(e,t,n){let r=["add",e.source,"-a",t];return e.skill?r.push("--skill",e.skill):n&&n.length>0?r.push("--skill",...n,"-y"):r.push("--skill","*","-y"),e.global&&r.push("--global"),r}o(qc,"buildPullArgs");async function zc(e){q(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Yc(e.source)}catch(r){if(r instanceof f)throw r;let i=r instanceof Error?r.message:String(r);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let r of bn)try{kn(qc(e,r,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${r}: ${s}`),n=!0}n?(console.log(`
172
+ `)}}let d=U(i,"extensions.yml");sc(d)||(c="write .specify/extensions.yml",ic(U(n,"extensions.yml"),d)),c=`write init-options.json under specifyDir=${i}`,cr(U(i,"init-options.json"),`${JSON.stringify(tf,null,2)}
173
+ `),c=`link .specify/memory/constitution.md in specifyDir=${i}`,Pn(s,{recursive:!0}),kn({target:Zg.join("..","..","AGENTS.md"),linkPath:U(s,"constitution.md"),label:".specify/memory/constitution.md"})}catch(d){let u=d instanceof Error?d.message:String(d);throw new Error(`installSpecKit failed while ${c} (appDir=${e}, vendorDir=${t}): ${u}`,{cause:d})}}r(cc,"installSpecKit");import{execFileSync as Tn}from"child_process";import{mkdtempSync as nf,readdirSync as of,rmSync as rf}from"fs";import{createRequire as sf}from"module";import{tmpdir as af}from"os";import{join as cf,resolve as lc}from"path";import{InvalidArgumentError as lf}from"commander";import pf from"enquirer";var pc="cognitedata/builder-skills",pr=["claude-code","cursor","github-copilot","opencode","codex"],df=sf(import.meta.url).resolve("skills/bin/cli.mjs");function dr(e,t={}){try{Tn(process.execPath,[df,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw Ae(),new m(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and try again."})}}r(dr,"execSkillsCli");function uf(){return pr.map(e=>["add",pc,"-a",e,"--skill","*","-y"])}r(uf,"pullAllArgsPerAgent");var mf=1e4;async function dc(e,t={}){let n=t.exec??dr;Ae();let o=t.timeout??mf,i=t.readdir??(c=>of(c));for(let c of uf())try{n(c,{cwd:e,timeout:o,stdio:["pipe","pipe","inherit"]})}catch(l){let p=l instanceof Error?l.message:String(l);console.warn("\u26A0\uFE0F Could not pull skills for args ["+c.join(" ")+"]:",p)}let s=new Set;for(let c of[lc(e,".claude","skills"),lc(e,".agents","skills")])try{i(c).forEach(l=>s.add(l))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}r(dc,"pullAllSkillsInto");function gf(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new lf("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}r(gf,"validateSource");function ff(e){let t=nf(cf(af(),"skills-"));try{try{Tn("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(o){throw Ae(),new m(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:o})}let n;try{n=Tn("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Tn("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(o=>!!o&&!o.startsWith("."))}finally{rf(t,{recursive:!0,force:!0})}}r(ff,"listRemoteSkills");async function hf(e,t={}){let n=r(c=>pf.prompt(c),"defaultPrompt"),{listSkills:o=ff,prompt:i=n}=t,s=o(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}r(hf,"pickSkillsInteractive");function yf(e,t,n){let o=["add",e.source,"-a",t];return e.skill?o.push("--skill",e.skill):n&&n.length>0?o.push("--skill",...n,"-y"):o.push("--skill","*","-y"),e.global&&o.push("--global"),o}r(yf,"buildPullArgs");async function Sf(e){Ae(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await hf(e.source)}catch(o){if(o instanceof m)throw o;let i=o instanceof Error?o.message:String(o);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let o of pr)try{dr(yf(e,o,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${o}: ${s}`),n=!0}n?(console.log(`
54
174
  Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
55
- Skills pulled successfully`)}o(zc,"handlePull");function ei(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
56
- Supports: ${bn.join(", ")}`).addHelpText("after",`
175
+ Skills pulled successfully`)}r(Sf,"handlePull");function uc(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
176
+ Supports: ${pr.join(", ")}`).addHelpText("after",`
57
177
  Examples:
58
178
  npx @cognite/cli apps skills pull Pull all skills
59
179
  npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
60
- npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",Vc,Zo).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(zc),t.command("list").description("List installed skills").action(()=>{kn(["list"])}),t}o(ei,"registerSkillsCommand");var ni=Et(Wc(Xc(import.meta.url)),"..","..","_templates");async function tl(){let e=Et(ni,"app","new","prompt.js");return(await import(Zc(e).href)).default}o(tl,"loadPromptDefs");function nl(e,t){return!e||t?null:Jc(e)}o(nl,"resolveDirName");function rl(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let r=t??n;if(!r)throw new Error("App creation completed without a target directory or name.");return{cwd:Et(process.cwd(),r),display:r}}o(rl,"resolveAppLocation");function ol(e,t,n){let r=` npm install
180
+ npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",gf,pc).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(Sf),t.command("list").description("List installed skills").action(()=>{dr(["list"])}),t}r(uc,"registerSkillsCommand");var gc=Rn(wf(Cf(import.meta.url)),"..","..","_templates");async function xf(){let e=Rn(gc,"app","new","prompt.js");return(await import(Af(e).href)).default}r(xf,"loadPromptDefs");function kf(e,t){return!e||t?null:vf(e)}r(kf,"resolveDirName");function Pf(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let o=t??n;if(!o)throw new Error("App creation completed without a target directory or name.");return{cwd:Rn(process.cwd(),o),display:o}}r(Pf,"resolveAppLocation");function Tf(e,t,n){let o=` npm install
61
181
  npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
62
182
  To start spec-driven development:
63
183
  Run /speckit.specify in Claude Code, Cursor, or GitHub Copilot and describe your app.
64
- `:"",p=` # Or fully non-interactive (deploys first target from app.json):
184
+ `:"",c=` # Or fully non-interactive (deploys first target from app.json):
65
185
  npx @cognite/cli apps deploy`;if(e){console.log(`
66
186
  \u2705 App created successfully in current directory!
67
187
 
68
188
  Next steps:
69
- ${r}
189
+ ${o}
70
190
  ${a}
71
191
  ${i}
72
192
  ${s}
73
- ${p}
193
+ ${c}
74
194
  `);return}console.log(`
75
195
  \u2705 App created successfully!
76
196
 
@@ -78,13 +198,13 @@ To open in Cursor:
78
198
  cursor "${t}"
79
199
  Or:
80
200
  cd "${t}"
81
- ${r}
201
+ ${o}
82
202
  ${a}
83
203
  ${i}
84
204
  cd "${t}"
85
205
  ${s}
86
- ${p}
87
- `)}o(ol,"printSuccessMessage");async function il(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await Qo(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(il,"pullSkillsInto");function sl(e,t={}){let{isGitInstalled:n=je,isInsideGitRepo:r=Ve,gitInitAndCommit:i=ar}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(sl,"maybeInitGit");async function al(e,t){let n=e==="."||e==="./",r=nl(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await tl(),c=wt(p),l=n?ti(process.cwd()):r?ti(r):null;await Go(c,a,l);let d=Vo({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await el(["app","new"],{templates:ni,cwd:process.cwd(),logger:new Qc(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let u=rl(n,r,i);vt({target:"AGENTS.md",linkPath:Et(u.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&Jo({appDir:u.cwd}),await il(u.cwd),sl(u.cwd),ol(n,u.display,s)}o(al,"handleCreate");function ri(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
206
+ ${c}
207
+ `)}r(Tf,"printSuccessMessage");async function Rf(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await dc(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}r(Rf,"pullSkillsInto");function If(e,t={}){let{isGitInstalled:n=fn,isInsideGitRepo:o=yn,gitInitAndCommit:i=ya}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!o(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let c=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",c)}}}r(If,"maybeInitGit");async function Df(e,t){let n=e==="."||e==="./",o=kf(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},c=await xf(),l=xn(c),p=n?mc(process.cwd()):o?mc(o):null;await oc(l,a,p);let d=nc({isCurrentDir:n,dirName:o,onAppName:r(g=>{i=g},"onAppName"),onUseSpecKit:r(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await bf(["app","new"],{templates:gc,cwd:process.cwd(),logger:new Ef(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let u=Pf(n,o,i);kn({target:"AGENTS.md",linkPath:Rn(u.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&cc({appDir:u.cwd}),await Rf(u.cwd),If(u.cwd),Tf(n,u.display,s)}r(Df,"handleCreate");function fc(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
88
208
  Non-interactive use (CI, scripts, AI agents):
89
209
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
90
210
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -97,31 +217,30 @@ Examples:
97
217
  --display-name "My App" --description "My app" \\
98
218
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
99
219
  --base-url https://greenfield.cognitedata.com
100
- Fully non-interactive`).action(al)}o(ri,"registerCreateCommand");import pl from"path";async function cl(e,t,n){return St(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"deactivate"})}o(cl,"defaultBuildApiClient");async function ll(e,t,n={}){let{loadEnvFile:r=O,loadAppConfig:i=b,getApiClient:s=cl,isSessionAuthEnabled:a=E}=n,p=pl.resolve(process.cwd(),e);r(p);let c=i(p);M(c);let l=t.interactive?await $(c,t):T(c.deployments,t.deployment);if(!t.interactive&&!a()){let y=F(l);if(y.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${y.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:d}=c,u=await s(l,t,d),g=await u.getActiveVersion(d);if(!g){console.log(` ${d} has no active version \u2014 nothing to deactivate.`);return}await u.deactivateVersion(d,g.version),console.log(`\u2713 Deactivated ${d} @ ${g.version} \u2014 active alias removed`)}o(ll,"handleDeactivate");function oi(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return n()&&U().forEach(i=>r.addOption(i)),r.addHelpText("after",`
220
+ Fully non-interactive`).action(Df)}r(fc,"registerCreateCommand");import $f from"path";async function Of(e,t,n){return tn(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"deactivate"})}r(Of,"defaultBuildApiClient");async function Ff(e,t,n={}){let{loadEnvFile:o=j,loadAppConfig:i=k,getApiClient:s=Of}=n,a=$f.resolve(process.cwd(),e);o(a);let c=i(a);H(c);let l=t.interactive?await F(c,t):$(c.deployments,t.deployment),{externalId:p}=c,d=await s(l,t,p),u=await d.getActiveVersion(p);if(!u){console.log(` ${p} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(p,u.version),console.log(`\u2713 Deactivated ${p} @ ${u.version} \u2014 active alias removed`)}r(Ff,"handleDeactivate");function hc(e){let t=e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return J().forEach(n=>t.addOption(n)),t.addHelpText("after",`
101
221
  Examples:
102
222
  npx @cognite/cli apps deactivate . Deactivate using env-var auth
103
- npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((i,s)=>ll(i,s))}o(oi,"registerDeactivateCommand");import dl from"path";import ul from"enquirer";async function ml(e,t,n){return St(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"delete"})}o(ml,"defaultBuildApiClient");async function fl(e){let{confirmed:t}=await ul.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}o(fl,"defaultConfirm");async function gl(e,t,n={}){let{loadEnvFile:r=O,loadAppConfig:i=b,getApiClient:s=ml,confirm:a=fl,isSessionAuthEnabled:p=E}=n,c=dl.resolve(process.cwd(),e);r(c);let l=i(c);M(l);let d=t.interactive?await $(l,t):T(l.deployments,t.deployment);if(!t.interactive&&!p()){let h=F(d);if(h.length>0)throw new f(`Deployment ${d.org}/${d.project} is missing ${h.join(" and ")} in app.json.`,{hint:"Use `npx @cognite/cli@latest apps delete --interactive` for browser-based authentication instead."})}let u=await s(d,t,l.externalId),{externalId:g,versionTag:y}=l,m;try{m=await u.getVersion(g,y)}catch(h){throw h instanceof V?new f(`Version ${y} of ${g} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):h}if(m.alias==="ACTIVE")throw new f(`Cannot archive ${g} @ ${y}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(m.lifecycleState==="ARCHIVED"){console.log(` ${g} @ ${y} is already ARCHIVED \u2014 nothing to do.`);return}if(!t.force&&!await a(`Delete ${g} @ ${y}?`)){process.stderr.write(`Aborted.
104
- `);return}if(m.lifecycleState==="DRAFT"){await u.deleteVersion(g,y),console.log(`\u2713 Deleted ${g} @ ${y} (DRAFT removed)`);return}m.lifecycleState==="PUBLISHED"&&(await u.deprecateVersion(g,y),console.log(`\u2713 Deprecated ${g} @ ${y} is now DEPRECATED`)),await u.archiveVersion(g,y),console.log(`\u2713 Archived ${g} @ ${y} is now ARCHIVED`)}o(gl,"handleDelete");function ii(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=e.command("delete").description("Archive the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("-f, --force","Skip confirmation prompt",!1);return n()&&U().forEach(i=>r.addOption(i)),r.addHelpText("after",`
223
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((n,o)=>Ff(n,o))}r(hc,"registerDeactivateCommand");import Lf from"path";import Mf from"enquirer";async function Uf(e,t,n){return tn(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"delete"})}r(Uf,"defaultBuildApiClient");async function Nf(e){let{confirmed:t}=await Mf.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(Nf,"defaultConfirm");async function _f(e,t,n={}){let{loadEnvFile:o=j,loadAppConfig:i=k,getApiClient:s=Uf,confirm:a=Nf}=n,c=Lf.resolve(process.cwd(),e);o(c);let l=i(c);H(l);let p=t.interactive?await F(l,t):$(l.deployments,t.deployment),d=await s(p,t,l.externalId),{externalId:u,versionTag:g}=l,h;try{h=await d.getVersion(u,g)}catch(f){throw f instanceof oe?new m(`Version ${g} of ${u} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):f}if(h.alias==="ACTIVE")throw new m(`Cannot archive ${u} @ ${g}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(h.lifecycleState==="ARCHIVED"){console.log(` ${u} @ ${g} is already ARCHIVED \u2014 nothing to do.`);return}if(!t.force&&!await a(`Delete ${u} @ ${g}?`)){process.stderr.write(`Aborted.
224
+ `);return}if(h.lifecycleState==="DRAFT"){await d.deleteVersion(u,g),console.log(`\u2713 Deleted ${u} @ ${g} (DRAFT removed)`);return}h.lifecycleState==="PUBLISHED"&&(await d.deprecateVersion(u,g),console.log(`\u2713 Deprecated ${u} @ ${g} is now DEPRECATED`)),await d.archiveVersion(u,g),console.log(`\u2713 Archived ${u} @ ${g} is now ARCHIVED`)}r(_f,"handleDelete");function yc(e){let t=e.command("delete").description("Archive the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("-f, --force","Skip confirmation prompt",!1);return J().forEach(n=>t.addOption(n)),t.addHelpText("after",`
105
225
  Examples:
106
226
  npx @cognite/cli apps delete . Archive using env-var auth
107
227
  npx @cognite/cli apps delete . --interactive Archive using browser auth (no secrets needed)
108
- npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((i,s)=>gl(i,s))}o(ii,"registerDeleteCommand");import{existsSync as Rl}from"fs";import{rm as Fl}from"fs/promises";import pi from"enquirer";import{existsSync as El}from"fs";import{mkdir as bl,readFile as kl}from"fs/promises";import{basename as Pl,dirname as xl}from"path";import{execFileSync as bt}from"child_process";import Z from"fs";import L from"path";import{parseAndValidateManifestConfig as yl}from"@cognite/app-sdk/vite";import{BlobReader as hl,Uint8ArrayWriter as Sl,ZipWriter as wl}from"@zip.js/zip.js";var Pn="package.json",xn="package-lock.json",si="manifest.json",Dn=".cognite",vl=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],In=class In{constructor(t="dist"){this.distPath=L.isAbsolute(t)?t:L.join(process.cwd(),t),this.appRoot=L.dirname(this.distPath)}validateBuildDirectory(){if(!Z.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=L.join(this.appRoot,Pn);if(!Z.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=L.join(this.appRoot,xn);if(!Z.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new wl(new Sl,{level:9}),i=o(async(c,l)=>{await r.add(l,new hl(await Z.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await Z.promises.readdir(c,{withFileTypes:!0});for(let d of l){let u=L.join(c,d.name);d.isDirectory()?await s(u):await i(u,L.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=L.join(this.appRoot,Pn);await i(c,L.posix.join(Dn,Pn));let l=L.join(this.appRoot,si);if(Z.existsSync(l)){let u=Z.readFileSync(l,"utf-8");yl(u,l),await i(l,L.posix.join(Dn,si))}let d=L.join(this.appRoot,xn);await i(d,L.posix.join(Dn,xn)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await Z.promises.writeFile(t,a)}catch(c){throw new f(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=bt("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw q(),new f("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=bt("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(n,s);try{bt("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(Z.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${L.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=bt("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
109
- `).filter(Boolean),i=o(a=>a.split("/").some(p=>vl.some(c=>c.test(p))),"isSensitive"),s=r.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
228
+ npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((n,o)=>_f(n,o))}r(yc,"registerDeleteCommand");import{existsSync as Qf}from"fs";import{rm as eh}from"fs/promises";import wc from"enquirer";import{existsSync as zf}from"fs";import{mkdir as qf,readFile as Jf}from"fs/promises";import{basename as Wf,dirname as Zf}from"path";import{execFileSync as In}from"child_process";import Pe from"fs";import W from"path";import{parseAndValidateManifestConfig as jf}from"@cognite/app-sdk/vite";import{BlobReader as Hf,Uint8ArrayWriter as Bf,ZipWriter as Kf}from"@zip.js/zip.js";var ur="package.json",mr="package-lock.json",Sc="manifest.json",gr=".cognite",Vf=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],fr=class fr{constructor(t="dist"){this.distPath=W.isAbsolute(t)?t:W.join(process.cwd(),t),this.appRoot=W.dirname(this.distPath)}validateBuildDirectory(){if(!Pe.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=W.join(this.appRoot,ur);if(!Pe.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=W.join(this.appRoot,mr);if(!Pe.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let o=new Kf(new Bf,{level:9}),i=r(async(l,p)=>{await o.add(p,new Hf(await Pe.openAsBlob(l))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),s=r(async l=>{let p=await Pe.promises.readdir(l,{withFileTypes:!0});for(let d of p){let u=W.join(l,d.name);d.isDirectory()?await s(u):await i(u,W.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let l=W.join(this.appRoot,ur);await i(l,W.posix.join(gr,ur));let p=W.join(this.appRoot,Sc);if(Pe.existsSync(p)){let u=Pe.readFileSync(p,"utf-8");jf(u,p),await i(p,W.posix.join(gr,Sc))}let d=W.join(this.appRoot,mr);await i(d,W.posix.join(gr,mr)),a=await o.close()}catch(l){let p=l instanceof Error?l.message:String(l);throw new Error(`Failed to create zip: ${p}`)}try{await Pe.promises.writeFile(t,a)}catch(l){throw new m(`Failed to write bundle to ${t}`,{cause:l})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${c} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=In("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(l){throw Ae(),new m("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:l})}let o=In("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=o?o.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(n,s);try{In("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(l){let p=l instanceof Error?l.message:String(l);throw new Error(`Failed to create source archive: ${p}`)}let c=(Pe.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${W.basename(t)} (${c} MB)`),t}validateNoSensitiveFiles(t,n){let o=In("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
229
+ `).filter(Boolean),i=r(a=>a.split("/").some(c=>Vf.some(l=>l.test(c))),"isSensitive"),s=o.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
110
230
  `+s.map(a=>` ${a}`).join(`
111
231
  `)+`
112
- Hint: git rm --cached <file>`)}};o(In,"ApplicationPackager");var Q=In;import{existsSync as Al,readFileSync as Cl}from"fs";var ne=[".dev.sig",".cert.sig"];function $e(e,t={}){let n=t.existsSync??Al,r=t.readFileSync??((s,a)=>Cl(s,a)),i=[];for(let s of ne){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o($e,"discoverSignatures");async function kt(e,t,{existsSync:n=El,mkdir:r=bl,createZip:i=o((s,a)=>new Q(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,p=j(t,s,a);if(n(p)){let l=ne.some(d=>n(`${p}${d}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new f(`Bundle already exists: ${p}`,{hint:l,shouldReport:!1})}await r(xl(p),{recursive:!0}),await i(`${t}/dist`,p)}o(kt,"packageBundle");async function Oe(e,t,n,r,{readFile:i=kl,upload:s=o(async(a,p)=>new I(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,p,r),"uploadFn")}={}){let a=j(n,t.externalId,t.versionTag),p;try{p=await i(a)}catch(c){throw new f(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,Pl(a))}o(Oe,"uploadBundle");var Tn=o(async(e,t,n)=>{let r=await ye(e,n);await kt(t,n),await Oe(r,t,n,e.published)},"deploy"),Rn=o(async(e,t,n)=>{let r=await ye(e,n);await Oe(r,t,n,e.published)},"deployBundle");import{execSync as Dl}from"child_process";function Pt(e,t=!0,n={execSync:Dl}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new f(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}o(Pt,"buildApp");function ai(e,t){let{org:n,project:r,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(ai,"generateFusionUrl");import Il,{Chalk as Tl}from"chalk";var Me=new Tl({level:0});function re(e){return e.isTTY?Il:Me}o(re,"chalkForStream");async function $l(e){let{confirmed:t}=await pi.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}o($l,"defaultConfirm");async function Ol(e,t){let{selected:n}=await pi.prompt({type:"select",name:"selected",message:e,choices:t});return n}o(Ol,"defaultSelect");async function Ml(e){await Fl(e,{force:!0})}o(Ml,"defaultRm");function _l(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}o(_l,"classifyExistingBundle");async function Ul(e,t){let{versionTag:n,hasSigs:r}=e,i=r?`A signed bundle for v${n} already exists. What would you like to do?`:`A bundle for v${n} already exists. What would you like to do?`,s=await t.select(i,[{name:"reuse",message:"Deploy the existing bundle without rebuilding"},{name:"rebuild",message:"Rebuild and deploy (overwrites the existing bundle)",...r?{hint:"\u2014 discards existing signatures"}:{}},{name:"cancel",message:"Cancel \u2014 do nothing"}]);if(s==="rebuild"&&r){let a=re(process.stderr);if(console.warn(a.bold.red(`
113
- WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${ne.join(", ")}). You will have to re-sign before publishing.
114
- `)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}o(Ul,"promptBundleAction");async function Ll(e,t){for(let n of[e,...ne.map(r=>`${e}${r}`)])t.existsSync(n)&&await t.rm(n)}o(Ll,"removeBundleArtifacts");function Fn(e){let{appConfig:t,deployment:n,interactive:r}=e,i=r?"Deploy (Interactive)":"Deploy",s=r?`${n.project} @ ${n.baseUrl}`:`${n.org}/${n.project}`;console.log(["",i,"=".repeat(i.length),`App: ${t.name} (${t.externalId})`,`Version: ${t.versionTag}`,`Target: ${s}`,""].join(`
115
- `))}o(Fn,"printDeployInfo");function $n(e){let{appConfig:t,deployment:n}=e;console.log(`
116
- Successfully deployed ${t.name} version ${t.versionTag} to ${n.org?`${n.org}/`:""}${n.project}`),console.log("App is deployed in draft mode");let r=t.deployments.length>1?` -d ${n.project}`:"";console.log(`
117
- To sign: npx @cognite/cli apps sign --interactive${r}`),console.log(`To publish: npx @cognite/cli apps publish .${r}`),console.log(`To activate: npx @cognite/cli apps activate .${r}`),console.log(`
118
- To submit for certification: npx @cognite/cli apps submit`);let i=ai(n,t);i&&console.log(`
232
+ Hint: git rm --cached <file>`)}};r(fr,"ApplicationPackager");var Te=fr;import{existsSync as Gf,readFileSync as Yf}from"fs";var Fe=[".dev.sig",".cert.sig"];function vt(e,t={}){let n=t.existsSync??Gf,o=t.readFileSync??((s,a)=>Yf(s,a)),i=[];for(let s of Fe){let a=`${e}${s}`;if(!n(a))continue;let c=o(a,"utf8").trim();c.length>0&&i.push(c)}return i}r(vt,"discoverSignatures");async function hr(e,t,{existsSync:n=zf,mkdir:o=qf,createZip:i=r((s,a)=>new Te(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,c=re(t,s,a);if(n(c)){let p=Fe.some(d=>n(`${c}${d}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new m(`Bundle already exists: ${c}`,{hint:p,shouldReport:!1})}await o(Zf(c),{recursive:!0}),await i(`${t}/dist`,c)}r(hr,"packageBundle");async function yr(e,t,n,o,{readFile:i=Jf,upload:s=r(async(a,c)=>new M(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,c,o),"uploadFn")}={}){let a=re(n,t.externalId,t.versionTag),c;try{c=await i(a)}catch(l){throw new m(`Failed to read bundle file: ${a}`,{cause:l})}await s(c,Wf(a))}r(yr,"uploadBundle");import{execSync as Xf}from"child_process";function Dn(e,t=!0,n={execSync:Xf}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(o){throw new m(`npm run build failed in ${e}`,{cause:o,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}r(Dn,"buildApp");async function th(e){let{confirmed:t}=await wc.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(th,"defaultConfirm");async function nh(e,t){let{selected:n}=await wc.prompt({type:"select",name:"selected",message:e,choices:t});return n}r(nh,"defaultSelect");async function oh(e){await eh(e,{force:!0})}r(oh,"defaultRm");function rh(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}r(rh,"classifyExistingBundle");async function ih(e,t){let{versionTag:n,hasSigs:o}=e,i=o?`A signed bundle for v${n} already exists. What would you like to do?`:`A bundle for v${n} already exists. What would you like to do?`,s=await t.select(i,[{name:"reuse",message:"Deploy the existing bundle without rebuilding"},{name:"rebuild",message:"Rebuild and deploy (overwrites the existing bundle)",...o?{hint:"\u2014 discards existing signatures"}:{}},{name:"cancel",message:"Cancel \u2014 do nothing"}]);if(s==="rebuild"&&o){let a=P(process.stderr);if(console.warn(a.bold.red(`
233
+ WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${Fe.join(", ")}). You will have to re-sign before publishing.
234
+ `)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}r(ih,"promptBundleAction");async function sh(e,t){for(let n of[e,...Fe.map(o=>`${e}${o}`)])t.existsSync(n)&&await t.rm(n)}r(sh,"removeBundleArtifacts");function vc(e){let{appConfig:t,deployment:n,interactive:o}=e,i=o?"Deploy (Interactive)":"Deploy",s=o?`${n.project} @ ${n.baseUrl}`:`${n.org}/${n.project}`;console.log(["",i,"=".repeat(i.length),`App: ${t.name} (${t.externalId})`,`Version: ${t.versionTag}`,`Target: ${s}`,""].join(`
235
+ `))}r(vc,"printDeployInfo");function Cc(e){let{appConfig:t,deployment:n}=e;console.log(`
236
+ Successfully deployed ${t.name} version ${t.versionTag} to ${n.org?`${n.org}/`:""}${n.project}`),console.log("App is deployed in draft mode");let o=t.deployments.length>1?` -d ${n.project}`:"";console.log(`
237
+ To sign: npx @cognite/cli apps sign --interactive${o}`),console.log(`To publish: npx @cognite/cli apps publish .${o}`),console.log(`To activate: npx @cognite/cli apps activate .${o}`),console.log(`
238
+ To submit for certification: npx @cognite/cli apps submit`);let i=sa(n,t);i&&console.log(`
119
239
  Open your app:
120
- ${i}`)}o($n,"printDeployResult");function On(e){let{externalId:t,name:n,description:r,versionTag:i}=e;return{externalId:t,name:n,description:r,versionTag:i}}o(On,"toApp");async function Nl(e,t){let{appConfig:n,deployment:r,cwd:i,options:s,useExistingBundle:a}=e,{deployFn:p,buildApp:c,isSessionAuthEnabled:l,buildClient:d,packageBundle:u,uploadBundle:g}=t;if(l()&&!s.interactive){Fn({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&c(i);let m=await d(r,{interactive:!1,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod,confirmActionTarget:s.confirmActionTarget,action:"deploy"});console.log(`
121
- Deploying to ${r.org}/${r.project}...`);let h=On(n);a||await u(h,i),await g(m,h,i,!1),$n({appConfig:n,deployment:r});return}let y=F(r);if(y.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Fn({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&c(i),console.log(`
122
- Deploying to ${r.org}/${r.project}...`),await p({...r,published:!1},On(n),i),$n({appConfig:n,deployment:r})}o(Nl,"handleDeployNonInteractive");async function Hl(e,t){let{appConfig:n,deployment:r,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:p,buildClient:c,packageBundle:l,uploadBundle:d}=t;Fn({appConfig:n,deployment:r,interactive:!0}),!s.skipBuild&&!a&&p(i);let u=await c(r,{interactive:!0,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod});console.log(`
123
- Deploying to ${r.project}...`);let g=On(n);a||await l(g,i),await d(u,g,i,!1),$n({appConfig:n,deployment:r})}o(Hl,"handleDeployInteractive");async function Kl(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:i=b,deploy:s=Tn,deployBundle:a=Rn,confirm:p=$l,select:c=Ol,existsSync:l=Rl,rm:d=Ml,buildApp:u=Pt,isSessionAuthEnabled:g=E,buildClient:y=K,packageBundle:m=kt,uploadBundle:h=Oe}=n;r(t);let S=i(t);M(S);let A=j(t,S.externalId,S.versionTag),v=_l(A,e,l),w=v==="use-existing";if(v==="prompt"){let x=ne.some(J=>l(`${A}${J}`)),k=await Ul({versionTag:S.versionTag,hasSigs:x},{select:c,confirm:p});if(k==="cancel"){console.log(`
124
- Deployment cancelled. Nothing was deployed.`);return}k==="reuse"?w=!0:await Ll(A,{existsSync:l,rm:d})}if(e.interactive){let x=await $(S,e);await Hl({appConfig:S,deployment:x,cwd:t,options:e,useExistingBundle:w},{buildApp:u,buildClient:y,packageBundle:m,uploadBundle:h});return}let D=T(S.deployments,e.deployment);await Nl({appConfig:S,deployment:D,cwd:t,options:e,useExistingBundle:w},{deployFn:w?a:s,buildApp:u,isSessionAuthEnabled:g,buildClient:y,packageBundle:m,uploadBundle:h})}o(Kl,"handleDeploy");function ci(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=n()?"Deploy your app to Cognite Data Fusion. Run `auth login` to sign in, or use --interactive for a one-off browser login (no env-var secrets required).":"Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).",i=e.command("deploy").description(r).option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return n()&&U().forEach(s=>i.addOption(s)),i.addHelpText("after",`
240
+ ${i}`)}r(Cc,"printDeployResult");function Ac(e){let{externalId:t,name:n,description:o,versionTag:i}=e;return{externalId:t,name:n,description:o,versionTag:i}}r(Ac,"toApp");async function ah(e,t){let{appConfig:n,deployment:o,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:c,buildClient:l,packageBundle:p,uploadBundle:d}=t;vc({appConfig:n,deployment:o,interactive:!1});let u=await l(o,{interactive:!1,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod,confirmActionTarget:s.confirmActionTarget,action:"deploy"});!s.skipBuild&&!a&&c(i),console.log(`
241
+ Deploying to ${o.org}/${o.project}...`);let g=Ac(n);a||await p(g,i),await d(u,g,i,!1),Cc({appConfig:n,deployment:o})}r(ah,"handleDeployNonInteractive");async function ch(e,t){let{appConfig:n,deployment:o,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:c,buildClient:l,packageBundle:p,uploadBundle:d}=t;vc({appConfig:n,deployment:o,interactive:!0}),!s.skipBuild&&!a&&c(i);let u=await l(o,{interactive:!0,appId:n.externalId,orgHint:s.org,authMethod:s.authMethod});console.log(`
242
+ Deploying to ${o.project}...`);let g=Ac(n);a||await p(g,i),await d(u,g,i,!1),Cc({appConfig:n,deployment:o})}r(ch,"handleDeployInteractive");async function lh(e,t=process.cwd(),n={}){let{loadEnvFile:o=j,loadAppConfig:i=k,confirm:s=th,select:a=nh,existsSync:c=Qf,rm:l=oh,buildApp:p=Dn,buildClient:d=_,packageBundle:u=hr,uploadBundle:g=yr}=n;o(t);let h=i(t);H(h);let f=re(t,h.externalId,h.versionTag),y=rh(f,e,c),S=y==="use-existing";if(y==="prompt"){let v=Fe.some(x=>c(`${f}${x}`)),C=await ih({versionTag:h.versionTag,hasSigs:v},{select:a,confirm:s});if(C==="cancel"){console.log(`
243
+ Deployment cancelled. Nothing was deployed.`);return}C==="reuse"?S=!0:await sh(f,{existsSync:c,rm:l})}if(e.interactive){let v=await F(h,e);await ch({appConfig:h,deployment:v,cwd:t,options:e,useExistingBundle:S},{buildApp:p,buildClient:d,packageBundle:u,uploadBundle:g});return}let w=$(h.deployments,e.deployment);await ah({appConfig:h,deployment:w,cwd:t,options:e,useExistingBundle:S},{buildApp:p,buildClient:d,packageBundle:u,uploadBundle:g})}r(lh,"handleDeploy");function Ec(e){let t=e.command("deploy").description("Deploy your app to Cognite Data Fusion. Run `auth login` to sign in, or use --interactive for a one-off browser login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return J().forEach(n=>t.addOption(n)),t.addHelpText("after",`
125
244
  Environment (non-interactive):
126
245
  deployClientId and deploySecretName are configured per deployment in app.json.
127
246
  deploySecretName is the name of the environment variable that holds the client
@@ -135,10 +254,10 @@ Examples:
135
254
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
136
255
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
137
256
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
138
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(s=>Kl(s))}o(ci,"registerDeployCommand");import It from"fs";import zl from"os";import oe from"path";import Wl from"enquirer";import Mn from"fs";import xt from"path";import{BlobReader as jl,Uint8ArrayWriter as Bl,ZipReader as Vl}from"@zip.js/zip.js";import _e from"path";function li(e,t){let n=_e.resolve(e),r=_e.resolve(t),i=_e.relative(n,r);return i===""||_e.isAbsolute(i)?!1:i!==".."&&!i.startsWith(`..${_e.sep}`)}o(li,"isSafePath");var Gl=1e5,Yl=2*1024**3;async function di(e,t,n={}){let{openAsBlob:r=o(d=>Mn.openAsBlob(d),"openAsBlob"),mkdir:i=o((d,u)=>Mn.promises.mkdir(d,u),"mkdir"),writeFile:s=o((d,u)=>Mn.promises.writeFile(d,u),"writeFile"),maxEntries:a=Gl,maxTotalBytes:p=Yl}=n,c=await r(e),l=new Vl(new jl(c));try{let d;try{d=await l.getEntries()}catch(y){throw new f(`Could not read bundle: ${xt.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:y})}let u=0,g=0;for(let y of d){if(y.directory)continue;if(g++,g>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(u+=y.uncompressedSize,u>p)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(p/(1024*1024))} MB)`);if(xt.isAbsolute(y.filename))throw new Error(`Malicious zip entry rejected: ${y.filename}`);let m=xt.join(t,y.filename);if(!li(t,m))throw new Error(`Malicious zip entry rejected: ${y.filename}`);let h=await y.getData(new Bl);await i(xt.dirname(m),{recursive:!0}),await s(m,h)}}finally{await l.close()}}o(di,"extractZip");import{execFileSync as ql}from"child_process";function mi(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(mi,"isExitError");function ui(e){if(!mi(e)||e.status!==1)throw e}o(ui,"swallowDiffExit");var _n=class _n{constructor(t={execFileSync:ql}){this.deps=t}isSupported(){try{return this.deps.execFileSync("git",["--version"],{stdio:"pipe"}),!0}catch{return!1}}isIdentical(t,n){try{return this.deps.execFileSync("git",["diff","--no-index","--quiet","--ignore-cr-at-eol",t,n]),!0}catch(r){if(mi(r)&&r.status===1)return!1;throw r}}showStat(t,n){try{this.deps.execFileSync("git",["--no-pager","diff","--stat","--no-index","--ignore-cr-at-eol",t,n],{stdio:"inherit"})}catch(r){ui(r)}}showDiff(t,n,{usePager:r=!0}={}){let i=[];r||i.push("--no-pager"),i.push("diff","--word-diff=color","--no-index","--ignore-cr-at-eol",t,n);try{this.deps.execFileSync("git",i,{stdio:"inherit"})}catch(s){ui(s)}}};o(_n,"GitDiffer");var Dt=_n;var Jl=o(async e=>(await Wl.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function Xl(e,t,n={}){let{cwd:r=process.cwd(),buildApp:i=Pt,createPackager:s=o(w=>new Q(w),"createPackager"),extractZip:a=di,differ:p=new Dt,existsSync:c=o(w=>It.existsSync(w),"existsSync"),mkdtemp:l=o(w=>It.promises.mkdtemp(w),"mkdtemp"),mkdir:d=o(async(w,D)=>{await It.promises.mkdir(w,D)},"mkdir"),rm:u=o((w,D)=>It.promises.rm(w,D),"rm"),isInteractive:g=o(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:y=Jl,setExitCode:m=o(w=>{process.exitCode=w},"setExitCode")}=n;if(!p.isSupported())throw new f("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!c(e))throw new f(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await i(r);else{let w=oe.join(r,"dist");if(!c(w))throw new f("dist directory not found.",{hint:"Run without --skip-build to build the app first, or run `pnpm build` manually.",shouldReport:!1})}let h=await l(oe.join(zl.tmpdir(),"cognite-diff-")),S=oe.join(h,"ours.zip"),A=oe.join(h,"ours"),v=oe.join(h,"theirs");try{if(await d(A,{recursive:!0}),await d(v,{recursive:!0}),await s(oe.join(r,"dist")).createZip(S),console.log(`
139
- Extracting bundles...`),await a(S,A),await a(e,v),p.isIdentical(A,v)){console.log(`
257
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(n=>lh(n))}r(Ec,"registerDeployCommand");import Fn from"fs";import hh from"os";import Le from"path";import yh from"enquirer";import Sr from"fs";import $n from"path";import{BlobReader as ph,Uint8ArrayWriter as dh,ZipReader as uh}from"@zip.js/zip.js";import Ct from"path";function bc(e,t){let n=Ct.resolve(e),o=Ct.resolve(t),i=Ct.relative(n,o);return i===""||Ct.isAbsolute(i)?!1:i!==".."&&!i.startsWith(`..${Ct.sep}`)}r(bc,"isSafePath");var mh=1e5,gh=2*1024**3;async function xc(e,t,n={}){let{openAsBlob:o=r(d=>Sr.openAsBlob(d),"openAsBlob"),mkdir:i=r((d,u)=>Sr.promises.mkdir(d,u),"mkdir"),writeFile:s=r((d,u)=>Sr.promises.writeFile(d,u),"writeFile"),maxEntries:a=mh,maxTotalBytes:c=gh}=n,l=await o(e),p=new uh(new ph(l));try{let d;try{d=await p.getEntries()}catch(h){throw new m(`Could not read bundle: ${$n.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:h})}let u=0,g=0;for(let h of d){if(h.directory)continue;if(g++,g>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(u+=h.uncompressedSize,u>c)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(c/(1024*1024))} MB)`);if($n.isAbsolute(h.filename))throw new Error(`Malicious zip entry rejected: ${h.filename}`);let f=$n.join(t,h.filename);if(!bc(t,f))throw new Error(`Malicious zip entry rejected: ${h.filename}`);let y=await h.getData(new dh);await i($n.dirname(f),{recursive:!0}),await s(f,y)}}finally{await p.close()}}r(xc,"extractZip");import{execFileSync as fh}from"child_process";function Pc(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}r(Pc,"isExitError");function kc(e){if(!Pc(e)||e.status!==1)throw e}r(kc,"swallowDiffExit");var wr=class wr{constructor(t={execFileSync:fh}){this.deps=t}isSupported(){try{return this.deps.execFileSync("git",["--version"],{stdio:"pipe"}),!0}catch{return!1}}isIdentical(t,n){try{return this.deps.execFileSync("git",["diff","--no-index","--quiet","--ignore-cr-at-eol",t,n]),!0}catch(o){if(Pc(o)&&o.status===1)return!1;throw o}}showStat(t,n){try{this.deps.execFileSync("git",["--no-pager","diff","--stat","--no-index","--ignore-cr-at-eol",t,n],{stdio:"inherit"})}catch(o){kc(o)}}showDiff(t,n,{usePager:o=!0}={}){let i=[];o||i.push("--no-pager"),i.push("diff","--word-diff=color","--no-index","--ignore-cr-at-eol",t,n);try{this.deps.execFileSync("git",i,{stdio:"inherit"})}catch(s){kc(s)}}};r(wr,"GitDiffer");var On=wr;var Sh=r(async e=>(await yh.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function wh(e,t,n={}){let{cwd:o=process.cwd(),buildApp:i=Dn,createPackager:s=r(C=>new Te(C),"createPackager"),extractZip:a=xc,differ:c=new On,existsSync:l=r(C=>Fn.existsSync(C),"existsSync"),mkdtemp:p=r(C=>Fn.promises.mkdtemp(C),"mkdtemp"),mkdir:d=r(async(C,x)=>{await Fn.promises.mkdir(C,x)},"mkdir"),rm:u=r((C,x)=>Fn.promises.rm(C,x),"rm"),isInteractive:g=r(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:h=Sh,setExitCode:f=r(C=>{process.exitCode=C},"setExitCode")}=n;if(!c.isSupported())throw new m("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!l(e))throw new m(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await i(o);else{let C=Le.join(o,"dist");if(!l(C))throw new m("dist directory not found.",{hint:"Run without --skip-build to build the app first, or run `pnpm build` manually.",shouldReport:!1})}let y=await p(Le.join(hh.tmpdir(),"cognite-diff-")),S=Le.join(y,"ours.zip"),w=Le.join(y,"ours"),v=Le.join(y,"theirs");try{if(await d(w,{recursive:!0}),await d(v,{recursive:!0}),await s(Le.join(o,"dist")).createZip(S),console.log(`
258
+ Extracting bundles...`),await a(S,w),await a(e,v),c.isIdentical(w,v)){console.log(`
140
259
  Bundles are identical`);return}console.log(`
141
- \u274C The local build at ${oe.join(r,"dist")} differs from ${oe.basename(e)}.`);let D=g();(t.showStat!==void 0?t.showStat:D&&await y("Show stat summary?"))&&p.showStat(A,v),(t.showDiff!==void 0?t.showDiff:D&&await y("Show full diff?"))&&p.showDiff(A,v,{usePager:t.pager}),m(1)}finally{await u(h,{recursive:!0,force:!0})}}o(Xl,"handleDiff");function fi(e){return e.command("diff <bundle>").description("Diff a trusted local build against an untrusted bundle zip").option("--skip-build","Skip rebuilding the app before diffing",!1).option("--no-pager","Disable the pager and print diff output directly").option("--show-stat","Show a compact stat summary when bundles differ").option("--show-diff","Show the full word diff when bundles differ").addHelpText("after",`
260
+ \u274C The local build at ${Le.join(o,"dist")} differs from ${Le.basename(e)}.`);let x=g();(t.showStat!==void 0?t.showStat:x&&await h("Show stat summary?"))&&c.showStat(w,v),(t.showDiff!==void 0?t.showDiff:x&&await h("Show full diff?"))&&c.showDiff(w,v,{usePager:t.pager}),f(1)}finally{await u(y,{recursive:!0,force:!0})}}r(wh,"handleDiff");function Tc(e){return e.command("diff <bundle>").description("Diff a trusted local build against an untrusted bundle zip").option("--skip-build","Skip rebuilding the app before diffing",!1).option("--no-pager","Disable the pager and print diff output directly").option("--show-stat","Show a compact stat summary when bundles differ").option("--show-diff","Show the full word diff when bundles differ").addHelpText("after",`
142
261
  Builds the current source, packages it, then extracts both the local build
143
262
  and the provided bundle to temporary directories and runs:
144
263
 
@@ -149,76 +268,74 @@ Exit code 0 means the bundles are identical; exit code 1 means they differ.
149
268
  Examples:
150
269
  npx @cognite/cli apps diff untrusted.zip
151
270
  npx @cognite/cli apps diff untrusted.zip --skip-build
152
- npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>Xl(t,n))}o(fi,"registerDiffCommand");function Zl(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:r,local:i}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${r}" \u2192 "${i||"(none)"}"`)}}o(Zl,"printMetadataDiff");async function Ql(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:i=b,buildApiClient:s=K,createMetadataClient:a=o(S=>new I(S),"createMetadataClient"),getMissingCredentials:p=F,isSessionAuthEnabled:c=E}=n;r(t);let l=i(t);M(l);let d=e.interactive?await $(l,e):T(l.deployments,e.deployment);if(!e.interactive&&!c()){let S=p(d);if(S.length>0)throw new Error(`Deployment ${d.org}/${d.project} is missing ${S.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let u=await s(d,{interactive:e.interactive,appId:l.externalId,orgHint:e.org,authMethod:e.authMethod,confirmActionTarget:e.confirmActionTarget,action:"metadata update"}),g=a(u),y;try{y=await g.getApp(l.externalId)}catch(S){throw S instanceof Ce?new Error(`App '${l.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):S}let m={name:l.name,description:l.description||""},h=rn(y,m);if(h.length===0){console.log(""),console.log(`Metadata for '${l.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}Zl(l.externalId,h),await g.updateAppMetadata(l.externalId,l.name,l.description),console.log(""),console.log(`\u2705 Metadata for '${l.externalId}' updated`)}o(Ql,"handleUpdateMetadata");function gi(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description)."),i=r.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return n()&&U().forEach(s=>i.addOption(s)),i.addHelpText("after",`
271
+ npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>wh(t,n))}r(Tc,"registerDiffCommand");function vh(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:o,local:i}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${o}" \u2192 "${i||"(none)"}"`)}}r(vh,"printMetadataDiff");async function Ch(e,t=process.cwd(),n={}){let{loadEnvFile:o=j,loadAppConfig:i=k,buildApiClient:s=_,createMetadataClient:a=r(f=>new M(f),"createMetadataClient")}=n;o(t);let c=i(t);H(c);let l=e.interactive?await F(c,e):$(c.deployments,e.deployment),p=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org,authMethod:e.authMethod,confirmActionTarget:e.confirmActionTarget,action:"metadata update"}),d=a(p),u;try{u=await d.getApp(c.externalId)}catch(f){throw f instanceof Ze?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}let g={name:c.name,description:c.description||""},h=Eo(u,g);if(h.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}vh(c.externalId,h),await d.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}r(Ch,"handleUpdateMetadata");function Rc(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description)."),n=t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return J().forEach(o=>n.addOption(o)),n.addHelpText("after",`
153
272
  Examples:
154
273
  npx @cognite/cli apps metadata update . Push name/description using env-var auth
155
- npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((s,a)=>Ql(a)),r}o(gi,"registerMetadataCommand");async function ed(e,t,n){let r=await K(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"publish"});return new I(r)}o(ed,"defaultBuildApiClient");async function td(e,t={}){let n=t.loadEnvFile??O,r=t.loadAppConfig??b,i=t.buildApiClient??ed,s=t.discoverSignatures??$e,a=t.isSessionAuthEnabled??E,p=process.cwd();n(p);let c=r(p);M(c);let l=e.interactive?await $(c,e):T(c.deployments,e.deployment);if(!e.interactive&&!a()){let h=F(l);if(h.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${h.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let d=await i(l,e,c),{externalId:u,versionTag:g}=c,y;try{y=await d.getVersion(u,g)}catch(h){throw h instanceof V?new Error(`Version ${g} of ${u} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):h}if(y.alias==="ACTIVE"){console.log(` ${u} @ ${g} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${u} @ ${g} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${u} @ ${g}: version is ${y.lifecycleState} (terminal).`);let m=s(j(p,u,g));m.length>0&&await d.submitSignatures(u,g,m),await d.publishVersion(u,g),console.log(`\u2713 Published ${u} @ ${g} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(td,"handlePublish");function yi(e,t={isSessionAuthEnabled:E}){let{isSessionAuthEnabled:n}=t,r=e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return n()&&U().forEach(i=>r.addOption(i)),r.addHelpText("after",`
274
+ npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((o,i)=>Ch(i)),t}r(Rc,"registerMetadataCommand");async function Ah(e,t,n){let o=await _(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org,authMethod:t.authMethod,confirmActionTarget:t.confirmActionTarget,action:"publish"});return new M(o)}r(Ah,"defaultBuildApiClient");async function Eh(e,t={}){let n=t.loadEnvFile??j,o=t.loadAppConfig??k,i=t.buildApiClient??Ah,s=t.discoverSignatures??vt,a=process.cwd();n(a);let c=o(a);H(c);let l=e.interactive?await F(c,e):$(c.deployments,e.deployment),p=await i(l,e,c),{externalId:d,versionTag:u}=c,g;try{g=await p.getVersion(d,u)}catch(f){throw f instanceof oe?new Error(`Version ${u} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}if(g.alias==="ACTIVE"){console.log(` ${d} @ ${u} is already ACTIVE \u2014 nothing to do.`);return}if(g.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${u} is already PUBLISHED \u2014 nothing to do.`);return}if(g.lifecycleState==="DEPRECATED"||g.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${u}: version is ${g.lifecycleState} (terminal).`);let h=s(re(a,d,u));h.length>0&&await p.submitSignatures(d,u,h),await p.publishVersion(d,u),console.log(`\u2713 Published ${d} @ ${u} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}r(Eh,"handlePublish");function Ic(e){let t=e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return J().forEach(n=>t.addOption(n)),t.addHelpText("after",`
156
275
  Examples:
157
276
  npx @cognite/cli apps publish . Publish using env-var auth
158
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((i,s)=>td(s))}o(yi,"registerPublishCommand");import{spawnSync as nd}from"child_process";import{mkdirSync as rd}from"fs";import{join as od,resolve as hi}from"path";var id=["localhost","local.cognite.ai","*.local.cognite.ai"],sd={info:o(e=>{process.stdout.write(`${e}
159
- `)},"info"),error:o(e=>{process.stderr.write(`${e}
160
- `)},"error")},ad={spawnSync:nd,mkdirSync:rd,logger:sd,getConfig:P};function pd(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(pd,"hasMkcert");function cd({certDir:e,domains:t=id,deps:n={}}={}){let r={...ad,...n},{spawnSync:i,mkdirSync:s,logger:a}=r,p=e??od(r.getConfig().home,"certificates","mkcert");if(!pd(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(p,{recursive:!0});let l=hi(p,"localhost.pem"),d=hi(p,"localhost-key.pem");if(i("mkcert",["-cert-file",l,"-key-file",d,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${l}`),a.info(` key: ${d}`),{certFile:l,keyFile:d}}o(cd,"setupHttps");function ld(e){cd({certDir:e.certDir})}o(ld,"handleSetupHttps");function Si(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ~/.cognite-cli/certificates/mkcert)").addHelpText("after",`
277
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((n,o)=>Eh(o))}r(Ic,"registerPublishCommand");import{spawnSync as bh}from"child_process";import{mkdirSync as xh}from"fs";import{join as kh,resolve as Dc}from"path";var Ph=["localhost","local.cognite.ai","*.local.cognite.ai"],Th={info:r(e=>{process.stdout.write(`${e}
278
+ `)},"info"),error:r(e=>{process.stderr.write(`${e}
279
+ `)},"error")},Rh={spawnSync:bh,mkdirSync:xh,logger:Th,getConfig:D};function Ih(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}r(Ih,"hasMkcert");function Dh({certDir:e,domains:t=Ph,deps:n={}}={}){let o={...Rh,...n},{spawnSync:i,mkdirSync:s,logger:a}=o,c=e??kh(o.getConfig().home,"certificates","mkcert");if(!Ih(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(c,{recursive:!0});let p=Dc(c,"localhost.pem"),d=Dc(c,"localhost-key.pem");if(i("mkcert",["-cert-file",p,"-key-file",d,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${p}`),a.info(` key: ${d}`),{certFile:p,keyFile:d}}r(Dh,"setupHttps");function $h(e){Dh({certDir:e.certDir})}r($h,"handleSetupHttps");function $c(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ~/.cognite-cli/certificates/mkcert)").addHelpText("after",`
161
280
  Examples:
162
281
  npx @cognite/cli@latest apps setup-https Generate certs in ~/.cognite-cli/certificates/mkcert
163
- npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>ld(t))}o(Si,"registerSetupHttpsCommand");import{existsSync as Id,writeFileSync as Td}from"fs";import{basename as Rd,dirname as Fd,join as $d,resolve as Kn}from"path";import{parseScope as Od,signBundle as Md,validateScopes as _d}from"@cognite/app-sdk/codesigning";import{existsSync as Pd,readFileSync as xd}from"fs";import{pbkdf2 as md,randomBytes as fd}from"crypto";import{promisify as gd}from"util";import{CompactEncrypt as yd,base64url as wi,compactDecrypt as hd}from"jose";var dd=new TextEncoder,ud=new TextDecoder,Un={encode:o(e=>dd.encode(e),"encode"),decode:o(e=>ud.decode(e),"decode")};var Sd=gd(md),Hn=6e5,wd="sha512",Ln="PBKDF2-HMAC-SHA512",Nn=16,Tt="A256GCM",vd=32,Rt=2e6;async function vi(e,t,n){return await Sd(e,t,n,vd,wd)}o(vi,"deriveKey");async function Ai(e,t,n=Hn){if(!Number.isInteger(n)||n<1||n>Rt)throw new Error(`Invalid iterations: must be an integer between 1 and ${Rt}`);let r=fd(Nn),i=await vi(t.expose(),r,n);return await new yd(Un.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Tt,kdf:Ln,kdf_iter:n,kdf_salt:wi.encode(r)}).encrypt(i)}o(Ai,"encryptStringAsJwe");async function Ci(e,t){let{plaintext:n}=await hd(e,async r=>{if(!e.length)throw new Error("Unexpected JWE empty value");let i=t.expose();if(i.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(r.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(r.alg)}"; only "dir" is supported`);if(r.enc!==Tt)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${Tt}" is supported`);if(r.kdf!==Ln)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Ln}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>Rt)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Rt}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=wi.decode(r.kdf_salt);if(a.length!==Nn)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Nn} bytes, got ${a.length}`);return await vi(i,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Tt]});return Un.decode(n)}o(Ci,"decryptJweAsString");function Ei(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Ei,"isJweCompact");import Ad from"enquirer";async function Cd(e){return Ad.prompt(e)}o(Cd,"defaultPrompt");async function bi(e,t={}){let{prompt:n=Cd}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return C.from(r)}o(bi,"promptPassphrase");import bd from"enquirer";import{statSync as Ed}from"fs";function ki(e,t=Ed){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}o(ki,"sortByMtime");async function kd(e){return bd.prompt(e)}o(kd,"defaultPrompt");async function Pi(e,t={}){if(e.length===1)return e[0];let{prompt:n=kd,sortByMtime:r=ki}=t,i=r(e),s=i[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await n({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,Je(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(Pi,"promptSigningIdentity");function Dd(e){return{existsSync:e.existsSync??Pd,readFileSync:e.readFileSync??((t,n)=>xd(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??ze,readSigningKey:e.readSigningKey??We,isOS:e.isOS??(t=>N(t)),decryptJweAsString:e.decryptJweAsString??Ci,discoverLocalKeys:e.discoverLocalKeys??Xe,keysDir:e.keysDir??P().keysDir,promptPassphrase:e.promptPassphrase??bi,promptSigningIdentity:e.promptSigningIdentity??Pi}}o(Dd,"resolveDeps");async function xi(e,t={}){let n=Dd(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Ei(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:C.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:C.from(s),kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=r.find(s=>s.kid===e.kid);else if(e.interactive)i=await n.promptSigningIdentity(r);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(i.kid):await n.readSigningKey(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:C.from(await n.decryptJweAsString(n.readFileSync(i.source.path,"utf-8"),s)),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(xi,"resolvePrivateKey");var Ud=o(async(e,t,n,r,i)=>{let s=await K(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org,authMethod:i.authMethod,confirmActionTarget:i.confirmActionTarget,action:"sign"});await new I(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function Ld(e){return{existsSync:e.existsSync??Id,writeFileSync:e.writeFileSync??Td,createBundleStream:e.createBundleStream??Ze,signBundle:e.signBundle??Md,parseScope:e.parseScope??Od,validateScopes:e.validateScopes??_d,loadAppConfig:e.loadAppConfig??b,resolvePrivateKey:e.resolvePrivateKey??(t=>xi(t)),submitSignatures:e.submitSignatures??Ud,discoverSignatures:e.discoverSignatures??$e,isSessionAuthEnabled:e.isSessionAuthEnabled??E}}o(Ld,"resolveDeps");async function Di(e,t,n={},r=process.cwd()){let i=Ld(n),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(v=>({org:v.org,project:v.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?Kn(r,e):j(r,s,a);if(!i.existsSync(l)){let v=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${v}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
282
+ npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>$h(t))}r($c,"registerSetupHttpsCommand");import{existsSync as Zh,writeFileSync as Xh}from"fs";import{basename as Qh,dirname as ey,join as ty,resolve as br}from"path";import{parseScope as ny,signBundle as oy,validateScopes as ry}from"@cognite/app-sdk/codesigning";import{existsSync as qh,readFileSync as Jh}from"fs";import{pbkdf2 as Lh,randomBytes as Mh}from"crypto";import{promisify as Uh}from"util";import{CompactEncrypt as Nh,base64url as Oc,compactDecrypt as _h}from"jose";var Oh=new TextEncoder,Fh=new TextDecoder,vr={encode:r(e=>Oh.encode(e),"encode"),decode:r(e=>Fh.decode(e),"decode")};var jh=Uh(Lh),Er=6e5,Hh="sha512",Cr="PBKDF2-HMAC-SHA512",Ar=16,Ln="A256GCM",Bh=32,Mn=2e6;async function Fc(e,t,n){return await jh(e,t,n,Bh,Hh)}r(Fc,"deriveKey");async function Lc(e,t,n=Er){if(!Number.isInteger(n)||n<1||n>Mn)throw new Error(`Invalid iterations: must be an integer between 1 and ${Mn}`);let o=Mh(Ar),i=await Fc(t.expose(),o,n);return await new Nh(vr.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Ln,kdf:Cr,kdf_iter:n,kdf_salt:Oc.encode(o)}).encrypt(i)}r(Lc,"encryptStringAsJwe");async function Mc(e,t){let{plaintext:n}=await _h(e,async o=>{if(!e.length)throw new Error("Unexpected JWE empty value");let i=t.expose();if(i.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(o.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(o.alg)}"; only "dir" is supported`);if(o.enc!==Ln)throw new Error(`Unexpected JWE enc "${String(o.enc)}"; only "${Ln}" is supported`);if(o.kdf!==Cr)throw new Error(`Unexpected KDF "${String(o.kdf)}"; only "${Cr}" is supported`);let s=Number(o.kdf_iter);if(!Number.isInteger(s)||s<1||s>Mn)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Mn}`);if(typeof o.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Oc.decode(o.kdf_salt);if(a.length!==Ar)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Ar} bytes, got ${a.length}`);return await Fc(i,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Ln]});return vr.decode(n)}r(Mc,"decryptJweAsString");function Uc(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}r(Uc,"isJweCompact");import Kh from"enquirer";async function Vh(e){return Kh.prompt(e)}r(Vh,"defaultPrompt");async function Nc(e,t={}){let{prompt:n=Vh}=t,{passphrase:o}=await n({type:"password",name:"passphrase",message:e});return b.from(o)}r(Nc,"promptPassphrase");import Yh from"enquirer";import{statSync as Gh}from"fs";function _c(e,t=Gh){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,o)=>o.mtime-n.mtime).map(({key:n})=>n)}r(_c,"sortByMtime");async function zh(e){return Yh.prompt(e)}r(zh,"defaultPrompt");async function jc(e,t={}){if(e.length===1)return e[0];let{prompt:n=zh,sortByMtime:o=_c}=t,i=o(e),s=i[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:c}=await n({type:"select",name:"kid",message:"Select signing identity",choices:i.map(p=>({name:p.kid,message:[p.kid,p.email,Cn(p.source)].filter(Boolean).join(" \u2014 ")}))}),l=i.find(p=>p.kid===c);if(!l)throw new Error("No signing identity selected");return l}else throw new Error(`Unexpected choice: "${a}"`)}r(jc,"promptSigningIdentity");function Wh(e){return{existsSync:e.existsSync??qh,readFileSync:e.readFileSync??((t,n)=>Jh(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??wn,readSigningKey:e.readSigningKey??vn,isOS:e.isOS??(t=>X(t)),decryptJweAsString:e.decryptJweAsString??Mc,discoverLocalKeys:e.discoverLocalKeys??An,keysDir:e.keysDir??D().keysDir,promptPassphrase:e.promptPassphrase??Nc,promptSigningIdentity:e.promptSigningIdentity??jc}}r(Wh,"resolveDeps");async function Hc(e,t={}){let n=Wh(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Uc(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:b.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:b.from(s),kid:e.kid}}let o=await n.discoverLocalKeys(n.keysDir);if(o.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=o.find(s=>s.kid===e.kid);else if(e.interactive)i=await n.promptSigningIdentity(o);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(i.kid):await n.readSigningKey(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:b.from(await n.decryptJweAsString(n.readFileSync(i.source.path,"utf-8"),s)),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}r(Hc,"resolvePrivateKey");var iy=r(async(e,t,n,o,i)=>{let s=await _(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org,authMethod:i.authMethod,confirmActionTarget:i.confirmActionTarget,action:"sign"});await new M(s).submitSignatures(t,n,o)},"defaultSubmitSignatures");function sy(e){return{existsSync:e.existsSync??Zh,writeFileSync:e.writeFileSync??Xh,createBundleStream:e.createBundleStream??En,signBundle:e.signBundle??oy,parseScope:e.parseScope??ny,validateScopes:e.validateScopes??ry,loadAppConfig:e.loadAppConfig??k,resolvePrivateKey:e.resolvePrivateKey??(t=>Hc(t)),submitSignatures:e.submitSignatures??iy,discoverSignatures:e.discoverSignatures??vt}}r(sy,"resolveDeps");async function Bc(e,t,n={},o=process.cwd()){let i=sy(n),s=t.appid,a=t.appVersion,c=[],l=i.loadAppConfig(o);if(s=s??l.externalId,a=a??l.versionTag,t.scope&&t.scope.length>0?c=t.scope.map(i.parseScope):c=l.deployments.map(v=>({org:v.org,project:v.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let p=e?br(o,e):re(o,s,a);if(!i.existsSync(p)){let v=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${p}${v}`)}let d=i.validateScopes(c);if(d.length>0)throw new Error(`Invalid scopes:
164
283
  ${d.join(`
165
- `)}`);let{privateKeyPem:u,kid:g}=await i.resolvePrivateKey({keyPath:t.key?Kn(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),y=i.createBundleStream(l),m=await i.signBundle({privateKeyPem:u.expose(),kid:g,appId:s,version:a,bundleStream:y,role:t.asCertifier?"certifier":"developer",scopes:p}),h=t.output?Kn(r,t.output):$d(Fd(l),`${Rd(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(h,m.token,"utf-8"),console.log(`\u2705 Signed: ${h}`),console.log(` kid: ${m.kid}`),console.log(` bundle: ${m.payload.bundleSha256}`),console.log(` scopes: ${m.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
166
- Payload:`,JSON.stringify(m.payload,null,2));let S=Array.from(new Set([...i.discoverSignatures(l),m.token])),A=t.interactive?await $(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):T(c.deployments,t.deployment);if(!t.browserAuth&&!i.isSessionAuthEnabled()){let v=F(A);if(v.length>0)throw new Error(`Deployment ${A.org}/${A.project} is missing ${v.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(A,s,a,S,t),console.log(`
167
- To publish: npx @cognite/cli apps publish .`)}o(Di,"handleSign");function Ii(e,t={}){let n=t.isSessionAuthEnabled??E,r=e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)");return n()&&U().forEach(i=>r.addOption(i)),r.action((i,s)=>{let a={...s,appid:s.identifier??s.appid,scope:s.requirements??s.scope};return Di(i,a,t)})}o(Ii,"registerSignCommand");function Nd(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Nd,"describeStatus");function Hd(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let r=n.status==="VALID"?"\u2705":"\u274C",i=new Date(n.signatureIat).toISOString();t.push(` ${r} ${n.signerKid} (${n.signerRole}, signed ${i}) \u2014 ${n.status}`)}return t}o(Hd,"formatSignatures");async function Kd(e,t,n){let r=await K(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod});return new I(r)}o(Kd,"defaultBuildApiClient");async function jd(e,t={}){let{loadEnvFile:n=O,loadAppConfig:r=b,getApiClient:i=Kd,isSessionAuthEnabled:s=E}=t,a=process.cwd();n(a);let p=r(a);M(p);let c=e.interactive?await $(p,e):T(p.deployments,e.deployment);if(!e.interactive&&!s()){let d=F(c);if(d.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${d.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p.externalId);console.log(""),console.log(`App: ${p.name} (${p.externalId})`),console.log(`Version: ${p.versionTag} (local)`);try{let d=await l.getVersion(p.externalId,p.versionTag);console.log(`Status: ${Nd(d)}`);let u=await Bd(l,p.externalId,p.versionTag);if(console.log(""),u==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let g of Hd(u))console.log(g);d.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(d){if(d instanceof V){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw d}}o(jd,"handleStatus");async function Bd(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ue(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}o(Bd,"fetchSignatures");function Ti(e,t={isSessionAuthEnabled:E}){let n=e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)");return t.isSessionAuthEnabled()&&n.addOption(vn()),n.addHelpText("after",`
284
+ `)}`);let{privateKeyPem:u,kid:g}=await i.resolvePrivateKey({keyPath:t.key?br(o,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),h=i.createBundleStream(p),f=await i.signBundle({privateKeyPem:u.expose(),kid:g,appId:s,version:a,bundleStream:h,role:t.asCertifier?"certifier":"developer",scopes:c}),y=t.output?br(o,t.output):ty(ey(p),`${Qh(p)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(y,f.token,"utf-8"),console.log(`\u2705 Signed: ${y}`),console.log(` kid: ${f.kid}`),console.log(` bundle: ${f.payload.bundleSha256}`),console.log(` scopes: ${f.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
285
+ Payload:`,JSON.stringify(f.payload,null,2));let S=Array.from(new Set([...i.discoverSignatures(p),f.token])),w=t.interactive?await F(l,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):$(l.deployments,t.deployment);await i.submitSignatures(w,s,a,S,t),console.log(`
286
+ To publish: npx @cognite/cli apps publish .`)}r(Bc,"handleSign");function Kc(e,t={}){let n=e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)");return J().forEach(o=>n.addOption(o)),n.action((o,i)=>{let s={...i,appid:i.identifier??i.appid,scope:i.requirements??i.scope};return Bc(o,s,t)})}r(Kc,"registerSignCommand");function ay(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}r(ay,"describeStatus");function cy(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let o=n.status==="VALID"?"\u2705":"\u274C",i=new Date(n.signatureIat).toISOString();t.push(` ${o} ${n.signerKid} (${n.signerRole}, signed ${i}) \u2014 ${n.status}`)}return t}r(cy,"formatSignatures");async function ly(e,t,n){let o=await _(e,{interactive:t.interactive,appId:n,orgHint:t.org,authMethod:t.authMethod});return new M(o)}r(ly,"defaultBuildApiClient");async function py(e,t={}){let{loadEnvFile:n=j,loadAppConfig:o=k,getApiClient:i=ly}=t,s=process.cwd();n(s);let a=o(s);H(a);let c=e.interactive?await F(a,e):$(a.deployments,e.deployment),l=await i(c,e,a.externalId);console.log(""),console.log(`App: ${a.name} (${a.externalId})`),console.log(`Version: ${a.versionTag} (local)`);try{let p=await l.getVersion(a.externalId,a.versionTag);console.log(`Status: ${ay(p)}`);let d=await dy(l,a.externalId,a.versionTag);if(console.log(""),d==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let u of cy(d))console.log(u);p.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(p){if(p instanceof oe){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw p}}r(py,"handleStatus");async function dy(e,t,n){try{return await e.listSignatures(t,n)}catch(o){if(ae(o)&&o.status===404||o instanceof Error&&/status code: 404/.test(o.message))return"endpoint-unavailable";throw o}}r(dy,"fetchSignatures");function Vc(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addOption(sr()).addHelpText("after",`
168
287
  Examples:
169
288
  npx @cognite/cli apps status . Status using env-var auth
170
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((r,i)=>jd(i))}o(Ti,"registerStatusCommand");import{execFileSync as Vn}from"child_process";import Bn from"fs";import Ue from"path";import qd from"readline";var Ri="https://cognite.zendesk.com",Vd="360001234312",Gd="tf_360015295097",Yd="cognite_flows_certifications";function Fi(e,t,n){let r=new URLSearchParams({ticket_form_id:Vd,tf_priority:"normal",tf_subject:e,[Gd]:Yd,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}o(Fi,"buildUrl");function $i(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o($i,"escapeHtml");function jn(e){return e.map($i).join("<br>")}o(jn,"toHtml");function Oi(e,t=Ri){let{appName:n,externalId:r,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${r}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${r}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return Fi(`App Review Request: ${n}`,jn(l.filter(d=>d!==void 0)),t)}o(Oi,"buildAppReviewUrl");function Mi(e,t,n,r,i=Ri){let s=jn(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${$i(r.replace(/\r\n/g,`
171
- `))}</pre>`,p=jn(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Fi(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(Mi,"buildKeyRegistrationUrl");function zd(){return new Promise(e=>{let t=qd.createInterface({input:process.stdin,output:process.stdout});t.question(`
172
- Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(zd,"defaultPressEnter");var Wd=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function Jd(e){let t=Wd.filter(({pattern:n})=>Vn("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:r,skill:i})=>` ${r} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
289
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((n,o)=>py(o))}r(Vc,"registerStatusCommand");import{execFileSync as Pr}from"child_process";import kr from"fs";import At from"path";import fy from"readline";var Gc="https://cognite.zendesk.com",uy="360001234312",my="tf_360015295097",gy="cognite_flows_certifications";function Yc(e,t,n){let o=new URLSearchParams({ticket_form_id:uy,tf_priority:"normal",tf_subject:e,[my]:gy,tf_description:t});return`${n}/hc/en-us/requests/new?${o}`}r(Yc,"buildUrl");function zc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}r(zc,"escapeHtml");function xr(e){return e.map(zc).join("<br>")}r(xr,"toHtml");function qc(e,t=Gc){let{appName:n,externalId:o,versionTag:i,archiveName:s,developerName:a,cdfProject:c,cdfCluster:l}=e,p=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${o}`,`Version: ${i}`,c?`CDF project: ${c}`:void 0,l?`CDF cluster: ${l}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${o}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return Yc(`App Review Request: ${n}`,xr(p.filter(d=>d!==void 0)),t)}r(qc,"buildAppReviewUrl");function Jc(e,t,n,o,i=Gc){let s=xr(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${zc(o.replace(/\r\n/g,`
290
+ `))}</pre>`,c=xr(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Yc(`Public Key Registration: ${t}`,`${s}<br>${a}${c}`,i)}r(Jc,"buildKeyRegistrationUrl");function hy(){return new Promise(e=>{let t=fy.createInterface({input:process.stdin,output:process.stdout});t.question(`
291
+ Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}r(hy,"defaultPressEnter");var yy=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function Sy(e){let t=yy.filter(({pattern:n})=>Pr("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:o,skill:i})=>` ${o} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
173
292
 
174
293
  `+n.join(`
175
- `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(Jd,"assertArtifactsCommitted");var Xd="\u2197 Launched your browser \u2014 look for a new tab with the Zendesk form.";async function Zd(e=process.cwd(),t={}){let{openInBrowser:n=Ir,revealInFileManager:r=Tr,pressEnter:i=zd,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(q(),!Ve(e))throw new Error("Not a git repository. Run this command from your app's root directory.");O(e);let a=b(e);M(a),Jd(e);let p=Ue.join(e,"dist","submit");Bn.mkdirSync(p,{recursive:!0});let c=Vn("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Vn("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
176
-
177
- The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,u=Ue.join(p,d);await new Q(Ue.join(e,"dist")).createSourceArchive(u);let y=`${a.externalId}-${a.versionTag}.zip`,m=Ue.join(e,".cognite-bundles",y),h=!1;Bn.existsSync(m)&&(Bn.copyFileSync(m,Ue.join(p,y)),h=!0);let S=Oi({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:pr(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});if(console.log(`
178
- \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(h?` ${y} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
179
- Attach all files from dist/submit/ to the Zendesk ticket.`),s()){await i();let A=n(S);r(u),A&&(console.log(`
180
- ${Xd}`),console.log(" If nothing opened, submit here:"),console.log(` \u{1F517} ${S}`))}else console.log(`
181
- \u{1F517} ${S}`)}o(Zd,"handleSubmit");function _i(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
182
- Examples:
183
- npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Zd())}o(_i,"registerSubmitCommand");function Ui(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return ri(t),ci(t),fi(t),Ti(t),gi(t),yi(t),No(t),oi(t),ii(t),Si(t),_i(t),ei(t),Ii(t),Yr(t),t}o(Ui,"registerAppsCommand");import Gn from"enquirer";function Qd(e){return{loadAppConfig:e.loadAppConfig??b,cwd:e.cwd??(()=>process.cwd()),loginForSession:e.loginForSession??(t=>ho(t)),writeSession:e.writeSession??(t=>mt(t)),readSessionMetadata:e.readSessionMetadata??(()=>fe()),clearSession:e.clearSession??(()=>ft()),promptSelectOrg:e.promptSelectOrg??eu,promptOrg:e.promptOrg??tu,promptConfirm:e.promptConfirm??nu,logger:e.logger??console,platform:e.platform??process.platform}}o(Qd,"resolveDeps");async function eu(e){let{selected:t}=await Gn.prompt({type:"select",name:"selected",message:"Select the organization to sign in to",choices:e});return t}o(eu,"defaultPromptSelectOrg");async function tu(){let{org:e}=await Gn.prompt({type:"input",name:"org",message:"Enter your organization name",validate:o(t=>t.trim().length>0?!0:"Organization name is required","validate")});return e.trim()}o(tu,"defaultPromptOrg");async function nu(e){let{confirmed:t}=await Gn.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}o(nu,"defaultPromptConfirm");function ru(e){if(e.port===void 0)return;let t=Number(e.port);if(!it(t))throw new f(st(e.port));return t}o(ru,"resolvePort");async function ou(e,t){let{logger:n,promptSelectOrg:r,promptOrg:i}=t;if(e.org)return e.org;let s=iu(t);if(s){let a=[...new Set(s.deployments.map(p=>p.org))];return a.length===1?(n.log(`Resolved organization from app.json: ${a[0]}`),a[0]):r(a)}return i()}o(ou,"resolveOrg");function iu(e){let{loadAppConfig:t,cwd:n}=e;try{return t(n())}catch(r){let i=r instanceof Error?r.message:String(r);if(/No app\.json found/.test(i))return null;throw r}}o(iu,"tryLoadAppConfig");function su(e){switch(e){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}o(su,"keyringBackendLabel");function au(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){if("code"in t&&t.code==="ERR_DLOPEN_FAILED")return!0;let r="message"in t&&typeof t.message=="string"?t.message:null;if(r&&/cannot find native binding/i.test(r))return!0;t="cause"in t?t.cause:void 0}return!1}o(au,"isNativeModuleLoadError");async function pu(e,t){let{logger:n,loginForSession:r,writeSession:i,readSessionMetadata:s,clearSession:a,promptConfirm:p,platform:c}=t,l=ru(e),d=s();if(d){if(!e.force&&ge(d)!=="EXPIRED"&&!await p(`A session for organization "${d.org}" already exists. Replace it?`)){n.error("Aborted.");return}await a()}let u=await ou(e,t),g=await r({org:u,port:l});try{await i(g)}catch(m){if(au(m)){let h=c==="win32"?"Install the Microsoft Visual C++ Redistributable from https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist and restart your terminal, then run `cognite auth login` again.":"Ensure the required system libraries are installed for your platform, then run `cognite auth login` again.";throw new f("The keyring native module could not be loaded \u2014 tokens were not persisted.",{hint:h,cause:m})}throw new f("Login succeeded but tokens could not be saved to the credential store.",{hint:`Ensure a credential store (${su(c)}) is available and unlocked, then run \`cognite auth login\` again.`,cause:m})}let y=re(process.stdout);n.log(""),n.log(`${y.green("\u2713")} Signed in to organization ${g.org}`)}o(pu,"handleLogin");function cu(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}o(cu,"getOrCreateAuthGroup");function Li(e,t={}){let n=Qd(t);cu(e).command("login").description("Sign in via the browser and persist a refreshable session").option("--org <org>","Organization to sign in to (resolved from app.json or prompted when omitted)").option("--force","Replace an existing session without prompting").option("--port <port>",`Pin the local callback port for the OAuth redirect (${De}). Defaults to 3000.`).action(i=>pu(i,n))}o(Li,"registerAuthLoginCommand");function lu(e){return{readSession:e.readSession??(()=>Te()),readSessionMetadata:e.readSessionMetadata??(()=>fe()),clearSession:e.clearSession??(()=>ft()),revokeRefreshToken:e.revokeRefreshToken??(t=>So(t)),logger:e.logger??console}}o(lu,"resolveDeps");async function du(e){let{readSessionMetadata:t,readSession:n,clearSession:r,revokeRefreshToken:i,logger:s}=e,a=null;try{a=t()}catch{await r(),s.log("Cleared corrupt session.");return}if(!a){s.log("No active session.");return}let p;try{p=(await n())?.refreshToken}catch{}if(await r(),p)try{await i(p)}catch{s.error("Logged out locally, but revoking the token at the identity provider failed. It may remain valid until it expires naturally."),s.log("Logged out.");return}s.log("Logged out.")}o(du,"handleLogout");function uu(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}o(uu,"getOrCreateAuthGroup");function Ni(e,t={}){let n=lu(t);uu(e).command("logout").description("Revoke and remove the persisted session").action(()=>du(n))}o(Ni,"registerAuthLogoutCommand");var mu="auth.cognite.com";function fu(e){return{ensureFreshSession:e.ensureFreshSession??ht,fetchUserInfo:e.fetchUserInfo??(t=>Ao(t)),logger:e.logger??console}}o(fu,"resolveDeps");function gu(e){return e.email??e.preferredUsername??e.name??e.sub}o(gu,"describeUser");var yu="(unknown cluster)";function hu(e,t){if(e.length===0)return[" - Projects: (none)"];let n=new Map;for(let i of e){let s=i.cluster??yu,a=n.get(s);a?a.push(i):n.set(s,[i])}let r=[` - Projects (${e.length}):`];for(let[i,s]of n){r.push(` ${t.dim(i)}`);for(let a of s){let p=a.isDefault?` ${t.green("[default]")}`:"";r.push(` ${a.name}${p}`)}}return r}o(hu,"formatProjects");function Su(){switch(process.platform){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}o(Su,"keyringBackendLabel");async function wu(e){let{ensureFreshSession:t,fetchUserInfo:n,logger:r}=e,i;try{i=await t()}catch(s){if(s instanceof Re){r.error(" Session expired. Run `npx @cognite/cli auth login` to sign in again."),process.exitCode=1;return}throw s}if(!i){r.error("Not signed in. Run `npx @cognite/cli auth login` to start a session."),process.exitCode=1;return}r.log(i.org);try{let s=await n(i),a=re(process.stdout);r.log(` ${a.green("\u2713")} Signed in as ${gu(s)}`);for(let p of hu(s.projects,a))r.log(p);r.log(` - Token storage: ${Su()}`)}catch(s){if(s instanceof Ee&&s.kind==="unreachable")r.error(` \u2717 Couldn't reach Cognite (${mu}): ${s.message}`),r.error(" Check your network connection, or run `npx @cognite/cli auth login` to sign in again.");else{let a=s instanceof Error?s.message:String(s);r.error(` \u2717 ${a}`),r.error(" Run `npx @cognite/cli auth login` to sign in again.")}process.exitCode=1}}o(wu,"handleStatus");function vu(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}o(vu,"getOrCreateAuthGroup");function Hi(e,t={}){let n=fu(t);vu(e).command("status").alias("whoami").description("Show the active session, verified against the identity provider").action(()=>wu(n))}o(Hi,"registerAuthStatusCommand");import{existsSync as bu,mkdirSync as ku,writeFileSync as Pu}from"fs";import{dirname as zn,join as Le}from"path";import{generateSigningKeyPair as xu}from"@cognite/app-sdk/codesigning";import Du from"open";function Ki(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,s))}o(Ki,"addMonthsClamped");function Yn(e){return e.toISOString().slice(0,10)}o(Yn,"formatIsoDate");function ji(e=new Date){return Yn(e)}o(ji,"todayIso");var Ft=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),Bi=32,Vi=44,Gi=60,Au="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Cu(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==Vi&&t.length!==Gi)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${Vi} (raw) or ${Gi} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Ft.length+Bi&&n.subarray(0,Ft.length).equals(Ft))return n.subarray(Ft.length).toString("base64");if(n.length===Bi)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(Cu,"pemBodyOneLine");function qn(e,t=Me,n=new Date){let r=Yi(e.issuedAt??ji(n)),i=Yi(e.expires),s=Cu(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
184
- `,"kv"),c="";return c+=`
185
- ${t.bold("Add this entry to")} ${t.magenta(Au)} ${t.bold("under")} ${t.cyan("publicKeys:")}
186
-
187
- `,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
188
- `,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(r)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(qn,"renderRegistryYamlBlock");function Yi(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}o(Yi,"toIsoInstant");import Eu from"clipboardy";function qi(e){return Eu.write(e)}o(qi,"copyToClipboard");function zi(e,t){return e.map((n,r)=>Math.max(n.length,...t.map(i=>i[r].length)))}o(zi,"computeColumnWidths");function Wi(e,t,n=e){return e.map((r,i)=>n[i]+" ".repeat(Math.max(0,t[i]-r.length))).join(" ").trimEnd()}o(Wi,"formatTableRow");function Iu(e){return{writeFileSync:e.writeFileSync??Pu,mkdirSync:e.mkdirSync??ku,existsSync:e.existsSync??bu,generateSigningKeyPair:e.generateSigningKeyPair??xu,encryptStringAsJwe:e.encryptStringAsJwe??Ai,storeKeyInKeychain:e.storeKeyInKeychain??$r,storeSigningKey:e.storeSigningKey??Lr,isOS:e.isOS??(t=>N(t)),promptKid:e.promptKid??Cr,promptExpiryMonths:e.promptExpiryMonths??br,promptEmail:e.promptEmail??kr,promptPassphrase:e.promptPassphrase??Pr,promptConfirmOverwrite:e.promptConfirmOverwrite??xr,discoverLocalKeys:e.discoverLocalKeys??(()=>Xe()),promptZendeskAction:e.promptZendeskAction??Er,openUrl:e.openUrl??(t=>Du(t)),copyToClipboard:e.copyToClipboard??qi}}o(Iu,"resolveDeps");function Xi(e,t={}){let n=Iu(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip the OS credential store (macOS Keychain / Windows Credential Manager) and write a passphrase-encrypted private key under ${P().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>$u(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Tu(n))}o(Xi,"registerKeysCommand");async function Tu(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
189
- `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${P().keysDir}).
190
- `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Je(a.source),a.email??"\u2014"]),i=zi(n,r),s=o(a=>Wi(a,i),"fmt");process.stdout.write(`${s(n)}
191
- `);for(let a of r)process.stdout.write(`${s(a)}
192
- `)}o(Tu,"handleList");function Ji(e,t,n){let r=Le(P().keysDir,`${e}${ee}`);return n.mkdirSync(zn(r),{recursive:!0}),n.writeFileSync(r,t),r}o(Ji,"writePublicKey");async function Ru(e,t,n,r,i,{force:s=!1}={}){let a=r??Le(P().keysDir,`${e}${Yt}`);if(i.mkdirSync(zn(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,n);return i.writeFileSync(a,p,{mode:384}),a}o(Ru,"writeEncryptedPrivateKey");function Fu(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{we(e.expires)}catch(i){r.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)r.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=de(e.kid),s=Le(P().keysDir,`${i}${ee}`);n(s)&&!e.force&&r.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){r.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)r.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{Se(e.email,"--email")}catch(i){r.push(i instanceof Error?i.message:String(i))}return t||r.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),r}o(Fu,"collectNonInteractiveErrors");async function $u(e,t,n=new Date){let{isOS:r,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,storeSigningKey:l,promptExpiryMonths:d,promptKid:u,promptEmail:g,promptPassphrase:y,promptConfirmOverwrite:m}=t,h=e.interactive??!1,S=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!h){let Y=Fu(e,S,i);if(Y.length>0)throw new Error(Y.join(`
193
- `))}let A;e.expires!==void 0?A=we(e.expires):A=await d();let v=Yn(Ki(n,A)),w;e.kid!==void 0?w=de(e.kid):w=await u();let D=Le(P().keysDir,`${w}${ee}`),G=i(D);if(G&&!e.force&&!await m(w)){process.stderr.write(`Aborted.
194
- `);return}let x;e.email!==void 0?x=Se(e.email,"--email"):x=await g();let k=S?{kind:"keychain"}:{kind:"file",passphrase:await y()};process.stderr.write(`
294
+ `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}r(Sy,"assertArtifactsCommitted");var wy="\u2197 Launched your browser \u2014 look for a new tab with the Zendesk form.";async function vy(e=process.cwd(),t={}){let{openInBrowser:n=mn,revealInFileManager:o=la,pressEnter:i=hy,isInteractive:s=r(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(Ae(),!yn(e))throw new Error("Not a git repository. Run this command from your app's root directory.");j(e);let a=k(e);H(a),Sy(e);let c=At.join(e,"dist","submit");kr.mkdirSync(c,{recursive:!0});let l=Pr("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Pr("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
295
+
296
+ The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${l}.zip`,u=At.join(c,d);await new Te(At.join(e,"dist")).createSourceArchive(u);let h=`${a.externalId}-${a.versionTag}.zip`,f=At.join(e,".cognite-bundles",h),y=!1;kr.existsSync(f)&&(kr.copyFileSync(f,At.join(c,h)),y=!0);let S=qc({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:Sa(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});if(console.log(`
297
+ \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${l})`),console.log(y?` ${h} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
298
+ Attach all files from dist/submit/ to the Zendesk ticket.`),s()){await i();let w=n(S);o(u),w&&(console.log(`
299
+ ${wy}`),console.log(" If nothing opened, submit here:"),console.log(` \u{1F517} ${S}`))}else console.log(`
300
+ \u{1F517} ${S}`)}r(vy,"handleSubmit");function Wc(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
301
+ Examples:
302
+ npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>vy())}r(Wc,"registerSubmitCommand");function Zc(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return fc(t),Ec(t),Tc(t),Vc(t),Rc(t),Ic(t),Za(t),hc(t),yc(t),$c(t),Wc(t),uc(t),Kc(t),Ja(t),t}r(Zc,"registerAppsCommand");import Tr from"enquirer";function Cy(e){return{loadAppConfig:e.loadAppConfig??k,cwd:e.cwd??(()=>process.cwd()),loginForSession:e.loginForSession??(t=>Oi(t)),writeSession:e.writeSession??(t=>Ut(t)),readSessionMetadata:e.readSessionMetadata??(()=>xe()),clearSession:e.clearSession??(()=>Nt()),promptSelectOrg:e.promptSelectOrg??Ay,promptOrg:e.promptOrg??Ey,promptConfirm:e.promptConfirm??by,logger:e.logger??console,platform:e.platform??process.platform}}r(Cy,"resolveDeps");async function Ay(e){let{selected:t}=await Tr.prompt({type:"select",name:"selected",message:"Select the organization to sign in to",choices:e});return t}r(Ay,"defaultPromptSelectOrg");async function Ey(){let{org:e}=await Tr.prompt({type:"input",name:"org",message:"Enter your organization name",validate:r(t=>t.trim().length>0?!0:"Organization name is required","validate")});return e.trim()}r(Ey,"defaultPromptOrg");async function by(e){let{confirmed:t}=await Tr.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}r(by,"defaultPromptConfirm");function xy(e){if(e.port===void 0)return;let t=Number(e.port);if(!Ht(t))throw new m(Bt(e.port));return t}r(xy,"resolvePort");async function ky(e,t){let{logger:n,promptSelectOrg:o,promptOrg:i}=t;if(e.org)return e.org;let s=Py(t);if(s){let a=[...new Set(s.deployments.map(c=>c.org))];return a.length===1?(n.log(`Resolved organization from app.json: ${a[0]}`),a[0]):o(a)}return i()}r(ky,"resolveOrg");function Py(e){let{loadAppConfig:t,cwd:n}=e;try{return t(n())}catch(o){let i=o instanceof Error?o.message:String(o);if(/No app\.json found/.test(i))return null;throw o}}r(Py,"tryLoadAppConfig");function Ty(e){switch(e){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}r(Ty,"keyringBackendLabel");function Ry(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){if("code"in t&&t.code==="ERR_DLOPEN_FAILED")return!0;let o="message"in t&&typeof t.message=="string"?t.message:null;if(o&&/cannot find native binding/i.test(o))return!0;t="cause"in t?t.cause:void 0}return!1}r(Ry,"isNativeModuleLoadError");async function Iy(e,t){let{logger:n,loginForSession:o,writeSession:i,readSessionMetadata:s,clearSession:a,promptConfirm:c,platform:l}=t,p=xy(e),d=s();if(d){if(!e.force&&je(d)!=="EXPIRED"&&!await c(`A session for organization "${d.org}" already exists. Replace it?`)){n.error("Aborted.");return}await a()}let u=await ky(e,t),g=await o({org:u,port:p});try{await i(g)}catch(f){if(Ry(f)){let y=l==="win32"?"Install the Microsoft Visual C++ Redistributable from https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist and restart your terminal, then run `cognite auth login` again.":"Ensure the required system libraries are installed for your platform, then run `cognite auth login` again.";throw new m("The keyring native module could not be loaded \u2014 tokens were not persisted.",{hint:y,cause:f})}throw new m("Login succeeded but tokens could not be saved to the credential store.",{hint:`Ensure a credential store (${Ty(l)}) is available and unlocked, then run \`cognite auth login\` again.`,cause:f})}let h=P(process.stdout);n.log(""),n.log(`${h.green("\u2713")} Signed in to organization ${g.org}`)}r(Iy,"handleLogin");function Dy(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(Dy,"getOrCreateAuthGroup");function Xc(e,t={}){let n=Cy(t);Dy(e).command("login").description("Sign in via the browser and persist a refreshable session").option("--org <org>","Organization to sign in to (resolved from app.json or prompted when omitted)").option("--force","Replace an existing session without prompting").option("--port <port>",`Pin the local callback port for the OAuth redirect (${dt}). Defaults to 3000.`).action(i=>Iy(i,n))}r(Xc,"registerAuthLoginCommand");function $y(e){return{readSession:e.readSession??(()=>lt()),readSessionMetadata:e.readSessionMetadata??(()=>xe()),clearSession:e.clearSession??(()=>Nt()),revokeRefreshToken:e.revokeRefreshToken??(t=>Fi(t)),logger:e.logger??console}}r($y,"resolveDeps");async function Oy(e){let{readSessionMetadata:t,readSession:n,clearSession:o,revokeRefreshToken:i,logger:s}=e,a=null;try{a=t()}catch{await o(),s.log("Cleared corrupt session.");return}if(!a){s.log("No active session.");return}let c;try{c=(await n())?.refreshToken}catch{}if(await o(),c)try{await i(c)}catch{s.error("Logged out locally, but revoking the token at the identity provider failed. It may remain valid until it expires naturally."),s.log("Logged out.");return}s.log("Logged out.")}r(Oy,"handleLogout");function Fy(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(Fy,"getOrCreateAuthGroup");function Qc(e,t={}){let n=$y(t);Fy(e).command("logout").description("Revoke and remove the persisted session").action(()=>Oy(n))}r(Qc,"registerAuthLogoutCommand");var Ly="auth.cognite.com";function My(e){return{ensureFreshSession:e.ensureFreshSession??We,fetchUserInfo:e.fetchUserInfo??(t=>Yt(t)),logger:e.logger??console}}r(My,"resolveDeps");function Uy(e){return e.email??e.preferredUsername??e.name??e.sub}r(Uy,"describeUser");var Ny="(unknown cluster)";function _y(e,t){if(e.length===0)return[" - Projects: (none)"];let n=new Map;for(let i of e){let s=i.cluster??Ny,a=n.get(s);a?a.push(i):n.set(s,[i])}let o=[` - Projects (${e.length}):`];for(let[i,s]of n){o.push(` ${t.dim(i)}`);for(let a of s){let c=a.isDefault?` ${t.green("[default]")}`:"";o.push(` ${a.name}${c}`)}}return o}r(_y,"formatProjects");function jy(){switch(process.platform){case"darwin":return"macOS Keychain";case"win32":return"Windows Credential Manager";default:return"Secret Service (libsecret / KWallet)"}}r(jy,"keyringBackendLabel");async function Hy(e){let{ensureFreshSession:t,fetchUserInfo:n,logger:o}=e,i;try{i=await t()}catch(s){if(s instanceof He){o.error(" Session expired. Run `npx @cognite/cli auth login` to sign in again."),process.exitCode=1;return}throw s}if(!i){o.error("Not signed in. Run `npx @cognite/cli auth login` to start a session."),process.exitCode=1;return}o.log(i.org);try{let s=await n(i),a=P(process.stdout);o.log(` ${a.green("\u2713")} Signed in as ${Uy(s)}`);for(let c of _y(s.projects,a))o.log(c);o.log(` - Token storage: ${jy()}`)}catch(s){if(s instanceof Je&&s.kind==="unreachable")o.error(` \u2717 Couldn't reach Cognite (${Ly}): ${s.message}`),o.error(" Check your network connection, or run `npx @cognite/cli auth login` to sign in again.");else{let a=s instanceof Error?s.message:String(s);o.error(` \u2717 ${a}`),o.error(" Run `npx @cognite/cli auth login` to sign in again.")}process.exitCode=1}}r(Hy,"handleStatus");function By(e){return e.commands.find(t=>t.name()==="auth")??e.command("auth").description("Manage your persisted CDF login session")}r(By,"getOrCreateAuthGroup");function el(e,t={}){let n=My(t);By(e).command("status").alias("whoami").description("Show the active session, verified against the identity provider").action(()=>Hy(n))}r(el,"registerAuthStatusCommand");import{existsSync as Yy,mkdirSync as zy,writeFileSync as qy}from"fs";import{dirname as Dr,join as Et}from"path";import{generateSigningKeyPair as Jy}from"@cognite/app-sdk/codesigning";import Wy from"open";function tl(e,t){let n=e.getUTCFullYear(),o=e.getUTCMonth()+t,i=new Date(Date.UTC(n,o+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,o,s))}r(tl,"addMonthsClamped");function Rr(e){return e.toISOString().slice(0,10)}r(Rr,"formatIsoDate");function nl(e=new Date){return Rr(e)}r(nl,"todayIso");var Un=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ol=32,rl=44,il=60,Ky="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Vy(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==rl&&t.length!==il)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${rl} (raw) or ${il} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Un.length+ol&&n.subarray(0,Un.length).equals(Un))return n.subarray(Un.length).toString("base64");if(n.length===ol)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}r(Vy,"pemBodyOneLine");function Ir(e,t=rt,n=new Date){let o=sl(e.issuedAt??nl(n)),i=sl(e.expires),s=Vy(e.publicKeyPem),a=" ",c=r((p,d)=>`${a}${t.cyan(p)}${t.dim(":")} ${d}
303
+ `,"kv"),l="";return l+=`
304
+ ${t.bold("Add this entry to")} ${t.magenta(Ky)} ${t.bold("under")} ${t.cyan("publicKeys:")}
305
+
306
+ `,l+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
307
+ `,l+=c("publicKey",t.green(s)),l+=c("email",t.yellow(e.email)),l+=c("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),l+=c("issuedAt",t.green(o)),l+=c("expiresAt",t.green(i)),l+=c("revokedAt",t.dim("null")),l}r(Ir,"renderRegistryYamlBlock");function sl(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}r(sl,"toIsoInstant");import Gy from"clipboardy";function al(e){return Gy.write(e)}r(al,"copyToClipboard");var cl=6;function Zy(e){return{writeFileSync:e.writeFileSync??qy,mkdirSync:e.mkdirSync??zy,existsSync:e.existsSync??Yy,generateSigningKeyPair:e.generateSigningKeyPair??Jy,encryptStringAsJwe:e.encryptStringAsJwe??Lc,storeKeyInKeychain:e.storeKeyInKeychain??_a,storeSigningKey:e.storeSigningKey??Va,isOS:e.isOS??(t=>X(t)),promptKid:e.promptKid??$a,promptEmail:e.promptEmail??Fa,promptPassphrase:e.promptPassphrase??La,promptConfirmOverwrite:e.promptConfirmOverwrite??Ma,discoverLocalKeys:e.discoverLocalKeys??(()=>An()),promptZendeskAction:e.promptZendeskAction??Oa,openUrl:e.openUrl??(t=>Wy(t)),copyToClipboard:e.copyToClipboard??al}}r(Zy,"resolveDeps");function pl(e,t={}){let n=Zy(t),o=e.command("keys").description("Manage code signing keys");o.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip the OS credential store (macOS Keychain / Windows Credential Manager) and write a passphrase-encrypted private key under ${D().keysDir} instead`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>tS(i,n)),o.command("list").description("List local signing identities and their storage location").action(()=>Xy(n))}r(pl,"registerKeysCommand");async function Xy(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
308
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${D().keysDir}).
309
+ `);return}let n=["KID","SOURCE","EMAIL"],o=t.map(a=>[a.kid,Cn(a.source),a.email??"\u2014"]),i=dn(n,o),s=r(a=>yt(a,i),"fmt");process.stdout.write(`${s(n)}
310
+ `);for(let a of o)process.stdout.write(`${s(a)}
311
+ `)}r(Xy,"handleList");function ll(e,t,n){let o=Et(D().keysDir,`${e}${Oe}`);return n.mkdirSync(Dr(o),{recursive:!0}),n.writeFileSync(o,t),o}r(ll,"writePublicKey");async function Qy(e,t,n,o,i,{force:s=!1}={}){let a=o??Et(D().keysDir,`${e}${rr}`);if(i.mkdirSync(Dr(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let c=await i.encryptStringAsJwe(t,n);return i.writeFileSync(a,c,{mode:384}),a}r(Qy,"writeEncryptedPrivateKey");function eS(e,t,n){let o=[];if(e.kid===void 0)o.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=Ge(e.kid),s=Et(D().keysDir,`${i}${Oe}`);n(s)&&!e.force&&o.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){o.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)o.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{tt(e.email,"--email")}catch(i){o.push(i instanceof Error?i.message:String(i))}return t||o.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),o}r(eS,"collectNonInteractiveErrors");async function tS(e,t,n=new Date){let{isOS:o,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:c,storeKeyInKeychain:l,storeSigningKey:p,promptKid:d,promptEmail:u,promptPassphrase:g,promptConfirmOverwrite:h}=t,f=e.interactive??!1,y=e.keychain!==!1&&!e.output&&(o("macos")||o("windows"));if(!f){let G=eS(e,y,i);if(G.length>0)throw new Error(G.join(`
312
+ `))}let S=Rr(tl(n,cl)),w;e.kid!==void 0?w=Ge(e.kid):w=await d();let v=Et(D().keysDir,`${w}${Oe}`),C=i(v);if(C&&!e.force&&!await h(w)){process.stderr.write(`Aborted.
313
+ `);return}let x;e.email!==void 0?x=tt(e.email,"--email"):x=await u();let L=y?{kind:"keychain"}:{kind:"file",passphrase:await g()};process.stderr.write(`
195
314
  Generating Ed25519 keypair...
196
315
 
197
- `);let{privateKeyPem:J,publicKeyPem:ie}=await p(w),_=C.from(J);if(k.kind==="keychain"){r("macos")?await c(w,_):await l(w,_);let Y=Ji(w,ie,t);process.stderr.write(`Public key: ${Y}
316
+ `);let{privateKeyPem:B,publicKeyPem:R}=await c(w),Z=b.from(B);if(L.kind==="keychain"){o("macos")?await l(w,Z):await p(w,Z);let G=ll(w,R,t);process.stderr.write(`Public key: ${G}
198
317
  `),process.stderr.write(`Private key: OS credential store (account: ${w})
199
- `)}else{let Y=await Ru(w,_,k.passphrase,e.output,t,{force:G}),Ss=Ji(w,ie,t);process.stderr.write(`Public key: ${Ss}
200
- `),process.stderr.write(`Private key: ${Y} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Hn.toLocaleString()})
201
- `)}let se=Le(P().keysDir,`${w}${qt}`);s(zn(se),{recursive:!0}),a(se,JSON.stringify({email:x}));let he=re(process.stderr);process.stderr.write(`
202
- Signing identity (kid): ${he.green(w)}
203
- `),process.stderr.write(`Expires: ${v} (${A} month${A===1?"":"s"} from today)
204
- `);let He={kid:w,publicKeyPem:ie,email:x,expires:v};h||(process.stderr.write(`
318
+ `)}else{let G=await Qy(w,Z,L.passphrase,e.output,t,{force:C}),ee=ll(w,R,t);process.stderr.write(`Public key: ${ee}
319
+ `),process.stderr.write(`Private key: ${G} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Er.toLocaleString()})
320
+ `)}let Q=Et(D().keysDir,`${w}${ir}`);s(Dr(Q),{recursive:!0}),a(Q,JSON.stringify({email:x}));let I=P(process.stderr);process.stderr.write(`
321
+ Signing identity (kid): ${I.green(w)}
322
+ `),process.stderr.write(`Expires: ${S} (${cl} months from today)
323
+ `);let N={kid:w,publicKeyPem:R,email:x,expires:S};f||(process.stderr.write(`
205
324
  Key registration data:
206
325
 
207
- `),process.stderr.write(qn(He,he,n)));let ae=Mi(w,x,v,qn(He,Me,n));process.stderr.write(`
208
- ${he.bold("Next:")}
326
+ `),process.stderr.write(Ir(N,I,n)));let ie=Jc(w,x,S,Ir(N,rt,n));process.stderr.write(`
327
+ ${I.bold("Next:")}
209
328
  `),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
210
- `);let Pe;if(e.copyLink?Pe="clipboard":h?Pe=await t.promptZendeskAction():Pe=null,Pe==="browser")try{await t.openUrl(ae),process.stderr.write(` Opening in browser...
211
- `)}catch{process.stderr.write(` URL: ${ae}
212
- `)}else if(Pe==="clipboard"){let Y=!1;try{await t.copyToClipboard(ae),Y=!0}catch{}process.stderr.write(Y&&!e.copyLink?` Link copied to clipboard.
213
- `:` URL: ${ae}
214
- `)}else process.stderr.write(` URL: ${ae}
329
+ `);let le;if(e.copyLink?le="clipboard":f?le=await t.promptZendeskAction():le=null,le==="browser")try{await t.openUrl(ie),process.stderr.write(` Opening in browser...
330
+ `)}catch{process.stderr.write(` URL: ${ie}
331
+ `)}else if(le==="clipboard"){let G=!1;try{await t.copyToClipboard(ie),G=!0}catch{}process.stderr.write(G&&!e.copyLink?` Link copied to clipboard.
332
+ `:` URL: ${ie}
333
+ `)}else process.stderr.write(` URL: ${ie}
215
334
  `);process.stderr.write(`
216
335
  2. Once your key is approved, sign your Dune app:
217
- `),process.stderr.write(` ${he.cyan(`cognite sign -s ${w}`)}
218
- `)}o($u,"handleGenerate");function Zi(e,t={}){let{isSessionAuthEnabled:n=E}=t;return Ui(e),n()&&(Li(e),Ni(e),Hi(e)),Xi(e),e}o(Zi,"registerCommands");import{performance as Qi}from"perf_hooks";var es=1e3,$t;function Ou(){$t=Qi.now()}o(Ou,"markActionStart");function Mu(){$t=void 0}o(Mu,"resetActionStart");function _u(){if($t!==void 0)return Math.max(0,Math.round(Qi.now()-$t))}o(_u,"snapshotActionDurationMs");function ts(){let e=_u();return Mu(),{...e!==void 0&&{actionDurationMs:e}}}o(ts,"takePerformanceFields");var Uu=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description","externalId"]);function Lu(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Uu.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Lu,"sanitizeOptions");function Nu(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(Nu,"getCommandPath");function ns(e){try{let t=e(process.cwd()),n=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...n&&{cogniteOrg:n.org,cogniteProject:n.project}}}catch{return{}}}o(ns,"tryLoadAppConfig");function Wn(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(Wn,"commandFromArgv");function rs(e,t,n=b){e.hook("preAction",()=>{Ou()}),e.hook("postAction",async(r,i)=>{try{let s={command:Nu(i),options:Lu(i.opts()),success:!0,...ns(n),...ts()};t.track("Flows.CLI.Command",{...s}),await t.flush(es)}catch{}})}o(rs,"instrument");async function os(e,t,n=b){try{let r={command:Wn(t),options:{},success:!1,...ns(n),...ts()};e.track("Flows.CLI.Command",{...r}),await e.flush(es)}catch{}}o(os,"trackFailure");var Hu="ERR_USE_AFTER_CLOSE";function ss(e){return e instanceof Error&&"code"in e&&e.code===Hu}o(ss,"isReadlineClosedError");function Ku(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Ku,"isPlainObject");function Jn(e){return e==null||ss(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Ku(e)&&Object.keys(e).length===0)}o(Jn,"isPromptCancel");var is=!1;function as(){is||(is=!0,process.on("uncaughtException",e=>{ss(e)&&(console.error(`
219
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Jn(e)&&(console.error(`
220
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(as,"installCancelHandler");import{homedir as ju,userInfo as Bu}from"os";var Vu=ju(),Gu=(()=>{try{return Bu().username}catch{return""}})();function ke(e,t=Vu){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}o(ke,"redactHomedir");function Yu(e,t=Gu){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(r,"$1<user>")}o(Yu,"redactUsername");var qu=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function ps(e){return e.replace(qu,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}o(ps,"redactCredentials");var zu=1e3,Wu="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Ju={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Xu(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Xu,"buildRelease");var Zu="192.0.2.0";function Qu(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:ke(t.filename)},...t.abs_path!==void 0&&{abs_path:ke(t.abs_path)},...t.module!==void 0&&{module:ke(t.module)}}))}o(Qu,"scrubStackFrames");function Ot(e){return ps(Yu(ke(e)))}o(Ot,"redactPii");function em(e){let t={...e.user,email:void 0,username:void 0,ip_address:Zu,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Ot(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Qu(s.stacktrace.frames)}}})),r=e.contexts?.cli,i=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?Ot(a):a])):void 0;return{...e,message:e.message!==void 0?Ot(e.message):e.message,...typeof e.culprit=="string"&&{culprit:Ot(e.culprit)},user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(em,"scrubPii");function cs(e={}){let t=e.env??process.env;if(sn(t))return Ju;let n=Xu(e),r="production",i=null,s=null;function a(){return{dsn:Wu,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:xe},contexts:{cli:{applicationId:xe,node:process.version,platform:process.platform}}},beforeSend:em}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,tm(c,l))}catch{}},async flush(c=zu){try{if(!i)return;await i.flush(c)}catch{}}}}o(cs,"createErrorReporter");function tm(e,t){let n={level:"fatal"},r={applicationId:xe,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),ir(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},sr(e)&&(n.contexts.http={url:e.requestUrl!==void 0?ke(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:ps(ke(i))}}return n}o(tm,"buildCaptureContext");import{mkdirSync as nm,readFileSync as rm,writeFileSync as om}from"fs";import{homedir as im}from"os";import{resolve as Mt}from"path";import{debuglog as sm}from"util";import{lt as am,parse as ls}from"semver";var pm="https://registry.npmjs.org/@cognite/cli/latest",cm=1500,ds="upgrade-check.json",us=Mt(process.env.XDG_CACHE_HOME||Mt(im(),".cache"),"@cognite","cli"),Xn=sm("cognite-flows");function lm(e,t){return!e||!t||!ls(e)||!ls(t)?!1:am(e,t)}o(lm,"isOutdated");async function dm({timeout:e=cm,registryUrl:t=pm,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let i=await r.json();return typeof i?.version=="string"?i.version:null}catch(r){return Xn("fetchLatestVersion failed (%s): %O",t,r),null}}o(dm,"fetchLatestVersion");function um(e=us,t=864e5){try{let n=rm(Mt(e,ds),"utf-8"),r=JSON.parse(n);return typeof r.latest!="string"||typeof r.fetchedAt!="number"||Date.now()-r.fetchedAt>t?null:{latest:r.latest,fetchedAt:r.fetchedAt}}catch(n){return Xn("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(um,"readUpgradeCheckCache");function mm(e,t){try{nm(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};om(Mt(e,ds),JSON.stringify(n))}catch(n){Xn("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(mm,"writeUpgradeCheckCache");async function fm({cacheDir:e=us,...t}={}){let n=await dm(t);n&&mm(e,n)}o(fm,"startBackgroundUpgradeCheck");function ms(e,{onOutdated:t,cacheDir:n,...r}={}){let i=um(n);if(i){lm(e,i.latest)&&t?.(e,i.latest);return}fm({cacheDir:n,...r})}o(ms,"preActionUpgradeCheck");import{default as Fb,chalkStderr as fs}from"chalk";function gs(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,i="\u2500".repeat(r),s=o(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
221
- `);return fs.bold.yellow(a)}o(gs,"formatUpgradeWarning");function hm(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(hm,"isDep0040Warning");var Qn=process,Sm=Qn.emit.bind(Qn);Qn.emit=function(e,...t){return e==="warning"&&hm(t[0])?!1:Sm(e,...t)};as();var Ne=new ym;Ne.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.9.0").showHelpAfterError().configureOutput({writeOut:o(e=>gm(1,e),"writeOut")});Ne.hook("preAction",()=>{ms("1.9.0",{onOutdated:o((e,t)=>{console.warn(`
222
- ${gs(e,t)}
223
- `)},"onOutdated")})});Zi(Ne);var hs=rt({packageName:"@cognite/cli",cliVersion:"1.9.0"}),ys=cs({packageName:"@cognite/cli",cliVersion:"1.9.0"});rs(Ne,hs);var Zn=process.argv.slice(2);Ne.parseAsync(Zn,{from:"user"}).catch(async e=>{await os(hs,Zn),Jn(e)&&(console.error(`
224
- Cancelled.`),process.exit(130)),(!(e instanceof f)||e.shouldReport)&&(await ys.captureError(e,{command:Wn(Zn)}),await ys.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof f&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
336
+ `),process.stderr.write(` ${I.cyan(`cognite sign -s ${w}`)}
337
+ `)}r(tS,"handleGenerate");function dl(e){return Zc(e),Xc(e),Qc(e),el(e),pl(e),e}r(dl,"registerCommands");import{homedir as nS,userInfo as oS}from"os";var rS=nS(),iS=(()=>{try{return oS().username}catch{return""}})();function nt(e,t=rS){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),o=t.replaceAll("\\","/");return o!==t&&(n=n.replaceAll(o,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}r(nt,"redactHomedir");function sS(e,t=iS){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(o,"$1<user>")}r(sS,"redactUsername");var aS=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function ul(e){return e.replace(aS,(t,n)=>{let o=t[n.length];return`${n}${o}[REDACTED]${o}`})}r(ul,"redactCredentials");var cS=1e3,lS="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",pS={captureError:r(async()=>{},"captureError"),flush:r(async()=>{},"flush")};function dS(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}r(dS,"buildRelease");var uS="192.0.2.0";function mS(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:nt(t.filename)},...t.abs_path!==void 0&&{abs_path:nt(t.abs_path)},...t.module!==void 0&&{module:nt(t.module)}}))}r(mS,"scrubStackFrames");function Nn(e){return ul(sS(nt(e)))}r(Nn,"redactPii");function gS(e){let t={...e.user,email:void 0,username:void 0,ip_address:uS,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Nn(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:mS(s.stacktrace.frames)}}})),o=e.contexts?.cli,i=o!==void 0?Object.fromEntries(Object.entries(o).map(([s,a])=>[s,typeof a=="string"?Nn(a):a])):void 0;return{...e,message:e.message!==void 0?Nn(e.message):e.message,...typeof e.culprit=="string"&&{culprit:Nn(e.culprit)},user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}r(gS,"scrubPii");function ml(e={}){let t=e.env??process.env;if(po(t))return pS;let n=dS(e),o="production",i=null,s=null;function a(){return{dsn:lS,release:n,environment:o,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:pt},contexts:{cli:{applicationId:pt,node:process.version,platform:process.platform}}},beforeSend:gS}}r(a,"buildInitOptions");async function c(){return i||(s||(s=(async()=>{try{let l=e.sdk??await import("@sentry/node");return l.init(a()),i=l,l}catch{return null}})()),s)}return r(c,"ensureSdk"),{async captureError(l,p){try{let d=await c();if(!d)return;d.captureException(l,fS(l,p))}catch{}},async flush(l=cS){try{if(!i)return;await i.flush(l)}catch{}}}}r(ml,"createErrorReporter");function fS(e,t){let n={level:"fatal"},o={applicationId:pt,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},o.command=t.command),ue(e)&&(e.hint&&(o.hint=e.hint),e.helpUrl&&(o.helpUrl=e.helpUrl),o.shouldReport=e.shouldReport),n.contexts={cli:o},xt(e)&&(n.contexts.http={url:e.requestUrl!==void 0?nt(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:ul(nt(i))}}return n}r(fS,"buildCaptureContext");import{mkdirSync as hS,readFileSync as yS,writeFileSync as SS}from"fs";import{homedir as wS}from"os";import{resolve as _n}from"path";import{debuglog as vS}from"util";import{lt as CS,parse as gl}from"semver";var AS="https://registry.npmjs.org/@cognite/cli/latest",ES=1500,fl="upgrade-check.json",hl=_n(process.env.XDG_CACHE_HOME||_n(wS(),".cache"),"@cognite","cli"),$r=vS("cognite-flows");function bS(e,t){return!e||!t||!gl(e)||!gl(t)?!1:CS(e,t)}r(bS,"isOutdated");async function xS({timeout:e=ES,registryUrl:t=AS,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let o=await n(t,{signal:AbortSignal.timeout(e)});if(!o?.ok)return null;let i=await o.json();return typeof i?.version=="string"?i.version:null}catch(o){return $r("fetchLatestVersion failed (%s): %O",t,o),null}}r(xS,"fetchLatestVersion");function kS(e=hl,t=864e5){try{let n=yS(_n(e,fl),"utf-8"),o=JSON.parse(n);return typeof o.latest!="string"||typeof o.fetchedAt!="number"||Date.now()-o.fetchedAt>t?null:{latest:o.latest,fetchedAt:o.fetchedAt}}catch(n){return $r("readUpgradeCheckCache failed (%s): %O",e,n),null}}r(kS,"readUpgradeCheckCache");function PS(e,t){try{hS(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};SS(_n(e,fl),JSON.stringify(n))}catch(n){$r("writeUpgradeCheckCache failed (%s): %O",e,n)}}r(PS,"writeUpgradeCheckCache");async function TS({cacheDir:e=hl,...t}={}){let n=await xS(t);n&&PS(e,n)}r(TS,"startBackgroundUpgradeCheck");function yl(e,{onOutdated:t,cacheDir:n,...o}={}){let i=kS(n);if(i){bS(e,i.latest)&&t?.(e,i.latest);return}TS({cacheDir:n,...o})}r(yl,"preActionUpgradeCheck");import{default as uF,chalkStderr as Sl}from"chalk";function wl(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],o=Math.max(...n.map(c=>[...c].length))+2,i="\u2500".repeat(o),s=r(c=>`\u2502 ${c}${" ".repeat(o-1-[...c].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
338
+ `);return Sl.bold.yellow(a)}r(wl,"formatUpgradeWarning");function DS(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}r(DS,"isDep0040Warning");var Fr=process,$S=Fr.emit.bind(Fr);Fr.emit=function(e,...t){return e==="warning"&&DS(t[0])?!1:$S(e,...t)};It();var ot=new IS;ot.name("cognite").description("Build and deploy React apps and Atlas agents to Cognite Data Fusion").version("1.10.0").showHelpAfterError().configureOutput({writeOut:r(e=>RS(1,e),"writeOut")});ot.hook("preAction",()=>{yl("1.10.0",{onOutdated:r((e,t)=>{console.warn(`
339
+ ${wl(e,t)}
340
+ `)},"onOutdated")})});dl(ot);var Lr=_t({packageName:"@cognite/cli",cliVersion:"1.10.0"}),vl=ml({packageName:"@cognite/cli",cliVersion:"1.10.0"});Zr(ot,Lr);ha(ot,{telemetry:Lr});var Or=process.argv.slice(2);ot.parseAsync(Or,{from:"user"}).catch(async e=>{await Xr(Lr,Or),eo(e)&&(console.error(`
341
+ Cancelled.`),process.exit(130)),(!(e instanceof m)||e.shouldReport)&&(await vl.captureError(e,{command:Qn(Or)}),await vl.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof m&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});