@cognite/cli 1.7.1-alpha.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/cli.js CHANGED
@@ -1,25 +1,25 @@
1
1
  #!/usr/bin/env node
2
- var _i=Object.defineProperty;var en=e=>{throw TypeError(e)};var i=(e,t)=>_i(e,"name",{value:t,configurable:!0});var tn=(e,t,n)=>t.has(e)||en("Cannot "+n);var nn=(e,t,n)=>(tn(e,t,"read from private field"),n?n.call(e):t.get(e)),rn=(e,t,n)=>t.has(e)?en("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),on=(e,t,n,r)=>(tn(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as Gc}from"fs";import{Command as Yc}from"commander";var et=class et 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:Mi(t.cause)}}};i(et,"HintedError");var u=et;function an(e){return e instanceof u}i(an,"isHintedError");var sn="https://docs.cognite.com/cdf/access/",Ki="https://status.cognite.com";function Li(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:Ki};default:return{}}}i(Li,"defaultHintForStatus");var tt=class tt extends u{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=Li(n),o=super.deriveDefaults(t);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(tt,"HintedHttpError");var te=tt;function pn(e){return e instanceof te}i(pn,"isHintedHttpError");function Ni(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(Ni,"hintForErrno");function Mi(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,o=Ni(r.code,r);if(o!==void 0)return o;t=r.cause}}i(Mi,"hintForCause");import{existsSync as $o,readFileSync as Ro}from"fs";import{join as To,resolve as _e}from"path";import{verifyBundle as Fo}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as Oo}from"jose";import ot from"enquirer";import{email as Hi,pipe as ji,safeParse as Vi,string as Bi}from"valibot";var Gi=ji(Bi(),Hi());function ae(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Vi(Gi,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}i(ae,"parseEmail");function pe(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(pe,"parseExpiryMonths");import{execFileSync as fe}from"child_process";function Pe(e={}){let{execFileSync:t=fe}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}i(Pe,"isGitInstalled");function xe(e,t={}){let{execFileSync:n=fe}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}i(xe,"isInsideGitRepo");function cn(e,t={}){let{execFileSync:n=fe}=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 ln(e={}){let{execFileSync:t=fe}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(ln,"gitUserName");function dn(e={}){let{execFileSync:t=fe}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(dn,"gitUserEmail");import{inspect as Yi}from"util";var nt="[REDACTED]",ye,Ae=class Ae{constructor(t){rn(this,ye);on(this,ye,t)}toString(){return nt}toJSON(){return nt}[Yi.custom](){return nt}expose(){return nn(this,ye)}static from(t){return new Ae(t)}};ye=new WeakMap,i(Ae,"SensitiveString");var w=Ae;var De=3,mn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",un=`Key expiry in months (${1}-${12})`,gn="Email address for the registry entry",fn=`Passphrase for the encrypted private key (min ${15} chars)`,yn="Confirm passphrase",hn=i(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Sn=i(e=>`Passphrases do not match (attempt ${e}/${De}).
3
- `,"passphraseMismatchMsg"),wn=`Passphrase confirmation failed after ${De} attempts`,vn=i(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Cn="How would you like to submit your key registration?",En="Open in browser",kn="Copy link to clipboard";async function Ie(e){return ot.prompt(e)}i(Ie,"defaultPrompt");function st(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}i(st,"parserAsValidator");var Ji=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function re(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(!Ji.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(re,"parseKid");async function bn(e={}){let{prompt:t=Ie}=e,{kid:n}=await t({type:"input",name:"kid",message:mn,validate:st(re)});return re(n)}i(bn,"promptKid");async function Pn(e={}){let{prompt:t=i(r=>ot.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Cn,choices:[{name:"browser",message:En},{name:"clipboard",message:kn}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}i(Pn,"promptZendeskAction");async function xn(e={}){let{prompt:t=Ie}=e,{months:n}=await t({type:"input",name:"months",message:un,initial:String(6),validate:st(r=>pe(r,"expiry"))});return pe(n,"expiry")}i(xn,"promptExpiryMonths");async function An(e={}){let{prompt:t=Ie,gitUserEmail:n=dn}=e,{email:r}=await t({type:"input",name:"email",message:gn,initial:n(),validate:st(o=>ae(o,"email"))});return ae(r,"email")}i(An,"promptEmail");async function Dn(e={}){let{prompt:t=Ie,stderr:n=process.stderr}=e;for(let r=1;r<=De;r+=1){let{passphrase:o}=await t({type:"password",name:"passphrase",message:fn,validate:i(a=>a.length>=15?!0:hn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:yn});if(o===s)return w.from(o);n.write(Sn(r))}throw new Error(wn)}i(Dn,"promptPassphrase");async function In(e,t={}){let{prompt:n=i(o=>ot.prompt(o),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:vn(e),initial:!1});return r}i(In,"promptConfirmOverwrite");import{existsSync as ao,readdirSync as po,readFileSync as co}from"fs";import{join as pt}from"path";import{execFile as Xi}from"child_process";import{promisify as Zi}from"util";import{execFileSync as $n}from"child_process";import{platform as Wi}from"os";import zi from"path";function A(e,t={}){let{platform:n=Wi}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}i(A,"isOS");function Rn(e,t={}){let{exec:n=$n,log:r=console.log}=t,[o,s]=A("macos",t)?["open",[e]]:A("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(Rn,"openInBrowser");function Tn(e,t={}){let{exec:n=$n,log:r=console.log}=t,[o,s]=A("macos",t)?["open",["-R",e]]:A("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[zi.dirname(e)]];try{n(o,s)}catch{r(`Could not open file manager \u2014 files are at:
5
- ${e}`)}}i(Tn,"revealInFileManager");var Fn="cognite-flows",Qi=Zi(Xi),On=i((e,t)=>Qi(e,t),"defaultExecFile"),eo=-25300,to=eo&255;function no(e){if(!(e instanceof Error)||!("code"in e)||e.code!==to)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}i(no,"isKeychainNotFoundError");async function Un(e,t,n={}){let r=t.expose();if(!A("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:o=On}=n;await o("security",["add-generic-password","-a",e,"-s",Fn,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}i(Un,"storeKeyInKeychain");async function Re(e,t={}){if(!A("macos",t))return null;let{execFile:n=On}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Fn,"-w"]);return w.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(no(r))return null;throw r}}i(Re,"readKeyFromKeychain");var Kn="cognite-cli-signing",ro="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.",io="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.",_n="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function oo(e){if(!(e instanceof Error))return _n;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?ro:t.includes("ambiguous")?io:_n}i(oo,"hintFor");function Ln(e,t,n){return new u(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:oo(n),shouldReport:!1})}i(Ln,"wrapKeyringError");async function Nn(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(Nn,"defaultCreateEntry");async function Mn(e,t,n={}){let{createEntry:r=Nn}=n,o=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(Kn,e)).setPassword(o)}catch(s){throw Ln("store",e,s)}}i(Mn,"storeSigningKey");async function Te(e,t={}){let{createEntry:n=Nn}=t;try{let o=(await n(Kn,e)).getPassword();return o===null?null:w.from(Buffer.from(o,"base64").toString("utf-8"))}catch(r){throw Ln("read",e,r)}}i(Te,"readSigningKey");import{homedir as so}from"os";import{join as at}from"path";function $(e={}){let{env:t=process.env,homedir:n=so}=e,r=t.COGNITE_CLI_HOME?.trim()||at(n(),".cognite-cli");return{home:r,keysDir:at(r,"keys"),sessionFile:at(r,"session.json")}}i($,"getConfig");var J=".pub.pem",ct=".key.jwe",lt=".meta.json";function Fe(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(Fe,"formatLocalKeySource");function lo(e){return{existsSync:e.existsSync??ao,readdirSync:e.readdirSync??po,readFileSync:e.readFileSync??((t,n)=>co(t,n)),isOS:e.isOS??(t=>A(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Re(t)),readSigningKey:e.readSigningKey??(t=>Te(t))}}i(lo,"resolveDeps");function mo(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(mo,"readEmailFromMeta");function uo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(J)):[]}i(uo,"publicKeyEntries");function go(e){return e.slice(0,-J.length)}i(go,"kidFromPublicKeyFilename");async function fo(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=pt(t,`${e}${ct}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}i(fo,"resolveSource");async function Oe(e=$().keysDir,t={}){let n=lo(t),r=new Set,o=uo(e,n).flatMap(s=>{let a=go(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 fo(s,e,n),c=pt(e,`${s}${lt}`),l;try{l=mo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:pt(e,a),email:l}}))}i(Oe,"discoverLocalKeys");import{createReadStream as yo}from"fs";function Ue(e){let t=yo(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(Ue,"createWebStreamFromFile");import ho from"path";var Hn=".cognite-bundles";function jn(e,t){return`${e}-${t}.zip`}i(jn,"bundleFileName");function B(e,t,n){return ho.join(e,Hn,jn(t,n))}i(B,"bundlePath");import{existsSync as Ao,readFileSync as Do}from"fs";import{resolve as Io}from"path";import{array as Vn,boolean as So,check as ce,forward as le,literal as wo,maxLength as vo,minLength as Co,nonEmpty as W,object as Bn,optional as G,picklist as Eo,pipe as H,safeParse as ko,string as L,url as Gn}from"valibot";var dt=H(L(),W("must not be empty")),mt=H(L(),W("must not be empty"),vo(256,"must be 256 characters or fewer")),ut=H(L(),W("must not be empty"),Gn("must be a valid URL")),bo=H(L(),W("must not be empty"),Gn("must be a valid URL")),gt=H(L(),W("must not be empty")),ft=H(L(),W("must not be empty")),Po=H(Bn({org:gt,project:ft,baseUrl:ut,deployClientId:G(L(),""),deploySecretName:G(L(),""),published:G(So(),!1),idpType:G(Eo(["cdf","entra_id","oauth"]),"cdf"),tenantId:G(L()),scopes:G(Vn(H(L(),W("must not be empty")))),tokenUrl:G(bo)}),le(ce(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),le(ce(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),le(ce(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),le(ce(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),xo=Bn({name:dt,externalId:mt,versionTag:H(L(),W("must not be empty")),description:G(L(),""),deployments:H(Vn(Po),Co(1,"must contain at least one deployment")),infra:G(wo("appsApi"))});function yt(e){let t=ko(xo,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(yt,"validateAppConfig");function E(e,t={}){let{validator:n=yt,existsSync:r=Ao,readFileSync:o=Do}=t,s=Io(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 Yn=[".dev.sig",".cert.sig",".sig"];function Uo(e){return{existsSync:e.existsSync??$o,readFileSync:e.readFileSync??((t,n)=>Ro(t,n)),createBundleStream:e.createBundleStream??Ue,verifyBundle:e.verifyBundle??Fo,loadAppConfig:e.loadAppConfig??E,defaultKeyDir:e.defaultKeyDir??(()=>$().keysDir)}}i(Uo,"resolveDeps");function _o(e,t){return Yn.map(n=>`${e}${n}`).find(n=>t(n))}i(_o,"findSiblingSignature");function Ko(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}i(Ko,"isCompactJws");function Lo(e){try{let t=Oo(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}i(Lo,"readKidFromToken");function No(e,t,n){try{re(e)}catch(o){throw new u(o instanceof Error?o.message:String(o),{shouldReport:!1})}if(!n.existsSync(t))throw new u(`Key directory not found: ${t}`,{shouldReport:!1});let r=To(t,`${e}${J}`);if(!n.existsSync(r))throw new u(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return n.readFileSync(r,"utf-8")}catch(o){throw new u(`Failed to read public key file: ${r}`,{cause:o,shouldReport:!1})}}i(No,"resolvePublicKeyForKid");function Mo(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(Mo,"printResult");async function qn(e,t,n={},r=process.cwd()){let o=Uo(n),s;if(e)s=_e(r,e);else{let l;try{l=o.loadAppConfig(r)}catch(d){let m=d instanceof Error?d.message:String(d);throw new u(m,{cause:d,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}s=B(r,l.externalId,l.versionTag)}if(!o.existsSync(s)){let l=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new u(`Bundle not found: ${s}`,{hint:l,shouldReport:!1})}let a=t.sig?_e(r,t.sig):_o(s,o.existsSync);if(!a)throw new u("No signature file found.",{hint:`Pass --sig <path> or place one of ${Yn.map(l=>`${s}${l}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!o.existsSync(a))throw new u(`Signature file not found: ${a}`,{shouldReport:!1});let p;try{p=o.readFileSync(a,"utf-8").trim()}catch(l){throw new u(`Failed to read signature file: ${a}`,{cause:l,shouldReport:!1})}if(!Ko(p))throw new u(`Malformed JWS in ${a}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let c;if(t.key){let l=_e(r,t.key);if(!o.existsSync(l))throw new u(`Public key not found: ${l}`,{shouldReport:!1});try{c=o.readFileSync(l,"utf-8")}catch(d){throw new u(`Failed to read public key file: ${l}`,{cause:d,shouldReport:!1})}}else{let l=t.keyDir?_e(r,t.keyDir):o.defaultKeyDir(),d=Lo(p);if(!d)throw new u("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});c=No(d,l,o)}try{let l=await o.verifyBundle({token:p,publicKeyPem:c,bundleStream:o.createBundleStream(s)});Mo(l,t.verbose??!1)}catch(l){let d=l instanceof Error?l.message:String(l);throw new u(`Bundle rejected: ${d}`,{shouldReport:!1})}}i(qn,"handleVerify");function Jn(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",`
2
+ var ji=Object.defineProperty;var rn=e=>{throw TypeError(e)};var i=(e,t)=>ji(e,"name",{value:t,configurable:!0});var on=(e,t,n)=>t.has(e)||rn("Cannot "+n);var sn=(e,t,n)=>(on(e,t,"read from private field"),n?n.call(e):t.get(e)),an=(e,t,n)=>t.has(e)?rn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),pn=(e,t,n,r)=>(on(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as pl}from"fs";import{Command as cl}from"commander";var it=class it 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:Yi(t.cause)}}};i(it,"HintedError");var y=it;function ln(e){return e instanceof y}i(ln,"isHintedError");var cn="https://docs.cognite.com/cdf/access/",Bi="https://status.cognite.com";function Vi(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:cn};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:cn};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:Bi};default:return{}}}i(Vi,"defaultHintForStatus");var ot=class ot extends y{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=Vi(n),o=super.deriveDefaults(t);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(ot,"HintedHttpError");var te=ot;function dn(e){return e instanceof te}i(dn,"isHintedHttpError");function Gi(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(Gi,"hintForErrno");function Yi(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,o=Gi(r.code,r);if(o!==void 0)return o;t=r.cause}}i(Yi,"hintForCause");import{existsSync as _o,readFileSync as Lo}from"fs";import{join as Ko,resolve as Ke}from"path";import{verifyBundle as No}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as Mo}from"jose";import ct from"enquirer";import{email as qi,pipe as Ji,safeParse as zi,string as Wi}from"valibot";var Xi=Ji(Wi(),qi());function ae(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!zi(Xi,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}i(ae,"parseEmail");function pe(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(pe,"parseExpiryMonths");import{execFileSync as he}from"child_process";function Ae(e={}){let{execFileSync:t=he}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}i(Ae,"isGitInstalled");function De(e,t={}){let{execFileSync:n=he}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}i(De,"isInsideGitRepo");function mn(e,t={}){let{execFileSync:n=he}=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(mn,"gitInitAndCommit");function un(e={}){let{execFileSync:t=he}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(un,"gitUserName");function gn(e={}){let{execFileSync:t=he}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(gn,"gitUserEmail");import{inspect as Zi}from"util";var st="[REDACTED]",Se,Ie=class Ie{constructor(t){an(this,Se);pn(this,Se,t)}toString(){return st}toJSON(){return st}[Zi.custom](){return st}expose(){return sn(this,Se)}static from(t){return new Ie(t)}};Se=new WeakMap,i(Ie,"SensitiveString");var C=Ie;var $e=3,fn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",yn=`Key expiry in months (${1}-${12})`,hn="Email address for the registry entry",Sn=`Passphrase for the encrypted private key (min ${15} chars)`,wn="Confirm passphrase",vn=i(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Cn=i(e=>`Passphrases do not match (attempt ${e}/${$e}).
3
+ `,"passphraseMismatchMsg"),En=`Passphrase confirmation failed after ${$e} attempts`,bn=i(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),kn="How would you like to submit your key registration?",Pn="Open in browser",xn="Copy link to clipboard";async function Re(e){return ct.prompt(e)}i(Re,"defaultPrompt");function lt(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}i(lt,"parserAsValidator");var eo=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function re(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(!eo.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(re,"parseKid");async function An(e={}){let{prompt:t=Re}=e,{kid:n}=await t({type:"input",name:"kid",message:fn,validate:lt(re)});return re(n)}i(An,"promptKid");async function Dn(e={}){let{prompt:t=i(r=>ct.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:kn,choices:[{name:"browser",message:Pn},{name:"clipboard",message:xn}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}i(Dn,"promptZendeskAction");async function In(e={}){let{prompt:t=Re}=e,{months:n}=await t({type:"input",name:"months",message:yn,initial:String(6),validate:lt(r=>pe(r,"expiry"))});return pe(n,"expiry")}i(In,"promptExpiryMonths");async function $n(e={}){let{prompt:t=Re,gitUserEmail:n=gn}=e,{email:r}=await t({type:"input",name:"email",message:hn,initial:n(),validate:lt(o=>ae(o,"email"))});return ae(r,"email")}i($n,"promptEmail");async function Rn(e={}){let{prompt:t=Re,stderr:n=process.stderr}=e;for(let r=1;r<=$e;r+=1){let{passphrase:o}=await t({type:"password",name:"passphrase",message:Sn,validate:i(a=>a.length>=15?!0:vn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:wn});if(o===s)return C.from(o);n.write(Cn(r))}throw new Error(En)}i(Rn,"promptPassphrase");async function Tn(e,t={}){let{prompt:n=i(o=>ct.prompt(o),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:bn(e),initial:!1});return r}i(Tn,"promptConfirmOverwrite");import{existsSync as go,readdirSync as fo,readFileSync as yo}from"fs";import{join as mt}from"path";import{execFile as ro}from"child_process";import{promisify as io}from"util";import{execFileSync as Fn}from"child_process";import{platform as to}from"os";import no from"path";function U(e,t={}){let{platform:n=to}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}i(U,"isOS");function On(e,t={}){let{exec:n=Fn,log:r=console.log}=t,[o,s]=U("macos",t)?["open",[e]]:U("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(On,"openInBrowser");function Un(e,t={}){let{exec:n=Fn,log:r=console.log}=t,[o,s]=U("macos",t)?["open",["-R",e]]:U("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[no.dirname(e)]];try{n(o,s)}catch{r(`Could not open file manager \u2014 files are at:
5
+ ${e}`)}}i(Un,"revealInFileManager");var _n="cognite-flows",oo=io(ro),Ln=i((e,t)=>oo(e,t),"defaultExecFile"),so=-25300,ao=so&255;function po(e){if(!(e instanceof Error)||!("code"in e)||e.code!==ao)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}i(po,"isKeychainNotFoundError");async function Kn(e,t,n={}){let r=t.expose();if(!U("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:o=Ln}=n;await o("security",["add-generic-password","-a",e,"-s",_n,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}i(Kn,"storeKeyInKeychain");async function Fe(e,t={}){if(!U("macos",t))return null;let{execFile:n=Ln}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",_n,"-w"]);return C.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(po(r))return null;throw r}}i(Fe,"readKeyFromKeychain");var Mn="cognite-cli-signing",co="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.",lo="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.",Nn="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function mo(e){if(!(e instanceof Error))return Nn;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?co:t.includes("ambiguous")?lo:Nn}i(mo,"hintFor");function Hn(e,t,n){return new y(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:mo(n),shouldReport:!1})}i(Hn,"wrapKeyringError");async function jn(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(jn,"defaultCreateEntry");async function Bn(e,t,n={}){let{createEntry:r=jn}=n,o=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(Mn,e)).setPassword(o)}catch(s){throw Hn("store",e,s)}}i(Bn,"storeSigningKey");async function Oe(e,t={}){let{createEntry:n=jn}=t;try{let o=(await n(Mn,e)).getPassword();return o===null?null:C.from(Buffer.from(o,"base64").toString("utf-8"))}catch(r){throw Hn("read",e,r)}}i(Oe,"readSigningKey");import{homedir as uo}from"os";import{join as dt}from"path";function I(e={}){let{env:t=process.env,homedir:n=uo}=e,r=t.COGNITE_CLI_HOME?.trim()||dt(n(),".cognite-cli");return{home:r,keysDir:dt(r,"keys"),sessionFile:dt(r,"session.json")}}i(I,"getConfig");var z=".pub.pem",ut=".key.jwe",gt=".meta.json";function Ue(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(Ue,"formatLocalKeySource");function ho(e){return{existsSync:e.existsSync??go,readdirSync:e.readdirSync??fo,readFileSync:e.readFileSync??((t,n)=>yo(t,n)),isOS:e.isOS??(t=>U(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Fe(t)),readSigningKey:e.readSigningKey??(t=>Oe(t))}}i(ho,"resolveDeps");function So(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(So,"readEmailFromMeta");function wo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(z)):[]}i(wo,"publicKeyEntries");function vo(e){return e.slice(0,-z.length)}i(vo,"kidFromPublicKeyFilename");async function Co(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=mt(t,`${e}${ut}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}i(Co,"resolveSource");async function _e(e=I().keysDir,t={}){let n=ho(t),r=new Set,o=wo(e,n).flatMap(s=>{let a=vo(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 Co(s,e,n),c=mt(e,`${s}${gt}`),l;try{l=So(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:mt(e,a),email:l}}))}i(_e,"discoverLocalKeys");import{createReadStream as Eo}from"fs";function Le(e){let t=Eo(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(Le,"createWebStreamFromFile");import bo from"path";var Vn=".cognite-bundles";function Gn(e,t){return`${e}-${t}.zip`}i(Gn,"bundleFileName");function M(e,t,n){return bo.join(e,Vn,Gn(t,n))}i(M,"bundlePath");import{existsSync as Fo,readFileSync as Oo}from"fs";import{resolve as Uo}from"path";import{array as Yn,boolean as ko,check as ce,forward as le,literal as Po,maxLength as xo,minLength as Ao,nonEmpty as W,object as qn,optional as q,picklist as Do,pipe as V,safeParse as Io,string as H,url as Jn}from"valibot";var ft=V(H(),W("must not be empty")),yt=V(H(),W("must not be empty"),xo(256,"must be 256 characters or fewer")),ht=V(H(),W("must not be empty"),Jn("must be a valid URL")),$o=V(H(),W("must not be empty"),Jn("must be a valid URL")),St=V(H(),W("must not be empty")),wt=V(H(),W("must not be empty")),Ro=V(qn({org:St,project:wt,baseUrl:ht,deployClientId:q(H(),""),deploySecretName:q(H(),""),published:q(ko(),!1),idpType:q(Do(["cdf","entra_id","oauth"]),"cdf"),tenantId:q(H()),scopes:q(Yn(V(H(),W("must not be empty")))),tokenUrl:q($o)}),le(ce(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),le(ce(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),le(ce(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),le(ce(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),le(ce(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),To=qn({name:ft,externalId:yt,versionTag:V(H(),W("must not be empty")),description:q(H(),""),deployments:V(Yn(Ro),Ao(1,"must contain at least one deployment")),infra:q(Po("appsApi"))});function vt(e){let t=Io(To,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(vt,"validateAppConfig");function E(e,t={}){let{validator:n=vt,existsSync:r=Fo,readFileSync:o=Oo}=t,s=Uo(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 zn=[".dev.sig",".cert.sig",".sig"];function Ho(e){return{existsSync:e.existsSync??_o,readFileSync:e.readFileSync??((t,n)=>Lo(t,n)),createBundleStream:e.createBundleStream??Le,verifyBundle:e.verifyBundle??No,loadAppConfig:e.loadAppConfig??E,defaultKeyDir:e.defaultKeyDir??(()=>I().keysDir)}}i(Ho,"resolveDeps");function jo(e,t){return zn.map(n=>`${e}${n}`).find(n=>t(n))}i(jo,"findSiblingSignature");function Bo(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}i(Bo,"isCompactJws");function Vo(e){try{let t=Mo(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}i(Vo,"readKidFromToken");function Go(e,t,n){let{existsSync:r,readFileSync:o}=n;try{re(e)}catch(a){throw new y(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!r(t))throw new y(`Key directory not found: ${t}`,{shouldReport:!1});let s=Ko(t,`${e}${z}`);if(!r(s))throw new y(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return o(s,"utf-8")}catch(a){throw new y(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}i(Go,"resolvePublicKeyForKid");function Yo(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(Yo,"printResult");async function Wn(e,t,n={},r=process.cwd()){let{existsSync:o,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=Ho(n),d;if(e)d=Ke(r,e);else{let u;try{u=a(r)}catch(f){let S=f instanceof Error?f.message:String(f);throw new y(S,{cause:f,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=M(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 y(`Bundle not found: ${d}`,{hint:u,shouldReport:!1})}let m=t.sig?Ke(r,t.sig):jo(d,o);if(!m)throw new y("No signature file found.",{hint:`Pass --sig <path> or place one of ${zn.map(u=>`${d}${u}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!o(m))throw new y(`Signature file not found: ${m}`,{shouldReport:!1});let g;try{g=s(m,"utf-8").trim()}catch(u){throw new y(`Failed to read signature file: ${m}`,{cause:u,shouldReport:!1})}if(!Bo(g))throw new y(`Malformed JWS in ${m}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let h;if(t.key){let u=Ke(r,t.key);if(!o(u))throw new y(`Public key not found: ${u}`,{shouldReport:!1});try{h=s(u,"utf-8")}catch(f){throw new y(`Failed to read public key file: ${u}`,{cause:f,shouldReport:!1})}}else{let u=t.keyDir?Ke(r,t.keyDir):l(),f=Vo(g);if(!f)throw new y("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});h=Go(f,u,{existsSync:o,readFileSync:s})}try{let u=await c({token:g,publicKeyPem:h,bundleStream:p(d)});Yo(u,t.verbose??!1)}catch(u){let f=u instanceof Error?u.message:String(u);throw new y(`Bundle rejected: ${f}`,{shouldReport:!1})}}i(Wn,"handleVerify");function Xn(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
6
  Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
7
7
 
8
8
  Examples:
9
9
  cognite apps verify Verify default bundle (path from app.json)
10
10
  cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
11
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)=>qn(n,r,t))}i(Jn,"registerVerifyCommand");var Wn="https://docs.cognite.com/cdf/access/";function K(e){return e!==null&&typeof e=="object"}i(K,"isRecord");function ie(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(ie,"isHttpError");function Ho(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
- See: ${Wn}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
- See: ${Wn}`;default:return}}i(Ho,"httpStatusHint");function Y(e){let t=e instanceof Error?e:new Error(String(e));if(!ie(t))return null;let n=Ho(t.status);return n?Object.assign(new Error(`${t.message}
15
- ${n}`),{cause:t}):null}i(Y,"enrichedHttpError");function jo(e){if(!K(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(K(n)){let r=n.error;if(K(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}i(jo,"findMissingArray");function Vo(e,t){if(!ie(e)||e.status!==400)return!1;let n=jo(e);return n?n.some(r=>K(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}i(Vo,"isMissingExternalIdError");function Ke(e,t){return ie(e)&&e.status===404||Vo(e,t)}i(Ke,"isNotFoundError");var Xn=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Zn=["ACTIVE","PREVIEW"],ht=class ht extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};i(ht,"AppVersionNotFoundError");var j=ht,St=class St extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};i(St,"AppNotFoundError");var de=St;function Le(e,t){return e.includes(t)}i(Le,"includesValue");function Bo(e){return Le(Xn,e)}i(Bo,"isAppVersionLifecycleState");function Go(e){return Le(Zn,e)}i(Go,"isAppVersionAlias");function Yo(e){return typeof e.version=="string"&&Bo(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Go(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}i(Yo,"isAppVersion");function zn(e){if(!K(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Yo(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}i(zn,"parseAppVersion");function qo(e){if(!K(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(qo,"parseAppMetadata");var wt=class wt{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 Y(o)??o}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw Y(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return qo(r.data)}catch(r){throw Ke(r,[t])?new de(t):Y(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 u("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=w.from(l),m=`${this.client.getBaseUrl()}${c}`,f=new AbortController,h=setTimeout(()=>f.abort(),300*1e3),g;try{g=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:f.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new u("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 u(`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(h)}if(!g.ok){let y=await g.text(),S;try{S=JSON.parse(y)}catch{}let b=y;if(K(S)){let V=S.error;if(typeof V=="string")b=V;else if(K(V)){let I=V.message,k=V.code;b=typeof I=="string"?I:k!=null?`Unknown error (code: ${k})`:y}else{let I=S.message;b=typeof I=="string"?I:y}}let v=g.headers.get("x-request-id"),C=v?` | X-Request-ID: ${v}`:"",z=K(S)?S:y;throw new te(`Upload failed: ${g.status} \u2014 ${b}${C}`,{httpStatusCode:g.status,requestUrl:m,responseBody:z})}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 zn(a.data)}catch(a){throw Ke(a,[t,n])?new j(t,n):Y(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(!K(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 zn(s[0])}catch(o){if(Ke(o,[t]))return null;throw Y(o)??o}}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 Y(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 Y(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 zo(a.data)}catch(a){throw Y(a)??a}}};i(wt,"AppHostingApi");var Ne=wt,Jo=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Wo=["developer","certifier"];function zo(e){if(!K(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=Xo(n);return r?[r]:[]})}i(zo,"parseStoredSignatures");function Xo(e){if(!K(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Le(Wo,n)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!Le(Jo,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(Xo,"parseStoredSignature");function vt(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(vt,"diffAppMetadata");function Zo(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(Zo,"formatMetadataDriftError");var Ct=class Ct{constructor(t){this.api=new Ne(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(ie(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=vt(o,{name:n,description:r});if(s.length!==0)throw new u(Zo(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 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(`
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)=>Wn(n,r,t))}i(Xn,"registerVerifyCommand");var Zn="https://docs.cognite.com/cdf/access/";function K(e){return e!==null&&typeof e=="object"}i(K,"isRecord");function ie(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(ie,"isHttpError");function qo(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
13
+ See: ${Zn}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
14
+ See: ${Zn}`;default:return}}i(qo,"httpStatusHint");function G(e){let t=e instanceof Error?e:new Error(String(e));if(!ie(t))return null;let n=qo(t.status);return n?Object.assign(new Error(`${t.message}
15
+ ${n}`),{cause:t}):null}i(G,"enrichedHttpError");function Jo(e){if(!K(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(K(n)){let r=n.error;if(K(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}i(Jo,"findMissingArray");function zo(e,t){if(!ie(e)||e.status!==400)return!1;let n=Jo(e);return n?n.some(r=>K(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}i(zo,"isMissingExternalIdError");function Ne(e,t){return ie(e)&&e.status===404||zo(e,t)}i(Ne,"isNotFoundError");var er=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],tr=["ACTIVE","PREVIEW"],Ct=class Ct extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};i(Ct,"AppVersionNotFoundError");var j=Ct,Et=class Et extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};i(Et,"AppNotFoundError");var de=Et;function Me(e,t){return e.includes(t)}i(Me,"includesValue");function Wo(e){return Me(er,e)}i(Wo,"isAppVersionLifecycleState");function Xo(e){return Me(tr,e)}i(Xo,"isAppVersionAlias");function Zo(e){return typeof e.version=="string"&&Wo(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Xo(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}i(Zo,"isAppVersion");function Qn(e){if(!K(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Zo(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}i(Qn,"parseAppVersion");function Qo(e){if(!K(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(Qo,"parseAppMetadata");var bt=class bt{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 G(o)??o}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw G(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return Qo(r.data)}catch(r){throw Ne(r,[t])?new de(t):G(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 y("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=C.from(l),m=`${this.client.getBaseUrl()}${c}`,g=new AbortController,h=setTimeout(()=>g.abort(),300*1e3),u;try{u=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:g.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new y("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 y(`Failed to upload version to ${m}`,{cause:f,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(h)}if(!u.ok){let f=await u.text(),S;try{S=JSON.parse(f)}catch{}let b=f;if(K(S)){let L=S.error;if(typeof L=="string")b=L;else if(K(L)){let D=L.message,k=L.code;b=typeof D=="string"?D:k!=null?`Unknown error (code: ${k})`:f}else{let D=S.message;b=typeof D=="string"?D:f}}let w=u.headers.get("x-request-id"),v=w?` | X-Request-ID: ${w}`:"",Y=K(S)?S:f;throw new te(`Upload failed: ${u.status} \u2014 ${b}${v}`,{httpStatusCode:u.status,requestUrl:m,responseBody:Y})}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 Qn(a.data)}catch(a){throw Ne(a,[t,n])?new j(t,n):G(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(!K(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 Qn(s[0])}catch(o){if(Ne(o,[t]))return null;throw G(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 G(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 G(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 G(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 ns(a.data)}catch(a){throw G(a)??a}}};i(bt,"AppHostingApi");var He=bt,es=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],ts=["developer","certifier"];function ns(e){if(!K(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=rs(n);return r?[r]:[]})}i(ns,"parseStoredSignatures");function rs(e){if(!K(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Me(ts,n)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!Me(es,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(rs,"parseStoredSignature");function kt(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(kt,"diffAppMetadata");function is(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(is,"formatMetadataDriftError");var Pt=class Pt{constructor(t){this.api=new He(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(ie(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=kt(o,{name:n,description:r});if(s.length!==0)throw new y(is(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
17
  \u{1F680} Deploying application via App Hosting API...
18
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(Ct,"AppHostingClient");var P=Ct;import{CogniteClient as Os}from"@cognite/sdk";import{CogniteClient as ps}from"@cognite/sdk";function Qo(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}i(Qo,"exponentialBackoffWithJitter");function es(e){return new Promise(t=>setTimeout(t,e))}i(es,"sleep");async function Qn(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),o=t.delayInMsCalculator??Qo;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 es(p),s++}}i(Qn,"retryAsync");var ts="https://auth.cognite.com/oauth2/token",ns=i(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function er({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let o;try{o=await Qn(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new u(`Failed to fetch access token from ${t}`,{cause:p})}if(!o.ok){let p=await o.text();throw new te(`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 u(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!ns(a))throw new u(`No access token in ${e} authentication response`,{hint:r});return w.from(a.access_token)}i(er,"fetchOAuthToken");var rs=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"),is=i(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=rs()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return w.from(t)},"getSecretFromEnv"),os=i((e,t)=>{let n=t.expose();return er({idp:"CDF",tokenUrl:ts,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"),tr=i(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:o,missingTokenHint:s})=>er({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"),ss=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"),as=i((e,t,n,r,o)=>tr({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:o!==void 0?o:[ss(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Et=i(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return w.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=is(r);if(o==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return tr({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 as(n,l,s,a,p)}return os(n,l)},"getToken");async function he(e,t,n=process.env,r){let o=await Et(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new ps(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:i(async()=>o.expose(),"oidcTokenProvider")});return await a.authenticate(),a}i(he,"getSdk");import Es from"os";import ks from"path";import bs from"open";import{buildAuthorizationUrl as Ps,calculatePKCECodeChallenge as xs,discovery as As,None as Ds,randomPKCECodeVerifier as Is,randomState as $s}from"openid-client";import nr from"mixpanel";var cs="5c4d853e7c3b77b1eb4468d5329b278c",Se="cognite-cli",ls=2e3,rr={env:process.env,init:nr.init.bind(nr)},ds={track:i(()=>{},"track"),flush:i(async()=>{},"flush")};function kt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}i(kt,"isTelemetryDisabled");function ms(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(ms,"detectCiEnvironment");function us(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}i(us,"isDebug");function Me(e={}){let t=e.env??rr.env,n=e.init??rr.init,r=e.packageName,o=e.cliVersion,s=us(t),a=ms(t);if(kt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
20
- `),ds;let p,c=new Set;function l(){if(p)return p;try{return p=n(cs,{geolocate:!1,keepAlive:!1}),p}catch{return}}return i(l,"getClient"),{track(d,m={}){let f=l();if(!f)return;let h={...m,applicationId:Se,...r&&{packageName:r},...o&&{cliVersion:o},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(h)}
21
- `);let g=i(()=>{},"finish"),y=new Promise(S=>{g=S});c.add(y);try{f.track(d,h,g)}catch{g()}y.finally(()=>c.delete(y))},async flush(d=ls){if(c.size===0)return;let m,f=new Promise(h=>{m=setTimeout(h,d),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),f])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
22
- `)}}}i(Me,"createTelemetry");import fs from"https";import{authorizationCodeGrant as ys}from"openid-client";function ir(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}i(ir,"escapeHtml");function bt(e,t,n){let r=ir(t),o=ir(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
19
+ \u2705 Deployment successful!`)}};i(Pt,"AppHostingClient");var P=Pt;import{CogniteClient as Hs}from"@cognite/sdk";import{CogniteClient as gs}from"@cognite/sdk";function os(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}i(os,"exponentialBackoffWithJitter");function ss(e){return new Promise(t=>setTimeout(t,e))}i(ss,"sleep");async function nr(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),o=t.delayInMsCalculator??os;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 ss(p),s++}}i(nr,"retryAsync");var as="https://auth.cognite.com/oauth2/token",ps=i(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function rr({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let o;try{o=await nr(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new y(`Failed to fetch access token from ${t}`,{cause:p})}if(!o.ok){let p=await o.text();throw new te(`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 y(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!ps(a))throw new y(`No access token in ${e} authentication response`,{hint:r});return C.from(a.access_token)}i(rr,"fetchOAuthToken");var cs=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"),ls=i(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=cs()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return C.from(t)},"getSecretFromEnv"),ds=i((e,t)=>{let n=t.expose();return rr({idp:"CDF",tokenUrl:as,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"),ir=i(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:o,missingTokenHint:s})=>rr({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"),ms=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"),us=i((e,t,n,r,o)=>ir({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:o!==void 0?o:[ms(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),xt=i(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return C.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=ls(r);if(o==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return ir({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 us(n,l,s,a,p)}return ds(n,l)},"getToken");async function me(e,t,n=process.env,r){let o=await xt(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new gs(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:i(async()=>o.expose(),"oidcTokenProvider")});return await a.authenticate(),a}i(me,"getSdk");import Ds from"os";import Is from"path";import $s from"open";import{buildAuthorizationUrl as Rs,calculatePKCECodeChallenge as Ts,discovery as Fs,None as Os,randomPKCECodeVerifier as Us,randomState as _s}from"openid-client";import or from"mixpanel";var fs="5c4d853e7c3b77b1eb4468d5329b278c",we="cognite-cli",ys=2e3,sr={env:process.env,init:or.init.bind(or)},hs={track:i(()=>{},"track"),flush:i(async()=>{},"flush")};function At(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}i(At,"isTelemetryDisabled");function Ss(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(Ss,"detectCiEnvironment");function ws(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}i(ws,"isDebug");function je(e={}){let t=e.env??sr.env,n=e.init??sr.init,r=e.packageName,o=e.cliVersion,s=ws(t),a=Ss(t);if(At(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
20
+ `),hs;let p,c=new Set;function l(){if(p)return p;try{return p=n(fs,{geolocate:!1,keepAlive:!1}),p}catch{return}}return i(l,"getClient"),{track(d,m={}){let g=l();if(!g)return;let h={...m,applicationId:we,...r&&{packageName:r},...o&&{cliVersion:o},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(h)}
21
+ `);let u=i(()=>{},"finish"),f=new Promise(S=>{u=S});c.add(f);try{g.track(d,h,u)}catch{u()}f.finally(()=>c.delete(f))},async flush(d=ys){if(c.size===0)return;let m,g=new Promise(h=>{m=setTimeout(h,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(je,"createTelemetry");import Cs from"https";import{authorizationCodeGrant as Es}from"openid-client";function ar(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}i(ar,"escapeHtml");function Dt(e,t,n){let r=ar(t),o=ar(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
23
23
  <h1>${r}</h1><p>${o}</p><p>You can close this window.</p>${e==="success"?`<style>
24
24
  @keyframes checkmark {
25
25
  0% { transform: scale(0); }
@@ -28,34 +28,37 @@ Examples:
28
28
  }
29
29
  h1 { animation: checkmark 0.5s ease-out; }
30
30
  </style>`:""}
31
- </body></html>`}i(bt,"generateHtml");import gs from"net";function or(e,t){return new Promise(n=>{let r=new gs.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(or,"isHostPortFree");function He(e,t={}){return A("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(He,"freePortHint");async function sr(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([or(e,"127.0.0.1"),or(e,"::1")])).every(Boolean)}i(sr,"isPortFree");async function hs(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"}),t.end(bt("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"}),t.end(bt("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}i(hs,"handleCallback");function Ss(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}i(Ss,"formatTimeoutMinutes");function ar(e,t,n,r,o,s={createServer:fs.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:ys}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,f)=>{try{let h=await hs(m,f,n,r,o,s);h.shouldClose&&(d(),h.error?p(h.error):h.tokens?a(h.tokens):p(new Error("No tokens received")))}catch(h){d(),p(h instanceof Error?h:new Error(String(h)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Ss(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}i(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new u(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:He(e.port)})):p(new u(`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(ar,"startCallbackServer");import{mkdirSync as ws}from"fs";import{loadLocalCertificates as vs}from"@cognite/app-sdk/https";var Cs={loadLocalCertificates:vs,mkdirSync:ws,logger:console};async function pr(e,t=Cs){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:o}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new u(`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(pr,"getOrCreateCertificates");var Rs={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:ks.join(Es.homedir(),".cdf-login")},Ts={open:bs,getOrCreateCertificates:pr,startCallbackServer:ar,isPortFree:sr,discovery:As,buildAuthorizationUrl:Ps,randomPKCECodeVerifier:Is,calculatePKCECodeChallenge:xs,randomState:$s,logger:console,telemetry:Me()};async function lr(e,t=Rs,n){return n===void 0?cr(e,t,Ts):cr(e,t,n)}i(lr,"login");async function Fs(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,Ds())}catch(n){throw new u(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:n})}}i(Fs,"fetchOpenIdConfig");async function cr(e,t,n){if(!await n.isPortFree(t.port))throw n.telemetry?.track("Flows.CLI.PortInUse",{port:t.port}),new u(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:He(t.port)});n.logger.log(`\u{1F510} Starting CDF login flow...
32
- `),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let o=await Fs(n,t),s=n.randomPKCECodeVerifier(),a=await n.calculatePKCECodeChallenge(s),p=n.randomState(),c={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:a,code_challenge_method:"S256",state:p};e&&(c.organization_hint=e);let l=n.buildAuthorizationUrl(o,c).toString(),d=await n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
33
- `);try{await n.open(l)}catch(m){let f=m instanceof Error?m.message:String(m);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${f}`),n.logger.error(`Please open this URL manually:
34
- `),n.logger.error(l),n.logger.error("")}return n.startCallbackServer(t,d,o,s,p)}i(cr,"loginImpl");async function R(e,t,n={}){let{login:r=lr,getSdk:o=he,createClient:s=i(a=>new Os(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=w.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(R,"getClientForDeployment");import dr from"enquirer";var mr="Enter custom target...";function ur(e,t){let n=t.map((r,o)=>` ${o}: ${r.org}/${r.project}`).join(`
31
+ </body></html>`}i(Dt,"generateHtml");import vs from"net";function pr(e,t){return new Promise(n=>{let r=new vs.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(pr,"isHostPortFree");function Be(e,t={}){return U("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(Be,"freePortHint");async function cr(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([pr(e,"127.0.0.1"),pr(e,"::1")])).every(Boolean)}i(cr,"isPortFree");async function bs(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"}),t.end(Dt("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"}),t.end(Dt("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}i(bs,"handleCallback");function ks(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}i(ks,"formatTimeoutMinutes");function lr(e,t,n,r,o,s={createServer:Cs.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Es}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,g)=>{try{let h=await bs(m,g,n,r,o,s);h.shouldClose&&(d(),h.error?p(h.error):h.tokens?a(h.tokens):p(new Error("No tokens received")))}catch(h){d(),p(h instanceof Error?h:new Error(String(h)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${ks(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}i(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new y(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:Be(e.port)})):p(new y(`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(lr,"startCallbackServer");import{mkdirSync as Ps}from"fs";import{loadLocalCertificates as xs}from"@cognite/app-sdk/https";var As={loadLocalCertificates:xs,mkdirSync:Ps,logger:console};async function dr(e,t=As){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:o}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new y(`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(dr,"getOrCreateCertificates");var Ls="openid profile email",Ks={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Is.join(Ds.homedir(),".cdf-login")},Ns={open:$s,getOrCreateCertificates:dr,startCallbackServer:lr,isPortFree:cr,discovery:Fs,buildAuthorizationUrl:Rs,randomPKCECodeVerifier:Us,calculatePKCECodeChallenge:Ts,randomState:_s,logger:console,telemetry:je()};async function ur(e,t=Ks,n){return n===void 0?mr(e,t,Ns):mr(e,t,n)}i(ur,"login");async function Ms(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,Os())}catch(r){throw new y(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}i(Ms,"fetchOpenIdConfig");async function mr(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 y(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:Be(t.port)});s.log(`\u{1F510} Starting CDF login flow...
32
+ `),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let u=await Ms(n,t),f=a(),S=await p(f),b=c(),w={redirect_uri:t.redirectUri,scope:t.scope??Ls,code_challenge:S,code_challenge_method:"S256",state:b};e&&(w.organization_hint=e);let v=l(u,w).toString(),Y=await d(t.certDir);e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
33
+ `);try{await m(v)}catch(L){let D=L instanceof Error?L.message:String(L);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${D}`),s.error(`Please open this URL manually:
34
+ `),s.error(v),s.error("")}return g(t,Y,u,f,b)}i(mr,"loginImpl");async function N(e,t,n={}){let{login:r=ur,getSdk:o=me,createClient:s=i(a=>new Hs(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=C.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,"getClientForDeployment");async function Ve(e,t,n){let r=await N(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new P(r)}i(Ve,"buildAppHostingClient");import gr from"enquirer";var fr="Enter custom target...";function yr(e,t){let n=t.map((r,o)=>` ${o}: ${r.org}/${r.project}`).join(`
35
35
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
36
- ${n}`)}i(ur,"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;ur(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;ur(t,e)}i(D,"findDeployment");function T(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}i(T,"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 D(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),mr],{selected:r}=await dr.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==mr){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 dr.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(F,"resolveDeployment");import{existsSync as Us}from"fs";import{resolve as _s}from"path";import{config as Ks}from"dotenv";function O(e,t={existsSync:Us,config:Ks}){let n=_s(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}i(O,"loadEnvFile");function U(e){e.infra!=="appsApi"&&(console.error(`
36
+ ${n}`)}i(yr,"deploymentNotFoundError");function x(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;yr(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;yr(t,e)}i(x,"findDeployment");function $(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}i($,"getMissingCredentials");async function R(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 x(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),fr],{selected:r}=await gr.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==fr){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 gr.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(R,"resolveDeployment");import{existsSync as js}from"fs";import{resolve as Bs}from"path";import{config as Vs}from"dotenv";function T(e,t={existsSync:js,config:Vs}){let n=Bs(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}i(T,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
37
37
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
38
38
 
39
39
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
40
40
  the old CDF Application Registry. This deploy path has been removed.
41
41
 
42
42
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
43
- `),process.exit(1))}i(U,"assertAppHostingInfra");async function Ls(e){let t=process.cwd();O(t);let n=E(t);U(n);let r=e.interactive?await F(n,e):D(n.deployments,e.deployment);if(!e.interactive){let d=T(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 R(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(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(Ls,"handleActivate");function gr(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",`
43
+ `),process.exit(1))}i(F,"assertAppHostingInfra");async function Gs(e){let t=process.cwd();T(t);let n=E(t);F(n);let r=e.interactive?await R(n,e):x(n.deployments,e.deployment);if(!e.interactive){let d=$(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 P(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(Gs,"handleActivate");function hr(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
44
  Examples:
45
45
  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)=>Ls(n))}i(gr,"registerActivateCommand");import{basename as Dr,dirname as wa,normalize as va,resolve as Ye}from"path";import{fileURLToPath as Ca,pathToFileURL as Ea}from"url";import{Logger as ka,runner as ba}from"hygen";import{safeParse as Ns}from"valibot";function we(e,t){return n=>{let r=Ns(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}i(we,"toPromptValidator");var fr={name:we("App name",mt),displayName:we("Display name",dt),baseUrl:we("Base URL",ut),org:we("Org",gt),project:we("Project",ft)};function Ms(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}i(Ms,"composeValidators");function je(e){return e.map(t=>{if(!(t.name in fr))return t;let n=fr[t.name];return{...t,validate:Ms(t.validate,n)}})}i(je,"applySchemaValidators");import{basename as yr}from"path";import hr from"enquirer";function Pt(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}i(Pt,"kebabCase");var Hs={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 or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
47
- `),initial:!1};async function js(e,t,n){return e!==void 0?e:t?!!(await n([Hs])).useSpecKit:!1}i(js,"resolveSpecKit");function Vs(e){return typeof e=="function"}i(Vs,"isFunctionInitial");function Sr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}i(Sr,"normalizeCluster");function wr({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:o={},specKit:s,prompt:a=hr.prompt.bind(hr)}){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?yr(process.cwd()):t?yr(t):null,m=l&&d!==null,f=!m&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,h=je(f),g=m&&d?{...c,name:d}:c,y=new Set(Object.keys(g)),S=h.filter(k=>!y.has(k.name)),b=S.findIndex(k=>k.name==="baseUrl"),v;if(m){let k=Sr(g.cluster),X=i(x=>Vs(x.initial)?x.initial():x.initial,"resolveInitial"),Z=i(x=>{if(x.name==="baseUrl")return`https://${k}.cognitedata.com`;let Q=X(x);if(Q===void 0)throw new Error(`Non-interactive mode: --${Pt(x.name)} has no default. Pass it as a flag.`);return Q},"deriveValue");v=Object.fromEntries(S.map(x=>[x.name,Z(x)]))}else if(b!==-1){let k=S.filter(ee=>ee.name!=="baseUrl"),X=k.length>0?await a(k):{},Z=typeof X.cluster=="string"?X.cluster:"",Q=`https://${Sr(Z||g.cluster)}.cognitedata.com`,se=S[b],be=await a([{...se,initial:Q}]);v={...X,...be}}else v=S.length>0?await a(S):{};let C={...g,...v},z=typeof C.name=="string"?C.name:"";z&&n(z);let I=await js(s,!m&&S.length>0,a);return r?.(I),{...C,name:z,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:I}},"prompt")})}i(wr,"createAppPrompter");async function vr(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:`--${Pt(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(vr,"validatePresets");import{cpSync as xt,existsSync as Ws,mkdirSync as At,writeFileSync as zs}from"fs";import{dirname as Be,posix as Xs,resolve as N}from"path";import{fileURLToPath as Er}from"url";import{copyFileSync as Bs,symlinkSync as Gs}from"fs";import{dirname as Ys,join as qs}from"path";function Js(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}i(Js,"errno");function Cr(e){return e instanceof Error?e.message:String(e)}i(Cr,"messageOf");function Ve({target:e,linkPath:t,label:n,symlink:r=Gs,copyFile:o=Bs}){try{return r(e,t),!0}catch(s){let a=Js(s);if(a==="EEXIST")return!0;let p=Cr(s);if(a==="EPERM"||a==="EACCES")try{let c=qs(Ys(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: ${Cr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}i(Ve,"linkOrCopyOrWarn");var Zs=N(Be(Er(import.meta.url)),"..","..","_vendor","spec-kit"),Qs=N(Be(Er(import.meta.url)),"..","..","_cognite-spec-extensions"),ea={branch_numbering:"sequential"},ta=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],na=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function kr({appDir:e,vendorDir:t=Zs,cogniteExtensionsDir:n=Qs}){let r=N(e,".specify"),o=N(r,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of ta){let l=N(e,c);s=`copy ${p} to ${c}`,At(Be(l),{recursive:!0}),xt(N(t,p),l,{recursive:!0})}for(let{from:p,to:c}of na){let l=N(e,c);s=`copy cognite extension ${p} to ${c}`,At(Be(l),{recursive:!0}),xt(N(n,p),l,{recursive:!0})}let a=N(r,"extensions.yml");Ws(a)||(s="write .specify/extensions.yml",xt(N(n,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${r}`,zs(N(r,"init-options.json"),`${JSON.stringify(ea,null,2)}
48
- `),s=`link .specify/memory/constitution.md in specifyDir=${r}`,At(o,{recursive:!0}),Ve({target:Xs.join("..","..","AGENTS.md"),linkPath:N(o,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}i(kr,"installSpecKit");import{execFileSync as Ge}from"child_process";import{mkdtempSync as ra,readdirSync as ia,rmSync as oa}from"fs";import{createRequire as sa}from"module";import{tmpdir as aa}from"os";import{join as pa,resolve as br}from"path";import{InvalidArgumentError as ca}from"commander";import la from"enquirer";var Pr="cognitedata/builder-skills",Dt=["claude-code","cursor","github-copilot","opencode","codex"],da=sa(import.meta.url).resolve("skills/bin/cli.mjs");function It(e,t={}){try{Ge(process.execPath,[da,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw new u(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and that git is installed, then try again."})}}i(It,"execSkillsCli");function ma(){return Dt.map(e=>["add",Pr,"-a",e,"--skill","*","-y"])}i(ma,"pullAllArgsPerAgent");var ua=1e4;async function xr(e,t={}){let n=t.exec??It,r=t.timeout??ua,o=t.readdir??(p=>ia(p));for(let p of ma())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[br(e,".claude","skills"),br(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(xr,"pullAllSkillsInto");function ga(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new ca("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}i(ga,"validateSource");function fa(e){let t=ra(pa(aa(),"skills-"));try{try{Ge("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let n;try{n=Ge("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Ge("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{oa(t,{recursive:!0,force:!0})}}i(fa,"listRemoteSkills");async function ya(e,t={}){let n=i(p=>la.prompt(p),"defaultPrompt"),{listSkills:r=fa,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(ya,"pickSkillsInteractive");function ha(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(ha,"buildPullArgs");async function Sa(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await ya(e.source)}catch(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 Dt)try{It(ha(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(`
46
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Gs(n))}i(hr,"registerActivateCommand");import{basename as Fr,dirname as xa,normalize as Aa,resolve as ze}from"path";import{fileURLToPath as Da,pathToFileURL as Ia}from"url";import{Logger as $a,runner as Ra}from"hygen";import{safeParse as Ys}from"valibot";function ve(e,t){return n=>{let r=Ys(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}i(ve,"toPromptValidator");var Sr={name:ve("App name",yt),displayName:ve("Display name",ft),baseUrl:ve("Base URL",ht),org:ve("Org",St),project:ve("Project",wt)};function qs(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}i(qs,"composeValidators");function Ge(e){return e.map(t=>{if(!(t.name in Sr))return t;let n=Sr[t.name];return{...t,validate:qs(t.validate,n)}})}i(Ge,"applySchemaValidators");import{basename as wr}from"path";import vr from"enquirer";function It(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}i(It,"kebabCase");var Js={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 zs(e,t,n){return e!==void 0?e:t?!!(await n([Js])).useSpecKit:!1}i(zs,"resolveSpecKit");function Ws(e){return typeof e=="function"}i(Ws,"isFunctionInitial");function Cr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}i(Cr,"normalizeCluster");function Er({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:o={},specKit:s,prompt:a=vr.prompt.bind(vr)}){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?wr(process.cwd()):t?wr(t):null,m=l&&d!==null,g=!m&&d?p.map(k=>k.name==="name"?{...k,initial:d}:k):p,h=Ge(g),u=m&&d?{...c,name:d}:c,f=new Set(Object.keys(u)),S=h.filter(k=>!f.has(k.name)),b=S.findIndex(k=>k.name==="baseUrl"),w;if(m){let k=Cr(u.cluster),X=i(O=>Ws(O.initial)?O.initial():O.initial,"resolveInitial"),Z=i(O=>{if(O.name==="baseUrl")return`https://${k}.cognitedata.com`;let Q=X(O);if(Q===void 0)throw new Error(`Non-interactive mode: --${It(O.name)} has no default. Pass it as a flag.`);return Q},"deriveValue");w=Object.fromEntries(S.map(O=>[O.name,Z(O)]))}else if(b!==-1){let k=S.filter(ee=>ee.name!=="baseUrl"),X=k.length>0?await a(k):{},Z=typeof X.cluster=="string"?X.cluster:"",Q=`https://${Cr(Z||u.cluster)}.cognitedata.com`,se=S[b],xe=await a([{...se,initial:Q}]);w={...X,...xe}}else w=S.length>0?await a(S):{};let v={...u,...w},Y=typeof v.name=="string"?v.name:"";Y&&n(Y);let D=await zs(s,!m&&S.length>0,a);return r?.(D),{...v,name:Y,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:D}},"prompt")})}i(Er,"createAppPrompter");async function br(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:`--${It(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(br,"validatePresets");import{cpSync as Pr,existsSync as xr,mkdirSync as qe,readdirSync as na,readFileSync as ra,writeFileSync as $t}from"fs";import{basename as ia,dirname as Rt,posix as oa,resolve as A}from"path";import{fileURLToPath as Ar}from"url";import{copyFileSync as Xs,symlinkSync as Zs}from"fs";import{dirname as Qs,join as ea}from"path";function ta(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}i(ta,"errno");function kr(e){return e instanceof Error?e.message:String(e)}i(kr,"messageOf");function Ye({target:e,linkPath:t,label:n,symlink:r=Zs,copyFile:o=Xs}){try{return r(e,t),!0}catch(s){let a=ta(s);if(a==="EEXIST")return!0;let p=kr(s);if(a==="EPERM"||a==="EACCES")try{let c=ea(Qs(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: ${kr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}i(Ye,"linkOrCopyOrWarn");var sa=A(Rt(Ar(import.meta.url)),"..","..","_vendor","spec-kit"),aa=A(Rt(Ar(import.meta.url)),"..","..","_cognite-spec-extensions"),pa=["claude-code","cursor","github-copilot"],ca={branch_numbering:"sequential"};function Dr({appDir:e,vendorDir:t=sa,cogniteExtensionsDir:n=aa,agents:r=pa}){let o=A(e,".specify"),s=A(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:h}of l){let u=A(e,h);p=`copy ${ia(m)}/${g} to ${h}`,qe(Rt(u),{recursive:!0}),Pr(A(m,g),u,{recursive:!0})}if(a.has("github-copilot")){let m=A(e,".github","agents"),g=A(e,".github","prompts");p="create .github/agents and .github/prompts dirs",qe(m,{recursive:!0}),qe(g,{recursive:!0});for(let h of[A(t,"commands"),A(n,"commands")])if(xr(h))for(let u of na(h)){if(!u.endsWith(".md"))continue;let f=u.slice(0,-3);p=`copy ${u} to .github/agents/${f}.agent.md`,$t(A(m,`${f}.agent.md`),ra(A(h,u))),p=`write .github/prompts/${f}.prompt.md`,$t(A(g,`${f}.prompt.md`),`---
48
+ agent: ${f}
49
+ ---
50
+ `)}}let d=A(o,"extensions.yml");xr(d)||(p="write .specify/extensions.yml",Pr(A(n,"extensions.yml"),d)),p=`write init-options.json under specifyDir=${o}`,$t(A(o,"init-options.json"),`${JSON.stringify(ca,null,2)}
51
+ `),p=`link .specify/memory/constitution.md in specifyDir=${o}`,qe(s,{recursive:!0}),Ye({target:oa.join("..","..","AGENTS.md"),linkPath:A(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(Dr,"installSpecKit");import{execFileSync as Je}from"child_process";import{mkdtempSync as la,readdirSync as da,rmSync as ma}from"fs";import{createRequire as ua}from"module";import{tmpdir as ga}from"os";import{join as fa,resolve as Ir}from"path";import{InvalidArgumentError as ya}from"commander";import ha from"enquirer";var $r="cognitedata/builder-skills",Tt=["claude-code","cursor","github-copilot","opencode","codex"],Sa=ua(import.meta.url).resolve("skills/bin/cli.mjs");function Ft(e,t={}){try{Je(process.execPath,[Sa,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw new y(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and that git is installed, then try again."})}}i(Ft,"execSkillsCli");function wa(){return Tt.map(e=>["add",$r,"-a",e,"--skill","*","-y"])}i(wa,"pullAllArgsPerAgent");var va=1e4;async function Rr(e,t={}){let n=t.exec??Ft,r=t.timeout??va,o=t.readdir??(p=>da(p));for(let p of wa())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[Ir(e,".claude","skills"),Ir(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(Rr,"pullAllSkillsInto");function Ca(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new ya("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}i(Ca,"validateSource");function Ea(e){let t=la(fa(ga(),"skills-"));try{try{Je("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let n;try{n=Je("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Je("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{ma(t,{recursive:!0,force:!0})}}i(Ea,"listRemoteSkills");async function ba(e,t={}){let n=i(p=>ha.prompt(p),"defaultPrompt"),{listSkills:r=Ea,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(ba,"pickSkillsInteractive");function ka(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(ka,"buildPullArgs");async function Pa(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await ba(e.source)}catch(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 Tt)try{Ft(ka(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(`
49
52
  Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
50
- Skills pulled successfully`)}i(Sa,"handlePull");function Ar(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
51
- Supports: ${Dt.join(", ")}`).addHelpText("after",`
53
+ Skills pulled successfully`)}i(Pa,"handlePull");function Tr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
54
+ Supports: ${Tt.join(", ")}`).addHelpText("after",`
52
55
  Examples:
53
56
  npx @cognite/cli apps skills pull Pull all skills
54
57
  npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
55
- 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",ga,Pr).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(Sa),t.command("list").description("List installed skills").action(()=>{It(["list"])}),t}i(Ar,"registerSkillsCommand");var Ir=Ye(wa(Ca(import.meta.url)),"..","..","_templates");async function Pa(){let e=Ye(Ir,"app","new","prompt.js");return(await import(Ea(e).href)).default}i(Pa,"loadPromptDefs");function xa(e,t){return!e||t?null:va(e)}i(xa,"resolveDirName");function Aa(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:Ye(process.cwd(),r),display:r}}i(Aa,"resolveAppLocation");function Da(e,t,n){let r=` npm install
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",Ca,$r).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(Pa),t.command("list").description("List installed skills").action(()=>{Ft(["list"])}),t}i(Tr,"registerSkillsCommand");var Or=ze(xa(Da(import.meta.url)),"..","..","_templates");async function Ta(){let e=ze(Or,"app","new","prompt.js");return(await import(Ia(e).href)).default}i(Ta,"loadPromptDefs");function Fa(e,t){return!e||t?null:Aa(e)}i(Fa,"resolveDirName");function Oa(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:ze(process.cwd(),r),display:r}}i(Oa,"resolveAppLocation");function Ua(e,t,n){let r=` npm install
56
59
  npm run dev`,o="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
57
60
  To start spec-driven development:
58
- Run /speckit.specify in Claude Code or Cursor and describe your app.
61
+ Run /speckit.specify in Claude Code, Cursor, or GitHub Copilot and describe your app.
59
62
  `:"",p=` # Or fully non-interactive (deploys first target from app.json):
60
63
  npx @cognite/cli apps deploy`;if(e){console.log(`
61
64
  \u2705 App created successfully in current directory!
@@ -79,7 +82,7 @@ ${o}
79
82
  cd "${t}"
80
83
  ${s}
81
84
  ${p}
82
- `)}i(Da,"printSuccessMessage");async function Ia(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await xr(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}i(Ia,"pullSkillsInto");function $a(e,t={}){let{isGitInstalled:n=Pe,isInsideGitRepo:r=xe,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($a,"maybeInitGit");async function Ra(e,t){let n=e==="."||e==="./",r=xa(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 Pa(),c=je(p),l=n?Dr(process.cwd()):r?Dr(r):null;await vr(c,a,l);let d=wr({isCurrentDir:n,dirName:r,onAppName:i(f=>{o=f},"onAppName"),onUseSpecKit:i(f=>{s=f},"onUseSpecKit"),presets:a,specKit:t.specKit});await ba(["app","new"],{templates:Ir,cwd:process.cwd(),logger:new ka(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Aa(n,r,o);Ve({target:"AGENTS.md",linkPath:Ye(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&kr({appDir:m.cwd}),await Ia(m.cwd),$a(m.cwd),Da(n,m.display,s)}i(Ra,"handleCreate");function $r(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",`
85
+ `)}i(Ua,"printSuccessMessage");async function _a(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await Rr(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}i(_a,"pullSkillsInto");function La(e,t={}){let{isGitInstalled:n=Ae,isInsideGitRepo:r=De,gitInitAndCommit:o=mn}=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(La,"maybeInitGit");async function Ka(e,t){let n=e==="."||e==="./",r=Fa(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 Ta(),c=Ge(p),l=n?Fr(process.cwd()):r?Fr(r):null;await br(c,a,l);let d=Er({isCurrentDir:n,dirName:r,onAppName:i(g=>{o=g},"onAppName"),onUseSpecKit:i(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await Ra(["app","new"],{templates:Or,cwd:process.cwd(),logger:new $a(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Oa(n,r,o);Ye({target:"AGENTS.md",linkPath:ze(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&Dr({appDir:m.cwd}),await _a(m.cwd),La(m.cwd),Ua(n,m.display,s)}i(Ka,"handleCreate");function Ur(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",`
83
86
  Non-interactive use (CI, scripts, AI agents):
84
87
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
85
88
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -92,22 +95,27 @@ Examples:
92
95
  --display-name "My App" --description "My app" \\
93
96
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
94
97
  --base-url https://greenfield.cognitedata.com
95
- Fully non-interactive`).action(Ra)}i($r,"registerCreateCommand");import Ta from"path";async function Fa(e,t,n){let r=await R(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new P(r)}i(Fa,"defaultGetApiClient");async function Oa(e,t,n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,getApiClient:s=Fa}=n,a=Ta.resolve(process.cwd(),e);r(a);let p=o(a);U(p);let c=t.interactive?await F(p,t):D(p.deployments,t.deployment);if(!t.interactive){let f=T(c);if(f.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${f.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(Oa,"handleDeactivate");function Rr(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",`
98
+ Fully non-interactive`).action(Ka)}i(Ur,"registerCreateCommand");import Na from"path";async function Ma(e,t,n={}){let{loadEnvFile:r=T,loadAppConfig:o=E,getApiClient:s=Ve}=n,a=Na.resolve(process.cwd(),e);r(a);let p=o(a);F(p);let c=t.interactive?await R(p,t):x(p.deployments,t.deployment);if(!t.interactive){let g=$(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(Ma,"handleDeactivate");function _r(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",`
96
99
  Examples:
97
100
  npx @cognite/cli apps deactivate . Deactivate using env-var auth
98
- npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Oa(t,n))}i(Rr,"registerDeactivateCommand");import{mkdir as Ma,readFile as Ha}from"fs/promises";import{basename as ja,dirname as Va}from"path";import{execFileSync as qe}from"child_process";import q from"fs";import _ from"path";import{parseAndValidateManifestConfig as Ua}from"@cognite/app-sdk/vite";import{BlobReader as _a,Uint8ArrayWriter as Ka,ZipWriter as La}from"@zip.js/zip.js";var $t="package.json",Rt="package-lock.json",Tr="manifest.json",Tt=".cognite",Na=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Ft=class Ft{constructor(t="dist"){this.distPath=_.isAbsolute(t)?t:_.join(process.cwd(),t),this.appRoot=_.dirname(this.distPath)}validateBuildDirectory(){if(!q.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=_.join(this.appRoot,$t);if(!q.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=_.join(this.appRoot,Rt);if(!q.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 La(new Ka,{level:9}),o=i(async(c,l)=>{await r.add(l,new _a(await q.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=i(async c=>{let l=await q.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=_.join(c,d.name);d.isDirectory()?await s(m):await o(m,_.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=_.join(this.appRoot,$t);await o(c,_.posix.join(Tt,$t));let l=_.join(this.appRoot,Tr);if(q.existsSync(l)){let m=q.readFileSync(l,"utf-8");Ua(m,l),await o(l,_.posix.join(Tt,Tr))}let d=_.join(this.appRoot,Rt);await o(d,_.posix.join(Tt,Rt)),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 q.promises.writeFile(t,a)}catch(c){throw new u(`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=qe("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=qe("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{qe("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=(q.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${_.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=qe("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
99
- `).filter(Boolean),o=i(a=>a.split("/").some(p=>Na.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:
101
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Ma(t,n))}i(_r,"registerDeactivateCommand");import Ha from"path";import ja from"enquirer";async function Ba(e){let{confirmed:t}=await ja.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(Ba,"defaultConfirm");async function Va(e,t,n={}){let{loadEnvFile:r=T,loadAppConfig:o=E,getApiClient:s=Ve,confirm:a=Ba}=n,p=Ha.resolve(process.cwd(),e);r(p);let c=o(p);F(c);let l=t.interactive?await R(c,t):x(c.deployments,t.deployment);if(!t.interactive){let u=$(l);if(u.length>0)throw new y(`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,h;try{h=await d.getVersion(m,g)}catch(u){throw u instanceof j?new y(`Version ${g} of ${m} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):u}if(h.alias==="ACTIVE")throw new y(`Cannot archive ${m} @ ${g}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(h.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(h.lifecycleState==="DRAFT"){await d.deleteVersion(m,g),console.log(`\u2713 Deleted ${m} @ ${g} (DRAFT removed)`);return}h.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(Va,"handleDelete");function Lr(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
+ Examples:
104
+ npx @cognite/cli apps delete . Archive using env-var auth
105
+ 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)=>Va(t,n))}i(Lr,"registerDeleteCommand");import{existsSync as ip}from"fs";import op from"enquirer";import{existsSync as Za}from"fs";import{mkdir as Qa,readFile as ep}from"fs/promises";import{basename as tp,dirname as np}from"path";import{execFileSync as We}from"child_process";import J from"fs";import _ from"path";import{parseAndValidateManifestConfig as Ga}from"@cognite/app-sdk/vite";import{BlobReader as Ya,Uint8ArrayWriter as qa,ZipWriter as Ja}from"@zip.js/zip.js";var Ot="package.json",Ut="package-lock.json",Kr="manifest.json",_t=".cognite",za=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Lt=class Lt{constructor(t="dist"){this.distPath=_.isAbsolute(t)?t:_.join(process.cwd(),t),this.appRoot=_.dirname(this.distPath)}validateBuildDirectory(){if(!J.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=_.join(this.appRoot,Ot);if(!J.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=_.join(this.appRoot,Ut);if(!J.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 Ja(new qa,{level:9}),o=i(async(c,l)=>{await r.add(l,new Ya(await J.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=i(async c=>{let l=await J.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=_.join(c,d.name);d.isDirectory()?await s(m):await o(m,_.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=_.join(this.appRoot,Ot);await o(c,_.posix.join(_t,Ot));let l=_.join(this.appRoot,Kr);if(J.existsSync(l)){let m=J.readFileSync(l,"utf-8");Ga(m,l),await o(l,_.posix.join(_t,Kr))}let d=_.join(this.appRoot,Ut);await o(d,_.posix.join(_t,Ut)),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 J.promises.writeFile(t,a)}catch(c){throw new y(`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=We("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=We("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{We("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=(J.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${_.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=We("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=>za.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:
100
108
  `+s.map(a=>` ${a}`).join(`
101
109
  `)+`
102
- Hint: git rm --cached <file>`)}};i(Ft,"ApplicationPackager");var oe=Ft;async function Je(e,t,n,r){let{externalId:o,name:s,description:a,versionTag:p}=t,c=B(n,o,p);await Ma(Va(c),{recursive:!0}),await new oe(`${n}/dist`).createZip(c,!0);let l;try{l=await Ha(c)}catch(d){throw new u(`Failed to read bundle file: ${c}`,{cause:d})}await new P(e).deploy(o,s,a,p,l,ja(c),r)}i(Je,"packageAndUpload");var Ot=i(async(e,t,n)=>{let r=await he(e,n);await Je(r,t,n,e.published)},"deploy");import{existsSync as Ba,readFileSync as Ga}from"fs";var Fr=[".dev.sig",".cert.sig"];function ve(e,t={}){let n=t.existsSync??Ba,r=t.readFileSync??((s,a)=>Ga(s,a)),o=[];for(let s of Fr){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(ve,"discoverSignatures");import{execSync as Ya}from"child_process";function Ut(e,t=!0,n={execSync:Ya}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new u(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}i(Ut,"buildApp");function Or(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(Or,"generateFusionUrl");function Ur(e,t,n){let r=n?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",o=n?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",r,"=".repeat(r.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${o}`,""].join(`
103
- `))}i(Ur,"printDeployInfo");function _r(e,t){console.log(`
104
- \u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let n=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
105
- To sign: npx @cognite/cli apps sign --interactive${n}`),console.log(`To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`),console.log(`
106
- To submit for certification: npx @cognite/cli apps submit`);let r=Or(t,e);r&&console.log(`
107
- \u{1F517} Open your app:
108
- ${r}`)}i(_r,"printDeployResult");async function qa(e,t,n,r,o){let s=T(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Ur(e,t,!1),r.skipBuild||Ut(n),console.log(`
109
- \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await o({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n),_r(e,t)}i(qa,"handleDeployNonInteractive");async function Ja(e,t,n,r){Ur(e,t,!0),r.skipBuild||Ut(n);let o=await R(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
110
- \u{1F4E4} Deploying to ${t.project}...`),await Je(o,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n,!1),_r(e,t)}i(Ja,"handleDeployInteractive");async function Wa(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,deploy:s=Ot}=n;r(t);let a=o(t);if(U(a),e.interactive){let c=await F(a,e);await Ja(a,c,t,e);return}let p=D(a.deployments,e.deployment);await qa(a,p,t,e,s)}i(Wa,"handleDeploy");function Kr(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",`
110
+ Hint: git rm --cached <file>`)}};i(Lt,"ApplicationPackager");var oe=Lt;import{existsSync as Wa,readFileSync as Xa}from"fs";var ue=[".dev.sig",".cert.sig"];function Ce(e,t={}){let n=t.existsSync??Wa,r=t.readFileSync??((s,a)=>Xa(s,a)),o=[];for(let s of ue){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Ce,"discoverSignatures");async function Xe(e,t,{existsSync:n=Za,mkdir:r=Qa,createZip:o=i((s,a)=>new oe(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,p=M(t,s,a);if(n(p)){let l=ue.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 y(`Bundle already exists: ${p}`,{hint:l,shouldReport:!1})}await r(np(p),{recursive:!0}),await o(`${t}/dist`,p)}i(Xe,"packageBundle");async function Ee(e,t,n,r,{readFile:o=ep,upload:s=i(async(a,p)=>new P(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,p,r),"uploadFn")}={}){let a=M(n,t.externalId,t.versionTag),p;try{p=await o(a)}catch(c){throw new y(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,tp(a))}i(Ee,"uploadBundle");var Kt=i(async(e,t,n)=>{let r=await me(e,n);await Xe(t,n),await Ee(r,t,n,e.published)},"deploy"),Nt=i(async(e,t,n)=>{let r=await me(e,n);await Ee(r,t,n,e.published)},"deployBundle");import{execSync as rp}from"child_process";function Mt(e,t=!0,n={execSync:rp}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new y(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}i(Mt,"buildApp");function Nr(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(Nr,"generateFusionUrl");async function sp(e){let{confirmed:t}=await op.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(sp,"defaultConfirm");function ap(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}i(ap,"classifyExistingBundle");async function pp(e,t){let{zip:n,versionTag:r,hasSigs:o}=e,s=o?`A signed bundle for v${r} already exists. Deploy it without rebuilding? (existing signatures will be preserved)`:`A bundle for v${r} already exists. Deploy it without rebuilding?`;if(await t.confirm(s))return!0;let a=o?"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 y(`Bundle already exists: ${n}`,{hint:a,shouldReport:!1})}i(pp,"promptBundleReuse");function Mr(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(`
111
+ `))}i(Mr,"printDeployInfo");function Hr(e){let{appConfig:t,deployment:n}=e;console.log(`
112
+ 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(`
113
+ 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(`
114
+ To submit for certification: npx @cognite/cli apps submit`);let o=Nr(n,t);o&&console.log(`
115
+ Open your app:
116
+ ${o}`)}i(Hr,"printDeployResult");async function cp(e,t){let{appConfig:n,deployment:r,cwd:o,options:s,useExistingBundle:a}=e,{deployFn:p}=t,c=$(r);if(c.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${c.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Mr({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&Mt(o),console.log(`
117
+ Deploying to ${r.org}/${r.project}...`),await p({...r,published:!1},{externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag},o),Hr({appConfig:n,deployment:r})}i(cp,"handleDeployNonInteractive");async function lp(e){let{appConfig:t,deployment:n,cwd:r,options:o,useExistingBundle:s}=e;Mr({appConfig:t,deployment:n,interactive:!0}),!o.skipBuild&&!s&&Mt(r);let a=await N(n,{interactive:!0,appId:t.externalId,orgHint:o.org});console.log(`
118
+ Deploying to ${n.project}...`);let p={externalId:t.externalId,name:t.name,description:t.description,versionTag:t.versionTag};s||await Xe(p,r),await Ee(a,p,r,!1),Hr({appConfig:t,deployment:n})}i(lp,"handleDeployInteractive");async function dp(e,t=process.cwd(),n={}){let{loadEnvFile:r=T,loadAppConfig:o=E,deploy:s=Kt,deployBundle:a=Nt,confirm:p=sp,existsSync:c=ip}=n;r(t);let l=o(t);F(l);let d=M(t,l.externalId,l.versionTag),m=ap(d,e,c),g=m==="use-existing"||m==="prompt"&&await pp({zip:d,versionTag:l.versionTag,hasSigs:ue.some(f=>c(`${d}${f}`))},{confirm:p});if(e.interactive){let f=await R(l,e);await lp({appConfig:l,deployment:f,cwd:t,options:e,useExistingBundle:g});return}let h=x(l.deployments,e.deployment);await cp({appConfig:l,deployment:h,cwd:t,options:e,useExistingBundle:g},{deployFn:g?a:s})}i(dp,"handleDeploy");function jr(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",`
111
119
  Environment (non-interactive):
112
120
  deployClientId and deploySecretName are configured per deployment in app.json.
113
121
  deploySecretName is the name of the environment variable that holds the client
@@ -121,75 +129,75 @@ Examples:
121
129
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
122
130
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
123
131
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
124
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Wa(t))}i(Kr,"registerDeployCommand");function za(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(za,"printMetadataDiff");async function Xa(e,t=process.cwd(),n={}){let{loadEnvFile:r=O,loadAppConfig:o=E,getClientForDeployment:s=R,createMetadataClient:a=i(y=>new P(y),"createMetadataClient"),getMissingCredentials:p=T}=n;r(t);let c=o(t);U(c);let l=e.interactive?await F(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),f;try{f=await m.getApp(c.externalId)}catch(y){throw y instanceof de?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}let h={name:c.name,description:c.description||""},g=vt(f,h);if(g.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}za(c.externalId,g),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}i(Xa,"handleUpdateMetadata");function Lr(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",`
132
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>dp(t))}i(jr,"registerDeployCommand");function mp(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(mp,"printMetadataDiff");async function up(e,t=process.cwd(),n={}){let{loadEnvFile:r=T,loadAppConfig:o=E,getClientForDeployment:s=N,createMetadataClient:a=i(f=>new P(f),"createMetadataClient"),getMissingCredentials:p=$}=n;r(t);let c=o(t);F(c);let l=e.interactive?await R(c,e):x(c.deployments,e.deployment);if(!e.interactive){let f=p(l);if(f.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${f.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(f){throw f instanceof de?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}let h={name:c.name,description:c.description||""},u=kt(g,h);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}mp(c.externalId,u),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}i(up,"handleUpdateMetadata");function Br(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",`
125
133
  Examples:
126
134
  npx @cognite/cli apps metadata update . Push name/description using env-var auth
127
- npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>Xa(r)),t}i(Lr,"registerMetadataCommand");async function Za(e,t,n){let r=await R(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new P(r)}i(Za,"defaultBuildApiClient");async function Qa(e,t={}){let n=t.loadEnvFile??O,r=t.loadAppConfig??E,o=t.buildApiClient??Za,s=t.discoverSignatures??ve,a=process.cwd();n(a);let p=r(a);U(p);let c=e.interactive?await F(p,e):D(p.deployments,e.deployment);if(!e.interactive){let g=T(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.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,f;try{f=await l.getVersion(d,m)}catch(g){throw g instanceof j?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):g}if(f.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(f.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(f.lifecycleState==="DEPRECATED"||f.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${f.lifecycleState} (terminal).`);let h=s(B(a,d,m));h.length>0&&await l.submitSignatures(d,m,h),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(Qa,"handlePublish");function Nr(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",`
135
+ npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>up(r)),t}i(Br,"registerMetadataCommand");async function gp(e,t,n){let r=await N(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new P(r)}i(gp,"defaultBuildApiClient");async function fp(e,t={}){let n=t.loadEnvFile??T,r=t.loadAppConfig??E,o=t.buildApiClient??gp,s=t.discoverSignatures??Ce,a=process.cwd();n(a);let p=r(a);F(p);let c=e.interactive?await R(p,e):x(p.deployments,e.deployment);if(!e.interactive){let u=$(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 h=s(M(a,d,m));h.length>0&&await l.submitSignatures(d,m,h),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(fp,"handlePublish");function Vr(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",`
128
136
  Examples:
129
137
  npx @cognite/cli apps publish . Publish using env-var auth
130
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>Qa(n))}i(Nr,"registerPublishCommand");import{spawnSync as ep}from"child_process";import{mkdirSync as tp}from"fs";import{resolve as _t}from"path";var np=["localhost","local.cognite.ai","*.local.cognite.ai"],rp={info:i(e=>{process.stdout.write(`${e}
138
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>fp(n))}i(Vr,"registerPublishCommand");import{spawnSync as yp}from"child_process";import{mkdirSync as hp}from"fs";import{join as Sp,resolve as Gr}from"path";var wp=["localhost","local.cognite.ai","*.local.cognite.ai"],vp={info:i(e=>{process.stdout.write(`${e}
131
139
  `)},"info"),error:i(e=>{process.stderr.write(`${e}
132
- `)},"error")},ip={spawnSync:ep,mkdirSync:tp,logger:rp};function op(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}i(op,"hasMkcert");function sp({certDir:e=_t(process.cwd(),"certificates/mkcert"),domains:t=np,deps:n={}}={}){let r={...ip,...n},{spawnSync:o,mkdirSync:s,logger:a}=r;if(!op(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(e,{recursive:!0});let c=_t(e,"localhost.pem"),l=_t(e,"localhost-key.pem");if(o("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}i(sp,"setupHttps");function ap(e){sp({certDir:e.certDir})}i(ap,"handleSetupHttps");function Mr(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
140
+ `)},"error")},Cp={spawnSync:yp,mkdirSync:hp,logger:vp,getConfig:I};function Ep(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}i(Ep,"hasMkcert");function bp({certDir:e,domains:t=wp,deps:n={}}={}){let r={...Cp,...n},{spawnSync:o,mkdirSync:s,logger:a}=r,p=e??Sp(r.getConfig().home,"certificates","mkcert");if(!Ep(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=Gr(p,"localhost.pem"),d=Gr(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(bp,"setupHttps");function kp(e){bp({certDir:e.certDir})}i(kp,"handleSetupHttps");function Yr(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",`
133
141
  Examples:
134
- npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
135
- npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>ap(t))}i(Mr,"registerSetupHttpsCommand");import{existsSync as Ap,writeFileSync as Dp}from"fs";import{basename as Ip,dirname as $p,join as Rp,resolve as Ht}from"path";import{parseScope as Tp,signBundle as Fp,validateScopes as Op}from"@cognite/app-sdk/codesigning";import{existsSync as bp,readFileSync as Pp}from"fs";import{pbkdf2 as lp,randomBytes as dp}from"crypto";import{promisify as mp}from"util";import{CompactEncrypt as up,base64url as Hr,compactDecrypt as gp}from"jose";var pp=new TextEncoder,cp=new TextDecoder,Kt={encode:i(e=>pp.encode(e),"encode"),decode:i(e=>cp.decode(e),"decode")};var fp=mp(lp),Mt=6e5,yp="sha512",Lt="PBKDF2-HMAC-SHA512",Nt=16,We="A256GCM",hp=32,ze=2e6;async function jr(e,t,n){return await fp(e,t,n,hp,yp)}i(jr,"deriveKey");async function Vr(e,t,n=Mt){if(!Number.isInteger(n)||n<1||n>ze)throw new Error(`Invalid iterations: must be an integer between 1 and ${ze}`);let r=dp(Nt),o=await jr(t.expose(),r,n);return await new up(Kt.encode(e.expose())).setProtectedHeader({alg:"dir",enc:We,kdf:Lt,kdf_iter:n,kdf_salt:Hr.encode(r)}).encrypt(o)}i(Vr,"encryptStringAsJwe");async function Br(e,t){let{plaintext:n}=await gp(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!==We)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${We}" is supported`);if(r.kdf!==Lt)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Lt}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>ze)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${ze}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Hr.decode(r.kdf_salt);if(a.length!==Nt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Nt} bytes, got ${a.length}`);return await jr(o,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[We]});return Kt.decode(n)}i(Br,"decryptJweAsString");function Sp(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}i(Sp,"isJweCompact");var Gr=Sp;import wp from"enquirer";async function vp(e){return wp.prompt(e)}i(vp,"defaultPrompt");async function Yr(e,t={}){let{prompt:n=vp}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return w.from(r)}i(Yr,"promptPassphrase");import Ep from"enquirer";import{statSync as Cp}from"fs";function qr(e,t=Cp){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}i(qr,"sortByMtime");async function kp(e){return Ep.prompt(e)}i(kp,"defaultPrompt");async function Jr(e,t={}){if(e.length===1)return e[0];let{prompt:n=kp,sortByMtime:r=qr}=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,Fe(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(Jr,"promptSigningIdentity");function xp(e){return{existsSync:e.existsSync??bp,readFileSync:e.readFileSync??((t,n)=>Pp(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Re,readSigningKey:e.readSigningKey??Te,isOS:e.isOS??(t=>A(t)),decryptJweAsString:e.decryptJweAsString??Br,discoverLocalKeys:e.discoverLocalKeys??Oe,keysDir:e.keysDir??$().keysDir,promptPassphrase:e.promptPassphrase??Yr,promptSigningIdentity:e.promptSigningIdentity??Jr}}i(xp,"resolveDeps");async function Wr(e,t={}){let n=xp(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(Gr(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:w.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:w.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:w.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(Wr,"resolvePrivateKey");var Up=i(async(e,t,n,r,o)=>{let s=await R(e,{interactive:o.browserAuth??!1,appId:t,orgHint:o.org});await new P(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function _p(e){return{existsSync:e.existsSync??Ap,writeFileSync:e.writeFileSync??Dp,createBundleStream:e.createBundleStream??Ue,signBundle:e.signBundle??Fp,parseScope:e.parseScope??Tp,validateScopes:e.validateScopes??Op,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>Wr(t)),submitSignatures:e.submitSignatures??Up,discoverSignatures:e.discoverSignatures??ve}}i(_p,"resolveDeps");async function zr(e,t,n={},r=process.cwd()){let o=_p(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(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?Ht(r,e):B(r,s,a);if(!o.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=o.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
142
+ npx @cognite/cli@latest apps setup-https Generate certs in ~/.cognite-cli/certificates/mkcert
143
+ npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>kp(t))}i(Yr,"registerSetupHttpsCommand");import{existsSync as Vp,writeFileSync as Gp}from"fs";import{basename as Yp,dirname as qp,join as Jp,resolve as Gt}from"path";import{parseScope as zp,signBundle as Wp,validateScopes as Xp}from"@cognite/app-sdk/codesigning";import{existsSync as Hp,readFileSync as jp}from"fs";import{pbkdf2 as Ap,randomBytes as Dp}from"crypto";import{promisify as Ip}from"util";import{CompactEncrypt as $p,base64url as qr,compactDecrypt as Rp}from"jose";var Pp=new TextEncoder,xp=new TextDecoder,Ht={encode:i(e=>Pp.encode(e),"encode"),decode:i(e=>xp.decode(e),"decode")};var Tp=Ip(Ap),Vt=6e5,Fp="sha512",jt="PBKDF2-HMAC-SHA512",Bt=16,Ze="A256GCM",Op=32,Qe=2e6;async function Jr(e,t,n){return await Tp(e,t,n,Op,Fp)}i(Jr,"deriveKey");async function zr(e,t,n=Vt){if(!Number.isInteger(n)||n<1||n>Qe)throw new Error(`Invalid iterations: must be an integer between 1 and ${Qe}`);let r=Dp(Bt),o=await Jr(t.expose(),r,n);return await new $p(Ht.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Ze,kdf:jt,kdf_iter:n,kdf_salt:qr.encode(r)}).encrypt(o)}i(zr,"encryptStringAsJwe");async function Wr(e,t){let{plaintext:n}=await Rp(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!==Ze)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${Ze}" is supported`);if(r.kdf!==jt)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${jt}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>Qe)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Qe}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=qr.decode(r.kdf_salt);if(a.length!==Bt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Bt} bytes, got ${a.length}`);return await Jr(o,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Ze]});return Ht.decode(n)}i(Wr,"decryptJweAsString");function Up(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}i(Up,"isJweCompact");var Xr=Up;import _p from"enquirer";async function Lp(e){return _p.prompt(e)}i(Lp,"defaultPrompt");async function Zr(e,t={}){let{prompt:n=Lp}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return C.from(r)}i(Zr,"promptPassphrase");import Np from"enquirer";import{statSync as Kp}from"fs";function Qr(e,t=Kp){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}i(Qr,"sortByMtime");async function Mp(e){return Np.prompt(e)}i(Mp,"defaultPrompt");async function ei(e,t={}){if(e.length===1)return e[0];let{prompt:n=Mp,sortByMtime:r=Qr}=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,Ue(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(ei,"promptSigningIdentity");function Bp(e){return{existsSync:e.existsSync??Hp,readFileSync:e.readFileSync??((t,n)=>jp(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Fe,readSigningKey:e.readSigningKey??Oe,isOS:e.isOS??(t=>U(t)),decryptJweAsString:e.decryptJweAsString??Wr,discoverLocalKeys:e.discoverLocalKeys??_e,keysDir:e.keysDir??I().keysDir,promptPassphrase:e.promptPassphrase??Zr,promptSigningIdentity:e.promptSigningIdentity??ei}}i(Bp,"resolveDeps");async function ti(e,t={}){let n=Bp(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(Xr(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:C.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:C.from(s),kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let 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:C.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(ti,"resolvePrivateKey");var Zp=i(async(e,t,n,r,o)=>{let s=await N(e,{interactive:o.browserAuth??!1,appId:t,orgHint:o.org});await new P(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function Qp(e){return{existsSync:e.existsSync??Vp,writeFileSync:e.writeFileSync??Gp,createBundleStream:e.createBundleStream??Le,signBundle:e.signBundle??Wp,parseScope:e.parseScope??zp,validateScopes:e.validateScopes??Xp,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>ti(t)),submitSignatures:e.submitSignatures??Zp,discoverSignatures:e.discoverSignatures??Ce}}i(Qp,"resolveDeps");async function ni(e,t,n={},r=process.cwd()){let o=Qp(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?Gt(r,e):M(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:
136
144
  ${d.join(`
137
- `)}`);let{privateKeyPem:m,kid:f}=await o.resolvePrivateKey({keyPath:t.key?Ht(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),h=o.createBundleStream(l),g=await o.signBundle({privateKeyPem:m.expose(),kid:f,appId:s,version:a,bundleStream:h,role:t.asCertifier?"certifier":"developer",scopes:p}),y=t.output?Ht(r,t.output):Rp($p(l),`${Ip(l)}.${t.asCertifier?"cert":"dev"}.sig`);o.writeFileSync(y,g.token,"utf-8"),console.log(`\u2705 Signed: ${y}`),console.log(` kid: ${g.kid}`),console.log(` bundle: ${g.payload.bundleSha256}`),console.log(` scopes: ${g.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
138
- Payload:`,JSON.stringify(g.payload,null,2));let S=Array.from(new Set([...o.discoverSignatures(l),g.token])),b=t.interactive?await F(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):D(c.deployments,t.deployment);if(!t.browserAuth){let v=T(b);if(v.length>0)throw new Error(`Deployment ${b.org}/${b.project} is missing ${v.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await o.submitSignatures(b,s,a,S,t),console.log(`
139
- To publish: npx @cognite/cli apps publish .`)}i(zr,"handleSign");function Xr(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 zr(n,o,t)})}i(Xr,"registerSignCommand");function Kp(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}i(Kp,"describeStatus");function Lp(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(Lp,"formatSignatures");async function Np(e){let t=process.cwd();O(t);let n=E(t);U(n);let r=e.interactive?await F(n,e):D(n.deployments,e.deployment);if(!e.interactive){let a=T(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 R(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(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: ${Kp(a)}`);let p=await Mp(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 Lp(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(Np,"handleStatus");async function Mp(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ie(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}i(Mp,"fetchSignatures");function Zr(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",`
145
+ `)}`);let{privateKeyPem:m,kid:g}=await o.resolvePrivateKey({keyPath:t.key?Gt(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),h=o.createBundleStream(l),u=await o.signBundle({privateKeyPem:m.expose(),kid:g,appId:s,version:a,bundleStream:h,role:t.asCertifier?"certifier":"developer",scopes:p}),f=t.output?Gt(r,t.output):Jp(qp(l),`${Yp(l)}.${t.asCertifier?"cert":"dev"}.sig`);o.writeFileSync(f,u.token,"utf-8"),console.log(`\u2705 Signed: ${f}`),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(`
146
+ Payload:`,JSON.stringify(u.payload,null,2));let S=Array.from(new Set([...o.discoverSignatures(l),u.token])),b=t.interactive?await R(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):x(c.deployments,t.deployment);if(!t.browserAuth){let w=$(b);if(w.length>0)throw new Error(`Deployment ${b.org}/${b.project} is missing ${w.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await o.submitSignatures(b,s,a,S,t),console.log(`
147
+ To publish: npx @cognite/cli apps publish .`)}i(ni,"handleSign");function ri(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 ni(n,o,t)})}i(ri,"registerSignCommand");function ec(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}i(ec,"describeStatus");function tc(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(tc,"formatSignatures");async function nc(e){let t=process.cwd();T(t);let n=E(t);F(n);let r=e.interactive?await R(n,e):x(n.deployments,e.deployment);if(!e.interactive){let a=$(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 P(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: ${ec(a)}`);let p=await rc(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 tc(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(nc,"handleStatus");async function rc(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(ie(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}i(rc,"fetchSignatures");function ii(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",`
140
148
  Examples:
141
149
  npx @cognite/cli apps status . Status using env-var auth
142
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Np(n))}i(Zr,"registerStatusCommand");import{execFileSync as Bt}from"child_process";import Vt from"fs";import Ce from"path";import Bp from"readline";var Qr="https://cognite.zendesk.com",Hp="360001234312",jp="tf_360015295097",Vp="cognite_flows_certifications";function ei(e,t,n){let r=new URLSearchParams({ticket_form_id:Hp,tf_priority:"normal",tf_subject:e,[jp]:Vp,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}i(ei,"buildUrl");function ti(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}i(ti,"escapeHtml");function jt(e){return e.map(ti).join("<br>")}i(jt,"toHtml");function ni(e,t=Qr){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 ei(`App Review Request: ${n}`,jt(l.filter(d=>d!==void 0)),t)}i(ni,"buildAppReviewUrl");function ri(e,t,n,r,o=Qr){let s=jt(["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>${ti(r.replace(/\r\n/g,`
143
- `))}</pre>`,p=jt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return ei(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,o)}i(ri,"buildKeyRegistrationUrl");function Gp(){return new Promise(e=>{let t=Bp.createInterface({input:process.stdin,output:process.stdout});t.question(`
144
- Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}i(Gp,"defaultPressEnter");var Yp=[{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 qp(e){let t=Yp.filter(({pattern:n})=>Bt("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:
150
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>nc(n))}i(ii,"registerStatusCommand");import{execFileSync as Jt}from"child_process";import qt from"fs";import be from"path";import ac from"readline";var oi="https://cognite.zendesk.com",ic="360001234312",oc="tf_360015295097",sc="cognite_flows_certifications";function si(e,t,n){let r=new URLSearchParams({ticket_form_id:ic,tf_priority:"normal",tf_subject:e,[oc]:sc,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}i(si,"buildUrl");function ai(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}i(ai,"escapeHtml");function Yt(e){return e.map(ai).join("<br>")}i(Yt,"toHtml");function pi(e,t=oi){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 si(`App Review Request: ${n}`,Yt(l.filter(d=>d!==void 0)),t)}i(pi,"buildAppReviewUrl");function ci(e,t,n,r,o=oi){let s=Yt(["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>${ai(r.replace(/\r\n/g,`
151
+ `))}</pre>`,p=Yt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return si(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,o)}i(ci,"buildKeyRegistrationUrl");function pc(){return new Promise(e=>{let t=ac.createInterface({input:process.stdin,output:process.stdout});t.question(`
152
+ Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}i(pc,"defaultPressEnter");var cc=[{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 lc(e){let t=cc.filter(({pattern:n})=>Jt("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:
145
153
 
146
154
  `+n.join(`
147
- `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}i(qp,"assertArtifactsCommitted");async function Jp(e=process.cwd(),t={}){let{openInBrowser:n=Rn,revealInFileManager:r=Tn,pressEnter:o=Gp,isInteractive:s=i(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!Pe())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!xe(e))throw new Error("Not a git repository. Run this command from your app's root directory.");O(e);let a=E(e);U(a),qp(e);let p=Ce.join(e,"dist","submit");Vt.mkdirSync(p,{recursive:!0});let c=Bt("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Bt("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.
155
+ `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}i(lc,"assertArtifactsCommitted");async function dc(e=process.cwd(),t={}){let{openInBrowser:n=On,revealInFileManager:r=Un,pressEnter:o=pc,isInteractive:s=i(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!Ae())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!De(e))throw new Error("Not a git repository. Run this command from your app's root directory.");T(e);let a=E(e);F(a),lc(e);let p=be.join(e,"dist","submit");qt.mkdirSync(p,{recursive:!0});let c=Jt("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Jt("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.
148
156
 
149
- The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=Ce.join(p,d);await new oe(Ce.join(e,"dist")).createSourceArchive(m);let h=`${a.externalId}-${a.versionTag}.zip`,g=Ce.join(e,".cognite-bundles",h),y=!1;Vt.existsSync(g)&&(Vt.copyFileSync(g,Ce.join(p,h)),y=!0);let S=ni({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:ln(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
150
- \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(y?` ${h} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
157
+ The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=be.join(p,d);await new oe(be.join(e,"dist")).createSourceArchive(m);let h=`${a.externalId}-${a.versionTag}.zip`,u=be.join(e,".cognite-bundles",h),f=!1;qt.existsSync(u)&&(qt.copyFileSync(u,be.join(p,h)),f=!0);let S=pi({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:un(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
158
+ \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(f?` ${h} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
151
159
  Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
152
- \u{1F517} ${S}`),s()&&(await o(),n(S),r(m))}i(Jp,"handleSubmit");function ii(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
160
+ \u{1F517} ${S}`),s()&&(await o(),n(S),r(m))}i(dc,"handleSubmit");function li(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
153
161
  Examples:
154
- npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Jp())}i(ii,"registerSubmitCommand");function oi(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return $r(t),Kr(t),Zr(t),Lr(t),Nr(t),gr(t),Rr(t),Mr(t),ii(t),Ar(t),Xr(t),Jn(t),t}i(oi,"registerAppsCommand");import{existsSync as ec,mkdirSync as tc,writeFileSync as nc}from"fs";import{dirname as qt,join as ke}from"path";import{generateSigningKeyPair as rc}from"@cognite/app-sdk/codesigning";import ic from"open";function si(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(si,"addMonthsClamped");function Gt(e){return e.toISOString().slice(0,10)}i(Gt,"formatIsoDate");function ai(e=new Date){return Gt(e)}i(ai,"todayIso");import Wp,{Chalk as zp}from"chalk";var Ee=new zp({level:0});function pi(e){return e.isTTY?Wp:Ee}i(pi,"chalkForStream");var Xe=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),ci=32,li=44,di=60,Xp="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Zp(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==li&&t.length!==di)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${li} (raw) or ${di} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===Xe.length+ci&&n.subarray(0,Xe.length).equals(Xe))return n.subarray(Xe.length).toString("base64");if(n.length===ci)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(Zp,"pemBodyOneLine");function Yt(e,t=Ee,n=new Date){let r=mi(e.issuedAt??ai(n)),o=mi(e.expires),s=Zp(e.publicKeyPem),a=" ",p=i((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
162
+ npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>dc())}i(li,"registerSubmitCommand");function di(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Ur(t),jr(t),ii(t),Br(t),Vr(t),hr(t),_r(t),Lr(t),Yr(t),li(t),Tr(t),ri(t),Xn(t),t}i(di,"registerAppsCommand");import{existsSync as hc,mkdirSync as Sc,writeFileSync as wc}from"fs";import{dirname as Xt,join as Pe}from"path";import{generateSigningKeyPair as vc}from"@cognite/app-sdk/codesigning";import Cc from"open";function mi(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(mi,"addMonthsClamped");function zt(e){return e.toISOString().slice(0,10)}i(zt,"formatIsoDate");function ui(e=new Date){return zt(e)}i(ui,"todayIso");import mc,{Chalk as uc}from"chalk";var ke=new uc({level:0});function gi(e){return e.isTTY?mc:ke}i(gi,"chalkForStream");var et=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),fi=32,yi=44,hi=60,gc="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function fc(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==yi&&t.length!==hi)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${yi} (raw) or ${hi} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===et.length+fi&&n.subarray(0,et.length).equals(et))return n.subarray(et.length).toString("base64");if(n.length===fi)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(fc,"pemBodyOneLine");function Wt(e,t=ke,n=new Date){let r=Si(e.issuedAt??ui(n)),o=Si(e.expires),s=fc(e.publicKeyPem),a=" ",p=i((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
155
163
  `,"kv"),c="";return c+=`
156
- ${t.bold("Add this entry to")} ${t.magenta(Xp)} ${t.bold("under")} ${t.cyan("publicKeys:")}
164
+ ${t.bold("Add this entry to")} ${t.magenta(gc)} ${t.bold("under")} ${t.cyan("publicKeys:")}
157
165
 
158
166
  `,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
159
- `,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(Yt,"renderRegistryYamlBlock");function mi(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(mi,"toIsoInstant");import Qp from"clipboardy";function ui(e){return Qp.write(e)}i(ui,"copyToClipboard");function oc(e){return{writeFileSync:e.writeFileSync??nc,mkdirSync:e.mkdirSync??tc,existsSync:e.existsSync??ec,generateSigningKeyPair:e.generateSigningKeyPair??rc,encryptStringAsJwe:e.encryptStringAsJwe??Vr,storeKeyInKeychain:e.storeKeyInKeychain??Un,storeSigningKey:e.storeSigningKey??Mn,isOS:e.isOS??(t=>A(t)),promptKid:e.promptKid??bn,promptExpiryMonths:e.promptExpiryMonths??xn,promptEmail:e.promptEmail??An,promptPassphrase:e.promptPassphrase??Dn,promptConfirmOverwrite:e.promptConfirmOverwrite??In,discoverLocalKeys:e.discoverLocalKeys??(()=>Oe()),promptZendeskAction:e.promptZendeskAction??Pn,openUrl:e.openUrl??(t=>ic(t)),copyToClipboard:e.copyToClipboard??ui}}i(oc,"resolveDeps");function fi(e,t={}){let n=oc(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=>cc(o,n)),r.command("list").description("List local signing identities and their storage location").action(()=>sc(n))}i(fi,"registerKeysCommand");async function sc(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
160
- `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${$().keysDir}).
161
- `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Fe(a.source),a.email??"\u2014"]),o=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=i(a=>a.map((p,c)=>p.padEnd(o[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
167
+ `,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(Wt,"renderRegistryYamlBlock");function Si(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(Si,"toIsoInstant");import yc from"clipboardy";function wi(e){return yc.write(e)}i(wi,"copyToClipboard");function Ec(e){return{writeFileSync:e.writeFileSync??wc,mkdirSync:e.mkdirSync??Sc,existsSync:e.existsSync??hc,generateSigningKeyPair:e.generateSigningKeyPair??vc,encryptStringAsJwe:e.encryptStringAsJwe??zr,storeKeyInKeychain:e.storeKeyInKeychain??Kn,storeSigningKey:e.storeSigningKey??Bn,isOS:e.isOS??(t=>U(t)),promptKid:e.promptKid??An,promptExpiryMonths:e.promptExpiryMonths??In,promptEmail:e.promptEmail??$n,promptPassphrase:e.promptPassphrase??Rn,promptConfirmOverwrite:e.promptConfirmOverwrite??Tn,discoverLocalKeys:e.discoverLocalKeys??(()=>_e()),promptZendeskAction:e.promptZendeskAction??Dn,openUrl:e.openUrl??(t=>Cc(t)),copyToClipboard:e.copyToClipboard??wi}}i(Ec,"resolveDeps");function Ci(e,t={}){let n=Ec(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(o=>xc(o,n)),r.command("list").description("List local signing identities and their storage location").action(()=>bc(n))}i(Ci,"registerKeysCommand");async function bc(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
168
+ `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${I().keysDir}).
169
+ `);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Ue(a.source),a.email??"\u2014"]),o=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=i(a=>a.map((p,c)=>p.padEnd(o[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
162
170
  `);for(let a of r)process.stdout.write(`${s(a)}
163
- `)}i(sc,"handleList");function gi(e,t,n){let r=ke($().keysDir,`${e}${J}`);return n.mkdirSync(qt(r),{recursive:!0}),n.writeFileSync(r,t),r}i(gi,"writePublicKey");async function ac(e,t,n,r,o,{force:s=!1}={}){let a=r??ke($().keysDir,`${e}${ct}`);if(o.mkdirSync(qt(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(ac,"writeEncryptedPrivateKey");function pc(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{pe(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=re(e.kid),s=ke($().keysDir,`${o}${J}`);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{ae(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(pc,"collectNonInteractiveErrors");async function cc(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:f,promptPassphrase:h,promptConfirmOverwrite:g}=t,y=e.interactive??!1,S=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!y){let M=pc(e,S,o);if(M.length>0)throw new Error(M.join(`
164
- `))}let b;e.expires!==void 0?b=pe(e.expires):b=await d();let v=Gt(si(n,b)),C;e.kid!==void 0?C=re(e.kid):C=await m();let z=ke($().keysDir,`${C}${J}`),V=o(z);if(V&&!e.force&&!await g(C)){process.stderr.write(`Aborted.
165
- `);return}let I;e.email!==void 0?I=ae(e.email,"--email"):I=await f();let k=S?{kind:"keychain"}:{kind:"file",passphrase:await h()};process.stderr.write(`
171
+ `)}i(bc,"handleList");function vi(e,t,n){let r=Pe(I().keysDir,`${e}${z}`);return n.mkdirSync(Xt(r),{recursive:!0}),n.writeFileSync(r,t),r}i(vi,"writePublicKey");async function kc(e,t,n,r,o,{force:s=!1}={}){let a=r??Pe(I().keysDir,`${e}${ut}`);if(o.mkdirSync(Xt(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(kc,"writeEncryptedPrivateKey");function Pc(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{pe(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=re(e.kid),s=Pe(I().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{ae(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(Pc,"collectNonInteractiveErrors");async function xc(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:h,promptConfirmOverwrite:u}=t,f=e.interactive??!1,S=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!f){let B=Pc(e,S,o);if(B.length>0)throw new Error(B.join(`
172
+ `))}let b;e.expires!==void 0?b=pe(e.expires):b=await d();let w=zt(mi(n,b)),v;e.kid!==void 0?v=re(e.kid):v=await m();let Y=Pe(I().keysDir,`${v}${z}`),L=o(Y);if(L&&!e.force&&!await u(v)){process.stderr.write(`Aborted.
173
+ `);return}let D;e.email!==void 0?D=ae(e.email,"--email"):D=await g();let k=S?{kind:"keychain"}:{kind:"file",passphrase:await h()};process.stderr.write(`
166
174
  Generating Ed25519 keypair...
167
175
 
168
- `);let{privateKeyPem:X,publicKeyPem:Z}=await p(C),x=w.from(X);if(k.kind==="keychain"){r("macos")?await c(C,x):await l(C,x);let M=gi(C,Z,t);process.stderr.write(`Public key: ${M}
169
- `),process.stderr.write(`Private key: OS credential store (account: ${C})
170
- `)}else{let M=await ac(C,x,k.passphrase,e.output,t,{force:V}),Ui=gi(C,Z,t);process.stderr.write(`Public key: ${Ui}
171
- `),process.stderr.write(`Private key: ${M} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Mt.toLocaleString()})
172
- `)}let Q=ke($().keysDir,`${C}${lt}`);s(qt(Q),{recursive:!0}),a(Q,JSON.stringify({email:I}));let se=pi(process.stderr);process.stderr.write(`
173
- Signing identity (kid): ${se.green(C)}
174
- `),process.stderr.write(`Expires: ${v} (${b} month${b===1?"":"s"} from today)
175
- `);let be={kid:C,publicKeyPem:Z,email:I,expires:v};y||(process.stderr.write(`
176
+ `);let{privateKeyPem:X,publicKeyPem:Z}=await p(v),O=C.from(X);if(k.kind==="keychain"){r("macos")?await c(v,O):await l(v,O);let B=vi(v,Z,t);process.stderr.write(`Public key: ${B}
177
+ `),process.stderr.write(`Private key: OS credential store (account: ${v})
178
+ `)}else{let B=await kc(v,O,k.passphrase,e.output,t,{force:L}),Hi=vi(v,Z,t);process.stderr.write(`Public key: ${Hi}
179
+ `),process.stderr.write(`Private key: ${B} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Vt.toLocaleString()})
180
+ `)}let Q=Pe(I().keysDir,`${v}${gt}`);s(Xt(Q),{recursive:!0}),a(Q,JSON.stringify({email:D}));let se=gi(process.stderr);process.stderr.write(`
181
+ Signing identity (kid): ${se.green(v)}
182
+ `),process.stderr.write(`Expires: ${w} (${b} month${b===1?"":"s"} from today)
183
+ `);let xe={kid:v,publicKeyPem:Z,email:D,expires:w};f||(process.stderr.write(`
176
184
  Key registration data:
177
185
 
178
- `),process.stderr.write(Yt(be,se,n)));let ee=ri(C,I,v,Yt(be,Ee,n));process.stderr.write(`
186
+ `),process.stderr.write(Wt(xe,se,n)));let ee=ci(v,D,w,Wt(xe,ke,n));process.stderr.write(`
179
187
  ${se.bold("Next:")}
180
188
  `),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
181
- `);let ge;if(e.copyLink?ge="clipboard":y?ge=await t.promptZendeskAction():ge=null,ge==="browser")try{await t.openUrl(ee),process.stderr.write(` Opening in browser...
189
+ `);let ye;if(e.copyLink?ye="clipboard":f?ye=await t.promptZendeskAction():ye=null,ye==="browser")try{await t.openUrl(ee),process.stderr.write(` Opening in browser...
182
190
  `)}catch{process.stderr.write(` URL: ${ee}
183
- `)}else if(ge==="clipboard"){let M=!1;try{await t.copyToClipboard(ee),M=!0}catch{}process.stderr.write(M&&!e.copyLink?` Link copied to clipboard.
191
+ `)}else if(ye==="clipboard"){let B=!1;try{await t.copyToClipboard(ee),B=!0}catch{}process.stderr.write(B&&!e.copyLink?` Link copied to clipboard.
184
192
  `:` URL: ${ee}
185
193
  `)}else process.stderr.write(` URL: ${ee}
186
194
  `);process.stderr.write(`
187
195
  2. Once your key is approved, sign your Dune app:
188
- `),process.stderr.write(` ${se.cyan(`cognite sign -s ${C}`)}
189
- `)}i(cc,"handleGenerate");import{performance as yi}from"perf_hooks";var hi=1e3,Ze;function lc(){Ze=yi.now()}i(lc,"markActionStart");function dc(){Ze=void 0}i(dc,"resetActionStart");function mc(){if(Ze!==void 0)return Math.max(0,Math.round(yi.now()-Ze))}i(mc,"snapshotActionDurationMs");function Si(){let e=mc();return dc(),{...e!==void 0&&{actionDurationMs:e}}}i(Si,"takePerformanceFields");var uc=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function gc(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:uc.has(t)?[t,n]:[t,"[REDACTED]"]))}i(gc,"sanitize");function fc(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}i(fc,"getCommandPath");function wi(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(wi,"tryLoadAppConfig");function Jt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}i(Jt,"commandFromArgv");function vi(e,t,n=E){e.hook("preAction",()=>{lc()}),e.hook("postAction",async(r,o)=>{try{let s={command:fc(o),options:gc(o.opts()),success:!0,...wi(n),...Si()};t.track("Flows.CLI.Command",{...s}),await t.flush(hi)}catch{}})}i(vi,"instrument");async function Ci(e,t,n=E){try{let r={command:Jt(t),options:{},success:!1,...wi(n),...Si()};e.track("Flows.CLI.Command",{...r}),await e.flush(hi)}catch{}}i(Ci,"trackFailure");var yc="ERR_USE_AFTER_CLOSE";function ki(e){return e instanceof Error&&"code"in e&&e.code===yc}i(ki,"isReadlineClosedError");function hc(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(hc,"isPlainObject");function Wt(e){return e==null||ki(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&hc(e)&&Object.keys(e).length===0)}i(Wt,"isPromptCancel");var Ei=!1;function bi(){Ei||(Ei=!0,process.on("uncaughtException",e=>{ki(e)&&(console.error(`
190
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Wt(e)&&(console.error(`
191
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}i(bi,"installCancelHandler");import{homedir as Sc,userInfo as wc}from"os";var vc=Sc(),Cc=(()=>{try{return wc().username}catch{return""}})();function me(e,t=vc){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(me,"redactHomedir");function Ec(e,t=Cc){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(Ec,"redactUsername");var kc=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Pi(e){return e.replace(kc,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}i(Pi,"redactCredentials");var bc=1e3,Pc="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",xc={captureError:i(async()=>{},"captureError"),flush:i(async()=>{},"flush")};function Ac(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}i(Ac,"buildRelease");var Dc="192.0.2.0";function Ic(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:me(t.filename)},...t.abs_path!==void 0&&{abs_path:me(t.abs_path)},...t.module!==void 0&&{module:me(t.module)}}))}i(Ic,"scrubStackFrames");function zt(e){return Pi(Ec(me(e)))}i(zt,"redactPii");function $c(e){let t={...e.user,email:void 0,username:void 0,ip_address:Dc,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?zt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Ic(s.stacktrace.frames)}}})),r=e.contexts?.cli,o=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?zt(a):a])):void 0;return{...e,message:e.message!==void 0?zt(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...o!==void 0&&{contexts:{...e.contexts,cli:o}}}}i($c,"scrubPii");function xi(e={}){let t=e.env??process.env;if(kt(t))return xc;let n=Ac(e),r="production",o=null,s=null;function a(){return{dsn:Pc,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Se},contexts:{cli:{applicationId:Se,node:process.version,platform:process.platform}}},beforeSend:$c}}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,Rc(c,l))}catch{}},async flush(c=bc){try{if(!o)return;await o.flush(c)}catch{}}}}i(xi,"createErrorReporter");function Rc(e,t){let n={level:"fatal"},r={applicationId:Se,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),an(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},pn(e)&&(n.contexts.http={url:e.requestUrl!==void 0?me(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:Pi(me(o))}}return n}i(Rc,"buildCaptureContext");import{mkdirSync as Tc,readFileSync as Fc,writeFileSync as Oc}from"fs";import{homedir as Uc}from"os";import{resolve as Qe}from"path";import{debuglog as _c}from"util";import{lt as Kc,parse as Ai}from"semver";var Lc="https://registry.npmjs.org/@cognite/cli/latest",Nc=1500,Di="upgrade-check.json",Ii=Qe(process.env.XDG_CACHE_HOME||Qe(Uc(),".cache"),"@cognite","cli"),Xt=_c("cognite-flows");function Mc(e,t){return!e||!t||!Ai(e)||!Ai(t)?!1:Kc(e,t)}i(Mc,"isOutdated");async function Hc({timeout:e=Nc,registryUrl:t=Lc,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 Xt("fetchLatestVersion failed (%s): %O",t,r),null}}i(Hc,"fetchLatestVersion");function jc(e=Ii,t=864e5){try{let n=Fc(Qe(e,Di),"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 Xt("readUpgradeCheckCache failed (%s): %O",e,n),null}}i(jc,"readUpgradeCheckCache");function Vc(e,t){try{Tc(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Oc(Qe(e,Di),JSON.stringify(n))}catch(n){Xt("writeUpgradeCheckCache failed (%s): %O",e,n)}}i(Vc,"writeUpgradeCheckCache");async function Bc({cacheDir:e=Ii,...t}={}){let n=await Hc(t);n&&Vc(e,n)}i(Bc,"startBackgroundUpgradeCheck");function $i(e,{onOutdated:t,cacheDir:n,...r}={}){let o=jc(n);if(o){Mc(e,o.latest)&&t?.(e,o.latest);return}Bc({cacheDir:n,...r})}i($i,"preActionUpgradeCheck");import{default as Gh,chalkStderr as Ri}from"chalk";function Ti(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(`
192
- `);return Ri.bold.yellow(a)}i(Ti,"formatUpgradeWarning");function qc(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}i(qc,"isDep0040Warning");var Qt=process,Jc=Qt.emit.bind(Qt);Qt.emit=function(e,...t){return e==="warning"&&qc(t[0])?!1:Jc(e,...t)};bi();var ue=new Yc;ue.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.7.1-alpha.1").showHelpAfterError().configureOutput({writeOut:i(e=>Gc(1,e),"writeOut")});ue.hook("preAction",()=>{$i("1.7.1-alpha.1",{onOutdated:i((e,t)=>{console.warn(`
193
- ${Ti(e,t)}
194
- `)},"onOutdated")})});oi(ue);fi(ue);var Oi=Me({packageName:"@cognite/cli",cliVersion:"1.7.1-alpha.1"}),Fi=xi({packageName:"@cognite/cli",cliVersion:"1.7.1-alpha.1"});vi(ue,Oi);var Zt=process.argv.slice(2);ue.parseAsync(Zt,{from:"user"}).catch(async e=>{await Ci(Oi,Zt),Wt(e)&&(console.error(`
195
- Cancelled.`),process.exit(130)),(!(e instanceof u)||e.shouldReport)&&(await Fi.captureError(e,{command:Jt(Zt)}),await Fi.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof u&&(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)});
196
+ `),process.stderr.write(` ${se.cyan(`cognite sign -s ${v}`)}
197
+ `)}i(xc,"handleGenerate");import{performance as Ei}from"perf_hooks";var bi=1e3,tt;function Ac(){tt=Ei.now()}i(Ac,"markActionStart");function Dc(){tt=void 0}i(Dc,"resetActionStart");function Ic(){if(tt!==void 0)return Math.max(0,Math.round(Ei.now()-tt))}i(Ic,"snapshotActionDurationMs");function ki(){let e=Ic();return Dc(),{...e!==void 0&&{actionDurationMs:e}}}i(ki,"takePerformanceFields");var $c=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Rc(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:$c.has(t)?[t,n]:[t,"[REDACTED]"]))}i(Rc,"sanitize");function Tc(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}i(Tc,"getCommandPath");function Pi(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(Pi,"tryLoadAppConfig");function Zt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}i(Zt,"commandFromArgv");function xi(e,t,n=E){e.hook("preAction",()=>{Ac()}),e.hook("postAction",async(r,o)=>{try{let s={command:Tc(o),options:Rc(o.opts()),success:!0,...Pi(n),...ki()};t.track("Flows.CLI.Command",{...s}),await t.flush(bi)}catch{}})}i(xi,"instrument");async function Ai(e,t,n=E){try{let r={command:Zt(t),options:{},success:!1,...Pi(n),...ki()};e.track("Flows.CLI.Command",{...r}),await e.flush(bi)}catch{}}i(Ai,"trackFailure");var Fc="ERR_USE_AFTER_CLOSE";function Ii(e){return e instanceof Error&&"code"in e&&e.code===Fc}i(Ii,"isReadlineClosedError");function Oc(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Oc,"isPlainObject");function Qt(e){return e==null||Ii(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Oc(e)&&Object.keys(e).length===0)}i(Qt,"isPromptCancel");var Di=!1;function $i(){Di||(Di=!0,process.on("uncaughtException",e=>{Ii(e)&&(console.error(`
198
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Qt(e)&&(console.error(`
199
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}i($i,"installCancelHandler");import{homedir as Uc,userInfo as _c}from"os";var Lc=Uc(),Kc=(()=>{try{return _c().username}catch{return""}})();function ge(e,t=Lc){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(ge,"redactHomedir");function Nc(e,t=Kc){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(Nc,"redactUsername");var Mc=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Ri(e){return e.replace(Mc,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}i(Ri,"redactCredentials");var Hc=1e3,jc="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Bc={captureError:i(async()=>{},"captureError"),flush:i(async()=>{},"flush")};function Vc(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}i(Vc,"buildRelease");var Gc="192.0.2.0";function Yc(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:ge(t.filename)},...t.abs_path!==void 0&&{abs_path:ge(t.abs_path)},...t.module!==void 0&&{module:ge(t.module)}}))}i(Yc,"scrubStackFrames");function nt(e){return Ri(Nc(ge(e)))}i(nt,"redactPii");function qc(e){let t={...e.user,email:void 0,username:void 0,ip_address:Gc,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?nt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Yc(s.stacktrace.frames)}}})),r=e.contexts?.cli,o=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?nt(a):a])):void 0;return{...e,message:e.message!==void 0?nt(e.message):e.message,...typeof e.culprit=="string"&&{culprit:nt(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(qc,"scrubPii");function Ti(e={}){let t=e.env??process.env;if(At(t))return Bc;let n=Vc(e),r="production",o=null,s=null;function a(){return{dsn:jc,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:we},contexts:{cli:{applicationId:we,node:process.version,platform:process.platform}}},beforeSend:qc}}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,Jc(c,l))}catch{}},async flush(c=Hc){try{if(!o)return;await o.flush(c)}catch{}}}}i(Ti,"createErrorReporter");function Jc(e,t){let n={level:"fatal"},r={applicationId:we,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),ln(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},dn(e)&&(n.contexts.http={url:e.requestUrl!==void 0?ge(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:Ri(ge(o))}}return n}i(Jc,"buildCaptureContext");import{mkdirSync as zc,readFileSync as Wc,writeFileSync as Xc}from"fs";import{homedir as Zc}from"os";import{resolve as rt}from"path";import{debuglog as Qc}from"util";import{lt as el,parse as Fi}from"semver";var tl="https://registry.npmjs.org/@cognite/cli/latest",nl=1500,Oi="upgrade-check.json",Ui=rt(process.env.XDG_CACHE_HOME||rt(Zc(),".cache"),"@cognite","cli"),en=Qc("cognite-flows");function rl(e,t){return!e||!t||!Fi(e)||!Fi(t)?!1:el(e,t)}i(rl,"isOutdated");async function il({timeout:e=nl,registryUrl:t=tl,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 en("fetchLatestVersion failed (%s): %O",t,r),null}}i(il,"fetchLatestVersion");function ol(e=Ui,t=864e5){try{let n=Wc(rt(e,Oi),"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 en("readUpgradeCheckCache failed (%s): %O",e,n),null}}i(ol,"readUpgradeCheckCache");function sl(e,t){try{zc(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Xc(rt(e,Oi),JSON.stringify(n))}catch(n){en("writeUpgradeCheckCache failed (%s): %O",e,n)}}i(sl,"writeUpgradeCheckCache");async function al({cacheDir:e=Ui,...t}={}){let n=await il(t);n&&sl(e,n)}i(al,"startBackgroundUpgradeCheck");function _i(e,{onOutdated:t,cacheDir:n,...r}={}){let o=ol(n);if(o){rl(e,o.latest)&&t?.(e,o.latest);return}al({cacheDir:n,...r})}i(_i,"preActionUpgradeCheck");import{default as DS,chalkStderr as Li}from"chalk";function Ki(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(`
200
+ `);return Li.bold.yellow(a)}i(Ki,"formatUpgradeWarning");function ll(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}i(ll,"isDep0040Warning");var nn=process,dl=nn.emit.bind(nn);nn.emit=function(e,...t){return e==="warning"&&ll(t[0])?!1:dl(e,...t)};$i();var fe=new cl;fe.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.8.0").showHelpAfterError().configureOutput({writeOut:i(e=>pl(1,e),"writeOut")});fe.hook("preAction",()=>{_i("1.8.0",{onOutdated:i((e,t)=>{console.warn(`
201
+ ${Ki(e,t)}
202
+ `)},"onOutdated")})});di(fe);Ci(fe);var Mi=je({packageName:"@cognite/cli",cliVersion:"1.8.0"}),Ni=Ti({packageName:"@cognite/cli",cliVersion:"1.8.0"});xi(fe,Mi);var tn=process.argv.slice(2);fe.parseAsync(tn,{from:"user"}).catch(async e=>{await Ai(Mi,tn),Qt(e)&&(console.error(`
203
+ Cancelled.`),process.exit(130)),(!(e instanceof y)||e.shouldReport)&&(await Ni.captureError(e,{command:Zt(tn)}),await Ni.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof y&&(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)});