@cognite/cli 1.9.0-alpha.0 → 1.9.0-alpha.2

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,14 @@
1
1
  #!/usr/bin/env node
2
- var io=Object.defineProperty;var gn=e=>{throw TypeError(e)};var i=(e,t)=>io(e,"name",{value:t,configurable:!0});var fn=(e,t,n)=>t.has(e)||gn("Cannot "+n);var Ie=(e,t,n)=>(fn(e,t,"read from private field"),n?n.call(e):t.get(e)),yn=(e,t,n)=>t.has(e)?gn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),hn=(e,t,n,r)=>(fn(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as Nl}from"fs";import{Command as Hl}from"commander";var ut=class ut 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:po(t.cause)}}};i(ut,"HintedError");var h=ut;function wn(e){return e instanceof h}i(wn,"isHintedError");var Sn="https://docs.cognite.com/cdf/access/",oo="https://status.cognite.com";function so(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Sn};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Sn};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:oo};default:return{}}}i(so,"defaultHintForStatus");var gt=class gt extends h{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=so(n),o=super.deriveDefaults(t);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(gt,"HintedHttpError");var oe=gt;function vn(e){return e instanceof oe}i(vn,"isHintedHttpError");function ao(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}}i(ao,"hintForErrno");function po(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,o=ao(r.code,r);if(o!==void 0)return o;t=r.cause}}i(po,"hintForCause");import{existsSync as Qo,readFileSync as es}from"fs";import{join as ts,resolve as Be}from"path";import{verifyBundle as ns}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as rs}from"jose";import St from"enquirer";import{email as co,pipe as lo,safeParse as mo,string as uo}from"valibot";var go=lo(uo(),co());function de(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!mo(go,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}i(de,"parseEmail");function me(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}i(me,"parseExpiryMonths");import{execFileSync as Re}from"child_process";import{execFileSync as fo}from"child_process";function $e(e={}){let{execFileSync:t=fo}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}i($e,"isGitInstalled");function G(e={}){if(!$e(e))throw new h("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})}i(G,"throwIfGitMissing");function Te(e,t={}){let{execFileSync:n=Re}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}i(Te,"isInsideGitRepo");function Cn(e,t={}){let{execFileSync:n=Re}=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"})}i(Cn,"gitInitAndCommit");function bn(e={}){let{execFileSync:t=Re}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(bn,"gitUserName");function En(e={}){let{execFileSync:t=Re}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(En,"gitUserEmail");import{inspect as yo}from"util";var ft="[REDACTED]",se,Fe=class Fe{constructor(t){yn(this,se);hn(this,se,t)}toString(){return ft}toJSON(){return ft}[yo.custom](){return ft}expose(){return Ie(this,se)}equals(t){return Ie(this,se)===Ie(t,se)}static from(t){return new Fe(t)}};se=new WeakMap,i(Fe,"SensitiveString");var b=Fe;var Oe=3,kn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",xn=`Key expiry in months (${1}-${12})`,Pn="Email address for the registry entry",An=`Passphrase for the encrypted private key (min ${15} chars)`,Dn="Confirm passphrase",In=i(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),$n=i(e=>`Passphrases do not match (attempt ${e}/${Oe}).
3
- `,"passphraseMismatchMsg"),Rn=`Passphrase confirmation failed after ${Oe} attempts`,Tn=i(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Fn="How would you like to submit your key registration?",On="Open in browser",Un="Copy link to clipboard";async function Ue(e){return St.prompt(e)}i(Ue,"defaultPrompt");function wt(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}i(wt,"parserAsValidator");var So=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function pe(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(!So.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}i(pe,"parseKid");async function _n(e={}){let{prompt:t=Ue}=e,{kid:n}=await t({type:"input",name:"kid",message:kn,validate:wt(pe)});return pe(n)}i(_n,"promptKid");async function Ln(e={}){let{prompt:t=i(r=>St.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Fn,choices:[{name:"browser",message:On},{name:"clipboard",message:Un}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}i(Ln,"promptZendeskAction");async function Kn(e={}){let{prompt:t=Ue}=e,{months:n}=await t({type:"input",name:"months",message:xn,initial:String(6),validate:wt(r=>me(r,"expiry"))});return me(n,"expiry")}i(Kn,"promptExpiryMonths");async function Mn(e={}){let{prompt:t=Ue,gitUserEmail:n=En}=e,{email:r}=await t({type:"input",name:"email",message:Pn,initial:n(),validate:wt(o=>de(o,"email"))});return de(r,"email")}i(Mn,"promptEmail");async function Nn(e={}){let{prompt:t=Ue,stderr:n=process.stderr}=e;for(let r=1;r<=Oe;r+=1){let{passphrase:o}=await t({type:"password",name:"passphrase",message:An,validate:i(a=>a.length>=15?!0:In(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Dn});if(o===s)return b.from(o);n.write($n(r))}throw new Error(Rn)}i(Nn,"promptPassphrase");async function Hn(e,t={}){let{prompt:n=i(o=>St.prompt(o),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:Tn(e),initial:!1});return r}i(Hn,"promptConfirmOverwrite");import{existsSync as Ro,readdirSync as To,readFileSync as Fo}from"fs";import{join as Ct}from"path";import{execFile as Co}from"child_process";import{promisify as bo}from"util";import{execFileSync as Bn}from"child_process";import{platform as wo}from"os";import vo from"path";function _(e,t={}){let{platform:n=wo}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}i(_,"isOS");function jn(e,t={}){let{exec:n=Bn,log:r=console.log}=t,[o,s]=_("macos",t)?["open",[e]]:_("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{n(o,s)}catch{r(`Could not open browser \u2014 open manually:
4
- ${e}`)}}i(jn,"openInBrowser");function Vn(e,t={}){let{exec:n=Bn,log:r=console.log}=t,[o,s]=_("macos",t)?["open",["-R",e]]:_("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[vo.dirname(e)]];try{n(o,s)}catch{r(`Could not open file manager \u2014 files are at:
5
- ${e}`)}}i(Vn,"revealInFileManager");var Gn="cognite-flows",Eo=bo(Co),Yn=i((e,t)=>Eo(e,t),"defaultExecFile"),ko=-25300,xo=ko&255;function Po(e){if(!(e instanceof Error)||!("code"in e)||e.code!==xo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}i(Po,"isKeychainNotFoundError");async function qn(e,t,n={}){let r=t.expose();if(!_("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:o=Yn}=n;await o("security",["add-generic-password","-a",e,"-s",Gn,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}i(qn,"storeKeyInKeychain");async function Le(e,t={}){if(!_("macos",t))return null;let{execFile:n=Yn}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Gn,"-w"]);return b.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(Po(r))return null;throw r}}i(Le,"readKeyFromKeychain");var Wn="cognite-cli-signing",Ao="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.",Do="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.",zn="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function Io(e){if(!(e instanceof Error))return zn;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?Ao:t.includes("ambiguous")?Do:zn}i(Io,"hintFor");function Jn(e,t,n){return new h(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:Io(n),shouldReport:!1})}i(Jn,"wrapKeyringError");async function Zn(e,t){let{Entry:n}=await import("@napi-rs/keyring"),r=new n(e,t);return{setPassword:i(o=>r.setPassword(o),"setPassword"),getPassword:i(()=>r.getPassword(),"getPassword"),deleteCredential:i(()=>r.deleteCredential(),"deleteCredential")}}i(Zn,"defaultCreateEntry");async function Xn(e,t,n={}){let{createEntry:r=Zn}=n,o=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(Wn,e)).setPassword(o)}catch(s){throw Jn("store",e,s)}}i(Xn,"storeSigningKey");async function Ke(e,t={}){let{createEntry:n=Zn}=t;try{let o=(await n(Wn,e)).getPassword();return o===null?null:b.from(Buffer.from(o,"base64").toString("utf-8"))}catch(r){throw Jn("read",e,r)}}i(Ke,"readSigningKey");import{homedir as $o}from"os";import{join as vt}from"path";function $(e={}){let{env:t=process.env,homedir:n=$o}=e,r=t.COGNITE_CLI_HOME?.trim()||vt(n(),".cognite-cli");return{home:r,keysDir:vt(r,"keys"),sessionFile:vt(r,"session.json")}}i($,"getConfig");var Z=".pub.pem",bt=".key.jwe",Et=".meta.json";function Me(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)"}}i(Me,"formatLocalKeySource");function Oo(e){return{existsSync:e.existsSync??Ro,readdirSync:e.readdirSync??To,readFileSync:e.readFileSync??((t,n)=>Fo(t,n)),isOS:e.isOS??(t=>_(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Le(t)),readSigningKey:e.readSigningKey??(t=>Ke(t))}}i(Oo,"resolveDeps");function Uo(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{}}i(Uo,"readEmailFromMeta");function _o(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(Z)):[]}i(_o,"publicKeyEntries");function Lo(e){return e.slice(0,-Z.length)}i(Lo,"kidFromPublicKeyFilename");async function Ko(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=Ct(t,`${e}${bt}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}i(Ko,"resolveSource");async function Ne(e=$().keysDir,t={}){let n=Oo(t),r=new Set,o=_o(e,n).flatMap(s=>{let a=Lo(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(o.map(async({kid:s,entry:a})=>{let p=await Ko(s,e,n),c=Ct(e,`${s}${Et}`),l;try{l=Uo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:Ct(e,a),email:l}}))}i(Ne,"discoverLocalKeys");import{createReadStream as Mo}from"fs";function He(e){let t=Mo(e);return new ReadableStream({start(n){t.on("data",r=>{let o=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(o))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}i(He,"createWebStreamFromFile");import No from"path";var Qn=".cognite-bundles";function er(e,t){return`${e}-${t}.zip`}i(er,"bundleFileName");function H(e,t,n){return No.join(e,Qn,er(t,n))}i(H,"bundlePath");import{existsSync as Jo,readFileSync as Zo}from"fs";import{resolve as Xo}from"path";import{array as tr,boolean as Ho,check as ue,forward as ge,literal as Bo,maxLength as jo,minLength as Vo,nonEmpty as X,object as nr,optional as z,picklist as Go,pipe as Y,safeParse as Yo,string as B,url as rr}from"valibot";var kt=Y(B(),X("must not be empty")),xt=Y(B(),X("must not be empty"),jo(256,"must be 256 characters or fewer")),Pt=Y(B(),X("must not be empty"),rr("must be a valid URL")),qo=Y(B(),X("must not be empty"),rr("must be a valid URL")),At=Y(B(),X("must not be empty")),Dt=Y(B(),X("must not be empty")),zo=Y(nr({org:At,project:Dt,baseUrl:Pt,deployClientId:z(B(),""),deploySecretName:z(B(),""),published:z(Ho(),!1),idpType:z(Go(["cdf","entra_id","oauth"]),"cdf"),tenantId:z(B()),scopes:z(tr(Y(B(),X("must not be empty")))),tokenUrl:z(qo)}),ge(ue(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),ge(ue(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),ge(ue(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),ge(ue(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),ge(ue(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),ge(ue(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Wo=nr({name:kt,externalId:xt,versionTag:Y(B(),X("must not be empty")),description:z(B(),""),deployments:Y(tr(zo),Vo(1,"must contain at least one deployment")),infra:z(Bo("appsApi"))});function It(e){let t=Yo(Wo,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",o=r?`"${r}" `:"";throw new Error(`app.json: ${o}${n.message}`)}i(It,"validateAppConfig");function E(e,t={}){let{validator:n=It,existsSync:r=Jo,readFileSync:o=Zo}=t,s=Xo(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=o(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)}i(E,"loadAppConfig");var ir=[".dev.sig",".cert.sig",".sig"];function is(e){return{existsSync:e.existsSync??Qo,readFileSync:e.readFileSync??((t,n)=>es(t,n)),createBundleStream:e.createBundleStream??He,verifyBundle:e.verifyBundle??ns,loadAppConfig:e.loadAppConfig??E,defaultKeyDir:e.defaultKeyDir??(()=>$().keysDir)}}i(is,"resolveDeps");function os(e,t){return ir.map(n=>`${e}${n}`).find(n=>t(n))}i(os,"findSiblingSignature");function ss(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}i(ss,"isCompactJws");function as(e){try{let t=rs(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}i(as,"readKidFromToken");function ps(e,t,n){let{existsSync:r,readFileSync:o}=n;try{pe(e)}catch(a){throw new h(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!r(t))throw new h(`Key directory not found: ${t}`,{shouldReport:!1});let s=ts(t,`${e}${Z}`);if(!r(s))throw new h(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return o(s,"utf-8")}catch(a){throw new h(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}i(ps,"resolvePublicKeyForKid");function cs(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 o=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${o}`)}t&&console.log(JSON.stringify(n,null,2))}i(cs,"printResult");async function or(e,t,n={},r=process.cwd()){let{existsSync:o,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=is(n),d;if(e)d=Be(r,e);else{let u;try{u=a(r)}catch(y){let v=y instanceof Error?y.message:String(y);throw new h(v,{cause:y,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=H(r,u.externalId,u.versionTag)}if(!o(d)){let u=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new h(`Bundle not found: ${d}`,{hint:u,shouldReport:!1})}let m=t.sig?Be(r,t.sig):os(d,o);if(!m)throw new h("No signature file found.",{hint:`Pass --sig <path> or place one of ${ir.map(u=>`${d}${u}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!o(m))throw new h(`Signature file not found: ${m}`,{shouldReport:!1});let g;try{g=s(m,"utf-8").trim()}catch(u){throw new h(`Failed to read signature file: ${m}`,{cause:u,shouldReport:!1})}if(!ss(g))throw new h(`Malformed JWS in ${m}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let f;if(t.key){let u=Be(r,t.key);if(!o(u))throw new h(`Public key not found: ${u}`,{shouldReport:!1});try{f=s(u,"utf-8")}catch(y){throw new h(`Failed to read public key file: ${u}`,{cause:y,shouldReport:!1})}}else{let u=t.keyDir?Be(r,t.keyDir):l(),y=as(g);if(!y)throw new h("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});f=ps(y,u,{existsSync:o,readFileSync:s})}try{let u=await c({token:g,publicKeyPem:f,bundleStream:p(d)});cs(u,t.verbose??!1)}catch(u){let y=u instanceof Error?u.message:String(u);throw new h(`Bundle rejected: ${y}`,{shouldReport:!1})}}i(or,"handleVerify");function sr(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)=>or(n,r,t))}i(sr,"registerVerifyCommand");var ar="https://docs.cognite.com/cdf/access/";function M(e){return e!==null&&typeof e=="object"}i(M,"isRecord");function ce(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(ce,"isHttpError");function ls(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
- See: ${ar}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
- See: ${ar}`;default:return}}i(ls,"httpStatusHint");function q(e){let t=e instanceof Error?e:new Error(String(e));if(!ce(t))return null;let n=ls(t.status);return n?Object.assign(new Error(`${t.message}
15
- ${n}`),{cause:t}):null}i(q,"enrichedHttpError");function ds(e){if(!M(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(M(n)){let r=n.error;if(M(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}i(ds,"findMissingArray");function ms(e,t){if(!ce(e)||e.status!==400)return!1;let n=ds(e);return n?n.some(r=>M(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}i(ms,"isMissingExternalIdError");function je(e,t){return ce(e)&&e.status===404||ms(e,t)}i(je,"isNotFoundError");var cr=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],lr=["ACTIVE","PREVIEW"],$t=class $t extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};i($t,"AppVersionNotFoundError");var j=$t,Rt=class Rt extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};i(Rt,"AppNotFoundError");var fe=Rt;function Ve(e,t){return e.includes(t)}i(Ve,"includesValue");function us(e){return Ve(cr,e)}i(us,"isAppVersionLifecycleState");function gs(e){return Ve(lr,e)}i(gs,"isAppVersionAlias");function fs(e){return typeof e.version=="string"&&us(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||gs(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}i(fs,"isAppVersion");function pr(e){if(!M(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!fs(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}i(pr,"parseAppVersion");function ys(e){if(!M(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}}i(ys,"parseAppMetadata");var Tt=class Tt{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(o){throw q(o)??o}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw q(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return ys(r.data)}catch(r){throw je(r,[t])?new fe(t):q(r)??r}}async uploadVersion(t,n,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),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 h("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=b.from(l),m=`${this.client.getBaseUrl()}${c}`,g=new AbortController,f=setTimeout(()=>g.abort(),300*1e3),u;try{u=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:g.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new h("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 h(`Failed to upload version to ${m}`,{cause:y,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(f)}if(!u.ok){let y=await u.text(),v;try{v=JSON.parse(y)}catch{}let C=y;if(M(v)){let L=v.error;if(typeof L=="string")C=L;else if(M(L)){let P=L.message,k=L.code;C=typeof P=="string"?P:k!=null?`Unknown error (code: ${k})`:y}else{let P=v.message;C=typeof P=="string"?P:y}}let w=u.headers.get("x-request-id"),S=w?` | X-Request-ID: ${w}`:"",x=M(v)?v:y;throw new oe(`Upload failed: ${u.status} \u2014 ${C}${S}`,{httpStatusCode:u.status,requestUrl:m,responseBody:x})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return pr(a.data)}catch(a){throw je(a,[t,n])?new j(t,n):q(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/versions/list`;try{let o=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!M(o.data)||!Array.isArray(o.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=o.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 pr(s[0])}catch(o){if(je(o,[t]))return null;throw q(o)??o}}async deleteVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/delete`;try{await this.client.post(o,{data:{items:n.map(s=>({version:s}))}})}catch(s){throw q(s)??s}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(s){throw q(s)??s}}async submitSignatures(t,n,r){let o=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw q(p)??p}}async listSignatures(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return ws(a.data)}catch(a){throw q(a)??a}}};i(Tt,"AppHostingApi");var Ge=Tt,hs=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],Ss=["developer","certifier"];function ws(e){if(!M(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=vs(n);return r?[r]:[]})}i(ws,"parseStoredSignatures");function vs(e){if(!M(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Ve(Ss,n)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!Ve(hs,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(vs,"parseStoredSignature");function Ft(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}i(Ft,"diffAppMetadata");function Cs(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:r,local:o}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${r}" \u2192 "${o}"`)}return t.join(`
16
- `)}i(Cs,"formatMetadataDriftError");var Ot=class Ot{constructor(t){this.api=new Ge(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,s){return this.api.uploadVersion(t,n,r,o,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(o){if(ce(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,r);return}throw o}}async checkMetadataDrift(t,n,r){let o;try{o=await this.getApp(t)}catch{return}let s=Ft(o,{name:n,description:r});if(s.length!==0)throw new h(Cs(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 o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,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,o,s,a),p&&await this.publishAndActivate(t,o),console.log(`
19
- \u2705 Deployment successful!`)}};i(Ot,"AppHostingClient");var A=Ot;import{CogniteClient as oa}from"@cognite/sdk";import _s from"os";import Ls from"path";import Ks from"open";import{buildAuthorizationUrl as Ms,calculatePKCECodeChallenge as Ns,discovery as Hs,None as Bs,randomPKCECodeVerifier as js,randomState as Vs}from"openid-client";import dr from"mixpanel";var bs="5c4d853e7c3b77b1eb4468d5329b278c",Es="api-eu.mixpanel.com",ve="cognite-cli",ks=2e3,mr={env:process.env,init:dr.init.bind(dr)},xs={track:i(()=>{},"track"),flush:i(async()=>{},"flush")};function Ut(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}i(Ut,"isTelemetryDisabled");function Ps(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"}i(Ps,"detectCiEnvironment");function As(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}i(As,"isDebug");function Ye(e={}){let t=e.env??mr.env,n=e.init??mr.init,r=e.packageName,o=e.cliVersion,s=As(t),a=Ps(t);if(Ut(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
20
- `),xs;let p,c=new Set;function l(){if(p)return p;try{return p=n(bs,{geolocate:!1,keepAlive:!1,host:Es}),p}catch{return}}return i(l,"getClient"),{track(d,m={}){let g=l();if(!g)return;let f={...m,applicationId:ve,...r&&{packageName:r},...o&&{cliVersion:o},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(f)}
21
- `);let u=i(()=>{},"finish"),y=new Promise(v=>{u=v});c.add(y);try{g.track(d,f,u)}catch{u()}y.finally(()=>c.delete(y))},async flush(d=ks){if(c.size===0)return;let m,g=new Promise(f=>{m=setTimeout(f,d),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),g])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
22
- `)}}}i(Ye,"createTelemetry");import Is from"https";import{authorizationCodeGrant as $s}from"openid-client";function ur(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}i(ur,"escapeHtml");function _t(e,t,n){let r=ur(t),o=ur(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
23
- <h1>${r}</h1><p>${o}</p><p>You can close this window.</p>${e==="success"?`<style>
2
+ var Ka=Object.defineProperty;var Kr=e=>{throw TypeError(e)};var o=(e,t)=>Ka(e,"name",{value:t,configurable:!0});var Vr=(e,t,n)=>t.has(e)||Kr("Cannot "+n);var rt=(e,t,n)=>(Vr(e,t,"read from private field"),n?n.call(e):t.get(e)),Gr=(e,t,n)=>t.has(e)?Kr("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Yr=(e,t,n,r)=>(Vr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as Vf}from"fs";import{Command as Gf}from"commander";var pn=class pn 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:qa(t.cause)}}};o(pn,"HintedError");var m=pn;function fe(e){return e instanceof m}o(fe,"isHintedError");var qr="https://docs.cognite.com/cdf/access/",Va="https://status.cognite.com";function Ga(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:qr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:qr};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:Va};default:return{}}}o(Ga,"defaultHintForStatus");var cn=class cn 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,r=Ga(n),i=super.deriveDefaults(t);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(cn,"HintedHttpError");var le=cn;function Jr(e){return e instanceof le}o(Jr,"isHintedHttpError");function Ya(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(Ya,"hintForErrno");function qa(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,i=Ya(r.code,r);if(i!==void 0)return i;t=r.cause}}o(qa,"hintForCause");import{Command as Ja,Option as ot}from"commander";var zr=Object.freeze({interactive:new ot("--interactive","Use browser-based authentication instead of env-var credentials").default(!1),baseUrl:new ot("--base-url <url>","CDF base URL (only with --interactive)"),project:new ot("--project <project>","CDF project name (only with --interactive)"),org:new ot("--org <org>","Organization hint for login (only with --interactive)")}),Zf=Object.values(zr).map(e=>e.long),st=class st extends Ja{constructor(t){super(t);for(let n of Object.values(zr))this.addOption(n)}createCommand(t){return new st(t)}};o(st,"BaseCommand");var de=st,ln=class ln extends de{constructor(t){super(t),this.configure()}};o(ln,"CommandGroup");var it=ln;import{performance as Qr}from"perf_hooks";import{existsSync as op,readFileSync as ip}from"fs";import{resolve as sp}from"path";import{array as Wr,boolean as za,check as Te,forward as $e,literal as Wa,maxLength as Xa,minLength as Za,nonEmpty as ye,object as Xr,optional as ue,picklist as Qa,pipe as ee,safeParse as ep,string as Y,url as Zr}from"valibot";var dn=ee(Y(),ye("must not be empty")),un=ee(Y(),ye("must not be empty"),Xa(256,"must be 256 characters or fewer")),mn=ee(Y(),ye("must not be empty"),Zr("must be a valid URL")),tp=ee(Y(),ye("must not be empty"),Zr("must be a valid URL")),gn=ee(Y(),ye("must not be empty")),fn=ee(Y(),ye("must not be empty")),np=ee(Xr({org:gn,project:fn,baseUrl:mn,deployClientId:ue(Y(),""),deploySecretName:ue(Y(),""),published:ue(za(),!1),idpType:ue(Qa(["cdf","entra_id","oauth"]),"cdf"),tenantId:ue(Y()),scopes:ue(Wr(ee(Y(),ye("must not be empty")))),tokenUrl:ue(tp)}),$e(Te(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),$e(Te(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),$e(Te(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),$e(Te(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),$e(Te(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),$e(Te(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),rp=Xr({name:dn,externalId:un,versionTag:ee(Y(),ye("must not be empty")),description:ue(Y(),""),deployments:ee(Wr(np),Za(1,"must contain at least one deployment")),infra:ue(Wa("appsApi"))});function yn(e){let t=ep(rp,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(yn,"validateAppConfig");function x(e,t={}){let{validator:n=yn,existsSync:r=op,readFileSync:i=ip}=t,s=sp(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(x,"loadAppConfig");var Oe=1e3,at;function ap(){at=Qr.now()}o(ap,"markActionStart");function pp(){at=void 0}o(pp,"resetActionStart");function hn(){if(at!==void 0)return Math.max(0,Math.round(Qr.now()-at))}o(hn,"snapshotActionDurationMs");function eo(){let e=hn();return pp(),{...e!==void 0&&{actionDurationMs:e}}}o(eo,"takePerformanceFields");var cp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description","externalId"]);function Sn(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:cp.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Sn,"sanitizeOptions");function lp(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(lp,"getCommandPath");function to(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(to,"tryLoadAppConfig");function wn(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(wn,"commandFromArgv");function no(e,t,n=x){e.hook("preAction",()=>{ap()}),e.hook("postAction",async(r,i)=>{try{let s={command:lp(i),options:Sn(i.opts()),success:!0,...to(n),...eo()};t.track("Flows.CLI.Command",{...s}),await t.flush(Oe)}catch{}})}o(no,"instrument");async function ro(e,t,n=x){try{let r={command:wn(t),options:{},success:!1,...to(n),...eo()};e.track("Flows.CLI.Command",{...r}),await e.flush(Oe)}catch{}}o(ro,"trackFailure");var dp=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 oo(e,t){if(!e||t.name()==="eval")return;let n=dp[t.name()];if(n)try{e.track(n,{command:t.name(),options:Sn(t.optsWithGlobals()),success:!0}),await e.flush(Oe)}catch{}}o(oo,"trackAgentsCommand");import{existsSync as ni}from"fs";import{mkdir as ri,readFile as Zo,writeFile as Gn}from"fs/promises";import{basename as fl,dirname as yl,join as Ue,resolve as Yn}from"path";import{fileURLToPath as hl}from"url";import{Option as Ee}from"commander";import up,{Chalk as mp}from"chalk";var Be=new mp({level:0});function D(e){return e.isTTY?up:Be}o(D,"chalkForStream");var gp="ERR_USE_AFTER_CLOSE";function so(e){return e instanceof Error&&"code"in e&&e.code===gp}o(so,"isReadlineClosedError");function fp(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(fp,"isPlainObject");function vn(e){return e==null||so(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&fp(e)&&Object.keys(e).length===0)}o(vn,"isPromptCancel");var io=!1;function pt(){io||(io=!0,process.on("uncaughtException",e=>{so(e)&&(console.error(`
3
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{vn(e)&&(console.error(`
4
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(pt,"installCancelHandler");import{readFile as yp}from"fs/promises";import{join as hp}from"path";import{array as Ve,looseObject as ao,nullable as Sp,object as po,optional as W,parse as co,record as wp,string as B,unknown as vp}from"valibot";import{parse as Cp,stringify as Ap}from"yaml";var P=Object.freeze({config:"agent.yaml",readme:"README.md",readmeTemplate:"README_TEMPLATE.md",evalDir:"eval",evalCases:"cases.yaml",evalCasesTemplate:"EVAL_CASES_TEMPLATE.yaml"}),Ke={dirName:"my-agent",model:"azure/gpt-4.1-mini",runtimeVersion:"1.3.0"};var Ep=po({agentExternalId:B()}),bp=po({question:B()}),xp=ao({name:B(),type:B(),description:B(),instructions:W(B()),configuration:W(Sp(wp(B(),vp())))}),lo=ao({externalId:B(),name:B(),description:W(B()),instructions:W(B()),model:W(B()),runtimeVersion:W(B()),labels:W(Ve(B())),exampleQuestions:W(Ve(bp)),skills:W(Ve(B())),subagents:W(Ve(Ep)),tools:W(Ve(xp),[])});function kp(e){let t=Cp(e);return co(lo,t)}o(kp,"parseAgentYaml");function te(e){let t=co(lo,e);return Ap(t,{lineWidth:0})}o(te,"serializeAgentYaml");async function ne(e){let t=hp(e,P.config),n;try{n=await yp(t,"utf8")}catch{throw new m(`No ${P.config} found at:
5
+ ${t}`,{hint:"Run this command from an agent project directory, or pass the directory as an argument.",shouldReport:!1})}return kp(n)}o(ne,"readAgentYaml");function ve(e){let{createdTime:t,lastUpdatedTime:n,ownerId:r,...i}=e;return i}o(ve,"toAgentCreate");import uo from"enquirer";var Cn=class Cn{constructor(t,n,r,i=[],s,a=uo.prompt.bind(uo)){this.dirArg=t;this.flags=n;this.isInteractive=r;this.availableModels=i;this.apiDefaultModel=s;this.promptFn=a}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?Ge(this.promptFn,{message:"Agent name (used as directory and externalId)",initial:"my-agent",validate:mo("Agent name")}):Ke.dirName}async getDisplayName(t){let n=this.flags.displayName?.trim();return n||(this.isInteractive?Ge(this.promptFn,{message:"Display name",initial:t,validate:mo("Display name")}):t)}async getDescription(){let t=this.flags.description?.trim();if(t)return t;if(this.isInteractive){let n=await Ge(this.promptFn,{message:"Description (optional)",initial:"",validate:o(()=>!0,"validate")});if(n)return n}}async getModel(){let t=this.flags.model?.trim();return t||(this.isInteractive&&this.availableModels.length>0?Ge(this.promptFn,{message:"Model",choices:this.availableModels,initial:Math.max(this.availableModels.indexOf(this.apiDefaultModel??""),0)}):this.apiDefaultModel??Ke.model)}async getInstructions(){let t=this.flags.instructions?.trim();if(t)return t;if(this.isInteractive){let n=await Ge(this.promptFn,{message:"Instructions (system prompt, leave blank for default)",initial:"",validate:o(()=>!0,"validate")});if(n)return n}return Pp}};o(Cn,"AgentCreateResolver");var ct=Cn,Pp=["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(`
6
+ `);function mo(e){return o(function(n){return n.trim()?!0:`${e} is required`},"_requiredInner")}o(mo,"required");async function Ge(e,t){if("choices"in t){let{value:r}=await e({type:"select",name:"value",...t});return r.trim()}let{value:n}=await e({type:"input",name:"value",...t});return n.trim()}o(Ge,"ask");var lt={"cdf-version":"beta"};function re(e){async function t(c){let l=p(e.project).concat("/ai/agents");return(await e.post(l,{data:{items:[c]},headers:lt})).data.items[0]}o(t,"upsert");async function n(c){let l=p(e.project).concat("/ai/agents/byids"),d;try{d=await e.post(l,{data:{items:[{externalId:c}]},headers:lt})}catch(g){throw r(g)&&g.status===422?new m(`Agent "${c}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1}):g}let u=d.data?.items??[];if(!u.length)throw new m(`Agent "${c}" not found.`,{hint:"Check the externalId and try again.",shouldReport:!1});return u[0]}o(n,"getByExternalId");function r(c){return typeof c=="object"&&c!==null&&"status"in c&&typeof c.status=="number"}o(r,"isHttpError");async function i(){let c=p(e.project).concat("/ai/agents");return(await e.get(c,{headers:lt})).data}o(i,"list");async function s(){let c=p(e.project).concat("/ai/availability");return(await e.get(c,{headers:lt})).data}o(s,"getServiceAvailability");async function a(){let l=(await s()).items.find(d=>d.path==="/ai/agents");return{models:l?.supportedLanguageModels??[],defaultModel:l?.defaultLanguageModel}}o(a,"getAvailableModels");function p(c){return`/api/v1/projects/${encodeURIComponent(c)}`}return o(p,"getBaseUrl"),{upsert:t,getByExternalId:n,list:i,getServiceAvailability:s,getAvailableModels:a}}o(re,"getAgentsService");import{CogniteClient as dl}from"@cognite/sdk";import{existsSync as Op,mkdirSync as Fp,readFileSync as Lp,renameSync as Up,rmSync as Mp,writeFileSync as _p}from"fs";import{dirname as jp}from"path";import{isoTimestamp as Np,literal as Hp,nonEmpty as So,object as Bp,pipe as wo,safeParse as Kp,string as vo}from"valibot";import{homedir as Dp}from"os";import{join as An}from"path";function I(e={}){let{env:t=process.env,homedir:n=Dp}=e,r=t.COGNITE_CLI_HOME?.trim()||An(n(),".cognite-cli");return{home:r,keysDir:An(r,"keys"),sessionFile:An(r,"session.json")}}o(I,"getConfig");import{inspect as Ip}from"util";var En="[REDACTED]",Ce,dt=class dt{constructor(t){Gr(this,Ce);Yr(this,Ce,t)}toString(){return En}toJSON(){return En}[Ip.custom](){return En}expose(){return rt(this,Ce)}equals(t){return rt(this,Ce)===rt(t,Ce)}static from(t){return new dt(t)}};Ce=new WeakMap,o(dt,"SensitiveString");var E=dt;var Ae="cognite-cli-session",Rp=1280,Tp=process.platform==="win32"?Rp:1/0,bn="cognite-session/chunks=";function ut(e,t){return`${e}/chunk/${t}`}o(ut,"chunkAccount");function xn(e){if(!e.startsWith(bn))return null;let t=Number(e.slice(bn.length));return Number.isFinite(t)&&t>0?t:null}o(xn,"parseChunkCount");async function $p(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($p,"defaultCreateEntry");function kn(e){return{createEntry:e.createEntry??$p,chunkSize:e.chunkSize??Tp}}o(kn,"resolveDeps");async function go(e,t,n={}){let{createEntry:r,chunkSize:i}=kn(n),s=await r(Ae,e),a=s.getPassword();if(a!==null){let l=xn(a);if(l!==null)for(let d=0;d<l;d++)(await r(Ae,ut(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(`${bn}${c.length}`);for(let l=0;l<c.length;l++)(await r(Ae,ut(e,l))).setPassword(c[l])}o(go,"storeSessionToken");async function fo(e,t={}){let{createEntry:n}=kn(t),r=(await n(Ae,e)).getPassword();if(r===null)return null;let i=xn(r);if(i===null)return E.from(r);let s=[];for(let a=0;a<i;a++){let p=(await n(Ae,ut(e,a))).getPassword();if(p===null)return null;s.push(p)}return E.from(s.join(""))}o(fo,"readSessionToken");async function yo(e,t={}){let{createEntry:n}=kn(t),r=await n(Ae,e),i=r.getPassword();if(i!==null){let s=xn(i);if(s!==null)for(let a=0;a<s;a++)(await n(Ae,ut(e,a))).deleteCredential()}r.deleteCredential()}o(yo,"deleteSessionToken");var mt=1,Co=o(e=>`${e}/accessToken`,"accessTokenAccount"),Ao=o(e=>`${e}/refreshToken`,"refreshTokenAccount"),ho=wo(vo(),So("must not be empty"),Np("must be an ISO 8601 timestamp")),Vp=Bp({version:Hp(mt),org:wo(vo(),So("must not be empty")),accessTokenExpiresAt:ho,refreshTokenExpiresAt:ho});function Dn(e){return{sessionFile:e.sessionFile??I().sessionFile,existsSync:e.existsSync??Op,readFileSync:e.readFileSync??Lp,writeFileSync:e.writeFileSync??_p,mkdirSync:e.mkdirSync??Fp,renameSync:e.renameSync??Up,rmSync:e.rmSync??Mp,storeSecret:e.storeSecret??go,readSecret:e.readSecret??fo,deleteSecret:e.deleteSecret??yo}}o(Dn,"resolveDeps");var Pn="Run `npx @cognite/cli auth logout` to clear it, then `npx @cognite/cli auth login` to sign in again.";function gt(e={}){let t=Dn(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. ${Pn}`)}let i=Kp(Vp,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}. ${Pn}`)}return i.output}o(gt,"readSessionMetadata");async function In(e={}){let t=Dn(e),n=gt(e);if(!n)return null;let[r,i]=await Promise.all([t.readSecret(Co(n.org)),t.readSecret(Ao(n.org))]);if(!r||!i)throw new Error(`Session metadata exists but its tokens are missing from the keychain. ${Pn}`);return{...n,accessToken:r,refreshToken:i}}o(In,"readSession");async function Eo(e,t={}){let n=Dn(t);await n.storeSecret(Co(e.org),e.accessToken),await n.storeSecret(Ao(e.org),e.refreshToken);let r={version:mt,org:e.org,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshTokenExpiresAt:e.refreshTokenExpiresAt};n.mkdirSync(jp(n.sessionFile),{recursive:!0,mode:448});let i=`${n.sessionFile}.tmp`;n.writeFileSync(i,`${JSON.stringify(r,null,2)}
7
+ `,{mode:384});try{n.renameSync(i,n.sessionFile)}catch(s){throw n.rmSync(i,{force:!0}),s}}o(Eo,"writeSession");var Gp=300*1e3;function ft(e,t=new Date){let n=t.getTime();return Date.parse(e.refreshTokenExpiresAt)<=n?"EXPIRED":Date.parse(e.accessTokenExpiresAt)-n<=Gp?"EXPIRING":"VALID"}o(ft,"tokenState");import Oc from"path";import{lock as Fc}from"proper-lockfile";import{None as wc,discovery as vc,tokenRevocation as jh,refreshTokenGrant as Cc}from"openid-client";import pc from"os";import cc from"path";import lc from"open";import{buildAuthorizationUrl as dc,calculatePKCECodeChallenge as uc,discovery as mc,None as gc,randomPKCECodeVerifier as fc,randomState as yc}from"openid-client";import bo from"mixpanel";var Yp="5c4d853e7c3b77b1eb4468d5329b278c",qp="api-eu.mixpanel.com",Ye="cognite-cli",Jp=2e3,xo={env:process.env,init:bo.init.bind(bo)},zp={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Rn(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Rn,"isTelemetryDisabled");function Wp(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(Wp,"detectCiEnvironment");function Xp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Xp,"isDebug");function yt(e={}){let t=e.env??xo.env,n=e.init??xo.init,r=e.packageName,i=e.cliVersion,s=Xp(t),a=Wp(t);if(Rn(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
8
+ `),zp;let p,c=new Set;function l(){if(p)return p;try{return p=n(Yp,{geolocate:!1,keepAlive:!1,host:qp}),p}catch{return}}return o(l,"getClient"),{track(d,u={}){let g=l();if(!g)return;let f={...u,applicationId:Ye,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(f)}
9
+ `);let y=o(()=>{},"finish"),h=new Promise(C=>{y=C});c.add(h);try{g.track(d,f,y)}catch{y()}h.finally(()=>c.delete(h))},async flush(d=Jp){if(c.size===0)return;let u,g=new Promise(f=>{u=setTimeout(f,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)
10
+ `)}}}o(yt,"createTelemetry");import tc from"https";import{authorizationCodeGrant as nc}from"openid-client";function ko(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(ko,"escapeHtml");function Tn(e,t,n){let r=ko(t),i=ko(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
11
+ <h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
24
12
  @keyframes checkmark {
25
13
  0% { transform: scale(0); }
26
14
  50% { transform: scale(1.2); }
@@ -28,35 +16,93 @@ Examples:
28
16
  }
29
17
  h1 { animation: checkmark 0.5s ease-out; }
30
18
  </style>`:""}
31
- </body></html>`}i(_t,"generateHtml");import Ds from"net";function gr(e,t){return new Promise(n=>{let r=new Ds.Socket,o=i(s=>{r.removeAllListeners(),r.destroy(),n(s)},"done");r.setTimeout(500),r.once("connect",()=>o(!1)),r.once("timeout",()=>o(!0)),r.once("error",()=>o(!0)),r.connect(e,t)})}i(gr,"isHostPortFree");function qe(e,t={}){return _("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}i(qe,"freePortHint");async function fr(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([gr(e,"127.0.0.1"),gr(e,"::1")])).every(Boolean)}i(fr,"isPortFree");async function Rs(e,t,n,r,o,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:o});return t.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),t.end(_t("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),t.end(_t("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}i(Rs,"handleCallback");function Ts(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}i(Ts,"formatTimeoutMinutes");function yr(e,t,n,r,o,s={createServer:Is.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:$s}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,g)=>{try{let f=await Rs(m,g,n,r,o,s);f.shouldClose&&(d(),f.error?p(f.error):f.tokens?a(f.tokens):p(new Error("No tokens received")))}catch(f){d(),p(f instanceof Error?f:new Error(String(f)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Ts(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close(),c.closeIdleConnections?.()}i(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new h(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:qe(e.port)})):p(new h(`Login callback server failed: ${m.message}`,{cause:m}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}i(yr,"startCallbackServer");import{mkdirSync as Fs}from"fs";import{loadLocalCertificates as Os}from"@cognite/app-sdk/https";var Us={loadLocalCertificates:Os,mkdirSync:Fs,logger:console};async function hr(e,t=Us){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:o}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new h(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return o==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:n,key:r}}i(hr,"getOrCreateCertificates");var Gs="openid profile email",Ys={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Ls.join(_s.homedir(),".cdf-login")},qs={open:Ks,getOrCreateCertificates:hr,startCallbackServer:yr,isPortFree:fr,discovery:Hs,buildAuthorizationUrl:Ms,randomPKCECodeVerifier:js,calculatePKCECodeChallenge:Ns,randomState:Vs,logger:console,telemetry:Ye()};async function wr(e,t=Ys,n){return n===void 0?Sr(e,t,qs):Sr(e,t,n)}i(wr,"login");async function zs(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,Bs())}catch(r){throw new h(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}i(zs,"fetchOpenIdConfig");async function Sr(e,t,n){let{isPortFree:r,telemetry:o,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:p,randomState:c,buildAuthorizationUrl:l,getOrCreateCertificates:d,open:m,startCallbackServer:g}=n;if(!await r(t.port))throw o?.track("Flows.CLI.PortInUse",{port:t.port}),new h(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:qe(t.port)});s.log(`\u{1F510} Starting CDF login flow...
32
- `),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let u=await zs(n,t),y=a(),v=await p(y),C=c(),w={redirect_uri:t.redirectUri,scope:t.scope??Gs,code_challenge:v,code_challenge_method:"S256",state:C};e&&(w.organization_hint=e);let S=l(u,w).toString(),x=await d(t.certDir);e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
33
- `);try{await m(S)}catch(L){let P=L instanceof Error?L.message:String(L);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${P}`),s.error(`Please open this URL manually:
34
- `),s.error(S),s.error("")}return g(t,x,u,y,C)}i(Sr,"loginImpl");import{CogniteClient as ia}from"@cognite/sdk";function Ws(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}i(Ws,"exponentialBackoffWithJitter");function Js(e){return new Promise(t=>setTimeout(t,e))}i(Js,"sleep");async function vr(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),o=t.delayInMsCalculator??Ws;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=o(s);t.onAttemptFail?.(a,s,p),await Js(p),s++}}i(vr,"retryAsync");var Zs="https://auth.cognite.com/oauth2/token",Xs=i(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Cr({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let o;try{o=await vr(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new h(`Failed to fetch access token from ${t}`,{cause:p})}if(!o.ok){let p=await o.text();throw new oe(`Failed to get token from ${e}: ${o.status} ${o.statusText}`,{httpStatusCode:o.status,requestUrl:t,responseBody:p})}let s=await o.text(),a;try{a=JSON.parse(s)}catch{throw new h(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!Xs(a))throw new h(`No access token in ${e} authentication response`,{hint:r});return b.from(a.access_token)}i(Cr,"fetchOAuthToken");var Qs=i(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),ea=i(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Qs()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return b.from(t)},"getSecretFromEnv"),ta=i((e,t)=>{let n=t.expose();return Cr({idp:"CDF",tokenUrl:Zs,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"),br=i(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:o,missingTokenHint:s})=>Cr({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",...o!==void 0?{scope:o.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),na=i((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"),ra=i((e,t,n,r,o)=>br({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:o!==void 0?o:[na(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Lt=i(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return b.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=ea(r);if(o==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return br({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(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return ra(n,l,s,a,p)}return ta(n,l)},"getToken");async function ye(e,t,n=process.env,r){let o=await Lt(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new ia(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:i(async()=>o.expose(),"oidcTokenProvider")});return await a.authenticate(),a}i(ye,"getSdk");async function N(e,t,n={}){let{login:r=wr,getSdk:o=ye,createClient:s=i(a=>new oa(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=b.from(p.access_token),l=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:i(async()=>c.expose(),"getToken")});return await l.authenticate(),l}return o(e,t.appId)}i(N,"buildAppHostingApiClient");async function ze(e,t,n={}){let r=await N(e,t,n);return new A(r)}i(ze,"buildAppHostingClient");import Er from"enquirer";var kr="Enter custom target...";function xr(e,t){let n=t.map((r,o)=>` ${o}: ${r.org}/${r.project}`).join(`
19
+ </body></html>`}o(Tn,"generateHtml");import ec from"net";import{execFileSync as Po}from"child_process";import{platform as Zp}from"os";import Qp from"path";function K(e,t={}){let{platform:n=Zp}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(K,"isOS");function ht(e,t={}){let{exec:n=Po,log:r=console.log}=t,[i,s]=K("macos",t)?["open",[e]]:K("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{n(i,s)}catch{r(`Could not open browser \u2014 open manually:
20
+ ${e}`)}}o(ht,"openInBrowser");function Do(e,t={}){let{exec:n=Po,log:r=console.log}=t,[i,s]=K("macos",t)?["open",["-R",e]]:K("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Qp.dirname(e)]];try{n(i,s)}catch{r(`Could not open file manager \u2014 files are at:
21
+ ${e}`)}}o(Do,"revealInFileManager");function Io(e,t){return new Promise(n=>{let r=new ec.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(Io,"isHostPortFree");function wt(e,t={}){return K("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}o(wt,"freePortHint");async function Ro(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([Io(e,"127.0.0.1"),Io(e,"::1")])).every(Boolean)}o(Ro,"isPortFree");async function rc(e,t,n,r,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html",Connection:"close"}),t.end(Tn("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html",Connection:"close"}),t.end(Tn("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(rc,"handleCallback");function oc(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(oc,"formatTimeoutMinutes");function To(e,t,n,r,i,s={createServer:tc.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:nc}){return new Promise((a,p)=>{let c=s.createServer(t,async(u,g)=>{try{let f=await rc(u,g,n,r,i,s);f.shouldClose&&(d(),f.error?p(f.error):f.tokens?a(f.tokens):p(new Error("No tokens received")))}catch(f){d(),p(f instanceof Error?f:new Error(String(f)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${oc(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close(),c.closeIdleConnections?.()}o(d,"cleanup"),c.on("error",u=>{d(),u.code==="EADDRINUSE"||u.code==="EACCES"?p(new m(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:u,hint:wt(e.port)})):p(new m(`Login callback server failed: ${u.message}`,{cause:u}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(To,"startCallbackServer");import{mkdirSync as ic}from"fs";import{loadLocalCertificates as sc}from"@cognite/app-sdk/https";var ac={loadLocalCertificates:sc,mkdirSync:ic,logger:console};async function $o(e,t=ac){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:i}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new m(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:n,key:r}}o($o,"getOrCreateCertificates");var $n="openid profile email",On={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:cc.join(pc.homedir(),".cdf-login")},hc={open:lc,getOrCreateCertificates:$o,startCallbackServer:To,isPortFree:Ro,discovery:mc,buildAuthorizationUrl:dc,randomPKCECodeVerifier:fc,calculatePKCECodeChallenge:uc,randomState:yc,logger:console,telemetry:yt()};async function Fn(e,t=On,n){return n===void 0?Oo(e,t,hc):Oo(e,t,n)}o(Fn,"login");async function Sc(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,gc())}catch(r){throw new m(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}o(Sc,"fetchOpenIdConfig");async function Oo(e,t,n){let{isPortFree:r,telemetry:i,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:p,randomState:c,buildAuthorizationUrl:l,getOrCreateCertificates:d,open:u,startCallbackServer:g}=n;if(!await r(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:wt(t.port)});s.log(`\u{1F510} Starting CDF login flow...
22
+ `),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let y=await Sc(n,t),h=a(),C=await p(h),S=c(),v={redirect_uri:t.redirectUri,scope:t.scope??$n,code_challenge:C,code_challenge_method:"S256",state:S};e&&(v.organization_hint=e);let w=l(y,v).toString(),b=await d(t.certDir);e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
23
+ `);try{await u(w)}catch(k){let T=k instanceof Error?k.message:String(k);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${T}`),s.error(`Please open this URL manually:
24
+ `),s.error(w),s.error("")}return g(t,b,y,h,S)}o(Oo,"loginImpl");var Ac={...On,scope:`${$n} offline_access`},Ec=3600,bc=720*60*60;function xc(e){return vc(new URL(e.authority),e.clientId,void 0,wc())}o(xc,"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 kc(e,t,n=new Date,r={}){let i=t.access_token?E.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?E.from(t.refresh_token):r.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(),p=(Fo(t.expires_in)??Ec)*1e3,c=(Fo(t.refresh_expires_in)??bc)*1e3;return{version:mt,org:e.org,accessToken:i,refreshToken:s,accessTokenExpiresAt:new Date(a+p).toISOString(),refreshTokenExpiresAt:new Date(a+c).toISOString()}}o(kc,"buildSession");async function Lo(e,t={}){let n=t.discovery??xc,r=t.refreshTokenGrant??((p,c)=>Cc(p,c.expose())),i=t.now??(()=>new Date),s=await n(Ac),a=await r(s,e.refreshToken);return kc({org:e.org},a,i(),{previousRefreshToken:e.refreshToken})}o(Lo,"refreshSession");function Uo(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(Uo,"isInvalidGrant");var Pc="https://auth.cognite.com",Ln=class Ln extends Error{constructor(n,r,i){super(r,i);this.kind=n;this.name="SessionVerificationError"}};o(Ln,"SessionVerificationError");var vt=Ln;function Dc(e){return e instanceof Error?"cause"in e&&e.cause instanceof Error?e.cause.message:e.message:String(e)}o(Dc,"describeTransportError");function Ic(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(Ic,"isJwtClaims");function Rc(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 Ic(n)?n:{}}catch{return{}}}o(Rc,"decodeJwtClaims");function Tc(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(Tc,"isCogIdpProjectsResponse");function $c(e){if(e)try{return new URL(e).host}catch{return}}o($c,"clusterFromApiUrl");async function Mo(e,t={}){let n=t.fetch??globalThis.fetch,r=`${Pc}/api/v0/orgs/${encodeURIComponent(e.org)}/projects`,i;try{i=await n(r,{headers:{Authorization:`Bearer ${e.accessToken.expose()}`}})}catch(l){throw new vt("unreachable",Dc(l),{cause:l})}if(!i.ok)throw new vt("rejected",`CogIdP rejected the token: ${i.status} ${i.statusText}`);let s=await i.json(),p=((Tc(s)?s:{}).items??[]).map(l=>({name:l.name,cluster:$c(l.apiUrl),...l.isDefault?{isDefault:!0}:{}})),c=Rc(e.accessToken);return{sub:c.sub??"unknown",email:c.email,name:c.name,preferredUsername:c.preferred_username,projects:p}}o(Mo,"fetchSessionUserInfo");var Lc=3e4,Mn=class Mn 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"}};o(Mn,"SessionExpiredError");var qe=Mn;function Ct(e){return new qe(e)}o(Ct,"expiredError");async function Uc(e,t,n){let r=await e(Oc.dirname(t),{stale:Lc,retries:{retries:10,factor:1.5,minTimeout:100,maxTimeout:1e3}});try{return await n()}finally{await r()}}o(Uc,"withSessionLock");async function Un(e={}){let t=e.readSession??(()=>In()),n=e.now??(()=>new Date),r=e.sessionFile??I().sessionFile,i=e.lock??Fc,s=await t();if(!s)return;let a=ft(s,n());if(a==="EXPIRED")throw Ct();return a==="VALID"?s:Uc(i,r,async()=>{let p=await t()??s,c=ft(p,n());if(c==="EXPIRED")throw Ct();return c==="VALID"?p:Mc(p,e)})}o(Un,"ensureFreshSession");async function Mc(e,t){let n=t.readSession??(()=>In()),r=t.writeSession??(s=>Eo(s)),i=t.refreshSession??(s=>Lo(s));try{let s=await i(e);return await r(s),s}catch(s){if(!Uo(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 Ct(p)}throw Ct(s)}}o(Mc,"refreshAndPersist");import{CogniteClient as ll}from"@cognite/sdk";var _o="https://docs.cognite.com/cdf/access/";function V(e){return e!==null&&typeof e=="object"}o(V,"isRecord");function oe(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(oe,"isHttpError");function _n(e){return V(e.data)?e.data:void 0}o(_n,"httpErrorResponseBody");function jo(e){let t=_n(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}o(jo,"cdfApiErrorMessage");function _c(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
25
+ See: ${_o}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
26
+ See: ${_o}`;default:return}}o(_c,"httpStatusHint");function ie(e){let t=e instanceof Error?e:new Error(String(e));if(!oe(t))return null;let n=_c(t.status);return n?Object.assign(new Error(`${t.message}
27
+ ${n}`),{cause:t}):null}o(ie,"enrichedHttpError");function jc(e){if(!V(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(V(n)){let r=n.error;if(V(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(jc,"findMissingArray");function Nc(e,t){if(!oe(e)||e.status!==400)return!1;let n=jc(e);return n?n.some(r=>V(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(Nc,"isMissingExternalIdError");function At(e,t){return oe(e)&&e.status===404||Nc(e,t)}o(At,"isNotFoundError");var Ho=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Bo=["ACTIVE","PREVIEW"],jn=class jn extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(jn,"AppVersionNotFoundError");var q=jn,Nn=class Nn extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};o(Nn,"AppNotFoundError");var Fe=Nn;function Et(e,t){return e.includes(t)}o(Et,"includesValue");function Hc(e){return Et(Ho,e)}o(Hc,"isAppVersionLifecycleState");function Bc(e){return Et(Bo,e)}o(Bc,"isAppVersionAlias");function Kc(e){return typeof e.version=="string"&&Hc(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Bc(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Kc,"isAppVersion");function No(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(!Kc(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}o(No,"parseAppVersion");function Vc(e){if(!V(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(Vc,"parseAppMetadata");var Hn=class Hn{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 ie(i)??i}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw ie(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return Vc(r.data)}catch(r){throw At(r,[t])?new Fe(t):ie(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 m("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=E.from(l),u=`${this.client.getBaseUrl()}${c}`,g=new AbortController,f=setTimeout(()=>g.abort(),300*1e3),y;try{y=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 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:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(f)}if(!y.ok){let h=await y.text(),C;try{C=JSON.parse(h)}catch{}let S=h;if(V(C)){let k=C.error;if(typeof k=="string")S=k;else if(V(k)){let T=k.message,A=k.code;S=typeof T=="string"?T:A!=null?`Unknown error (code: ${A})`:h}else{let T=C.message;S=typeof T=="string"?T:h}}let v=y.headers.get("x-request-id"),w=v?` | X-Request-ID: ${v}`:"",b=V(C)?C:h;throw new le(`Upload failed: ${y.status} \u2014 ${S}${w}`,{httpStatusCode:y.status,requestUrl:u,responseBody:b})}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 No(a.data)}catch(a){throw At(a,[t,n])?new q(t,n):ie(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(!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 No(s[0])}catch(i){if(At(i,[t]))return null;throw ie(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 ie(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 ie(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 ie(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 qc(a.data)}catch(a){throw ie(a)??a}}};o(Hn,"AppHostingApi");var bt=Hn,Gc=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],Yc=["developer","certifier"];function qc(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 r=Jc(n);return r?[r]:[]})}o(qc,"parseStoredSignatures");function Jc(e){if(!V(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Et(Yc,n)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!Et(Gc,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Jc,"parseStoredSignature");function Bn(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(Bn,"diffAppMetadata");function zc(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(`
28
+ `)}o(zc,"formatMetadataDriftError");var Kn=class Kn{constructor(t){this.api=new bt(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(oe(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=Bn(i,{name:n,description:r});if(s.length!==0)throw new m(zc(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(`
29
+ \u{1F680} Deploying application via App Hosting API...
30
+ `),await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
31
+ \u2705 Deployment successful!`)}};o(Kn,"AppHostingClient");var U=Kn;import{CogniteClient as il}from"@cognite/sdk";function Wc(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Wc,"exponentialBackoffWithJitter");function Xc(e){return new Promise(t=>setTimeout(t,e))}o(Xc,"sleep");async function Ko(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Wc;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 Xc(p),s++}}o(Ko,"retryAsync");var Zc="https://auth.cognite.com/oauth2/token",Qc=o(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Vo({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let i;try{i=await Ko(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new m(`Failed to fetch access token from ${t}`,{cause:p})}if(!i.ok){let p=await i.text();throw new le(`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 m(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!Qc(a))throw new m(`No access token in ${e} authentication response`,{hint:r});return E.from(a.access_token)}o(Vo,"fetchOAuthToken");var el=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,i]of Object.entries(t))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=i}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),tl=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=el()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return E.from(t)},"getSecretFromEnv"),nl=o((e,t)=>{let n=t.expose();return Vo({idp:"CDF",tokenUrl:Zc,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"),Go=o(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:i,missingTokenHint:s})=>Vo({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"),rl=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"),ol=o((e,t,n,r,i)=>Go({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:i!==void 0?i:[rl(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Vn=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return E.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=tl(r);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Go({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 ol(n,l,s,a,p)}return nl(n,l)},"getToken");async function Le(e,t,n=process.env,r){let i=await Vn(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new il(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(Le,"getSdk");import PS from"enquirer";import{HttpError as MS}from"@cognite/sdk";import{array as Yo,number as al,object as qo,optional as pl,safeParse as jS,string as cl}from"valibot";var HS=qo({projects:pl(Yo(qo({projectUrlName:cl(),groups:Yo(al())})))});async function _(e,t,n={}){let{login:r=Fn,getSdk:i=Le,createClient:s=o(a=>new ll(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=E.from(p.access_token),l=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>c.expose(),"getToken")});return await l.authenticate(),l}return i(e,t.appId)}o(_,"buildAppHostingApiClient");async function xt(e,t,n={}){let r=await _(e,t,n);return new U(r)}o(xt,"buildAppHostingClient");import Jo from"enquirer";var zo="Enter custom target...";function Wo(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
35
32
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
36
- ${n}`)}i(xr,"deploymentNotFoundError");function D(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;xr(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;xr(t,e)}i(D,"findDeployment");function R(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}i(R,"getMissingCredentials");async function T(e,t){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 D(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),kr],{selected:r}=await Er.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==kr){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 o=await Er.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:i(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:o.org||"",project:o.project,baseUrl:o.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}i(T,"resolveDeployment");import{existsSync as sa}from"fs";import{resolve as aa}from"path";import{config as pa}from"dotenv";function F(e,t={existsSync:sa,config:pa}){let n=aa(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}i(F,"loadEnvFile");function O(e){e.infra!=="appsApi"&&(console.error(`
33
+ ${n}`)}o(Wo,"deploymentNotFoundError");function R(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;Wo(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Wo(t,e)}o(R,"findDeployment");function j(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(j,"getMissingCredentials");async function F(e,t){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 R(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),zo],{selected:r}=await Jo.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==zo){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 Jo.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(F,"resolveDeployment");function Xo(e,t=process.cwd(),n={}){let r=n.readSessionMetadata??gt,i=n.loadAppConfig??x;if(e.org)return e.org;let s=r();if(s?.org)return s.org;try{let a=i(t),p=R(a.deployments,void 0);if(p.org)return p.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})}o(Xo,"resolveOrg");function $(e,t=1){return" ".repeat(t).concat(e)}o($,"indent");async function J(e,t=process.cwd(),n={}){let r=n.ensureFreshSession??Un,i=n.fetchUserInfo??Mo,s=n.loadAppConfig??x,a=n.createClient??(c=>new dl(c));if(e.interactive&&e.baseUrl&&e.project)return _(gl(e),{interactive:!0,appId:"cognite-cli",orgHint:e.org},n.getClient);let p=await ul(e,r,i,a);if(p)return p;try{let c=s(t),l=e.interactive?await F(c,e):R(c.deployments,void 0);return _(l,{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})}o(J,"getAgentClient");async function ul(e,t,n,r){let i;try{i=await t()}catch(l){if(l instanceof qe)throw new m("Your session has expired.",{hint:"Run `cognite auth login` to sign in again.",shouldReport:!1,cause:l});return null}if(!i)return null;let s=await n(i),a=ml(e.project,s.projects),p=`https://${a.cluster}`,c=r({appId:"cognite-cli",project:a.name,baseUrl:p,oidcTokenProvider:o(async()=>((await t())?.accessToken??i.accessToken).expose(),"oidcTokenProvider")});return await c.authenticate(),c}o(ul,"trySessionClient");function ml(e,t){if(e){let r=t.find(i=>i.name===e);if(!r?.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{...r,cluster:r.cluster}}let n=t.find(r=>r.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(r=>r.name).join(", ")}`,shouldReport:!1})}o(ml,"resolveSessionProject");function gl(e){return{org:e.org??"",project:e.project??"",baseUrl:e.baseUrl??"",deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(gl,"getDeployment");var qn=class qn extends de{constructor(){super("create");this.handle=o(async(n,r,i)=>{let s=i.optsWithGlobals(),a=s.prompt;a&&pt();let p={externalId:s.externalId,displayName:s.displayName,description:s.description,model:s.model,instructions:s.instructions,runtimeVersion:s.runtimeVersion},c=n==="."||n==="./",l=vl(n,c),d={models:[],defaultModel:Ke.model};try{let f=await J(s);d=await re(f).getAvailableModels()}catch{}let u=await new ct(l,p,a,d.models,d.defaultModel).resolve(),g=Cl(c,u.dirName);await Al(g,c,u.dirName),await Gn(Ue(g,P.config),this.buildAgentYaml(u)),await this.scaffoldEvalCases(g,u),await Gn(Ue(g,P.readme),await this.buildReadme(u)),this.printSummary(u)},"handle");this.buildAgentYaml=o(({dirName:n,...r})=>te(r),"buildAgentYaml");this.buildReadme=o(async n=>{let r=await Zo(Ue(ei,"agents","create",P.readmeTemplate),"utf8");return ti(r,{displayName:n.name})},"buildReadme");this.scaffoldEvalCases=o(async(n,r)=>{let i=Ue(n,P.evalDir);await ri(i,{recursive:!0});let s=await Zo(Ue(ei,"agents","create",P.evalCasesTemplate),"utf8"),a=ti(s,{displayName:r.name});await Gn(Ue(i,P.evalCases),a)},"scaffoldEvalCases");this.printSummary=o(n=>{let r=D(process.stdout),i=n.dirName;console.log(),console.log(r.green(`Created agent project at ${i}/`)),console.log(),console.log($(`directory: ${i}/`)),console.log($(`externalId: ${n.externalId}`)),console.log($(`display name: ${n.name}`)),n.model&&console.log($(`model: ${n.model}`)),console.log(),console.log("Next steps:"),console.log($(`1. Edit ${i}/${P.config} \u2014 add tools and refine instructions`)),console.log($(`2. cognite agents push ${i}`)),console.log($(`3. cognite agents open ${i}`)),console.log($(`4. Edit ${i}/${P.evalDir}/${P.evalCases} and run: cognite agents eval ${i}`)),console.log()},"printSummary");this.description("Scaffold a new agent project").argument("[dir]","Agent name / directory").addHelpText("after",Sl);for(let n of Object.values(oi))this.addOption(n);this.action(this.handle)}};o(qn,"CreateCommand");var kt=qn,oi=Object.freeze({externalId:new Ee("--external-id <id>","Agent externalId"),displayName:new Ee("--display-name <name>","Agent display name"),description:new Ee("--description <text>","Agent description"),model:new Ee("--model <model>","Language model (e.g. azure/gpt-4.1)"),instructions:new Ee("--instructions <text>","System prompt / instructions"),runtimeVersion:new Ee("--runtime-version <version>","Agent runtime version"),noPrompt:new Ee("--no-prompt","Skip interactive prompts, use defaults")}),Yw=Object.values(oi).map(e=>e.long),Sl=`
34
+ Examples:
35
+ cognite agents create Interactive scaffold
36
+ cognite agents create my-agent Scaffold with name "my-agent"
37
+ cognite agents create my-agent \\
38
+ --description "Helps with maintenance" \\
39
+ --model azure/gpt-4.1 \\
40
+ --no-prompt Fully non-interactive
41
+ `,ii=yl(hl(import.meta.url)),Qo=Yn(ii,"..","..","_templates"),wl=Yn(ii,"..","..","..","_templates"),ei=ni(Qo)?Qo:wl;function vl(e,t){return t?fl(process.cwd()):e}o(vl,"normalizeDirArg");function Cl(e,t){return e?process.cwd():Yn(process.cwd(),t)}o(Cl,"resolveTargetDir");async function Al(e,t,n){if(!t){if(ni(e))throw new m(`An agent folder named "${n}" already exists at:
42
+ ${e}`,{hint:"Use a different agent name or remove the existing directory.",shouldReport:!1});await ri(e)}}o(Al,"ensureTargetDir");function ti(e,t){return e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??"")}o(ti,"renderTemplate");import{resolve as gd}from"path";import{Option as Me}from"commander";import{readFile as El}from"fs/promises";import{join as bl}from"path";import{array as Jn,literal as Pt,minLength as zn,nonEmpty as Dt,object as xe,optional as xl,pipe as be,safeParse as kl,string as It,variant as Pl}from"valibot";import{parse as Dl}from"yaml";var Il=xe({type:Pt("correctness"),reference:be(It(),Dt("must not be empty"))}),Rl=xe({type:Pt("faithfulness"),context:be(It(),Dt("must not be empty"))}),Tl=xe({type:Pt("toolSelection")}),$l=xe({type:Pt("toolInvocation")}),Ol=Pl("type",[Il,Rl,Tl,$l]),si=["correctness","faithfulness","toolSelection","toolInvocation"],Fl=xe({input:be(It(),Dt("must not be empty")),scorers:xl(be(Jn(Ol),zn(1,"must contain at least one scorer")))}),Ll=xe({id:be(It(),Dt("must not be empty")),turns:be(Jn(Fl),zn(1,"must contain at least one turn"))}),Ul=xe({cases:be(Jn(Ll),zn(1,"must contain at least one case"))});function ai(e,t){let n=e;if(t?.caseFilter&&t.caseFilter.length>0&&(n=n.filter(r=>t.caseFilter.includes(r.id))),n.length===0)throw new m("No eval cases matched the filter.",{hint:"Check the --case flag values against the case ids in eval/cases.yaml.",shouldReport:!1});return n}o(ai,"filterEvalCases");async function pi(e){let t=bl(e,"eval","cases.yaml"),n;try{n=await El(t,"utf8")}catch{throw new m(`No eval/cases.yaml found at:
43
+ ${t}`,{hint:"Create eval/cases.yaml in your agent project directory with at least one case.",shouldReport:!1})}let r;try{r=Dl(n)}catch(s){throw new m("Failed to parse eval/cases.yaml: "+(s instanceof Error?s.message:String(s)),{hint:"Check the YAML syntax of your eval/cases.yaml file.",shouldReport:!1})}let i=kl(Ul,r);if(!i.success){let s=i.issues.map(a=>{let p=a.path?.map(c=>String(c.key)).join(".")??"";return p?`${p}: ${a.message}`:a.message}).join("; ");throw new m(`Invalid eval/cases.yaml: ${s}`,{shouldReport:!1})}return Ml(i.output.cases),i.output.cases}o(pi,"loadEvalCases");function Ml(e){for(let t of e)if(!t.turns.some(r=>r.scorers&&r.scorers.length>0))throw new m(`Invalid eval/cases.yaml: case "${t.id}" has no scored turns`,{hint:"Add scorers to at least one turn in each case.",shouldReport:!1})}o(Ml,"assertCaseHasScoredTurn");var _l=["name","description","instructions","model","runtimeVersion"],jl=["labels","tools","skills","subagents","exampleQuestions"];function ui(e,t){let n=ve(e),r=ve(t),i=[];for(let s of _l){let a=n[s],p=r[s];Nl(a,p)||i.push({field:s,local:ci(a),remote:ci(p)})}for(let s of jl){let a=n[s],p=r[s];Hl(s,a,p)||i.push({field:s,local:li(s,a),remote:li(s,p)})}return i}o(ui,"detectDrift");function mi(e,t){let r=["Warning: local agent.yaml differs from deployed config.",` Fields: ${e.map(i=>i.field).join(", ")}`];if(t?.verbose)for(let{field:i,remote:s,local:a}of e){let p=`${i}:`.padEnd(18);r.push(` ${p}"${s}" \u2192 "${a}"`)}return r.push(" Run with --upsert to push local changes before evaluating."),r.join(`
44
+ `)}o(mi,"formatAgentDriftWarning");function Nl(e,t){return Wn(e)===Wn(t)}o(Nl,"scalarValuesEqual");function Hl(e,t,n){return Zn(Xn(t),e)===Zn(Xn(n),e)}o(Hl,"arrayValuesEqual");function Wn(e){return e??""}o(Wn,"normalizeOptionalString");function ci(e){return Wn(e)}o(ci,"formatScalarValue");function li(e,t){return Zn(Xn(t),e)}o(li,"formatArrayValue");function Xn(e){return e??[]}o(Xn,"normalizeArray");function Zn(e,t){let n=[...e].sort((r,i)=>di(t,r).localeCompare(di(t,i)));return Je(n)}o(Zn,"stableArrayStringify");function di(e,t){if(typeof t!="object"||t===null)return Je(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 Je(t)}}o(di,"arrayItemSortKey");function Je(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>Je(r)).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${Je(t[r])}`).join(",")}}`}o(Je,"stableStringify");async function gi(e,t){if(e)try{e.track("Flows.CLI.Agents.Eval",{...t}),await e.flush(Oe)}catch{}}o(gi,"trackAgentsEval");function yi(e){let{modelId:t,service:n,verbose:r}=e;return{specificationVersion:"v2",provider:"cdf",modelId:t,supportedUrls:{},async doGenerate(i){return Bl(i,{modelId:t,service:n,verbose:r})},async doStream(i){throw new Error("CDF chat completions judge does not support streaming")}}}o(yi,"createCdfChatCompletionsModel");async function Bl(e,t){let{modelId:n,service:r,verbose:i}=t,s=Kl(e.responseFormat),a=Vl(e.prompt,s),p={model:n,messages:a,stream:!1,temperature:e.temperature,maxTokens:e.maxOutputTokens};i?.logJson("chat/completions request",p),i?.log("judge POST /ai/chat/completions");let c=performance.now(),l=await r.postChatCompletions(p);i?.log(`judge chat/completions HTTP 200 in ${((performance.now()-c)/1e3).toFixed(1)}s`),i?.logJson("chat/completions response",l);let d=l.choices[0]?.message?.content??"",u=l.choices[0]?.finishReason??"stop";return{content:[{type:"text",text:d}],finishReason:Gl(u),usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},warnings:[],request:{body:p},response:{modelId:l.model??n,body:l}}}o(Bl,"generateWithCdf");function Kl(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?`
45
+ ${e.description}`:""}
46
+ The JSON must conform to this schema${n}: ${t}`}o(Kl,"jsonResponseInstruction");function Vl(e,t){let n=[];t&&n.push({role:"system",content:t});for(let r of e){if(r.role==="system"){n.push({role:"system",content:r.content});continue}if(r.role==="user"){let i=fi(r.content);i&&n.push({role:"user",content:i});continue}if(r.role==="assistant"){let i=fi(r.content);i&&n.push({role:"assistant",content:i})}}return n}o(Vl,"toCdfMessages");function fi(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(`
47
+ `)}o(fi,"extractTextParts");function Gl(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"}}o(Gl,"mapFinishReason");var Yl="azure/gpt-5";function Qn(e={}){return e.cliModelId?.trim()||process.env.EVAL_JUDGE_MODEL?.trim()||e.agentModelFallback?.trim()||Yl}o(Qn,"resolveJudgeModelId");function hi(e){let t=e.modelId??Qn({cliModelId:e.cliModelId,agentModelFallback:e.agentModelFallback});return yi({modelId:t,service:e.service,verbose:e.verbose})}o(hi,"createJudgeModel");function Si(){let e=process.env.AGENT_CHAT_ROUTE?.trim().toLowerCase();return e==="public"||e==="agents"?"public":e==="internal"||e==="fusion"?"internal":"public"}o(Si,"resolveAgentChatRoute");function wi(e,t){let n=t==="internal"?"internal/agents/chat":"agents/chat";return`/api/v1/projects/${encodeURIComponent(e)}/ai/${n}`}o(wi,"formatAgentChatPath");function vi(e){return`/api/v1/projects/${encodeURIComponent(e)}/ai/chat/completions`}o(vi,"formatChatCompletionsPath");function ql(e){return typeof e=="object"&&e!==null&&e.type==="result"&&Array.isArray(e.messages)}o(ql,"isSessionResult");function Ci(e){let t=e.content?.text;if(typeof t=="string"&&t.length>0)return t;let n=[];for(let r of e.reasoning??[])for(let i of r.content??[])typeof i.text=="string"&&i.text.length>0&&n.push(i.text);return n.join(`
48
+ `).trim()}o(Ci,"messageText");function Rt(e){return e.map(t=>t.name).join(", ")}o(Rt,"formatToolNameList");function Jl(e){let t=[];for(let n of e)for(let r of n.reasoning??[])for(let i of r.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}o(Jl,"extractToolCalls");function zl(e){let t=[];for(let n of e){let r=!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){r=!0;break}}if(r)break}if(!r)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})}}return t}o(zl,"synthesizeToolConfirmationCalls");function Ai(e){let t=e.response;if(!ql(t))throw new Error("Unexpected agent chat response shape");let n=t.messages,r=n[n.length-1];if(!r)throw new Error("Agent returned no messages");let i=[...Jl(n),...zl(n)],s=r.actions?.find(a=>a.type==="toolConfirmation");if(s){let a=s.actionId??s.id;if(!a)throw new Error("Tool confirmation action missing actionId (both actionId and id are absent)");return{output:Ci(r),toolCalls:i,cursor:t.cursor,pendingToolConfirmation:{actionId:a,toolName:s.toolConfirmation?.toolName}}}return{output:Ci(r),toolCalls:i,cursor:t.cursor}}o(Ai,"extractAgentTurn");async function Ei(e){let t=e.allowToolConfirmation!==!1,n=e.maxTurns??8,r=e.verbose;r?.log(`agentExternalId=${e.agentExternalId} | auto-allow tools=${t}`);let i=e.cursor,s,a,p=[],c="",l=0;for(let d=0;d<n;d+=1){l+=1;let u=`turn ${l}/${n}`,g=s&&i?{agentExternalId:e.agentExternalId,cursor:i,messages:[{role:"action",type:"toolConfirmation",actionId:s,status:"ALLOW"}]}:{agentExternalId:e.agentExternalId,...i?{cursor:i}:{},messages:[{role:"user",content:{type:"text",text:e.input}}]};r?.log(`${u}: sending chat request\u2026`),r?.logJson(`${u} request body`,g),a=await e.service.postAgentChat(g),r?.logJson(`${u} response`,a);let f;try{f=Ai(a)}catch(y){throw new m(`Failed to parse agent response on turn ${l}/${n}`,{hint:"The CDF agent API returned an unexpected response shape. Run with --verbose to see the raw response.",cause:y})}if(p.push(...f.toolCalls),r?.log(`${u}: extracted output length=${f.output.length}, tools=[${Rt(f.toolCalls)}]`),f.output&&(c=f.output),f.pendingToolConfirmation){if(r?.log(`${u}: tool confirmation requested \u2014 tool=${f.pendingToolConfirmation.toolName??"?"} actionId=${f.pendingToolConfirmation.actionId}`),!t)throw new m(`Agent requested tool confirmation (${f.pendingToolConfirmation.toolName??"unknown"}) but allowToolConfirmation is false`,{hint:"Re-run with tool confirmation enabled, or adjust the agent to avoid confirmation prompts."});if(!f.cursor||!f.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=f.cursor,s=f.pendingToolConfirmation.actionId,r?.log(`${u}: auto-ALLOW, continuing with cursor\u2026`);continue}return r?.log(`${u}: conversation complete`),{output:c,toolCalls:p,turns:l,cursor:f.cursor??i,lastResponse:a}}throw new m(`Agent chat exceeded ${n} turns (tool confirmation loop?)`,{hint:"The agent may be stuck in a tool-confirmation loop. Increase maxTurns or inspect the agent configuration."})}o(Ei,"invokeAgentCase");import{createCorrectnessEvaluator as ed}from"@arizeai/phoenix-evals/llm/createCorrectnessEvaluator";import{createFaithfulnessEvaluator as td}from"@arizeai/phoenix-evals/llm/createFaithfulnessEvaluator";import{createToolInvocationEvaluator as nd}from"@arizeai/phoenix-evals/llm/createToolInvocationEvaluator";import{createToolSelectionEvaluator as rd}from"@arizeai/phoenix-evals/llm/createToolSelectionEvaluator";function bi(e){return{log(t){e(t)},logJson(t,n,r=6e3){e(`${t}:
49
+ ${Wl(n,r)}`)}}}o(bi,"createEvalLogger");function Wl(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)}
50
+ \u2026 (${n.length-t} more chars)`}o(Wl,"formatJson");function xi(e){return e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`}o(xi,"formatDurationMs");var Xl=.5,Zl={correctness:{pass:"correct",fail:"incorrect"},faithfulness:{pass:"faithful",fail:"unfaithful"},toolSelection:{pass:"correct",fail:"incorrect"},toolInvocation:{pass:"correct",fail:"incorrect"}};function Ql(e,t){let n=Zl[e];if(n){if(t.label===n.pass)return!0;if(t.label===n.fail)return!1}return(t.score??0)>=Xl}o(Ql,"scorerPassed");async function ze(e,t,n,r,i,s){s?.log(`scoring ${n.type} (Phoenix + CDF /ai/chat/completions)\u2026`),s?.logJson(`${n.type} judge input`,i);let a=performance.now(),p;try{p=await r.evaluate(i)}catch(d){if(fe(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 ${xi(performance.now()-a)}`),s?.logJson(`${n.type} judge result`,p);let c=Ql(n.type,p),l=typeof p.score=="number"?p.score:c?1:0;return{caseId:e,turnIndex:t,scorerType:n.type,score:l,label:p.label,explanation:p.explanation,passed:c}}o(ze,"runPhoenixLlmScorer");function ki(e=[]){return e.map(t=>`${t.name}: ${t.description}`).join(`
51
+ `)}o(ki,"formatAvailableTools");function od(e){return e.length>0?Rt(e):"No tools called"}o(od,"formatToolSelection");function id(e){if(e.input===void 0||e.input===null)return`${e.name}()`;if(typeof e.input=="object"&&!Array.isArray(e.input)){let t=Object.entries(e.input);if(t.length===0)return`${e.name}()`;let n=t.map(([r,i])=>`${r}=${JSON.stringify(i)}`).join(", ");return`${e.name}(${n})`}return`${e.name}(${JSON.stringify(e.input)})`}o(id,"formatToolInvocation");function sd(e){return e.length>0?e.map(id).join(`
52
+ `):"No tools called"}o(sd,"formatToolInvocations");function ad(e){let t=e.map(n=>`"${n}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}o(ad,"formatScorerTypeList");function pd(e,t){let n=e.turns.slice(0,t);return n.length===0?"":`Conversation so far:
53
+ `+n.map(r=>`User: ${r.input}
54
+ Assistant: ${r.output}`).join(`
55
+ `)+`
56
+
57
+ `}o(pd,"conversationContext");async function cd(e,t,n,r,i,s){let a=r.turns[t];if(!a)throw new m(`No agent response recorded for turn ${t+1} of case "${e.id}".`,{hint:"This is an internal mismatch between scored turns and executed turns."});let p=pd(r,t),c=s?.verbose;if(n.type==="correctness"){let d=ed({model:i});return ze(e.id,t,n,d,{input:`${p}User question:
58
+ ${a.input}
59
+
60
+ Reference criteria:
61
+ ${n.reference}`,output:a.output},c)}if(n.type==="faithfulness"){let d=td({model:i});return ze(e.id,t,n,d,{input:p?`${p}Current question:
62
+ ${a.input}`:a.input,output:a.output,context:n.context},c)}if(n.type==="toolSelection"){let d=rd({model:i});return ze(e.id,t,n,d,{input:p?`${p}Current question:
63
+ ${a.input}`:a.input,availableTools:ki(s?.tools),toolSelection:od(a.toolCalls)},c)}if(n.type==="toolInvocation"){let d=nd({model:i});return ze(e.id,t,n,d,{input:p?`${p}Current question:
64
+ ${a.input}`:a.input,availableTools:ki(s?.tools),toolSelection:sd(a.toolCalls)},c)}let l=n;throw new m(`Scorer type "${l.type}" is not supported yet.`,{hint:`The CLI eval schema currently supports only ${ad(si)} scorers.`,shouldReport:!1})}o(cd,"evaluateScorer");async function ld(e,t,n,r,i){let s=e.turns[t]?.scorers??[];return Promise.all(s.map(a=>cd(e,t,a,n,r,i)))}o(ld,"scoreTurn");async function Pi(e,t,n,r){return(await Promise.all(e.turns.map((s,a)=>ld(e,a,t,n,r)))).flat()}o(Pi,"scoreCase");function dd(e){return e.length>0&&e.every(t=>t.passed)}o(dd,"casePassed");function ud(e,t,n){if(n<=1)return e;let r=e instanceof Error?e.message:String(e);return new m(`turn ${t+1}/${n}: ${r}`,{hint:fe(e)?e.hint:void 0,helpUrl:fe(e)?e.helpUrl:void 0,shouldReport:fe(e)?e.shouldReport:void 0,cause:e})}o(ud,"annotateTurnFailure");async function md(e,t){let{service:n,agentExternalId:r,judgeModel:i,verbose:s}=t;s?.log(`--- case "${e.id}" invoke ---`);let a;try{let p=[],c;for(let[l,d]of e.turns.entries()){s?.log(` turn ${l+1}/${e.turns.length}: "${d.input}"`);let u;try{u=await Ei({service:n,agentExternalId:r,input:d.input,cursor:c,allowToolConfirmation:t.allowToolConfirmation,verbose:s})}catch(g){throw ud(g,l,e.turns.length)}c=u.cursor,p.push({input:d.input,output:u.output,toolCalls:u.toolCalls,apiRoundTrips:u.turns})}a={caseId:e.id,turns:p}}catch(p){return{evalCase:e,scores:[],passed:!1,invokeError:p instanceof Error?p:new Error(String(p))}}s?.log(`--- case "${e.id}" score (Phoenix) ---`);try{let p=await Pi(e,a,i,{verbose:s,tools:t.tools});return{evalCase:e,run:a,scores:p,passed:dd(p)}}catch(p){return{evalCase:e,run:a,scores:[],passed:!1,scoreError:p instanceof Error?p:new Error(String(p))}}}o(md,"runCase");async function Di(e){let{cases:t,verbose:n}=e,r=[];for(let s of t){let a=await md(s,e);if(r.push(a),e.failFast&&!a.passed){n?.log(`--- fail-fast: stopping after failed case "${s.id}" ---`);break}}let i=r.filter(s=>s.passed).length;return{totalCases:t.length,passedCases:i,failedCases:r.length-i,skippedCases:t.length-r.length,results:r}}o(Di,"runEval");var Ii={"cdf-version":"20230101-alpha"};function Ti(e,t){let n=wi(e.project,t),r=vi(e.project);async function i(a){try{return(await e.post(n,{data:a,headers:Ii})).data}catch(p){let c=t==="internal"&&oe(p)&&p.status===404?" Try the public route: set AGENT_CHAT_ROUTE=public.":"";throw Ri(p,"Agent chat",n,c||void 0)}}o(i,"postAgentChat");async function s(a){try{return(await e.post(r,{data:a,headers:Ii})).data}catch(p){throw Ri(p,"Chat completions",r)}}return o(s,"postChatCompletions"),{postAgentChat:i,postChatCompletions:s}}o(Ti,"getEvalService");function Ri(e,t,n,r){if(!oe(e))return e instanceof Error?e:new Error(String(e));let i=jo(e),s=i?`: ${i}`:"",a=r??"";return new le(`${t} failed (${e.status})${s}${a}`,{httpStatusCode:e.status,requestUrl:n,responseBody:_n(e),cause:e})}o(Ri,"wrapCdfApiError");function fd(e,t){return t?[...t,e]:[e]}o(fd,"collectCaseIds");var er=Object.freeze({case:new Me("--case <id>","Run only cases with this id (repeatable)").argParser(fd),judgeModel:new Me("--judge-model <model>","LLM model for scoring eval cases (e.g. azure/gpt-5)"),upsert:new Me("--upsert","Push local agent.yaml to CDF before running evals"),failFast:new Me("--fail-fast","Stop after the first failing case; skip the rest"),verbose:new Me("-v, --verbose","Log request/response traces to stderr"),failOnToolConfirmation:new Me("--fail-on-tool-confirmation","Fail a case instead of auto-approving when the agent requests tool confirmation")}),cC=Object.values(er).map(e=>e.long).filter(e=>e!=null);function yd(e,t,n){let r=e.passed?n.green("\u2713"):n.red("\u2717");if(t(`${r} ${e.evalCase.id}`),e.invokeError){t($(n.red("invoke: fail"))),t($(e.invokeError.message,2)),e.invokeError instanceof m&&e.invokeError.hint&&t($(n.yellow(`\u{1F4A1} ${e.invokeError.hint}`),2));return}if(e.scoreError){t($(n.red("score: fail"))),t($(e.scoreError.message,2)),e.scoreError instanceof m&&e.scoreError.hint&&t($(n.yellow(`\u{1F4A1} ${e.scoreError.hint}`),2));return}let i=[...new Set(e.scores.map(a=>a.turnIndex))],s=i.length>1;for(let a of i){let p=s?2:1;s&&t($(n.dim(`turn ${a+1}`)));for(let c of e.scores.filter(l=>l.turnIndex===a)){let l=c.passed?n.green("pass"):n.red("fail");t($(`${c.scorerType}: ${l}`,p)),c.explanation&&t($(n.dim(c.explanation),p+1))}}}o(yd,"formatCaseResult");async function hd(e,t,n,r){if(n.upsert){await t.upsert(ve(e)),r.writeStdout(r.c.green(`Pushed agent "${e.externalId}" to project "${r.project}"`));return}try{let i=await t.getByExternalId(e.externalId),s=ui(e,i);s.length>0&&r.writeStderr(r.c.yellow(mi(s,{verbose:n.verbose})))}catch(i){if(i instanceof m&&i.message.includes("not found"))r.writeStderr(r.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);r.writeStderr(r.c.yellow(`Warning: failed to fetch deployed agent "${e.externalId}": ${s}`))}}}o(hd,"ensureAgentConfigBeforeEval");async function $i(e,t,n={}){let r=n.readAgentYaml??ne,i=n.loadEvalCases??pi,s=n.writeStdout??(O=>console.log(O)),a=n.writeStderr??(O=>console.error(O)),p=n.chalk??D(process.stdout),c=n.getAgentClient??J,l=n.getAgentsService??re,d=n.getEvalService??Ti,u=n.runEval??Di,g=gd(e??"."),f=await r(g),y=await i(g),h=ai(y,{caseFilter:t.case}),C=await c(t,g),S=l(C);await hd(f,S,t,{project:C.project,writeStdout:s,writeStderr:a,c:p});let v=Si(),w=d(C,v),b=t.verbose?bi(O=>console.error(O)):void 0,k=Qn({cliModelId:t.judgeModel,agentModelFallback:f.model});s(`Judge model: ${p.cyan(k)}`),b?.log(`Agent: ${f.externalId}`),b?.log(`Loaded ${h.length} case(s): ${h.map(O=>O.id).join(", ")}`),b?.log(`judge model: ${k} (source: ${t.judgeModel?"--judge-model flag":process.env.EVAL_JUDGE_MODEL?"EVAL_JUDGE_MODEL env":f.model?"agent.yaml model fallback":"default"})`),b?.log(`agent chat route: ${v}`);let T=hi({cliModelId:t.judgeModel,agentModelFallback:f.model,service:w,verbose:b}),A=await u({cases:h,service:w,agentExternalId:f.externalId,judgeModel:T,verbose:b,tools:f.tools,allowToolConfirmation:!t.failOnToolConfirmation,failFast:t.failFast});for(let O of A.results)yd(O,s,p);let X=`${A.passedCases}/${A.totalCases} cases passed`,pe=A.failedCases>0?p.bold(p.red(X)):p.bold(p.green(X));s(`
65
+ ${pe}`),A.skippedCases>0&&s(p.yellow(`Stopped early (--fail-fast): ${A.skippedCases} case(s) not run.`)),A.failedCases>0&&(process.exitCode=1);let L=Array.from(new Set(h.flatMap(O=>O.turns.flatMap(Re=>Re.scorers?.map(ce=>ce.type)??[])))),Z=hn();await gi(n.telemetry,{caseCount:A.totalCases,passCount:A.passedCases,failCount:A.failedCases,scorersUsed:L,success:A.failedCases===0,...Z!==void 0&&{actionDurationMs:Z}})}o($i,"handleAgentsEval");import{Option as Ad}from"commander";function Tt(e,t){return e.map((n,r)=>Math.max(n.length,...t.map(i=>i[r].length)))}o(Tt,"computeColumnWidths");function We(e,t,n=e){return e.map((r,i)=>n[i]+" ".repeat(Math.max(0,t[i]-r.length))).join(" ").trimEnd()}o(We,"formatTableRow");import{writeFile as Oi}from"fs/promises";import{join as wd,resolve as vd}from"path";import{resolve as Sd}from"path";async function se(e,t,n={}){let r=n.readAgentYaml??ne,i=n.getAgentClient??J,s=n.getAgentsService??re,a=Sd(e??"."),p=await r(a),c=await i(t,a);await s(c).upsert(ve(p));let d=D(process.stdout);return console.log(d.green(`Pushed agent "${p.externalId}" to project "${c.project}"`)),{client:c,agentYaml:p}}o(se,"handleAgentsPush");var ke="published",tr=class tr extends de{constructor(){super("publish");this.handle=o(async(n,r,i)=>{let s=i.optsWithGlobals(),a=vd(n??"."),p=await ne(a),c=p.labels??[],l=wd(a,P.config);if(c.includes(ke))await se(n,s);else{let u={...p,labels:[...c,ke]};await Oi(l,te(u));try{await se(n,s)}catch(g){throw await Oi(l,te(p)),g}}let d=D(process.stdout);console.log(d.green(`Published agent "${p.externalId}"`))},"handle");this.description("Promote a draft agent to production").argument("[dir]","Agent project directory").addHelpText("after",Cd),this.action(this.handle)}};o(tr,"PublishCommand");var $t=tr,Cd=`
66
+ Examples:
67
+ cognite agents publish Publish agent in current directory
68
+ cognite agents publish ./my-agent Publish agent in my-agent directory
69
+ `;var Fi=Object.freeze({json:new Ad("--json","Output as JSON")});async function Li(e,t={}){let n=t.getAgentClient??J,r=t.getAgentsService??re,i=await n(e,process.cwd()),p=(await r(i).list()).items;if(e.json){console.log(JSON.stringify(p,null,2));return}if(p.length===0){console.log(`No agents found in project "${i.project}".`);return}let c=D(process.stdout),l=p.map(S=>({externalId:S.externalId,name:S.name,status:S.labels?.includes(ke)?"published":"draft",model:S.model,updated:Ed(S.lastUpdatedTime)})),d=["externalId","name","status","model","updated"],u=["External ID","Name","Status","Model","Updated"],g=l.map(S=>d.map(v=>S[v])),f=Tt(u,g);console.log(),console.log(c.bold(We(u,f))),console.log(c.dim(f.map(S=>"\u2500".repeat(S)).join(" ")));for(let S of l){let v=S.status==="published"?c.green(S.status):c.yellow(S.status),w=d.map(k=>S[k]),b=d.map(k=>k==="status"?v:S[k]);console.log(We(w,f,b))}console.log();let y=l.filter(S=>S.status==="published").length,h=l.length-y,C=[`${l.length} agent${l.length===1?"":"s"}`];y>0&&C.push(`${y} published`),h>0&&C.push(`${h} draft`),console.log(C.join(", "))}o(Li,"handleAgentsList");function Ed(e,t=Date.now()){let n=t-e;if(n<0)return"just now";let r=Math.floor(n/1e3);if(r<60)return"just now";let i=Math.floor(r/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`}o(Ed,"formatRelativeTime");import{resolve as bd}from"path";import{Option as xd}from"commander";function Ui(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(Ui,"generateFusionUrl");function Mi(e){let{org:t,project:n,cluster:r,agentExternalId:i}=e,s=new URLSearchParams({cluster:r,atlasOverride:i});return`https://${t}.fusion.cognite.com/${n}?${s}`}o(Mi,"generateAtlasAgentUrl");var nr=Object.freeze({upsert:new xd("--upsert","Push the agent to CDF before opening (upsert draft)").default(!1)}),zC=Object.values(nr).map(e=>e.long).filter(e=>e!=null);function kd(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})}}o(kd,"clusterFromBaseUrl");async function _i(e,t,n={}){let r=n.handleAgentsPush??se,i=n.readAgentYaml??ne,s=n.getAgentClient??J,a=n.resolveOrg??Xo,p=n.openInBrowser??ht,c=bd(e??"."),{client:l,agentYaml:d}=t.upsert?await r(e,t):{agentYaml:await i(c),client:await s(t,c)},u=a(t,c),g=l.project,f=kd(l),y=Mi({org:u,project:g,cluster:f,agentExternalId:d.externalId}),h=D(process.stdout);console.log(h.cyan(`Opening ${y}`)),p(y)}o(_i,"handleAgentsOpen");import{existsSync as Pd}from"fs";import{mkdir as Dd,writeFile as Id}from"fs/promises";import{join as Rd,resolve as Td}from"path";import{Option as ji}from"commander";async function Ni(e,t,n={getAgentClient:{}}){let r=await J(t,process.cwd(),n.getAgentClient),i=await re(r).getByExternalId(e),s=Td(t.dir),a=Rd(s,P.config);if(Pd(a)&&!t.force)throw new m(`${P.config} already exists at:
70
+ ${a}`,{hint:"Use --force to overwrite the existing file.",shouldReport:!1});await Dd(s,{recursive:!0}),await Id(a,te(i));let p=D(process.stdout);console.log(p.green(`Pulled agent "${i.name}" (${e}) to ${a}`))}o(Ni,"handleAgentsPull");var rr=Object.freeze({externalId:{name:"external-id",description:"externalId of the agent to pull"}}),or=Object.freeze({dir:new ji("--dir <path>","Output directory").default("."),force:new ji("--force",`Overwrite existing ${P.config} without prompting`)}),pA=Object.values(or).map(e=>e.long).filter(e=>e!=null);async function Hi(e){console.log("not yet implemented")}o(Hi,"handleAgentsStatus");import{writeFile as Bi}from"fs/promises";import{join as $d,resolve as Od}from"path";var ir=class ir extends de{constructor(){super("unpublish");this.handle=o(async(n,r,i)=>{let s=i.optsWithGlobals(),a=Od(n??"."),p=$d(a,P.config),c=await ne(a),l=c.labels??[];if(l.includes(ke)){let u={...c,labels:l.filter(g=>g!==ke)};await Bi(p,te(u));try{await se(n,s)}catch(g){throw await Bi(p,te(c)),g}}else await se(n,s);let d=D(process.stdout);console.log(d.green(`Unpublished agent "${c.externalId}"`))},"handle");this.description("Retract a published agent back to draft").argument("[dir]","Agent project directory").addHelpText("after",Fd),this.action(this.handle)}};o(ir,"UnpublishCommand");var Ot=ir,Fd=`
71
+ Examples:
72
+ cognite agents unpublish Unpublish agent in current directory
73
+ cognite agents unpublish ./my-agent Unpublish agent in my-agent directory
74
+ `;var ar=class ar extends it{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)=>oo(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 kt;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,r)=>{await se(t,r.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(nr))t.addOption(n);return t.action((n,r,i)=>_i(n,i.optsWithGlobals()))}publish(){let t=new $t;return this.addCommand(t),t}unpublish(){let t=new Ot;return this.addCommand(t),t}pull(){let t=this.command("pull").description("Pull an existing agent from CDF into the local project").argument(`<${rr.externalId.name}>`,rr.externalId.description);for(let n of Object.values(or))t.addOption(n);return t.action((n,r,i)=>Ni(n,i.optsWithGlobals()))}list(){let t=this.command("list").description("List agents in the CDF project");for(let n of Object.values(Fi))t.addOption(n);return t.action((n,r)=>Li(r.optsWithGlobals()))}status(){return this.command("status").description("Show the current status of the agent").action(t=>Hi(t))}eval(){let t=this.command("eval").description("Run eval cases for an agent").argument("[dir]","Agent directory");for(let n of Object.values(er))t.addOption(n);return t.action((n,r,i)=>$i(n,i.optsWithGlobals(),{telemetry:this.telemetry}))}};o(ar,"AgentsCommand");var sr=ar;function Ki(e,t={}){let n=new sr("agents",t.telemetry);return e.addCommand(n),n}o(Ki,"registerAgentsCommand");import{existsSync as pu,readFileSync as cu}from"fs";import{join as lu,resolve as Vt}from"path";import{verifyBundle as du}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as uu}from"jose";import lr from"enquirer";import{email as Ld,pipe as Ud,safeParse as Md,string as _d}from"valibot";var jd=Ud(_d(),Ld());function _e(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Md(jd,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(_e,"parseEmail");function je(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(je,"parseExpiryMonths");import{execFileSync as Lt}from"child_process";import{execFileSync as Nd}from"child_process";function Ft(e={}){let{execFileSync:t=Nd}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(Ft,"isGitInstalled");function ae(e={}){if(!Ft(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})}o(ae,"throwIfGitMissing");function Ut(e,t={}){let{execFileSync:n=Lt}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ut,"isInsideGitRepo");function Vi(e,t={}){let{execFileSync:n=Lt}=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(Vi,"gitInitAndCommit");function Gi(e={}){let{execFileSync:t=Lt}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(Gi,"gitUserName");function Yi(e={}){let{execFileSync:t=Lt}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(Yi,"gitUserEmail");var Mt=3,qi="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Ji=`Key expiry in months (${1}-${12})`,zi="Email address for the registry entry",Wi=`Passphrase for the encrypted private key (min ${15} chars)`,Xi="Confirm passphrase",Zi=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Qi=o(e=>`Passphrases do not match (attempt ${e}/${Mt}).
75
+ `,"passphraseMismatchMsg"),es=`Passphrase confirmation failed after ${Mt} attempts`,ts=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),ns="How would you like to submit your key registration?",rs="Open in browser",os="Copy link to clipboard";async function _t(e){return lr.prompt(e)}o(_t,"defaultPrompt");function dr(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(dr,"parserAsValidator");var Bd=/^[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(!Bd.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 is(e={}){let{prompt:t=_t}=e,{kid:n}=await t({type:"input",name:"kid",message:qi,validate:dr(De)});return De(n)}o(is,"promptKid");async function ss(e={}){let{prompt:t=o(r=>lr.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:ns,choices:[{name:"browser",message:rs},{name:"clipboard",message:os}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}o(ss,"promptZendeskAction");async function as(e={}){let{prompt:t=_t}=e,{months:n}=await t({type:"input",name:"months",message:Ji,initial:String(6),validate:dr(r=>je(r,"expiry"))});return je(n,"expiry")}o(as,"promptExpiryMonths");async function ps(e={}){let{prompt:t=_t,gitUserEmail:n=Yi}=e,{email:r}=await t({type:"input",name:"email",message:zi,initial:n(),validate:dr(i=>_e(i,"email"))});return _e(r,"email")}o(ps,"promptEmail");async function cs(e={}){let{prompt:t=_t,stderr:n=process.stderr}=e;for(let r=1;r<=Mt;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Wi,validate:o(a=>a.length>=15?!0:Zi(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Xi});if(i===s)return E.from(i);n.write(Qi(r))}throw new Error(es)}o(cs,"promptPassphrase");async function ls(e,t={}){let{prompt:n=o(i=>lr.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:ts(e),initial:!1});return r}o(ls,"promptConfirmOverwrite");import{existsSync as Zd,readdirSync as Qd,readFileSync as eu}from"fs";import{join as ur}from"path";import{execFile as Kd}from"child_process";import{promisify as Vd}from"util";var ds="cognite-flows",Gd=Vd(Kd),us=o((e,t)=>Gd(e,t),"defaultExecFile"),Yd=-25300,qd=Yd&255;function Jd(e){if(!(e instanceof Error)||!("code"in e)||e.code!==qd)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Jd,"isKeychainNotFoundError");async function ms(e,t,n={}){let r=t.expose();if(!K("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:i=us}=n;await i("security",["add-generic-password","-a",e,"-s",ds,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}o(ms,"storeKeyInKeychain");async function jt(e,t={}){if(!K("macos",t))return null;let{execFile:n=us}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",ds,"-w"]);return E.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(Jd(r))return null;throw r}}o(jt,"readKeyFromKeychain");var fs="cognite-cli-signing",zd="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.",Wd="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.",gs="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function Xd(e){if(!(e instanceof Error))return gs;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?zd:t.includes("ambiguous")?Wd:gs}o(Xd,"hintFor");function ys(e,t,n){return new m(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:Xd(n),shouldReport:!1})}o(ys,"wrapKeyringError");async function hs(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(hs,"defaultCreateEntry");async function Ss(e,t,n={}){let{createEntry:r=hs}=n,i=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(fs,e)).setPassword(i)}catch(s){throw ys("store",e,s)}}o(Ss,"storeSigningKey");async function Nt(e,t={}){let{createEntry:n=hs}=t;try{let i=(await n(fs,e)).getPassword();return i===null?null:E.from(Buffer.from(i,"base64").toString("utf-8"))}catch(r){throw ys("read",e,r)}}o(Nt,"readSigningKey");var he=".pub.pem",mr=".key.jwe",gr=".meta.json";function Ht(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(Ht,"formatLocalKeySource");function tu(e){return{existsSync:e.existsSync??Zd,readdirSync:e.readdirSync??Qd,readFileSync:e.readFileSync??((t,n)=>eu(t,n)),isOS:e.isOS??(t=>K(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>jt(t)),readSigningKey:e.readSigningKey??(t=>Nt(t))}}o(tu,"resolveDeps");function nu(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(nu,"readEmailFromMeta");function ru(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(he)):[]}o(ru,"publicKeyEntries");function ou(e){return e.slice(0,-he.length)}o(ou,"kidFromPublicKeyFilename");async function iu(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=ur(t,`${e}${mr}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}o(iu,"resolveSource");async function Bt(e=I().keysDir,t={}){let n=tu(t),r=new Set,i=ru(e,n).flatMap(s=>{let a=ou(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 iu(s,e,n),c=ur(e,`${s}${gr}`),l;try{l=nu(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:ur(e,a),email:l}}))}o(Bt,"discoverLocalKeys");import{createReadStream as su}from"fs";function Kt(e){let t=su(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(Kt,"createWebStreamFromFile");import au from"path";var ws=".cognite-bundles";function vs(e,t){return`${e}-${t}.zip`}o(vs,"bundleFileName");function z(e,t,n){return au.join(e,ws,vs(t,n))}o(z,"bundlePath");var Cs=[".dev.sig",".cert.sig",".sig"];function mu(e){return{existsSync:e.existsSync??pu,readFileSync:e.readFileSync??((t,n)=>cu(t,n)),createBundleStream:e.createBundleStream??Kt,verifyBundle:e.verifyBundle??du,loadAppConfig:e.loadAppConfig??x,defaultKeyDir:e.defaultKeyDir??(()=>I().keysDir)}}o(mu,"resolveDeps");function gu(e,t){return Cs.map(n=>`${e}${n}`).find(n=>t(n))}o(gu,"findSiblingSignature");function fu(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}o(fu,"isCompactJws");function yu(e){try{let t=uu(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}o(yu,"readKidFromToken");function hu(e,t,n){let{existsSync:r,readFileSync:i}=n;try{De(e)}catch(a){throw new m(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!r(t))throw new m(`Key directory not found: ${t}`,{shouldReport:!1});let s=lu(t,`${e}${he}`);if(!r(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})}}o(hu,"resolvePublicKeyForKid");function Su(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(Su,"printResult");async function As(e,t,n={},r=process.cwd()){let{existsSync:i,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=mu(n),d;if(e)d=Vt(r,e);else{let y;try{y=a(r)}catch(h){let C=h instanceof Error?h.message:String(h);throw new m(C,{cause:h,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=z(r,y.externalId,y.versionTag)}if(!i(d)){let y=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new m(`Bundle not found: ${d}`,{hint:y,shouldReport:!1})}let u=t.sig?Vt(r,t.sig):gu(d,i);if(!u)throw new m("No signature file found.",{hint:`Pass --sig <path> or place one of ${Cs.map(y=>`${d}${y}`).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(y){throw new m(`Failed to read signature file: ${u}`,{cause:y,shouldReport:!1})}if(!fu(g))throw new m(`Malformed JWS in ${u}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let f;if(t.key){let y=Vt(r,t.key);if(!i(y))throw new m(`Public key not found: ${y}`,{shouldReport:!1});try{f=s(y,"utf-8")}catch(h){throw new m(`Failed to read public key file: ${y}`,{cause:h,shouldReport:!1})}}else{let y=t.keyDir?Vt(r,t.keyDir):l(),h=yu(g);if(!h)throw new m("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});f=hu(h,y,{existsSync:i,readFileSync:s})}try{let y=await c({token:g,publicKeyPem:f,bundleStream:p(d)});Su(y,t.verbose??!1)}catch(y){let h=y instanceof Error?y.message:String(y);throw new m(`Bundle rejected: ${h}`,{shouldReport:!1})}}o(As,"handleVerify");function Es(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",`
76
+ Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
77
+
78
+ Examples:
79
+ cognite apps verify Verify default bundle (path from app.json)
80
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
81
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
82
+ cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,r)=>As(n,r,t))}o(Es,"registerVerifyCommand");import{existsSync as wu}from"fs";import{resolve as vu}from"path";import{config as Cu}from"dotenv";function N(e,t={existsSync:wu,config:Cu}){let n=vu(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(N,"loadEnvFile");function H(e){e.infra!=="appsApi"&&(console.error(`
37
83
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
38
84
 
39
85
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
40
86
  the old CDF Application Registry. This deploy path has been removed.
41
87
 
42
88
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
43
- `),process.exit(1))}i(O,"assertAppHostingInfra");async function ca(e){let t=process.cwd();F(t);let n=E(t);O(n);let r=e.interactive?await T(n,e):D(n.deployments,e.deployment);if(!e.interactive){let d=R(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let o=await N(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new A(o),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof j?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}i(ca,"handleActivate");function Pr(e){return 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)").addHelpText("after",`
89
+ `),process.exit(1))}o(H,"assertAppHostingInfra");async function Au(e){let t=process.cwd();N(t);let n=x(t);H(n);let r=e.interactive?await F(n,e):R(n.deployments,e.deployment);if(!e.interactive){let d=j(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await _(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new U(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof q?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(Au,"handleActivate");function bs(e){return 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)").addHelpText("after",`
44
90
  Examples:
45
91
  npx @cognite/cli apps activate . Activate using env-var auth
46
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>ca(n))}i(Pr,"registerActivateCommand");import{basename as Br,dirname as Va,normalize as Ga,resolve as Qe}from"path";import{fileURLToPath as Ya,pathToFileURL as qa}from"url";import{Logger as za,runner as Wa}from"hygen";import{safeParse as la}from"valibot";function Ce(e,t){return n=>{let r=la(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}i(Ce,"toPromptValidator");var Ar={name:Ce("App name",xt),displayName:Ce("Display name",kt),baseUrl:Ce("Base URL",Pt),org:Ce("Org",At),project:Ce("Project",Dt)};function da(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}i(da,"composeValidators");function We(e){return e.map(t=>{if(!(t.name in Ar))return t;let n=Ar[t.name];return{...t,validate:da(t.validate,n)}})}i(We,"applySchemaValidators");import{basename as Dr}from"path";import Ir from"enquirer";function Kt(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}i(Kt,"kebabCase");var ma={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(`
47
- `),initial:!1};async function ua(e,t,n){return e!==void 0?e:t?!!(await n([ma])).useSpecKit:!1}i(ua,"resolveSpecKit");function ga(e){return typeof e=="function"}i(ga,"isFunctionInitial");function $r(e){return(e??"").trim().replace(/\/+$/,"")||"api"}i($r,"normalizeCluster");function Rr({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:o={},specKit:s,prompt:a=Ir.prompt.bind(Ir)}){return()=>({prompt:i(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(o).filter(k=>k[1]!==void 0)),l=Object.keys(c).length>0,d=e?Dr(process.cwd()):t?Dr(t):null,m=l&&d!==null,g=!m&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,f=We(g),u=m&&d?{...c,name:d}:c,y=new Set(Object.keys(u)),v=f.filter(k=>!y.has(k.name)),C=v.findIndex(k=>k.name==="baseUrl"),w;if(m){let k=$r(u.cluster),te=i(U=>ga(U.initial)?U.initial():U.initial,"resolveInitial"),ne=i(U=>{if(U.name==="baseUrl")return`https://${k}.cognitedata.com`;let re=te(U);if(re===void 0)throw new Error(`Non-interactive mode: --${Kt(U.name)} has no default. Pass it as a flag.`);return re},"deriveValue");w=Object.fromEntries(v.map(U=>[U.name,ne(U)]))}else if(C!==-1){let k=v.filter(ie=>ie.name!=="baseUrl"),te=k.length>0?await a(k):{},ne=typeof te.cluster=="string"?te.cluster:"",re=`https://${$r(ne||u.cluster)}.cognitedata.com`,le=v[C],De=await a([{...le,initial:re}]);w={...te,...De}}else w=v.length>0?await a(v):{};let S={...u,...w},x=typeof S.name=="string"?S.name:"";x&&n(x);let P=await ua(s,!m&&v.length>0,a);return r?.(P),{...S,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:P}},"prompt")})}i(Rr,"createAppPrompter");async function Tr(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:`--${Kt(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}`)}}i(Tr,"validatePresets");import{cpSync as Or,existsSync as Ur,mkdirSync as Ze,readdirSync as va,readFileSync as Ca,writeFileSync as Mt}from"fs";import{basename as ba,dirname as Nt,posix as Ea,resolve as I}from"path";import{fileURLToPath as _r}from"url";import{copyFileSync as fa,symlinkSync as ya}from"fs";import{dirname as ha,join as Sa}from"path";function wa(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}i(wa,"errno");function Fr(e){return e instanceof Error?e.message:String(e)}i(Fr,"messageOf");function Je({target:e,linkPath:t,label:n,symlink:r=ya,copyFile:o=fa}){try{return r(e,t),!0}catch(s){let a=wa(s);if(a==="EEXIST")return!0;let p=Fr(s);if(a==="EPERM"||a==="EACCES")try{let c=Sa(ha(t),e);return o(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: ${Fr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}i(Je,"linkOrCopyOrWarn");var ka=I(Nt(_r(import.meta.url)),"..","..","_vendor","spec-kit"),xa=I(Nt(_r(import.meta.url)),"..","..","_cognite-spec-extensions"),Pa=["claude-code","cursor","github-copilot"],Aa={branch_numbering:"sequential"};function Lr({appDir:e,vendorDir:t=ka,cogniteExtensionsDir:n=xa,agents:r=Pa}){let o=I(e,".specify"),s=I(o,"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:m,from:g,to:f}of l){let u=I(e,f);p=`copy ${ba(m)}/${g} to ${f}`,Ze(Nt(u),{recursive:!0}),Or(I(m,g),u,{recursive:!0})}if(a.has("github-copilot")){let m=I(e,".github","agents"),g=I(e,".github","prompts");p="create .github/agents and .github/prompts dirs",Ze(m,{recursive:!0}),Ze(g,{recursive:!0});for(let f of[I(t,"commands"),I(n,"commands")])if(Ur(f))for(let u of va(f)){if(!u.endsWith(".md"))continue;let y=u.slice(0,-3);p=`copy ${u} to .github/agents/${y}.agent.md`,Mt(I(m,`${y}.agent.md`),Ca(I(f,u))),p=`write .github/prompts/${y}.prompt.md`,Mt(I(g,`${y}.prompt.md`),`---
48
- agent: ${y}
92
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Au(n))}o(bs,"registerActivateCommand");import{basename as Ns,dirname as rm,normalize as om,resolve as zt}from"path";import{fileURLToPath as im,pathToFileURL as sm}from"url";import{Logger as am,runner as pm}from"hygen";import{safeParse as Eu}from"valibot";function Xe(e,t){return n=>{let r=Eu(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(Xe,"toPromptValidator");var xs={name:Xe("App name",un),displayName:Xe("Display name",dn),baseUrl:Xe("Base URL",mn),org:Xe("Org",gn),project:Xe("Project",fn)};function bu(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(bu,"composeValidators");function Gt(e){return e.map(t=>{if(!(t.name in xs))return t;let n=xs[t.name];return{...t,validate:bu(t.validate,n)}})}o(Gt,"applySchemaValidators");import{basename as ks}from"path";import Ps from"enquirer";function fr(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(fr,"kebabCase");var xu={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(`
93
+ `),initial:!1};async function ku(e,t,n){return e!==void 0?e:t?!!(await n([xu])).useSpecKit:!1}o(ku,"resolveSpecKit");function Pu(e){return typeof e=="function"}o(Pu,"isFunctionInitial");function Ds(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(Ds,"normalizeCluster");function Is({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=Ps.prompt.bind(Ps)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(A=>A[1]!==void 0)),l=Object.keys(c).length>0,d=e?ks(process.cwd()):t?ks(t):null,u=l&&d!==null,g=!u&&d?p.map(A=>A.name==="name"?{...A,initial:d}:A):p,f=Gt(g),y=u&&d?{...c,name:d}:c,h=new Set(Object.keys(y)),C=f.filter(A=>!h.has(A.name)),S=C.findIndex(A=>A.name==="baseUrl"),v;if(u){let A=Ds(y.cluster),X=o(L=>Pu(L.initial)?L.initial():L.initial,"resolveInitial"),pe=o(L=>{if(L.name==="baseUrl")return`https://${A}.cognitedata.com`;let Z=X(L);if(Z===void 0)throw new Error(`Non-interactive mode: --${fr(L.name)} has no default. Pass it as a flag.`);return Z},"deriveValue");v=Object.fromEntries(C.map(L=>[L.name,pe(L)]))}else if(S!==-1){let A=C.filter(ce=>ce.name!=="baseUrl"),X=A.length>0?await a(A):{},pe=typeof X.cluster=="string"?X.cluster:"",Z=`https://${Ds(pe||y.cluster)}.cognitedata.com`,O=C[S],Re=await a([{...O,initial:Z}]);v={...X,...Re}}else v=C.length>0?await a(C):{};let w={...y,...v},b=typeof w.name=="string"?w.name:"";b&&n(b);let T=await ku(s,!u&&C.length>0,a);return r?.(T),{...w,name:b,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:T}},"prompt")})}o(Is,"createAppPrompter");async function Rs(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:`--${fr(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(Rs,"validatePresets");import{cpSync as $s,existsSync as Os,mkdirSync as qt,readdirSync as Ou,readFileSync as Fu,writeFileSync as yr}from"fs";import{basename as Lu,dirname as hr,posix as Uu,resolve as M}from"path";import{fileURLToPath as Fs}from"url";import{copyFileSync as Du,symlinkSync as Iu}from"fs";import{dirname as Ru,join as Tu}from"path";function $u(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o($u,"errno");function Ts(e){return e instanceof Error?e.message:String(e)}o(Ts,"messageOf");function Yt({target:e,linkPath:t,label:n,symlink:r=Iu,copyFile:i=Du}){try{return r(e,t),!0}catch(s){let a=$u(s);if(a==="EEXIST")return!0;let p=Ts(s);if(a==="EPERM"||a==="EACCES")try{let c=Tu(Ru(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: ${Ts(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o(Yt,"linkOrCopyOrWarn");var Mu=M(hr(Fs(import.meta.url)),"..","..","_vendor","spec-kit"),_u=M(hr(Fs(import.meta.url)),"..","..","_cognite-spec-extensions"),ju=["claude-code","cursor","github-copilot"],Nu={branch_numbering:"sequential"};function Ls({appDir:e,vendorDir:t=Mu,cogniteExtensionsDir:n=_u,agents:r=ju}){let i=M(e,".specify"),s=M(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:f}of l){let y=M(e,f);p=`copy ${Lu(u)}/${g} to ${f}`,qt(hr(y),{recursive:!0}),$s(M(u,g),y,{recursive:!0})}if(a.has("github-copilot")){let u=M(e,".github","agents"),g=M(e,".github","prompts");p="create .github/agents and .github/prompts dirs",qt(u,{recursive:!0}),qt(g,{recursive:!0});for(let f of[M(t,"commands"),M(n,"commands")])if(Os(f))for(let y of Ou(f)){if(!y.endsWith(".md"))continue;let h=y.slice(0,-3);p=`copy ${y} to .github/agents/${h}.agent.md`,yr(M(u,`${h}.agent.md`),Fu(M(f,y))),p=`write .github/prompts/${h}.prompt.md`,yr(M(g,`${h}.prompt.md`),`---
94
+ agent: ${h}
49
95
  ---
50
- `)}}let d=I(o,"extensions.yml");Ur(d)||(p="write .specify/extensions.yml",Or(I(n,"extensions.yml"),d)),p=`write init-options.json under specifyDir=${o}`,Mt(I(o,"init-options.json"),`${JSON.stringify(Aa,null,2)}
51
- `),p=`link .specify/memory/constitution.md in specifyDir=${o}`,Ze(s,{recursive:!0}),Je({target:Ea.join("..","..","AGENTS.md"),linkPath:I(s,"constitution.md"),label:".specify/memory/constitution.md"})}catch(d){let m=d instanceof Error?d.message:String(d);throw new Error(`installSpecKit failed while ${p} (appDir=${e}, vendorDir=${t}): ${m}`,{cause:d})}}i(Lr,"installSpecKit");import{execFileSync as Xe}from"child_process";import{mkdtempSync as Da,readdirSync as Ia,rmSync as $a}from"fs";import{createRequire as Ra}from"module";import{tmpdir as Ta}from"os";import{join as Fa,resolve as Kr}from"path";import{InvalidArgumentError as Oa}from"commander";import Ua from"enquirer";var Mr="cognitedata/builder-skills",Ht=["claude-code","cursor","github-copilot","opencode","codex"],_a=Ra(import.meta.url).resolve("skills/bin/cli.mjs");function Bt(e,t={}){try{Xe(process.execPath,[_a,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw G(),new h(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and try again."})}}i(Bt,"execSkillsCli");function La(){return Ht.map(e=>["add",Mr,"-a",e,"--skill","*","-y"])}i(La,"pullAllArgsPerAgent");var Ka=1e4;async function Nr(e,t={}){let n=t.exec??Bt;G();let r=t.timeout??Ka,o=t.readdir??(p=>Ia(p));for(let p of La())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[Kr(e,".claude","skills"),Kr(e,".agents","skills")])try{o(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.")}i(Nr,"pullAllSkillsInto");function Ma(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Oa("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}i(Ma,"validateSource");function Na(e){let t=Da(Fa(Ta(),"skills-"));try{try{Xe("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(r){throw G(),new h(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:r})}let n;try{n=Xe("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Xe("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{$a(t,{recursive:!0,force:!0})}}i(Na,"listRemoteSkills");async function Ha(e,t={}){let n=i(p=>Ua.prompt(p),"defaultPrompt"),{listSkills:r=Na,prompt:o=n}=t,s=r(e),{selected:a}=await o({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}i(Ha,"pickSkillsInteractive");function Ba(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}i(Ba,"buildPullArgs");async function ja(e){G(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Ha(e.source)}catch(r){if(r instanceof h)throw r;let o=r instanceof Error?r.message:String(r);console.error(`Failed to resolve skills interactively: ${o}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let r of Ht)try{Bt(Ba(e,r,t))}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`\u26A0\uFE0F Could not pull skills for ${r}: ${s}`),n=!0}n?(console.log(`
96
+ `)}}let d=M(i,"extensions.yml");Os(d)||(p="write .specify/extensions.yml",$s(M(n,"extensions.yml"),d)),p=`write init-options.json under specifyDir=${i}`,yr(M(i,"init-options.json"),`${JSON.stringify(Nu,null,2)}
97
+ `),p=`link .specify/memory/constitution.md in specifyDir=${i}`,qt(s,{recursive:!0}),Yt({target:Uu.join("..","..","AGENTS.md"),linkPath:M(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(Ls,"installSpecKit");import{execFileSync as Jt}from"child_process";import{mkdtempSync as Hu,readdirSync as Bu,rmSync as Ku}from"fs";import{createRequire as Vu}from"module";import{tmpdir as Gu}from"os";import{join as Yu,resolve as Us}from"path";import{InvalidArgumentError as qu}from"commander";import Ju from"enquirer";var Ms="cognitedata/builder-skills",Sr=["claude-code","cursor","github-copilot","opencode","codex"],zu=Vu(import.meta.url).resolve("skills/bin/cli.mjs");function wr(e,t={}){try{Jt(process.execPath,[zu,...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."})}}o(wr,"execSkillsCli");function Wu(){return Sr.map(e=>["add",Ms,"-a",e,"--skill","*","-y"])}o(Wu,"pullAllArgsPerAgent");var Xu=1e4;async function _s(e,t={}){let n=t.exec??wr;ae();let r=t.timeout??Xu,i=t.readdir??(p=>Bu(p));for(let p of Wu())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[Us(e,".claude","skills"),Us(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(_s,"pullAllSkillsInto");function Zu(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new qu("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Zu,"validateSource");function Qu(e){let t=Hu(Yu(Gu(),"skills-"));try{try{Jt("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(r){throw ae(),new m(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:r})}let n;try{n=Jt("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Jt("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{Ku(t,{recursive:!0,force:!0})}}o(Qu,"listRemoteSkills");async function em(e,t={}){let n=o(p=>Ju.prompt(p),"defaultPrompt"),{listSkills:r=Qu,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(em,"pickSkillsInteractive");function tm(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(tm,"buildPullArgs");async function nm(e){ae(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await em(e.source)}catch(r){if(r instanceof m)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 Sr)try{wr(tm(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(`
52
98
  Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
53
- Skills pulled successfully`)}i(ja,"handlePull");function Hr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
54
- Supports: ${Ht.join(", ")}`).addHelpText("after",`
99
+ Skills pulled successfully`)}o(nm,"handlePull");function js(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
100
+ Supports: ${Sr.join(", ")}`).addHelpText("after",`
55
101
  Examples:
56
102
  npx @cognite/cli apps skills pull Pull all skills
57
103
  npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
58
- 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",Ma,Mr).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(ja),t.command("list").description("List installed skills").action(()=>{Bt(["list"])}),t}i(Hr,"registerSkillsCommand");var jr=Qe(Va(Ya(import.meta.url)),"..","..","_templates");async function Ja(){let e=Qe(jr,"app","new","prompt.js");return(await import(qa(e).href)).default}i(Ja,"loadPromptDefs");function Za(e,t){return!e||t?null:Ga(e)}i(Za,"resolveDirName");function Xa(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:Qe(process.cwd(),r),display:r}}i(Xa,"resolveAppLocation");function Qa(e,t,n){let r=` npm install
59
- npm run dev`,o="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
104
+ 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",Zu,Ms).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(nm),t.command("list").description("List installed skills").action(()=>{wr(["list"])}),t}o(js,"registerSkillsCommand");var Hs=zt(rm(im(import.meta.url)),"..","..","_templates");async function cm(){let e=zt(Hs,"app","new","prompt.js");return(await import(sm(e).href)).default}o(cm,"loadPromptDefs");function lm(e,t){return!e||t?null:om(e)}o(lm,"resolveDirName");function dm(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:zt(process.cwd(),r),display:r}}o(dm,"resolveAppLocation");function um(e,t,n){let r=` npm install
105
+ npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
60
106
  To start spec-driven development:
61
107
  Run /speckit.specify in Claude Code, Cursor, or GitHub Copilot and describe your app.
62
108
  `:"",p=` # Or fully non-interactive (deploys first target from app.json):
@@ -66,7 +112,7 @@ To start spec-driven development:
66
112
  Next steps:
67
113
  ${r}
68
114
  ${a}
69
- ${o}
115
+ ${i}
70
116
  ${s}
71
117
  ${p}
72
118
  `);return}console.log(`
@@ -78,11 +124,11 @@ Or:
78
124
  cd "${t}"
79
125
  ${r}
80
126
  ${a}
81
- ${o}
127
+ ${i}
82
128
  cd "${t}"
83
129
  ${s}
84
130
  ${p}
85
- `)}i(Qa,"printSuccessMessage");async function ep(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await Nr(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}i(ep,"pullSkillsInto");function tp(e,t={}){let{isGitInstalled:n=$e,isInsideGitRepo:r=Te,gitInitAndCommit:o=Cn}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{o(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)}}}i(tp,"maybeInitGit");async function np(e,t){let n=e==="."||e==="./",r=Za(e,n),o=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Ja(),c=We(p),l=n?Br(process.cwd()):r?Br(r):null;await Tr(c,a,l);let d=Rr({isCurrentDir:n,dirName:r,onAppName:i(g=>{o=g},"onAppName"),onUseSpecKit:i(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await Wa(["app","new"],{templates:jr,cwd:process.cwd(),logger:new za(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Xa(n,r,o);Je({target:"AGENTS.md",linkPath:Qe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&Lr({appDir:m.cwd}),await ep(m.cwd),tp(m.cwd),Qa(n,m.display,s)}i(np,"handleCreate");function Vr(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",`
131
+ `)}o(um,"printSuccessMessage");async function mm(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await _s(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(mm,"pullSkillsInto");function gm(e,t={}){let{isGitInstalled:n=Ft,isInsideGitRepo:r=Ut,gitInitAndCommit:i=Vi}=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(gm,"maybeInitGit");async function fm(e,t){let n=e==="."||e==="./",r=lm(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 cm(),c=Gt(p),l=n?Ns(process.cwd()):r?Ns(r):null;await Rs(c,a,l);let d=Is({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await pm(["app","new"],{templates:Hs,cwd:process.cwd(),logger:new am(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let u=dm(n,r,i);Yt({target:"AGENTS.md",linkPath:zt(u.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&Ls({appDir:u.cwd}),await mm(u.cwd),gm(u.cwd),um(n,u.display,s)}o(fm,"handleCreate");function Bs(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",`
86
132
  Non-interactive use (CI, scripts, AI agents):
87
133
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
88
134
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -95,30 +141,30 @@ Examples:
95
141
  --display-name "My App" --description "My app" \\
96
142
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
97
143
  --base-url https://greenfield.cognitedata.com
98
- Fully non-interactive`).action(np)}i(Vr,"registerCreateCommand");import rp from"path";async function ip(e,t,n){return ze(e,{interactive:t.interactive,appId:n,orgHint:t.org})}i(ip,"defaultBuildApiClient");async function op(e,t,n={}){let{loadEnvFile:r=F,loadAppConfig:o=E,getApiClient:s=ip}=n,a=rp.resolve(process.cwd(),e);r(a);let p=o(a);O(p);let c=t.interactive?await T(p,t):D(p.deployments,t.deployment);if(!t.interactive){let g=R(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),m=await d.getActiveVersion(l);if(!m){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,m.version),console.log(`\u2713 Deactivated ${l} @ ${m.version} \u2014 active alias removed`)}i(op,"handleDeactivate");function Gr(e){return 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)").addHelpText("after",`
144
+ Fully non-interactive`).action(fm)}o(Bs,"registerCreateCommand");import ym from"path";async function hm(e,t,n){return xt(e,{interactive:t.interactive,appId:n,orgHint:t.org})}o(hm,"defaultBuildApiClient");async function Sm(e,t,n={}){let{loadEnvFile:r=N,loadAppConfig:i=x,getApiClient:s=hm}=n,a=ym.resolve(process.cwd(),e);r(a);let p=i(a);H(p);let c=t.interactive?await F(p,t):R(p.deployments,t.deployment);if(!t.interactive){let g=j(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),u=await d.getActiveVersion(l);if(!u){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,u.version),console.log(`\u2713 Deactivated ${l} @ ${u.version} \u2014 active alias removed`)}o(Sm,"handleDeactivate");function Ks(e){return 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)").addHelpText("after",`
99
145
  Examples:
100
146
  npx @cognite/cli apps deactivate . Deactivate using env-var auth
101
- npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>op(t,n))}i(Gr,"registerDeactivateCommand");import sp from"path";import ap from"enquirer";async function pp(e,t,n){return ze(e,{interactive:t.interactive,appId:n,orgHint:t.org})}i(pp,"defaultBuildApiClient");async function cp(e){let{confirmed:t}=await ap.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(cp,"defaultConfirm");async function lp(e,t,n={}){let{loadEnvFile:r=F,loadAppConfig:o=E,getApiClient:s=pp,confirm:a=cp}=n,p=sp.resolve(process.cwd(),e);r(p);let c=o(p);O(c);let l=t.interactive?await T(c,t):D(c.deployments,t.deployment);if(!t.interactive){let u=R(l);if(u.length>0)throw new h(`Deployment ${l.org}/${l.project} is missing ${u.join(" and ")} in app.json.`,{hint:"Use `npx @cognite/cli@latest apps delete --interactive` for browser-based authentication instead."})}let d=await s(l,t,c.externalId),{externalId:m,versionTag:g}=c,f;try{f=await d.getVersion(m,g)}catch(u){throw u instanceof j?new h(`Version ${g} of ${m} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):u}if(f.alias==="ACTIVE")throw new h(`Cannot archive ${m} @ ${g}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(f.lifecycleState==="ARCHIVED"){console.log(` ${m} @ ${g} is already ARCHIVED \u2014 nothing to do.`);return}if(!t.force&&!await a(`Delete ${m} @ ${g}?`)){process.stderr.write(`Aborted.
102
- `);return}if(f.lifecycleState==="DRAFT"){await d.deleteVersion(m,g),console.log(`\u2713 Deleted ${m} @ ${g} (DRAFT removed)`);return}f.lifecycleState==="PUBLISHED"&&(await d.deprecateVersion(m,g),console.log(`\u2713 Deprecated ${m} @ ${g} is now DEPRECATED`)),await d.archiveVersion(m,g),console.log(`\u2713 Archived ${m} @ ${g} is now ARCHIVED`)}i(lp,"handleDelete");function Yr(e){return 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).addHelpText("after",`
147
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Sm(t,n))}o(Ks,"registerDeactivateCommand");import wm from"path";import vm from"enquirer";async function Cm(e,t,n){return xt(e,{interactive:t.interactive,appId:n,orgHint:t.org})}o(Cm,"defaultBuildApiClient");async function Am(e){let{confirmed:t}=await vm.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}o(Am,"defaultConfirm");async function Em(e,t,n={}){let{loadEnvFile:r=N,loadAppConfig:i=x,getApiClient:s=Cm,confirm:a=Am}=n,p=wm.resolve(process.cwd(),e);r(p);let c=i(p);H(c);let l=t.interactive?await F(c,t):R(c.deployments,t.deployment);if(!t.interactive){let y=j(l);if(y.length>0)throw new m(`Deployment ${l.org}/${l.project} is missing ${y.join(" and ")} in app.json.`,{hint:"Use `npx @cognite/cli@latest apps delete --interactive` for browser-based authentication instead."})}let d=await s(l,t,c.externalId),{externalId:u,versionTag:g}=c,f;try{f=await d.getVersion(u,g)}catch(y){throw y instanceof q?new m(`Version ${g} of ${u} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):y}if(f.alias==="ACTIVE")throw new m(`Cannot archive ${u} @ ${g}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(f.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.
148
+ `);return}if(f.lifecycleState==="DRAFT"){await d.deleteVersion(u,g),console.log(`\u2713 Deleted ${u} @ ${g} (DRAFT removed)`);return}f.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`)}o(Em,"handleDelete");function Vs(e){return 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).addHelpText("after",`
103
149
  Examples:
104
150
  npx @cognite/cli apps delete . Archive using env-var auth
105
151
  npx @cognite/cli apps delete . --interactive Archive using browser auth (no secrets needed)
106
- npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((t,n)=>lp(t,n))}i(Yr,"registerDeleteCommand");import{existsSync as Pp}from"fs";import{rm as Ap}from"fs/promises";import Wr from"enquirer";import{existsSync as Sp}from"fs";import{mkdir as wp,readFile as vp}from"fs/promises";import{basename as Cp,dirname as bp}from"path";import{execFileSync as et}from"child_process";import W from"fs";import K from"path";import{parseAndValidateManifestConfig as dp}from"@cognite/app-sdk/vite";import{BlobReader as mp,Uint8ArrayWriter as up,ZipWriter as gp}from"@zip.js/zip.js";var jt="package.json",Vt="package-lock.json",qr="manifest.json",Gt=".cognite",fp=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Yt=class Yt{constructor(t="dist"){this.distPath=K.isAbsolute(t)?t:K.join(process.cwd(),t),this.appRoot=K.dirname(this.distPath)}validateBuildDirectory(){if(!W.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=K.join(this.appRoot,jt);if(!W.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=K.join(this.appRoot,Vt);if(!W.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 gp(new up,{level:9}),o=i(async(c,l)=>{await r.add(l,new mp(await W.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=i(async c=>{let l=await W.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=K.join(c,d.name);d.isDirectory()?await s(m):await o(m,K.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=K.join(this.appRoot,jt);await o(c,K.posix.join(Gt,jt));let l=K.join(this.appRoot,qr);if(W.existsSync(l)){let m=W.readFileSync(l,"utf-8");dp(m,l),await o(l,K.posix.join(Gt,qr))}let d=K.join(this.appRoot,Vt);await o(d,K.posix.join(Gt,Vt)),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 W.promises.writeFile(t,a)}catch(c){throw new h(`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=et("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw G(),new h("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=et("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",s=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(n,s);try{et("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=(W.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${K.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=et("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
107
- `).filter(Boolean),o=i(a=>a.split("/").some(p=>fp.some(c=>c.test(p))),"isSensitive"),s=r.filter(o);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
152
+ npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((t,n)=>Em(t,n))}o(Vs,"registerDeleteCommand");import{existsSync as Mm}from"fs";import{rm as _m}from"fs/promises";import Ys from"enquirer";import{existsSync as Tm}from"fs";import{mkdir as $m,readFile as Om}from"fs/promises";import{basename as Fm,dirname as Lm}from"path";import{execFileSync as Wt}from"child_process";import me from"fs";import G from"path";import{parseAndValidateManifestConfig as bm}from"@cognite/app-sdk/vite";import{BlobReader as xm,Uint8ArrayWriter as km,ZipWriter as Pm}from"@zip.js/zip.js";var vr="package.json",Cr="package-lock.json",Gs="manifest.json",Ar=".cognite",Dm=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Er=class Er{constructor(t="dist"){this.distPath=G.isAbsolute(t)?t:G.join(process.cwd(),t),this.appRoot=G.dirname(this.distPath)}validateBuildDirectory(){if(!me.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=G.join(this.appRoot,vr);if(!me.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=G.join(this.appRoot,Cr);if(!me.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 Pm(new km,{level:9}),i=o(async(c,l)=>{await r.add(l,new xm(await me.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await me.promises.readdir(c,{withFileTypes:!0});for(let d of l){let u=G.join(c,d.name);d.isDirectory()?await s(u):await i(u,G.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=G.join(this.appRoot,vr);await i(c,G.posix.join(Ar,vr));let l=G.join(this.appRoot,Gs);if(me.existsSync(l)){let u=me.readFileSync(l,"utf-8");bm(u,l),await i(l,G.posix.join(Ar,Gs))}let d=G.join(this.appRoot,Cr);await i(d,G.posix.join(Ar,Cr)),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 me.promises.writeFile(t,a)}catch(c){throw new m(`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=Wt("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw ae(),new m("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=Wt("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{Wt("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=(me.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${G.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=Wt("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
153
+ `).filter(Boolean),i=o(a=>a.split("/").some(p=>Dm.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:
108
154
  `+s.map(a=>` ${a}`).join(`
109
155
  `)+`
110
- Hint: git rm --cached <file>`)}};i(Yt,"ApplicationPackager");var J=Yt;import{existsSync as yp,readFileSync as hp}from"fs";var Q=[".dev.sig",".cert.sig"];function be(e,t={}){let n=t.existsSync??yp,r=t.readFileSync??((s,a)=>hp(s,a)),o=[];for(let s of Q){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(be,"discoverSignatures");async function tt(e,t,{existsSync:n=Sp,mkdir:r=wp,createZip:o=i((s,a)=>new J(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,p=H(t,s,a);if(n(p)){let l=Q.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 h(`Bundle already exists: ${p}`,{hint:l,shouldReport:!1})}await r(bp(p),{recursive:!0}),await o(`${t}/dist`,p)}i(tt,"packageBundle");async function Ee(e,t,n,r,{readFile:o=vp,upload:s=i(async(a,p)=>new A(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,p,r),"uploadFn")}={}){let a=H(n,t.externalId,t.versionTag),p;try{p=await o(a)}catch(c){throw new h(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,Cp(a))}i(Ee,"uploadBundle");var qt=i(async(e,t,n)=>{let r=await ye(e,n);await tt(t,n),await Ee(r,t,n,e.published)},"deploy"),zt=i(async(e,t,n)=>{let r=await ye(e,n);await Ee(r,t,n,e.published)},"deployBundle");import{execSync as Ep}from"child_process";function nt(e,t=!0,n={execSync:Ep}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new h(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}i(nt,"buildApp");function zr(e,t){let{org:n,project:r,baseUrl:o}=e,s;try{s=new URL(o).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}`}i(zr,"generateFusionUrl");import kp,{Chalk as xp}from"chalk";var ke=new xp({level:0});function rt(e){return e.isTTY?kp:ke}i(rt,"chalkForStream");async function Dp(e){let{confirmed:t}=await Wr.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(Dp,"defaultConfirm");async function Ip(e,t){let{selected:n}=await Wr.prompt({type:"select",name:"selected",message:e,choices:t});return n}i(Ip,"defaultSelect");async function $p(e){await Ap(e,{force:!0})}i($p,"defaultRm");function Rp(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}i(Rp,"classifyExistingBundle");async function Tp(e,t){let{versionTag:n,hasSigs:r}=e,o=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(o,[{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=rt(process.stderr);if(console.warn(a.bold.red(`
111
- WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${Q.join(", ")}). You will have to re-sign before publishing.
112
- `)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}i(Tp,"promptBundleAction");async function Fp(e,t){for(let n of[e,...Q.map(r=>`${e}${r}`)])t.existsSync(n)&&await t.rm(n)}i(Fp,"removeBundleArtifacts");function Jr(e){let{appConfig:t,deployment:n,interactive:r}=e,o=r?"Deploy (Interactive)":"Deploy",s=r?`${n.project} @ ${n.baseUrl}`:`${n.org}/${n.project}`;console.log(["",o,"=".repeat(o.length),`App: ${t.name} (${t.externalId})`,`Version: ${t.versionTag}`,`Target: ${s}`,""].join(`
113
- `))}i(Jr,"printDeployInfo");function Zr(e){let{appConfig:t,deployment:n}=e;console.log(`
156
+ Hint: git rm --cached <file>`)}};o(Er,"ApplicationPackager");var ge=Er;import{existsSync as Im,readFileSync as Rm}from"fs";var Se=[".dev.sig",".cert.sig"];function Ze(e,t={}){let n=t.existsSync??Im,r=t.readFileSync??((s,a)=>Rm(s,a)),i=[];for(let s of Se){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(Ze,"discoverSignatures");async function Xt(e,t,{existsSync:n=Tm,mkdir:r=$m,createZip:i=o((s,a)=>new ge(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,p=z(t,s,a);if(n(p)){let l=Se.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 m(`Bundle already exists: ${p}`,{hint:l,shouldReport:!1})}await r(Lm(p),{recursive:!0}),await i(`${t}/dist`,p)}o(Xt,"packageBundle");async function Qe(e,t,n,r,{readFile:i=Om,upload:s=o(async(a,p)=>new U(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,p,r),"uploadFn")}={}){let a=z(n,t.externalId,t.versionTag),p;try{p=await i(a)}catch(c){throw new m(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,Fm(a))}o(Qe,"uploadBundle");var br=o(async(e,t,n)=>{let r=await Le(e,n);await Xt(t,n),await Qe(r,t,n,e.published)},"deploy"),xr=o(async(e,t,n)=>{let r=await Le(e,n);await Qe(r,t,n,e.published)},"deployBundle");import{execSync as Um}from"child_process";function Zt(e,t=!0,n={execSync:Um}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new m(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}o(Zt,"buildApp");async function jm(e){let{confirmed:t}=await Ys.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}o(jm,"defaultConfirm");async function Nm(e,t){let{selected:n}=await Ys.prompt({type:"select",name:"selected",message:e,choices:t});return n}o(Nm,"defaultSelect");async function Hm(e){await _m(e,{force:!0})}o(Hm,"defaultRm");function Bm(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}o(Bm,"classifyExistingBundle");async function Km(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=D(process.stderr);if(console.warn(a.bold.red(`
157
+ WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${Se.join(", ")}). You will have to re-sign before publishing.
158
+ `)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}o(Km,"promptBundleAction");async function Vm(e,t){for(let n of[e,...Se.map(r=>`${e}${r}`)])t.existsSync(n)&&await t.rm(n)}o(Vm,"removeBundleArtifacts");function qs(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(`
159
+ `))}o(qs,"printDeployInfo");function Js(e){let{appConfig:t,deployment:n}=e;console.log(`
114
160
  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(`
115
161
  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(`
116
- To submit for certification: npx @cognite/cli apps submit`);let o=zr(n,t);o&&console.log(`
162
+ To submit for certification: npx @cognite/cli apps submit`);let i=Ui(n,t);i&&console.log(`
117
163
  Open your app:
118
- ${o}`)}i(Zr,"printDeployResult");async function Op(e,t){let{appConfig:n,deployment:r,cwd:o,options:s,useExistingBundle:a}=e,{deployFn:p,buildApp:c}=t,l=R(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Jr({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&c(o),console.log(`
119
- Deploying to ${r.org}/${r.project}...`),await p({...r,published:!1},{externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag},o),Zr({appConfig:n,deployment:r})}i(Op,"handleDeployNonInteractive");async function Up(e,t){let{appConfig:n,deployment:r,cwd:o,options:s,useExistingBundle:a}=e,{buildApp:p}=t;Jr({appConfig:n,deployment:r,interactive:!0}),!s.skipBuild&&!a&&p(o);let c=await N(r,{interactive:!0,appId:n.externalId,orgHint:s.org});console.log(`
120
- Deploying to ${r.project}...`);let l={externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag};a||await tt(l,o),await Ee(c,l,o,!1),Zr({appConfig:n,deployment:r})}i(Up,"handleDeployInteractive");async function _p(e,t=process.cwd(),n={}){let{loadEnvFile:r=F,loadAppConfig:o=E,deploy:s=qt,deployBundle:a=zt,confirm:p=Dp,select:c=Ip,existsSync:l=Pp,rm:d=$p,buildApp:m=nt}=n;r(t);let g=o(t);O(g);let f=H(t,g.externalId,g.versionTag),u=Rp(f,e,l),y=u==="use-existing";if(u==="prompt"){let w=Q.some(x=>l(`${f}${x}`)),S=await Tp({versionTag:g.versionTag,hasSigs:w},{select:c,confirm:p});if(S==="cancel"){console.log(`
121
- Deployment cancelled. Nothing was deployed.`);return}S==="reuse"?y=!0:await Fp(f,{existsSync:l,rm:d})}if(e.interactive){let w=await T(g,e);await Up({appConfig:g,deployment:w,cwd:t,options:e,useExistingBundle:y},{buildApp:m});return}let v=D(g.deployments,e.deployment);await Op({appConfig:g,deployment:v,cwd:t,options:e,useExistingBundle:y},{deployFn:y?a:s,buildApp:m})}i(_p,"handleDeploy");function Xr(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based 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)").addHelpText("after",`
164
+ ${i}`)}o(Js,"printDeployResult");async function Gm(e,t){let{appConfig:n,deployment:r,cwd:i,options:s,useExistingBundle:a}=e,{deployFn:p,buildApp:c}=t,l=j(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);qs({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&c(i),console.log(`
165
+ Deploying to ${r.org}/${r.project}...`),await p({...r,published:!1},{externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag},i),Js({appConfig:n,deployment:r})}o(Gm,"handleDeployNonInteractive");async function Ym(e,t){let{appConfig:n,deployment:r,cwd:i,options:s,useExistingBundle:a}=e,{buildApp:p}=t;qs({appConfig:n,deployment:r,interactive:!0}),!s.skipBuild&&!a&&p(i);let c=await _(r,{interactive:!0,appId:n.externalId,orgHint:s.org});console.log(`
166
+ Deploying to ${r.project}...`);let l={externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag};a||await Xt(l,i),await Qe(c,l,i,!1),Js({appConfig:n,deployment:r})}o(Ym,"handleDeployInteractive");async function qm(e,t=process.cwd(),n={}){let{loadEnvFile:r=N,loadAppConfig:i=x,deploy:s=br,deployBundle:a=xr,confirm:p=jm,select:c=Nm,existsSync:l=Mm,rm:d=Hm,buildApp:u=Zt}=n;r(t);let g=i(t);H(g);let f=z(t,g.externalId,g.versionTag),y=Bm(f,e,l),h=y==="use-existing";if(y==="prompt"){let v=Se.some(b=>l(`${f}${b}`)),w=await Km({versionTag:g.versionTag,hasSigs:v},{select:c,confirm:p});if(w==="cancel"){console.log(`
167
+ Deployment cancelled. Nothing was deployed.`);return}w==="reuse"?h=!0:await Vm(f,{existsSync:l,rm:d})}if(e.interactive){let v=await F(g,e);await Ym({appConfig:g,deployment:v,cwd:t,options:e,useExistingBundle:h},{buildApp:u});return}let C=R(g.deployments,e.deployment);await Gm({appConfig:g,deployment:C,cwd:t,options:e,useExistingBundle:h},{deployFn:h?a:s,buildApp:u})}o(qm,"handleDeploy");function zs(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based 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)").addHelpText("after",`
122
168
  Environment (non-interactive):
123
169
  deployClientId and deploySecretName are configured per deployment in app.json.
124
170
  deploySecretName is the name of the environment variable that holds the client
@@ -132,10 +178,10 @@ Examples:
132
178
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
133
179
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
134
180
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
135
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>_p(t))}i(Xr,"registerDeployCommand");import st from"fs";import jp from"os";import ee from"path";import Vp from"enquirer";import Wt from"fs";import it from"path";import{BlobReader as Lp,Uint8ArrayWriter as Kp,ZipReader as Mp}from"@zip.js/zip.js";import xe from"path";function Qr(e,t){let n=xe.resolve(e),r=xe.resolve(t),o=xe.relative(n,r);return o===""||xe.isAbsolute(o)?!1:o!==".."&&!o.startsWith(`..${xe.sep}`)}i(Qr,"isSafePath");var Np=1e5,Hp=2*1024**3;async function ei(e,t,n={}){let{openAsBlob:r=i(d=>Wt.openAsBlob(d),"openAsBlob"),mkdir:o=i((d,m)=>Wt.promises.mkdir(d,m),"mkdir"),writeFile:s=i((d,m)=>Wt.promises.writeFile(d,m),"writeFile"),maxEntries:a=Np,maxTotalBytes:p=Hp}=n,c=await r(e),l=new Mp(new Lp(c));try{let d;try{d=await l.getEntries()}catch(f){throw new h(`Could not read bundle: ${it.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:f})}let m=0,g=0;for(let f of d){if(f.directory)continue;if(g++,g>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(m+=f.uncompressedSize,m>p)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(p/(1024*1024))} MB)`);if(it.isAbsolute(f.filename))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let u=it.join(t,f.filename);if(!Qr(t,u))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let y=await f.getData(new Kp);await o(it.dirname(u),{recursive:!0}),await s(u,y)}}finally{await l.close()}}i(ei,"extractZip");import{execFileSync as Bp}from"child_process";function ni(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(ni,"isExitError");function ti(e){if(!ni(e)||e.status!==1)throw e}i(ti,"swallowDiffExit");var Jt=class Jt{constructor(t={execFileSync:Bp}){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(ni(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){ti(r)}}showDiff(t,n,{usePager:r=!0}={}){let o=[];r||o.push("--no-pager"),o.push("diff","--word-diff=color","--no-index","--ignore-cr-at-eol",t,n);try{this.deps.execFileSync("git",o,{stdio:"inherit"})}catch(s){ti(s)}}};i(Jt,"GitDiffer");var ot=Jt;var Gp=i(async e=>(await Vp.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function Yp(e,t,n={}){let{cwd:r=process.cwd(),buildApp:o=nt,createPackager:s=i(S=>new J(S),"createPackager"),extractZip:a=ei,differ:p=new ot,existsSync:c=i(S=>st.existsSync(S),"existsSync"),mkdtemp:l=i(S=>st.promises.mkdtemp(S),"mkdtemp"),mkdir:d=i(async(S,x)=>{await st.promises.mkdir(S,x)},"mkdir"),rm:m=i((S,x)=>st.promises.rm(S,x),"rm"),isInteractive:g=i(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:f=Gp,setExitCode:u=i(S=>{process.exitCode=S},"setExitCode")}=n;if(!p.isSupported())throw new h("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!c(e))throw new h(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await o(r);else{let S=ee.join(r,"dist");if(!c(S))throw new h("dist directory not found.",{hint:"Run without --skip-build to build the app first, or run `pnpm build` manually.",shouldReport:!1})}let y=await l(ee.join(jp.tmpdir(),"cognite-diff-")),v=ee.join(y,"ours.zip"),C=ee.join(y,"ours"),w=ee.join(y,"theirs");try{if(await d(C,{recursive:!0}),await d(w,{recursive:!0}),await s(ee.join(r,"dist")).createZip(v),console.log(`
136
- Extracting bundles...`),await a(v,C),await a(e,w),p.isIdentical(C,w)){console.log(`
181
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>qm(t))}o(zs,"registerDeployCommand");import tn from"fs";import eg from"os";import we from"path";import tg from"enquirer";import kr from"fs";import Qt from"path";import{BlobReader as Jm,Uint8ArrayWriter as zm,ZipReader as Wm}from"@zip.js/zip.js";import et from"path";function Ws(e,t){let n=et.resolve(e),r=et.resolve(t),i=et.relative(n,r);return i===""||et.isAbsolute(i)?!1:i!==".."&&!i.startsWith(`..${et.sep}`)}o(Ws,"isSafePath");var Xm=1e5,Zm=2*1024**3;async function Xs(e,t,n={}){let{openAsBlob:r=o(d=>kr.openAsBlob(d),"openAsBlob"),mkdir:i=o((d,u)=>kr.promises.mkdir(d,u),"mkdir"),writeFile:s=o((d,u)=>kr.promises.writeFile(d,u),"writeFile"),maxEntries:a=Xm,maxTotalBytes:p=Zm}=n,c=await r(e),l=new Wm(new Jm(c));try{let d;try{d=await l.getEntries()}catch(f){throw new m(`Could not read bundle: ${Qt.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:f})}let u=0,g=0;for(let f of d){if(f.directory)continue;if(g++,g>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(u+=f.uncompressedSize,u>p)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(p/(1024*1024))} MB)`);if(Qt.isAbsolute(f.filename))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let y=Qt.join(t,f.filename);if(!Ws(t,y))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let h=await f.getData(new zm);await i(Qt.dirname(y),{recursive:!0}),await s(y,h)}}finally{await l.close()}}o(Xs,"extractZip");import{execFileSync as Qm}from"child_process";function Qs(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(Qs,"isExitError");function Zs(e){if(!Qs(e)||e.status!==1)throw e}o(Zs,"swallowDiffExit");var Pr=class Pr{constructor(t={execFileSync:Qm}){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(Qs(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){Zs(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){Zs(s)}}};o(Pr,"GitDiffer");var en=Pr;var ng=o(async e=>(await tg.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function rg(e,t,n={}){let{cwd:r=process.cwd(),buildApp:i=Zt,createPackager:s=o(w=>new ge(w),"createPackager"),extractZip:a=Xs,differ:p=new en,existsSync:c=o(w=>tn.existsSync(w),"existsSync"),mkdtemp:l=o(w=>tn.promises.mkdtemp(w),"mkdtemp"),mkdir:d=o(async(w,b)=>{await tn.promises.mkdir(w,b)},"mkdir"),rm:u=o((w,b)=>tn.promises.rm(w,b),"rm"),isInteractive:g=o(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:f=ng,setExitCode:y=o(w=>{process.exitCode=w},"setExitCode")}=n;if(!p.isSupported())throw new m("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!c(e))throw new m(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await i(r);else{let w=we.join(r,"dist");if(!c(w))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 h=await l(we.join(eg.tmpdir(),"cognite-diff-")),C=we.join(h,"ours.zip"),S=we.join(h,"ours"),v=we.join(h,"theirs");try{if(await d(S,{recursive:!0}),await d(v,{recursive:!0}),await s(we.join(r,"dist")).createZip(C),console.log(`
182
+ Extracting bundles...`),await a(C,S),await a(e,v),p.isIdentical(S,v)){console.log(`
137
183
  Bundles are identical`);return}console.log(`
138
- \u274C The local build at ${ee.join(r,"dist")} differs from ${ee.basename(e)}.`);let x=g();(t.showStat!==void 0?t.showStat:x&&await f("Show stat summary?"))&&p.showStat(C,w),(t.showDiff!==void 0?t.showDiff:x&&await f("Show full diff?"))&&p.showDiff(C,w,{usePager:t.pager}),u(1)}finally{await m(y,{recursive:!0,force:!0})}}i(Yp,"handleDiff");function ri(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",`
184
+ \u274C The local build at ${we.join(r,"dist")} differs from ${we.basename(e)}.`);let b=g();(t.showStat!==void 0?t.showStat:b&&await f("Show stat summary?"))&&p.showStat(S,v),(t.showDiff!==void 0?t.showDiff:b&&await f("Show full diff?"))&&p.showDiff(S,v,{usePager:t.pager}),y(1)}finally{await u(h,{recursive:!0,force:!0})}}o(rg,"handleDiff");function ea(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",`
139
185
  Builds the current source, packages it, then extracts both the local build
140
186
  and the provided bundle to temporary directories and runs:
141
187
 
@@ -146,75 +192,73 @@ Exit code 0 means the bundles are identical; exit code 1 means they differ.
146
192
  Examples:
147
193
  npx @cognite/cli apps diff untrusted.zip
148
194
  npx @cognite/cli apps diff untrusted.zip --skip-build
149
- npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>Yp(t,n))}i(ri,"registerDiffCommand");function qp(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:r,local:o}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${r}" \u2192 "${o||"(none)"}"`)}}i(qp,"printMetadataDiff");async function zp(e,t=process.cwd(),n={}){let{loadEnvFile:r=F,loadAppConfig:o=E,buildApiClient:s=N,createMetadataClient:a=i(y=>new A(y),"createMetadataClient"),getMissingCredentials:p=R}=n;r(t);let c=o(t);O(c);let l=e.interactive?await T(c,e):D(c.deployments,e.deployment);if(!e.interactive){let y=p(l);if(y.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),m=a(d),g;try{g=await m.getApp(c.externalId)}catch(y){throw y instanceof fe?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}let f={name:c.name,description:c.description||""},u=Ft(g,f);if(u.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}qp(c.externalId,u),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}i(zp,"handleUpdateMetadata");function ii(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return 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)").addHelpText("after",`
195
+ npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>rg(t,n))}o(ea,"registerDiffCommand");function og(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(og,"printMetadataDiff");async function ig(e,t=process.cwd(),n={}){let{loadEnvFile:r=N,loadAppConfig:i=x,buildApiClient:s=_,createMetadataClient:a=o(h=>new U(h),"createMetadataClient"),getMissingCredentials:p=j}=n;r(t);let c=i(t);H(c);let l=e.interactive?await F(c,e):R(c.deployments,e.deployment);if(!e.interactive){let h=p(l);if(h.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${h.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),u=a(d),g;try{g=await u.getApp(c.externalId)}catch(h){throw h instanceof Fe?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):h}let f={name:c.name,description:c.description||""},y=Bn(g,f);if(y.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}og(c.externalId,y),await u.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}o(ig,"handleUpdateMetadata");function ta(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return 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)").addHelpText("after",`
150
196
  Examples:
151
197
  npx @cognite/cli apps metadata update . Push name/description using env-var auth
152
- npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>zp(r)),t}i(ii,"registerMetadataCommand");async function Wp(e,t,n){let r=await N(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new A(r)}i(Wp,"defaultBuildApiClient");async function Jp(e,t={}){let n=t.loadEnvFile??F,r=t.loadAppConfig??E,o=t.buildApiClient??Wp,s=t.discoverSignatures??be,a=process.cwd();n(a);let p=r(a);O(p);let c=e.interactive?await T(p,e):D(p.deployments,e.deployment);if(!e.interactive){let u=R(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await o(c,e,p),{externalId:d,versionTag:m}=p,g;try{g=await l.getVersion(d,m)}catch(u){throw u instanceof j?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):u}if(g.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(g.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(g.lifecycleState==="DEPRECATED"||g.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${g.lifecycleState} (terminal).`);let f=s(H(a,d,m));f.length>0&&await l.submitSignatures(d,m,f),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}i(Jp,"handlePublish");function oi(e){return 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)").addHelpText("after",`
198
+ npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>ig(r)),t}o(ta,"registerMetadataCommand");async function sg(e,t,n){let r=await _(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new U(r)}o(sg,"defaultBuildApiClient");async function ag(e,t={}){let n=t.loadEnvFile??N,r=t.loadAppConfig??x,i=t.buildApiClient??sg,s=t.discoverSignatures??Ze,a=process.cwd();n(a);let p=r(a);H(p);let c=e.interactive?await F(p,e):R(p.deployments,e.deployment);if(!e.interactive){let y=j(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p),{externalId:d,versionTag:u}=p,g;try{g=await l.getVersion(d,u)}catch(y){throw y instanceof q?new Error(`Version ${u} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}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 f=s(z(a,d,u));f.length>0&&await l.submitSignatures(d,u,f),await l.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.")}o(ag,"handlePublish");function na(e){return 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)").addHelpText("after",`
153
199
  Examples:
154
200
  npx @cognite/cli apps publish . Publish using env-var auth
155
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Jp(n))}i(oi,"registerPublishCommand");import{spawnSync as Zp}from"child_process";import{mkdirSync as Xp}from"fs";import{join as Qp,resolve as si}from"path";var ec=["localhost","local.cognite.ai","*.local.cognite.ai"],tc={info:i(e=>{process.stdout.write(`${e}
156
- `)},"info"),error:i(e=>{process.stderr.write(`${e}
157
- `)},"error")},nc={spawnSync:Zp,mkdirSync:Xp,logger:tc,getConfig:$};function rc(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}i(rc,"hasMkcert");function ic({certDir:e,domains:t=ec,deps:n={}}={}){let r={...nc,...n},{spawnSync:o,mkdirSync:s,logger:a}=r,p=e??Qp(r.getConfig().home,"certificates","mkcert");if(!rc(o))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."),o("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(p,{recursive:!0});let l=si(p,"localhost.pem"),d=si(p,"localhost-key.pem");if(o("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}}i(ic,"setupHttps");function oc(e){ic({certDir:e.certDir})}i(oc,"handleSetupHttps");function ai(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",`
201
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>ag(n))}o(na,"registerPublishCommand");import{spawnSync as pg}from"child_process";import{mkdirSync as cg}from"fs";import{join as lg,resolve as ra}from"path";var dg=["localhost","local.cognite.ai","*.local.cognite.ai"],ug={info:o(e=>{process.stdout.write(`${e}
202
+ `)},"info"),error:o(e=>{process.stderr.write(`${e}
203
+ `)},"error")},mg={spawnSync:pg,mkdirSync:cg,logger:ug,getConfig:I};function gg(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(gg,"hasMkcert");function fg({certDir:e,domains:t=dg,deps:n={}}={}){let r={...mg,...n},{spawnSync:i,mkdirSync:s,logger:a}=r,p=e??lg(r.getConfig().home,"certificates","mkcert");if(!gg(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=ra(p,"localhost.pem"),d=ra(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(fg,"setupHttps");function yg(e){fg({certDir:e.certDir})}o(yg,"handleSetupHttps");function oa(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",`
158
204
  Examples:
159
205
  npx @cognite/cli@latest apps setup-https Generate certs in ~/.cognite-cli/certificates/mkcert
160
- npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>oc(t))}i(ai,"registerSetupHttpsCommand");import{existsSync as kc,writeFileSync as xc}from"fs";import{basename as Pc,dirname as Ac,join as Dc,resolve as tn}from"path";import{parseScope as Ic,signBundle as $c,validateScopes as Rc}from"@cognite/app-sdk/codesigning";import{existsSync as Cc,readFileSync as bc}from"fs";import{pbkdf2 as pc,randomBytes as cc}from"crypto";import{promisify as lc}from"util";import{CompactEncrypt as dc,base64url as pi,compactDecrypt as mc}from"jose";var sc=new TextEncoder,ac=new TextDecoder,Zt={encode:i(e=>sc.encode(e),"encode"),decode:i(e=>ac.decode(e),"decode")};var uc=lc(pc),en=6e5,gc="sha512",Xt="PBKDF2-HMAC-SHA512",Qt=16,at="A256GCM",fc=32,pt=2e6;async function ci(e,t,n){return await uc(e,t,n,fc,gc)}i(ci,"deriveKey");async function li(e,t,n=en){if(!Number.isInteger(n)||n<1||n>pt)throw new Error(`Invalid iterations: must be an integer between 1 and ${pt}`);let r=cc(Qt),o=await ci(t.expose(),r,n);return await new dc(Zt.encode(e.expose())).setProtectedHeader({alg:"dir",enc:at,kdf:Xt,kdf_iter:n,kdf_salt:pi.encode(r)}).encrypt(o)}i(li,"encryptStringAsJwe");async function di(e,t){let{plaintext:n}=await mc(e,async r=>{if(!e.length)throw new Error("Unexpected JWE empty value");let o=t.expose();if(o.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!==at)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${at}" is supported`);if(r.kdf!==Xt)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Xt}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>pt)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${pt}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=pi.decode(r.kdf_salt);if(a.length!==Qt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Qt} bytes, got ${a.length}`);return await ci(o,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[at]});return Zt.decode(n)}i(di,"decryptJweAsString");function mi(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}i(mi,"isJweCompact");import yc from"enquirer";async function hc(e){return yc.prompt(e)}i(hc,"defaultPrompt");async function ui(e,t={}){let{prompt:n=hc}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return b.from(r)}i(ui,"promptPassphrase");import wc from"enquirer";import{statSync as Sc}from"fs";function gi(e,t=Sc){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}i(gi,"sortByMtime");async function vc(e){return wc.prompt(e)}i(vc,"defaultPrompt");async function fi(e,t={}){if(e.length===1)return e[0];let{prompt:n=vc,sortByMtime:r=gi}=t,o=r(e),s=o[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:o.map(l=>({name:l.kid,message:[l.kid,l.email,Me(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=o.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}i(fi,"promptSigningIdentity");function Ec(e){return{existsSync:e.existsSync??Cc,readFileSync:e.readFileSync??((t,n)=>bc(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Le,readSigningKey:e.readSigningKey??Ke,isOS:e.isOS??(t=>_(t)),decryptJweAsString:e.decryptJweAsString??di,discoverLocalKeys:e.discoverLocalKeys??Ne,keysDir:e.keysDir??$().keysDir,promptPassphrase:e.promptPassphrase??ui,promptSigningIdentity:e.promptSigningIdentity??fi}}i(Ec,"resolveDeps");async function yi(e,t={}){let n=Ec(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(mi(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 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 o;if(e.kid)o=r.find(s=>s.kid===e.kid);else if(e.interactive)o=await n.promptSigningIdentity(r);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!o)throw new Error(`No key found with kid "${e.kid}"`);switch(o.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(o.kid):await n.readSigningKey(o.kid);if(!s)throw new Error(`Key "${o.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:o.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${o.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 ${o.kid}: `);return{privateKeyPem:b.from(await n.decryptJweAsString(n.readFileSync(o.source.path,"utf-8"),s)),kid:o.kid}}case"public-only":throw new Error(`Key "${o.kid}" has no private key on this machine (public-only).`)}}i(yi,"resolvePrivateKey");var Tc=i(async(e,t,n,r,o)=>{let s=await N(e,{interactive:o.browserAuth??!1,appId:t,orgHint:o.org});await new A(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function Fc(e){return{existsSync:e.existsSync??kc,writeFileSync:e.writeFileSync??xc,createBundleStream:e.createBundleStream??He,signBundle:e.signBundle??$c,parseScope:e.parseScope??Ic,validateScopes:e.validateScopes??Rc,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>yi(t)),submitSignatures:e.submitSignatures??Tc,discoverSignatures:e.discoverSignatures??be}}i(Fc,"resolveDeps");async function hi(e,t,n={},r=process.cwd()){let o=Fc(n),s=t.appid,a=t.appVersion,p=[],c=o.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(o.parseScope):p=c.deployments.map(w=>({org:w.org,project:w.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?tn(r,e):H(r,s,a);if(!o.existsSync(l)){let w=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}${w}`)}let d=o.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
206
+ npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>yg(t))}o(oa,"registerSetupHttpsCommand");import{existsSync as Lg,writeFileSync as Ug}from"fs";import{basename as Mg,dirname as _g,join as jg,resolve as $r}from"path";import{parseScope as Ng,signBundle as Hg,validateScopes as Bg}from"@cognite/app-sdk/codesigning";import{existsSync as $g,readFileSync as Og}from"fs";import{pbkdf2 as wg,randomBytes as vg}from"crypto";import{promisify as Cg}from"util";import{CompactEncrypt as Ag,base64url as ia,compactDecrypt as Eg}from"jose";var hg=new TextEncoder,Sg=new TextDecoder,Dr={encode:o(e=>hg.encode(e),"encode"),decode:o(e=>Sg.decode(e),"decode")};var bg=Cg(wg),Tr=6e5,xg="sha512",Ir="PBKDF2-HMAC-SHA512",Rr=16,nn="A256GCM",kg=32,rn=2e6;async function sa(e,t,n){return await bg(e,t,n,kg,xg)}o(sa,"deriveKey");async function aa(e,t,n=Tr){if(!Number.isInteger(n)||n<1||n>rn)throw new Error(`Invalid iterations: must be an integer between 1 and ${rn}`);let r=vg(Rr),i=await sa(t.expose(),r,n);return await new Ag(Dr.encode(e.expose())).setProtectedHeader({alg:"dir",enc:nn,kdf:Ir,kdf_iter:n,kdf_salt:ia.encode(r)}).encrypt(i)}o(aa,"encryptStringAsJwe");async function pa(e,t){let{plaintext:n}=await Eg(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!==nn)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${nn}" is supported`);if(r.kdf!==Ir)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Ir}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>rn)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${rn}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=ia.decode(r.kdf_salt);if(a.length!==Rr)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Rr} bytes, got ${a.length}`);return await sa(i,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[nn]});return Dr.decode(n)}o(pa,"decryptJweAsString");function ca(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(ca,"isJweCompact");import Pg from"enquirer";async function Dg(e){return Pg.prompt(e)}o(Dg,"defaultPrompt");async function la(e,t={}){let{prompt:n=Dg}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return E.from(r)}o(la,"promptPassphrase");import Rg from"enquirer";import{statSync as Ig}from"fs";function da(e,t=Ig){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}o(da,"sortByMtime");async function Tg(e){return Rg.prompt(e)}o(Tg,"defaultPrompt");async function ua(e,t={}){if(e.length===1)return e[0];let{prompt:n=Tg,sortByMtime:r=da}=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,Ht(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(ua,"promptSigningIdentity");function Fg(e){return{existsSync:e.existsSync??$g,readFileSync:e.readFileSync??((t,n)=>Og(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??jt,readSigningKey:e.readSigningKey??Nt,isOS:e.isOS??(t=>K(t)),decryptJweAsString:e.decryptJweAsString??pa,discoverLocalKeys:e.discoverLocalKeys??Bt,keysDir:e.keysDir??I().keysDir,promptPassphrase:e.promptPassphrase??la,promptSigningIdentity:e.promptSigningIdentity??ua}}o(Fg,"resolveDeps");async function ma(e,t={}){let n=Fg(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(ca(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:E.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:E.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:E.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(ma,"resolvePrivateKey");var Kg=o(async(e,t,n,r,i)=>{let s=await _(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new U(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function Vg(e){return{existsSync:e.existsSync??Lg,writeFileSync:e.writeFileSync??Ug,createBundleStream:e.createBundleStream??Kt,signBundle:e.signBundle??Hg,parseScope:e.parseScope??Ng,validateScopes:e.validateScopes??Bg,loadAppConfig:e.loadAppConfig??x,resolvePrivateKey:e.resolvePrivateKey??(t=>ma(t)),submitSignatures:e.submitSignatures??Kg,discoverSignatures:e.discoverSignatures??Ze}}o(Vg,"resolveDeps");async function ga(e,t,n={},r=process.cwd()){let i=Vg(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?$r(r,e):z(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:
161
207
  ${d.join(`
162
- `)}`);let{privateKeyPem:m,kid:g}=await o.resolvePrivateKey({keyPath:t.key?tn(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),f=o.createBundleStream(l),u=await o.signBundle({privateKeyPem:m.expose(),kid:g,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p}),y=t.output?tn(r,t.output):Dc(Ac(l),`${Pc(l)}.${t.asCertifier?"cert":"dev"}.sig`);o.writeFileSync(y,u.token,"utf-8"),console.log(`\u2705 Signed: ${y}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(w=>`${w.org}/${w.project}`).join(", ")}`),t.verbose&&console.log(`
163
- Payload:`,JSON.stringify(u.payload,null,2));let v=Array.from(new Set([...o.discoverSignatures(l),u.token])),C=t.interactive?await T(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):D(c.deployments,t.deployment);if(!t.browserAuth){let w=R(C);if(w.length>0)throw new Error(`Deployment ${C.org}/${C.project} is missing ${w.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await o.submitSignatures(C,s,a,v,t),console.log(`
164
- To publish: npx @cognite/cli apps publish .`)}i(hi,"handleSign");function Si(e,t={}){return 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)").action((n,r)=>{let o={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return hi(n,o,t)})}i(Si,"registerSignCommand");function Oc(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}i(Oc,"describeStatus");function Uc(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let r=n.status==="VALID"?"\u2705":"\u274C",o=new Date(n.signatureIat).toISOString();t.push(` ${r} ${n.signerKid} (${n.signerRole}, signed ${o}) \u2014 ${n.status}`)}return t}i(Uc,"formatSignatures");async function _c(e){let t=process.cwd();F(t);let n=E(t);O(n);let r=e.interactive?await T(n,e):D(n.deployments,e.deployment);if(!e.interactive){let a=R(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let o=await N(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new A(o);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag);console.log(`Status: ${Oc(a)}`);let p=await Lc(s,n.externalId,n.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Uc(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof j){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}i(_c,"handleStatus");async function Lc(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ce(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}i(Lc,"fetchSignatures");function wi(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)").addHelpText("after",`
208
+ `)}`);let{privateKeyPem:u,kid:g}=await i.resolvePrivateKey({keyPath:t.key?$r(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),f=i.createBundleStream(l),y=await i.signBundle({privateKeyPem:u.expose(),kid:g,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p}),h=t.output?$r(r,t.output):jg(_g(l),`${Mg(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(h,y.token,"utf-8"),console.log(`\u2705 Signed: ${h}`),console.log(` kid: ${y.kid}`),console.log(` bundle: ${y.payload.bundleSha256}`),console.log(` scopes: ${y.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
209
+ Payload:`,JSON.stringify(y.payload,null,2));let C=Array.from(new Set([...i.discoverSignatures(l),y.token])),S=t.interactive?await F(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):R(c.deployments,t.deployment);if(!t.browserAuth){let v=j(S);if(v.length>0)throw new Error(`Deployment ${S.org}/${S.project} is missing ${v.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(S,s,a,C,t),console.log(`
210
+ To publish: npx @cognite/cli apps publish .`)}o(ga,"handleSign");function fa(e,t={}){return 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)").action((n,r)=>{let i={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return ga(n,i,t)})}o(fa,"registerSignCommand");function Gg(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Gg,"describeStatus");function Yg(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(Yg,"formatSignatures");async function qg(e){let t=process.cwd();N(t);let n=x(t);H(n);let r=e.interactive?await F(n,e):R(n.deployments,e.deployment);if(!e.interactive){let a=j(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await _(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new U(i);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag);console.log(`Status: ${Gg(a)}`);let p=await Jg(s,n.externalId,n.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Yg(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof q){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(qg,"handleStatus");async function Jg(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(oe(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}o(Jg,"fetchSignatures");function ya(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)").addHelpText("after",`
165
211
  Examples:
166
212
  npx @cognite/cli apps status . Status using env-var auth
167
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>_c(n))}i(wi,"registerStatusCommand");import{execFileSync as on}from"child_process";import rn from"fs";import Pe from"path";import Hc from"readline";var vi="https://cognite.zendesk.com",Kc="360001234312",Mc="tf_360015295097",Nc="cognite_flows_certifications";function Ci(e,t,n){let r=new URLSearchParams({ticket_form_id:Kc,tf_priority:"normal",tf_subject:e,[Mc]:Nc,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}i(Ci,"buildUrl");function bi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}i(bi,"escapeHtml");function nn(e){return e.map(bi).join("<br>")}i(nn,"toHtml");function Ei(e,t=vi){let{appName:n,externalId:r,versionTag:o,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: ${o}`,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}-${o}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return Ci(`App Review Request: ${n}`,nn(l.filter(d=>d!==void 0)),t)}i(Ei,"buildAppReviewUrl");function ki(e,t,n,r,o=vi){let s=nn(["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>${bi(r.replace(/\r\n/g,`
168
- `))}</pre>`,p=nn(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Ci(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,o)}i(ki,"buildKeyRegistrationUrl");function Bc(){return new Promise(e=>{let t=Hc.createInterface({input:process.stdin,output:process.stdout});t.question(`
169
- Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}i(Bc,"defaultPressEnter");var jc=[{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 Vc(e){let t=jc.filter(({pattern:n})=>on("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:o})=>` ${r} \u2192 /${o}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
213
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>qg(n))}o(ya,"registerStatusCommand");import{execFileSync as Lr}from"child_process";import Fr from"fs";import tt from"path";import Zg from"readline";var ha="https://cognite.zendesk.com",zg="360001234312",Wg="tf_360015295097",Xg="cognite_flows_certifications";function Sa(e,t,n){let r=new URLSearchParams({ticket_form_id:zg,tf_priority:"normal",tf_subject:e,[Wg]:Xg,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}o(Sa,"buildUrl");function wa(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(wa,"escapeHtml");function Or(e){return e.map(wa).join("<br>")}o(Or,"toHtml");function va(e,t=ha){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 Sa(`App Review Request: ${n}`,Or(l.filter(d=>d!==void 0)),t)}o(va,"buildAppReviewUrl");function Ca(e,t,n,r,i=ha){let s=Or(["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>${wa(r.replace(/\r\n/g,`
214
+ `))}</pre>`,p=Or(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Sa(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(Ca,"buildKeyRegistrationUrl");function Qg(){return new Promise(e=>{let t=Zg.createInterface({input:process.stdin,output:process.stdout});t.question(`
215
+ Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(Qg,"defaultPressEnter");var ef=[{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 tf(e){let t=ef.filter(({pattern:n})=>Lr("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:
170
216
 
171
217
  `+n.join(`
172
- `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}i(Vc,"assertArtifactsCommitted");async function Gc(e=process.cwd(),t={}){let{openInBrowser:n=jn,revealInFileManager:r=Vn,pressEnter:o=Bc,isInteractive:s=i(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(G(),!Te(e))throw new Error("Not a git repository. Run this command from your app's root directory.");F(e);let a=E(e);O(a),Vc(e);let p=Pe.join(e,"dist","submit");rn.mkdirSync(p,{recursive:!0});let c=on("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(on("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.
218
+ `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(tf,"assertArtifactsCommitted");async function nf(e=process.cwd(),t={}){let{openInBrowser:n=ht,revealInFileManager:r=Do,pressEnter:i=Qg,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(ae(),!Ut(e))throw new Error("Not a git repository. Run this command from your app's root directory.");N(e);let a=x(e);H(a),tf(e);let p=tt.join(e,"dist","submit");Fr.mkdirSync(p,{recursive:!0});let c=Lr("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Lr("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.
173
219
 
174
- The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=Pe.join(p,d);await new J(Pe.join(e,"dist")).createSourceArchive(m);let f=`${a.externalId}-${a.versionTag}.zip`,u=Pe.join(e,".cognite-bundles",f),y=!1;rn.existsSync(u)&&(rn.copyFileSync(u,Pe.join(p,f)),y=!0);let v=Ei({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:bn(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
175
- \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(y?` ${f} \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(`
220
+ The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,u=tt.join(p,d);await new ge(tt.join(e,"dist")).createSourceArchive(u);let f=`${a.externalId}-${a.versionTag}.zip`,y=tt.join(e,".cognite-bundles",f),h=!1;Fr.existsSync(y)&&(Fr.copyFileSync(y,tt.join(p,f)),h=!0);let C=va({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:Gi(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
221
+ \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(h?` ${f} \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(`
176
222
  Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
177
- \u{1F517} ${v}`),s()&&(await o(),n(v),r(m))}i(Gc,"handleSubmit");function xi(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
223
+ \u{1F517} ${C}`),s()&&(await i(),n(C),r(u))}o(nf,"handleSubmit");function Aa(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
178
224
  Examples:
179
- npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Gc())}i(xi,"registerSubmitCommand");function Pi(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Vr(t),Xr(t),ri(t),wi(t),ii(t),oi(t),Pr(t),Gr(t),Yr(t),ai(t),xi(t),Hr(t),Si(t),sr(t),t}i(Pi,"registerAppsCommand");import{existsSync as Wc,mkdirSync as Jc,writeFileSync as Zc}from"fs";import{dirname as pn,join as Ae}from"path";import{generateSigningKeyPair as Xc}from"@cognite/app-sdk/codesigning";import Qc from"open";function Ai(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,o=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),o);return new Date(Date.UTC(n,r,s))}i(Ai,"addMonthsClamped");function sn(e){return e.toISOString().slice(0,10)}i(sn,"formatIsoDate");function Di(e=new Date){return sn(e)}i(Di,"todayIso");var ct=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),Ii=32,$i=44,Ri=60,Yc="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function qc(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==$i&&t.length!==Ri)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${$i} (raw) or ${Ri} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===ct.length+Ii&&n.subarray(0,ct.length).equals(ct))return n.subarray(ct.length).toString("base64");if(n.length===Ii)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}i(qc,"pemBodyOneLine");function an(e,t=ke,n=new Date){let r=Ti(e.issuedAt??Di(n)),o=Ti(e.expires),s=qc(e.publicKeyPem),a=" ",p=i((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
225
+ npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>nf())}o(Aa,"registerSubmitCommand");function Ea(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Bs(t),zs(t),ea(t),ya(t),ta(t),na(t),bs(t),Ks(t),Vs(t),oa(t),Aa(t),js(t),fa(t),Es(t),t}o(Ea,"registerAppsCommand");import{existsSync as af,mkdirSync as pf,writeFileSync as cf}from"fs";import{dirname as _r,join as nt}from"path";import{generateSigningKeyPair as lf}from"@cognite/app-sdk/codesigning";import df from"open";function ba(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(ba,"addMonthsClamped");function Ur(e){return e.toISOString().slice(0,10)}o(Ur,"formatIsoDate");function xa(e=new Date){return Ur(e)}o(xa,"todayIso");var on=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ka=32,Pa=44,Da=60,rf="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function of(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==Pa&&t.length!==Da)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${Pa} (raw) or ${Da} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===on.length+ka&&n.subarray(0,on.length).equals(on))return n.subarray(on.length).toString("base64");if(n.length===ka)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(of,"pemBodyOneLine");function Mr(e,t=Be,n=new Date){let r=Ia(e.issuedAt??xa(n)),i=Ia(e.expires),s=of(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
180
226
  `,"kv"),c="";return c+=`
181
- ${t.bold("Add this entry to")} ${t.magenta(Yc)} ${t.bold("under")} ${t.cyan("publicKeys:")}
227
+ ${t.bold("Add this entry to")} ${t.magenta(rf)} ${t.bold("under")} ${t.cyan("publicKeys:")}
182
228
 
183
229
  `,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
184
- `,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(o)),c+=p("revokedAt",t.dim("null")),c}i(an,"renderRegistryYamlBlock");function Ti(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()}i(Ti,"toIsoInstant");import zc from"clipboardy";function Fi(e){return zc.write(e)}i(Fi,"copyToClipboard");function Oi(e,t){return e.map((n,r)=>Math.max(n.length,...t.map(o=>o[r].length)))}i(Oi,"computeColumnWidths");function Ui(e,t,n=e){return e.map((r,o)=>n[o]+" ".repeat(Math.max(0,t[o]-r.length))).join(" ").trimEnd()}i(Ui,"formatTableRow");function el(e){return{writeFileSync:e.writeFileSync??Zc,mkdirSync:e.mkdirSync??Jc,existsSync:e.existsSync??Wc,generateSigningKeyPair:e.generateSigningKeyPair??Xc,encryptStringAsJwe:e.encryptStringAsJwe??li,storeKeyInKeychain:e.storeKeyInKeychain??qn,storeSigningKey:e.storeSigningKey??Xn,isOS:e.isOS??(t=>_(t)),promptKid:e.promptKid??_n,promptExpiryMonths:e.promptExpiryMonths??Kn,promptEmail:e.promptEmail??Mn,promptPassphrase:e.promptPassphrase??Nn,promptConfirmOverwrite:e.promptConfirmOverwrite??Hn,discoverLocalKeys:e.discoverLocalKeys??(()=>Ne()),promptZendeskAction:e.promptZendeskAction??Ln,openUrl:e.openUrl??(t=>Qc(t)),copyToClipboard:e.copyToClipboard??Fi}}i(el,"resolveDeps");function Li(e,t={}){let n=el(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 ${$().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(o=>il(o,n)),r.command("list").description("List local signing identities and their storage location").action(()=>tl(n))}i(Li,"registerKeysCommand");async function tl(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
185
- `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${$().keysDir}).
186
- `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Me(a.source),a.email??"\u2014"]),o=Oi(n,r),s=i(a=>Ui(a,o),"fmt");process.stdout.write(`${s(n)}
230
+ `,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(Mr,"renderRegistryYamlBlock");function Ia(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(Ia,"toIsoInstant");import sf from"clipboardy";function Ra(e){return sf.write(e)}o(Ra,"copyToClipboard");function uf(e){return{writeFileSync:e.writeFileSync??cf,mkdirSync:e.mkdirSync??pf,existsSync:e.existsSync??af,generateSigningKeyPair:e.generateSigningKeyPair??lf,encryptStringAsJwe:e.encryptStringAsJwe??aa,storeKeyInKeychain:e.storeKeyInKeychain??ms,storeSigningKey:e.storeSigningKey??Ss,isOS:e.isOS??(t=>K(t)),promptKid:e.promptKid??is,promptExpiryMonths:e.promptExpiryMonths??as,promptEmail:e.promptEmail??ps,promptPassphrase:e.promptPassphrase??cs,promptConfirmOverwrite:e.promptConfirmOverwrite??ls,discoverLocalKeys:e.discoverLocalKeys??(()=>Bt()),promptZendeskAction:e.promptZendeskAction??ss,openUrl:e.openUrl??(t=>df(t)),copyToClipboard:e.copyToClipboard??Ra}}o(uf,"resolveDeps");function $a(e,t={}){let n=uf(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 ${I().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=>yf(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>mf(n))}o($a,"registerKeysCommand");async function mf(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
231
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${I().keysDir}).
232
+ `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Ht(a.source),a.email??"\u2014"]),i=Tt(n,r),s=o(a=>We(a,i),"fmt");process.stdout.write(`${s(n)}
187
233
  `);for(let a of r)process.stdout.write(`${s(a)}
188
- `)}i(tl,"handleList");function _i(e,t,n){let r=Ae($().keysDir,`${e}${Z}`);return n.mkdirSync(pn(r),{recursive:!0}),n.writeFileSync(r,t),r}i(_i,"writePublicKey");async function nl(e,t,n,r,o,{force:s=!1}={}){let a=r??Ae($().keysDir,`${e}${bt}`);if(o.mkdirSync(pn(a),{recursive:!0}),!s&&o.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 o.encryptStringAsJwe(t,n);return o.writeFileSync(a,p,{mode:384}),a}i(nl,"writeEncryptedPrivateKey");function rl(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{me(e.expires)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.kid===void 0)r.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let o=pe(e.kid),s=Ae($().keysDir,`${o}${Z}`);n(s)&&!e.force&&r.push(`Key "${o}" already exists. Use --force to overwrite without prompting.`)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.email===void 0)r.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{de(e.email,"--email")}catch(o){r.push(o instanceof Error?o.message:String(o))}return t||r.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),r}i(rl,"collectNonInteractiveErrors");async function il(e,t,n=new Date){let{isOS:r,existsSync:o,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,storeSigningKey:l,promptExpiryMonths:d,promptKid:m,promptEmail:g,promptPassphrase:f,promptConfirmOverwrite:u}=t,y=e.interactive??!1,v=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!y){let V=rl(e,v,o);if(V.length>0)throw new Error(V.join(`
189
- `))}let C;e.expires!==void 0?C=me(e.expires):C=await d();let w=sn(Ai(n,C)),S;e.kid!==void 0?S=pe(e.kid):S=await m();let x=Ae($().keysDir,`${S}${Z}`),L=o(x);if(L&&!e.force&&!await u(S)){process.stderr.write(`Aborted.
190
- `);return}let P;e.email!==void 0?P=de(e.email,"--email"):P=await g();let k=v?{kind:"keychain"}:{kind:"file",passphrase:await f()};process.stderr.write(`
234
+ `)}o(mf,"handleList");function Ta(e,t,n){let r=nt(I().keysDir,`${e}${he}`);return n.mkdirSync(_r(r),{recursive:!0}),n.writeFileSync(r,t),r}o(Ta,"writePublicKey");async function gf(e,t,n,r,i,{force:s=!1}={}){let a=r??nt(I().keysDir,`${e}${mr}`);if(i.mkdirSync(_r(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(gf,"writeEncryptedPrivateKey");function ff(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{je(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=nt(I().keysDir,`${i}${he}`);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{_e(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(ff,"collectNonInteractiveErrors");async function yf(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:f,promptConfirmOverwrite:y}=t,h=e.interactive??!1,C=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!h){let Q=ff(e,C,i);if(Q.length>0)throw new Error(Q.join(`
235
+ `))}let S;e.expires!==void 0?S=je(e.expires):S=await d();let v=Ur(ba(n,S)),w;e.kid!==void 0?w=De(e.kid):w=await u();let b=nt(I().keysDir,`${w}${he}`),k=i(b);if(k&&!e.force&&!await y(w)){process.stderr.write(`Aborted.
236
+ `);return}let T;e.email!==void 0?T=_e(e.email,"--email"):T=await g();let A=C?{kind:"keychain"}:{kind:"file",passphrase:await f()};process.stderr.write(`
191
237
  Generating Ed25519 keypair...
192
238
 
193
- `);let{privateKeyPem:te,publicKeyPem:ne}=await p(S),U=b.from(te);if(k.kind==="keychain"){r("macos")?await c(S,U):await l(S,U);let V=_i(S,ne,t);process.stderr.write(`Public key: ${V}
194
- `),process.stderr.write(`Private key: OS credential store (account: ${S})
195
- `)}else{let V=await nl(S,U,k.passphrase,e.output,t,{force:L}),ro=_i(S,ne,t);process.stderr.write(`Public key: ${ro}
196
- `),process.stderr.write(`Private key: ${V} (JWE, AES-256-GCM, PBKDF2-SHA512 x${en.toLocaleString()})
197
- `)}let re=Ae($().keysDir,`${S}${Et}`);s(pn(re),{recursive:!0}),a(re,JSON.stringify({email:P}));let le=rt(process.stderr);process.stderr.write(`
198
- Signing identity (kid): ${le.green(S)}
199
- `),process.stderr.write(`Expires: ${w} (${C} month${C===1?"":"s"} from today)
200
- `);let De={kid:S,publicKeyPem:ne,email:P,expires:w};y||(process.stderr.write(`
239
+ `);let{privateKeyPem:X,publicKeyPem:pe}=await p(w),L=E.from(X);if(A.kind==="keychain"){r("macos")?await c(w,L):await l(w,L);let Q=Ta(w,pe,t);process.stderr.write(`Public key: ${Q}
240
+ `),process.stderr.write(`Private key: OS credential store (account: ${w})
241
+ `)}else{let Q=await gf(w,L,A.passphrase,e.output,t,{force:k}),Ba=Ta(w,pe,t);process.stderr.write(`Public key: ${Ba}
242
+ `),process.stderr.write(`Private key: ${Q} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Tr.toLocaleString()})
243
+ `)}let Z=nt(I().keysDir,`${w}${gr}`);s(_r(Z),{recursive:!0}),a(Z,JSON.stringify({email:T}));let O=D(process.stderr);process.stderr.write(`
244
+ Signing identity (kid): ${O.green(w)}
245
+ `),process.stderr.write(`Expires: ${v} (${S} month${S===1?"":"s"} from today)
246
+ `);let Re={kid:w,publicKeyPem:pe,email:T,expires:v};h||(process.stderr.write(`
201
247
  Key registration data:
202
248
 
203
- `),process.stderr.write(an(De,le,n)));let ie=ki(S,P,w,an(De,ke,n));process.stderr.write(`
204
- ${le.bold("Next:")}
249
+ `),process.stderr.write(Mr(Re,O,n)));let ce=Ca(w,T,v,Mr(Re,Be,n));process.stderr.write(`
250
+ ${O.bold("Next:")}
205
251
  `),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
206
- `);let we;if(e.copyLink?we="clipboard":y?we=await t.promptZendeskAction():we=null,we==="browser")try{await t.openUrl(ie),process.stderr.write(` Opening in browser...
207
- `)}catch{process.stderr.write(` URL: ${ie}
208
- `)}else if(we==="clipboard"){let V=!1;try{await t.copyToClipboard(ie),V=!0}catch{}process.stderr.write(V&&!e.copyLink?` Link copied to clipboard.
209
- `:` URL: ${ie}
210
- `)}else process.stderr.write(` URL: ${ie}
252
+ `);let He;if(e.copyLink?He="clipboard":h?He=await t.promptZendeskAction():He=null,He==="browser")try{await t.openUrl(ce),process.stderr.write(` Opening in browser...
253
+ `)}catch{process.stderr.write(` URL: ${ce}
254
+ `)}else if(He==="clipboard"){let Q=!1;try{await t.copyToClipboard(ce),Q=!0}catch{}process.stderr.write(Q&&!e.copyLink?` Link copied to clipboard.
255
+ `:` URL: ${ce}
256
+ `)}else process.stderr.write(` URL: ${ce}
211
257
  `);process.stderr.write(`
212
258
  2. Once your key is approved, sign your Dune app:
213
- `),process.stderr.write(` ${le.cyan(`cognite sign -s ${S}`)}
214
- `)}i(il,"handleGenerate");import{performance as Ki}from"perf_hooks";var Mi=1e3,lt;function ol(){lt=Ki.now()}i(ol,"markActionStart");function sl(){lt=void 0}i(sl,"resetActionStart");function al(){if(lt!==void 0)return Math.max(0,Math.round(Ki.now()-lt))}i(al,"snapshotActionDurationMs");function Ni(){let e=al();return sl(),{...e!==void 0&&{actionDurationMs:e}}}i(Ni,"takePerformanceFields");var pl=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description","externalId"]);function cl(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:pl.has(t)?[t,n]:[t,"[REDACTED]"]))}i(cl,"sanitizeOptions");function ll(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}i(ll,"getCommandPath");function Hi(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{}}}i(Hi,"tryLoadAppConfig");function cn(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}i(cn,"commandFromArgv");function Bi(e,t,n=E){e.hook("preAction",()=>{ol()}),e.hook("postAction",async(r,o)=>{try{let s={command:ll(o),options:cl(o.opts()),success:!0,...Hi(n),...Ni()};t.track("Flows.CLI.Command",{...s}),await t.flush(Mi)}catch{}})}i(Bi,"instrument");async function ji(e,t,n=E){try{let r={command:cn(t),options:{},success:!1,...Hi(n),...Ni()};e.track("Flows.CLI.Command",{...r}),await e.flush(Mi)}catch{}}i(ji,"trackFailure");var dl="ERR_USE_AFTER_CLOSE";function Gi(e){return e instanceof Error&&"code"in e&&e.code===dl}i(Gi,"isReadlineClosedError");function ml(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(ml,"isPlainObject");function ln(e){return e==null||Gi(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&ml(e)&&Object.keys(e).length===0)}i(ln,"isPromptCancel");var Vi=!1;function Yi(){Vi||(Vi=!0,process.on("uncaughtException",e=>{Gi(e)&&(console.error(`
215
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{ln(e)&&(console.error(`
216
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}i(Yi,"installCancelHandler");import{homedir as ul,userInfo as gl}from"os";var fl=ul(),yl=(()=>{try{return gl().username}catch{return""}})();function he(e,t=fl){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}i(he,"redactHomedir");function hl(e,t=yl){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>")}i(hl,"redactUsername");var Sl=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function qi(e){return e.replace(Sl,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}i(qi,"redactCredentials");var wl=1e3,vl="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Cl={captureError:i(async()=>{},"captureError"),flush:i(async()=>{},"flush")};function bl(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}i(bl,"buildRelease");var El="192.0.2.0";function kl(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:he(t.filename)},...t.abs_path!==void 0&&{abs_path:he(t.abs_path)},...t.module!==void 0&&{module:he(t.module)}}))}i(kl,"scrubStackFrames");function dt(e){return qi(hl(he(e)))}i(dt,"redactPii");function xl(e){let t={...e.user,email:void 0,username:void 0,ip_address:El,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?dt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:kl(s.stacktrace.frames)}}})),r=e.contexts?.cli,o=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?dt(a):a])):void 0;return{...e,message:e.message!==void 0?dt(e.message):e.message,...typeof e.culprit=="string"&&{culprit:dt(e.culprit)},user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...o!==void 0&&{contexts:{...e.contexts,cli:o}}}}i(xl,"scrubPii");function zi(e={}){let t=e.env??process.env;if(Ut(t))return Cl;let n=bl(e),r="production",o=null,s=null;function a(){return{dsn:vl,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:ve},contexts:{cli:{applicationId:ve,node:process.version,platform:process.platform}}},beforeSend:xl}}i(a,"buildInitOptions");async function p(){return o||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),o=c,c}catch{return null}})()),s)}return i(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Pl(c,l))}catch{}},async flush(c=wl){try{if(!o)return;await o.flush(c)}catch{}}}}i(zi,"createErrorReporter");function Pl(e,t){let n={level:"fatal"},r={applicationId:ve,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),wn(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},vn(e)&&(n.contexts.http={url:e.requestUrl!==void 0?he(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let o=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:qi(he(o))}}return n}i(Pl,"buildCaptureContext");import{mkdirSync as Al,readFileSync as Dl,writeFileSync as Il}from"fs";import{homedir as $l}from"os";import{resolve as mt}from"path";import{debuglog as Rl}from"util";import{lt as Tl,parse as Wi}from"semver";var Fl="https://registry.npmjs.org/@cognite/cli/latest",Ol=1500,Ji="upgrade-check.json",Zi=mt(process.env.XDG_CACHE_HOME||mt($l(),".cache"),"@cognite","cli"),dn=Rl("cognite-flows");function Ul(e,t){return!e||!t||!Wi(e)||!Wi(t)?!1:Tl(e,t)}i(Ul,"isOutdated");async function _l({timeout:e=Ol,registryUrl:t=Fl,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 o=await r.json();return typeof o?.version=="string"?o.version:null}catch(r){return dn("fetchLatestVersion failed (%s): %O",t,r),null}}i(_l,"fetchLatestVersion");function Ll(e=Zi,t=864e5){try{let n=Dl(mt(e,Ji),"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 dn("readUpgradeCheckCache failed (%s): %O",e,n),null}}i(Ll,"readUpgradeCheckCache");function Kl(e,t){try{Al(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Il(mt(e,Ji),JSON.stringify(n))}catch(n){dn("writeUpgradeCheckCache failed (%s): %O",e,n)}}i(Kl,"writeUpgradeCheckCache");async function Ml({cacheDir:e=Zi,...t}={}){let n=await _l(t);n&&Kl(e,n)}i(Ml,"startBackgroundUpgradeCheck");function Xi(e,{onOutdated:t,cacheDir:n,...r}={}){let o=Ll(n);if(o){Ul(e,o.latest)&&t?.(e,o.latest);return}Ml({cacheDir:n,...r})}i(Xi,"preActionUpgradeCheck");import{default as Bw,chalkStderr as Qi}from"chalk";function eo(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,o="\u2500".repeat(r),s=i(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${o}\u2510`,...n.map(s),`\u2514${o}\u2518`].join(`
217
- `);return Qi.bold.yellow(a)}i(eo,"formatUpgradeWarning");function Bl(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}i(Bl,"isDep0040Warning");var un=process,jl=un.emit.bind(un);un.emit=function(e,...t){return e==="warning"&&Bl(t[0])?!1:jl(e,...t)};Yi();var Se=new Hl;Se.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.9.0-alpha.0").showHelpAfterError().configureOutput({writeOut:i(e=>Nl(1,e),"writeOut")});Se.hook("preAction",()=>{Xi("1.9.0-alpha.0",{onOutdated:i((e,t)=>{console.warn(`
218
- ${eo(e,t)}
219
- `)},"onOutdated")})});Pi(Se);Li(Se);var no=Ye({packageName:"@cognite/cli",cliVersion:"1.9.0-alpha.0"}),to=zi({packageName:"@cognite/cli",cliVersion:"1.9.0-alpha.0"});Bi(Se,no);var mn=process.argv.slice(2);Se.parseAsync(mn,{from:"user"}).catch(async e=>{await ji(no,mn),ln(e)&&(console.error(`
220
- Cancelled.`),process.exit(130)),(!(e instanceof h)||e.shouldReport)&&(await to.captureError(e,{command:cn(mn)}),await to.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof h&&(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)});
259
+ `),process.stderr.write(` ${O.cyan(`cognite sign -s ${w}`)}
260
+ `)}o(yf,"handleGenerate");import{homedir as hf,userInfo as Sf}from"os";var wf=hf(),vf=(()=>{try{return Sf().username}catch{return""}})();function Ne(e,t=wf){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(Ne,"redactHomedir");function Cf(e,t=vf){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(Cf,"redactUsername");var Af=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Oa(e){return e.replace(Af,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}o(Oa,"redactCredentials");var Ef=1e3,bf="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",xf={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function kf(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(kf,"buildRelease");var Pf="192.0.2.0";function Df(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:Ne(t.filename)},...t.abs_path!==void 0&&{abs_path:Ne(t.abs_path)},...t.module!==void 0&&{module:Ne(t.module)}}))}o(Df,"scrubStackFrames");function sn(e){return Oa(Cf(Ne(e)))}o(sn,"redactPii");function If(e){let t={...e.user,email:void 0,username:void 0,ip_address:Pf,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?sn(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Df(s.stacktrace.frames)}}})),r=e.contexts?.cli,i=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?sn(a):a])):void 0;return{...e,message:e.message!==void 0?sn(e.message):e.message,...typeof e.culprit=="string"&&{culprit:sn(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(If,"scrubPii");function Fa(e={}){let t=e.env??process.env;if(Rn(t))return xf;let n=kf(e),r="production",i=null,s=null;function a(){return{dsn:bf,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Ye},contexts:{cli:{applicationId:Ye,node:process.version,platform:process.platform}}},beforeSend:If}}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,Rf(c,l))}catch{}},async flush(c=Ef){try{if(!i)return;await i.flush(c)}catch{}}}}o(Fa,"createErrorReporter");function Rf(e,t){let n={level:"fatal"},r={applicationId:Ye,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),fe(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},Jr(e)&&(n.contexts.http={url:e.requestUrl!==void 0?Ne(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:Oa(Ne(i))}}return n}o(Rf,"buildCaptureContext");import{mkdirSync as Tf,readFileSync as $f,writeFileSync as Of}from"fs";import{homedir as Ff}from"os";import{resolve as an}from"path";import{debuglog as Lf}from"util";import{lt as Uf,parse as La}from"semver";var Mf="https://registry.npmjs.org/@cognite/cli/latest",_f=1500,Ua="upgrade-check.json",Ma=an(process.env.XDG_CACHE_HOME||an(Ff(),".cache"),"@cognite","cli"),jr=Lf("cognite-flows");function jf(e,t){return!e||!t||!La(e)||!La(t)?!1:Uf(e,t)}o(jf,"isOutdated");async function Nf({timeout:e=_f,registryUrl:t=Mf,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 jr("fetchLatestVersion failed (%s): %O",t,r),null}}o(Nf,"fetchLatestVersion");function Hf(e=Ma,t=864e5){try{let n=$f(an(e,Ua),"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 jr("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(Hf,"readUpgradeCheckCache");function Bf(e,t){try{Tf(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Of(an(e,Ua),JSON.stringify(n))}catch(n){jr("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(Bf,"writeUpgradeCheckCache");async function Kf({cacheDir:e=Ma,...t}={}){let n=await Nf(t);n&&Bf(e,n)}o(Kf,"startBackgroundUpgradeCheck");function _a(e,{onOutdated:t,cacheDir:n,...r}={}){let i=Hf(n);if(i){jf(e,i.latest)&&t?.(e,i.latest);return}Kf({cacheDir:n,...r})}o(_a,"preActionUpgradeCheck");import{default as jI,chalkStderr as ja}from"chalk";function Na(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(`
261
+ `);return ja.bold.yellow(a)}o(Na,"formatUpgradeWarning");function Yf(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Yf,"isDep0040Warning");var Hr=process,qf=Hr.emit.bind(Hr);Hr.emit=function(e,...t){return e==="warning"&&Yf(t[0])?!1:qf(e,...t)};pt();var Ie=new Gf;Ie.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.9.0-alpha.2").showHelpAfterError().configureOutput({writeOut:o(e=>Vf(1,e),"writeOut")});Ie.hook("preAction",()=>{_a("1.9.0-alpha.2",{onOutdated:o((e,t)=>{console.warn(`
262
+ ${Na(e,t)}
263
+ `)},"onOutdated")})});Ea(Ie);$a(Ie);var Br=yt({packageName:"@cognite/cli",cliVersion:"1.9.0-alpha.2"}),Ha=Fa({packageName:"@cognite/cli",cliVersion:"1.9.0-alpha.2"});no(Ie,Br);Ki(Ie,{telemetry:Br});var Nr=process.argv.slice(2);Ie.parseAsync(Nr,{from:"user"}).catch(async e=>{await ro(Br,Nr),vn(e)&&(console.error(`
264
+ Cancelled.`),process.exit(130)),(!(e instanceof m)||e.shouldReport)&&(await Ha.captureError(e,{command:wn(Nr)}),await Ha.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)});