@cognite/cli 1.5.0 → 1.5.1
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/chunk-MZWFUPT4.js +13 -0
- package/dist/cli/cli.js +78 -78
- package/dist/deploy/index.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5ABVQYYD.js +0 -13
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
var ae=Object.defineProperty;var i=(n,e)=>ae(n,"name",{value:e,configurable:!0});import{mkdir as Oe,readFile as Le}from"fs/promises";import{basename as He,dirname as Be}from"path";var D=class D extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:le(e.cause)}}};i(D,"HintedError");var l=D;var Y="https://docs.cognite.com/cdf/access/",ce="https://status.cognite.com";function pe(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Y};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Y};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:ce};default:return{}}}i(pe,"defaultHintForStatus");var U=class U extends l{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=pe(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var A=U;function ue(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.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 e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.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 e.port?`Port ${e.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(ue,"hintForErrno");function le(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=ue(r.code,r);if(o!==void 0)return o;e=r.cause}}i(le,"hintForCause");var z="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}i(g,"isRecord");function v(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(v,"isHttpError");function de(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${z}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${z}`;default:return}}i(de,"httpStatusHint");function E(n){let e=n instanceof Error?n:new Error(String(n));if(!v(e))return null;let t=de(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
+
${t}`),{cause:e}):null}i(E,"enrichedHttpError");function ge(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}i(ge,"findMissingArray");function he(n,e){if(!v(n)||n.status!==400)return!1;let t=ge(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(he,"isMissingExternalIdError");function N(n,e){return v(n)&&n.status===404||he(n,e)}i(N,"isNotFoundError");var W=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],X=["ACTIVE","PREVIEW"],V=class V extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};i(V,"AppVersionNotFoundError");var b=V;function T(n,e){return n.includes(e)}i(T,"includesValue");function fe(n){return T(W,n)}i(fe,"isAppVersionLifecycleState");function me(n){return T(X,n)}i(me,"isAppVersionAlias");function ye(n){return typeof n.version=="string"&&fe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||me(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(ye,"isAppVersion");function K(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!ye(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}i(K,"parseAppVersion");var _=class _{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(o){throw E(o)??o}}async uploadVersion(e,t,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",t),a.append("entryPath",s);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,u=await this.client.authenticate(),h=`${this.client.getBaseUrl()}${c}`,y=new AbortController,se=setTimeout(()=>y.abort(),300*1e3),S;try{S=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:a,signal:y.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new l("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 l(`Failed to upload version to ${h}`,{cause:f,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(se)}if(!S.ok){let f=await S.text(),w;try{w=JSON.parse(f)}catch{}let x=f;if(g(w)){let k=w.error;if(typeof k=="string")x=k;else if(g(k)){let C=k.message,J=k.code;x=typeof C=="string"?C:J!=null?`Unknown error (code: ${J})`:f}else{let C=w.message;x=typeof C=="string"?C:f}}let G=S.headers.get("x-request-id"),ie=G?` | X-Request-ID: ${G}`:"";throw new A(`Upload failed: ${S.status} \u2014 ${x}${ie}`,{httpStatusCode:S.status,requestUrl:h,responseBody:g(w)?w:f})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return K(a.data)}catch(a){throw N(a,[e,t])?new b(e,t):E(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let o=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(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 K(s[0])}catch(o){if(N(o,[e]))return null;throw E(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:t}})}catch(s){throw E(s)??s}}async submitSignatures(e,t,r){let o=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw E(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return we(a.data)}catch(a){throw E(a)??a}}};i(_,"AppHostingApi");var R=_,Ee=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Se=["developer","certifier"];function we(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Ae(t);return r?[r]:[]})}i(we,"parseStoredSignatures");function Ae(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!T(Se,t)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!T(Ee,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(Ae,"parseStoredSignature");var F=class F{constructor(e){this.api=new R(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,o,s){return this.api.uploadVersion(e,t,r,o,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(o){if(v(o)&&o.status===409){console.log(`\u2705 App '${e}' already exists`);return}throw o}}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let o=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(e,t,r,o,s,a,p=!1){console.log(`
|
|
5
|
+
\u{1F680} Deploying application via App Hosting API...
|
|
6
|
+
`),await this.ensureApp(e,t,r),await this.uploadVersion(e,o,s,a),p&&await this.publishAndActivate(e,o),console.log(`
|
|
7
|
+
\u2705 Deployment successful!`)}};i(F,"AppHostingClient");var I=F;import{execFileSync as $}from"child_process";import m from"fs";import d from"path";import{parseAndValidateManifestConfig as ke}from"@cognite/app-sdk/vite";import{BlobReader as Ce,Uint8ArrayWriter as ve,ZipWriter as Ie}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Z="manifest.json",H=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],B=class B{constructor(e="dist"){this.distPath=d.isAbsolute(e)?e:d.join(process.cwd(),e),this.appRoot=d.dirname(this.distPath)}validateBuildDirectory(){if(!m.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=d.join(this.appRoot,O);if(!m.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=d.join(this.appRoot,L);if(!m.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new Ie(new ve,{level:9}),o=i(async(c,u)=>{await r.add(u,new Ce(await m.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=i(async c=>{let u=await m.promises.readdir(c,{withFileTypes:!0});for(let h of u){let y=d.join(c,h.name);h.isDirectory()?await s(y):await o(y,d.relative(this.distPath,y).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=d.join(this.appRoot,O);await o(c,d.posix.join(H,O));let u=d.join(this.appRoot,Z);if(m.existsSync(u)){let y=m.readFileSync(u,"utf-8");ke(y,u),await o(u,d.posix.join(H,Z))}let h=d.join(this.appRoot,L);await o(h,d.posix.join(H,L)),a=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}try{await m.promises.writeFile(e,a)}catch(c){throw new l(`Failed to write bundle to ${e}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=$("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=$("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(t,s);try{$("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${u}`)}let p=(m.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${d.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=$("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
8
|
+
`).filter(Boolean),o=i(a=>a.split("/").some(p=>Pe.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:
|
|
9
|
+
`+s.map(a=>` ${a}`).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
Hint: git rm --cached <file>`)}};i(B,"ApplicationPackager");var P=B;import xe from"path";var Q=".cognite-bundles";function ee(n,e){return`${n}-${e}.zip`}i(ee,"bundleFileName");function j(n,e,t){return xe.join(n,Q,ee(e,t))}i(j,"bundlePath");import{CogniteClient as Fe}from"@cognite/sdk";function be(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(be,"exponentialBackoffWithJitter");function Te(n){return new Promise(e=>setTimeout(e,n))}i(Te,"sleep");async function te(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??be;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let p=o(s);e.onAttemptFail?.(a,s,p),await Te(p),s++}}i(te,"retryAsync");var Re=i(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function ne({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let o;try{o=await te(()=>fetch(e,t),{maxAttempts:3})}catch(p){throw new l(`Failed to fetch access token from ${e}`,{cause:p})}if(!o.ok){let p=await o.text();throw new A(`Failed to get token from ${n}: ${o.status} ${o.statusText}`,{httpStatusCode:o.status,requestUrl:e,responseBody:p})}let s=await o.text(),a;try{a=JSON.parse(s)}catch{throw new l(`Unexpected response from ${n} authentication (invalid JSON):
|
|
12
|
+
${s}`,{hint:r})}if(!Re(a))throw new l(`No access token in ${n} authentication response:
|
|
13
|
+
${s}`,{hint:r});return a.access_token}i(ne,"fetchOAuthToken");var $e=i(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=o}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),De=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=$e()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),Ue=i(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let e=n.replace(/^https?:\/\//,"");return e=e.split("/")[0],e=e.split(":")[0],e=e.replace(/\.cognitedata\.com$/,""),e}},"extractClusterFromUrl"),Ne=i((n,e)=>ne({idp:"CDF",tokenUrl:"https://auth.cognite.com/oauth2/token",init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${e}`)}`,"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"),Ve=i((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let t=Ue(n);if(!t)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);return`https://${t}.cognitedata.com/.default`},"resolveEntraScope"),_e=i((n,e,t,r,o)=>{let s=Ve(r,o);return ne({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,grant_type:"client_credentials",...s?{scope:s}:{}})},missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."})},"getTokenEntra"),M=i(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p}=n,c=De(r);if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return _e(t,c,s,a,p)}return Ne(t,c)},"getToken");async function q(n,e,t=process.env,r){let o=await M(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new Fe(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}i(q,"getSdk");async function re(n,e,t,r){let{externalId:o,name:s,description:a,versionTag:p}=e,c=j(t,o,p);await Oe(Be(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u;try{u=await Le(c)}catch(h){throw new l(`Failed to read bundle file: ${c}`,{cause:h})}await new I(n).deploy(o,s,a,p,u,He(c),r)}i(re,"packageAndUpload");var je=i(async(n,e,t)=>{let r=await q(n,t);await re(r,e,t,n.published)},"deploy");import{existsSync as Me,readFileSync as qe}from"fs";var oe=[".dev.sig",".cert.sig"];function Ge(n,e={}){let t=e.existsSync??Me,r=e.readFileSync??((s,a)=>qe(s,a)),o=[];for(let s of oe){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Ge,"discoverSignatures");export{I as a,P as b,Q as c,ee as d,j as e,M as f,q as g,re as h,je as i,oe as j,Ge as k};
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
See: ${
|
|
4
|
-
See: ${
|
|
5
|
-
${r}`),{cause:t}):null}o(
|
|
2
|
+
var oo=Object.defineProperty;var o=(e,t)=>oo(e,"name",{value:t,configurable:!0});import{writeSync as qp}from"fs";import{Command as Yp}from"commander";var Ke=class Ke extends Error{constructor(t,r={}){super(t),this.name="HintedError",r.cause!==void 0&&(this.cause=r.cause);let n=this.deriveDefaults(r);this.hint=r.hint??n.hint,this.helpUrl=r.helpUrl??n.helpUrl,this.shouldReport=r.shouldReport??!0}deriveDefaults(t){return{hint:po(t.cause)}}};o(Ke,"HintedError");var h=Ke;function Lt(e){return e instanceof h}o(Lt,"isHintedError");var _t="https://docs.cognite.com/cdf/access/",io="https://status.cognite.com";function so(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:_t};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:_t};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:io};default:return{}}}o(so,"defaultHintForStatus");var je=class je extends h{constructor(t,r){super(t,r),this.name="HintedHttpError",this.httpStatusCode=r.httpStatusCode,this.requestUrl=r.requestUrl,this.responseBody=r.responseBody}deriveDefaults(t){let{httpStatusCode:r}=t,n=so(r),i=super.deriveDefaults(t);return{hint:n.hint??i.hint,helpUrl:n.helpUrl}}};o(je,"HintedHttpError");var z=je;function Nt(e){return e instanceof z}o(Nt,"isHintedHttpError");function ao(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(ao,"hintForErrno");function po(e){let t=e,r=new Set;for(;t!=null&&!r.has(t)&&(r.add(t),typeof t=="object");){let n=t,i=ao(n.code,n);if(i!==void 0)return i;t=n.cause}}o(po,"hintForCause");var Kt="https://docs.cognite.com/cdf/access/";function I(e){return e!==null&&typeof e=="object"}o(I,"isRecord");function W(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(W,"isHttpError");function co(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
3
|
+
See: ${Kt}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
4
|
+
See: ${Kt}`;default:return}}o(co,"httpStatusHint");function X(e){let t=e instanceof Error?e:new Error(String(e));if(!W(t))return null;let r=co(t.status);return r?Object.assign(new Error(`${t.message}
|
|
5
|
+
${r}`),{cause:t}):null}o(X,"enrichedHttpError");function lo(e){if(!I(e))return null;let t=e.missing;if(Array.isArray(t))return t;let r=e.data;if(I(r)){let n=r.error;if(I(n)&&Array.isArray(n.missing))return n.missing;if(Array.isArray(r.missing))return r.missing}return null}o(lo,"findMissingArray");function mo(e,t){if(!W(e)||e.status!==400)return!1;let r=lo(e);return r?r.some(n=>I(n)&&typeof n.externalId=="string"&&t.includes(n.externalId)):!1}o(mo,"isMissingExternalIdError");function Me(e,t){return W(e)&&e.status===404||mo(e,t)}o(Me,"isNotFoundError");var Mt=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Ht=["ACTIVE","PREVIEW"],He=class He extends Error{constructor(t,r){super(`Version ${r} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=r}};o(He,"AppVersionNotFoundError");var j=He;function Se(e,t){return e.includes(t)}o(Se,"includesValue");function uo(e){return Se(Mt,e)}o(uo,"isAppVersionLifecycleState");function go(e){return Se(Ht,e)}o(go,"isAppVersionAlias");function fo(e){return typeof e.version=="string"&&uo(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")}o(fo,"isAppVersion");function jt(e){if(!I(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!fo(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}o(jt,"parseAppVersion");var Ve=class Ve{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,r,n){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:r,description:n}]}})}catch(i){throw X(i)??i}}async uploadVersion(t,r,n,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${r}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(n)]),i),a.append("version",r),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),d=`${this.client.getBaseUrl()}${c}`,m=new AbortController,y=setTimeout(()=>m.abort(),300*1e3),g;try{g=await fetch(d,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:m.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?new h("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new h(`Failed to upload version to ${d}`,{cause:u,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(y)}if(!g.ok){let u=await g.text(),w;try{w=JSON.parse(u)}catch{}let S=u;if(I(w)){let L=w.error;if(typeof L=="string")S=L;else if(I(L)){let A=L.message,M=L.code;S=typeof A=="string"?A:M!=null?`Unknown error (code: ${M})`:u}else{let A=w.message;S=typeof A=="string"?A:u}}let b=g.headers.get("x-request-id"),f=b?` | X-Request-ID: ${b}`:"";throw new z(`Upload failed: ${g.status} \u2014 ${S}${f}`,{httpStatusCode:g.status,requestUrl:d,responseBody:I(w)?w:u})}console.log(`\u2705 Version ${r} uploaded`)}async getVersion(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}`;try{let a=await this.client.get(s);return jt(a.data)}catch(a){throw Me(a,[t,r])?new j(t,r):X(a)??a}}async getActiveVersion(t){let r=encodeURIComponent(t),n=`${this.appsBasePath}/${r}/versions/list`;try{let i=await this.client.post(n,{data:{filter:{aliases:["ACTIVE"]}}});if(!I(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return jt(s[0])}catch(i){if(Me(i,[t]))return null;throw X(i)??i}}async updateVersions(t,r){let n=encodeURIComponent(t),i=`${this.appsBasePath}/${n}/versions/update`;try{await this.client.post(i,{data:{items:r}})}catch(s){throw X(s)??s}}async submitSignatures(t,r,n){let i=encodeURIComponent(t),s=encodeURIComponent(r),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:n}})}catch(p){throw X(p)??p}}async listSignatures(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return So(a.data)}catch(a){throw X(a)??a}}};o(Ve,"AppHostingApi");var we=Ve,yo=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],ho=["developer","certifier"];function So(e){if(!I(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(r=>{let n=wo(r);return n?[n]:[]})}o(So,"parseStoredSignatures");function wo(e){if(!I(e))return null;let{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Se(ho,r)||typeof n!="number"||typeof i!="number"||typeof s!="number"||!Se(yo,a)?null:{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}}o(wo,"parseStoredSignature");var Be=class Be{constructor(t){this.api=new we(t)}getVersion(t,r){return this.api.getVersion(t,r)}uploadVersion(t,r,n,i,s){return this.api.uploadVersion(t,r,n,i,s)}async ensureApp(t,r,n){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,r,n),console.log(`\u2705 App '${t}' created`)}catch(i){if(W(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async submitSignatures(t,r,n){n.length!==0&&(console.log(`\u{1F50F} Submitting ${n.length} signature${n.length===1?"":"s"} for version ${r}...`),await this.api.submitSignatures(t,r,n),console.log("\u2705 Signatures stored"))}listSignatures(t,r){return this.api.listSignatures(t,r)}async publishVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,r){console.log(`\u{1F680} Publishing and activating version ${r}...`),await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${r} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{alias:{setNull:!0}}}])}async activateVersion(t,r){let n=null;try{n=await this.api.getActiveVersion(t)}catch{n=null}let i=n&&n.version!==r?n.version:void 0;return await this.api.updateVersions(t,[{version:r,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,r,n,i,s,a,p=!1){console.log(`
|
|
6
6
|
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
-
`)
|
|
8
|
-
\u2705 Deployment successful!`)}
|
|
9
|
-
${
|
|
10
|
-
${
|
|
7
|
+
`),await this.ensureApp(t,r,n),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
|
|
8
|
+
\u2705 Deployment successful!`)}};o(Be,"AppHostingClient");var k=Be;import{existsSync as Io,readFileSync as $o}from"fs";import{resolve as To}from"path";import{array as Gt,boolean as vo,check as Vt,forward as Bt,literal as Co,maxLength as Eo,minLength as ko,nonEmpty as Z,object as qt,optional as G,picklist as bo,pipe as V,safeParse as Po,string as N,url as xo}from"valibot";var Ge=V(N(),Z("must not be empty")),qe=V(N(),Z("must not be empty"),Eo(256,"must be 256 characters or fewer")),Ye=V(N(),Z("must not be empty"),xo("must be a valid URL")),Je=V(N(),Z("must not be empty")),ze=V(N(),Z("must not be empty")),Ao=V(qt({org:Je,project:ze,baseUrl:Ye,deployClientId:G(N(),""),deploySecretName:G(N(),""),published:G(vo(),!1),idpType:G(bo(["cdf","entra_id"]),"cdf"),tenantId:G(N()),scopes:G(Gt(V(N(),Z("must not be empty"))))}),Bt(Vt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Bt(Vt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Do=qt({name:Ge,externalId:qe,versionTag:V(N(),Z("must not be empty")),description:G(N(),""),deployments:V(Gt(Ao),ko(1,"must contain at least one deployment")),infra:G(Co("appsApi"))});function We(e){let t=Po(Do,e);if(t.success)return t.output;let r=t.issues[0],n=r.path?.map(s=>s.key).join(".")??"",i=n?`"${n}" `:"";throw new Error(`app.json: ${i}${r.message}`)}o(We,"validateAppConfig");function C(e,t={}){let{validator:r=We,existsSync:n=Io,readFileSync:i=$o}=t,s=To(e,"app.json");if(!n(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return r(p)}o(C,"loadAppConfig");import{CogniteClient as ai}from"@cognite/sdk";import{CogniteClient as Mo}from"@cognite/sdk";function Ro(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Ro,"exponentialBackoffWithJitter");function Fo(e){return new Promise(t=>setTimeout(t,e))}o(Fo,"sleep");async function Yt(e,t={}){let r=t.maxAttempts??5,n=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Ro;if(r<1)throw new Error("`maxAttempts` must be 1 or greater");if(r>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=r||!n(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await Fo(p),s++}}o(Yt,"retryAsync");var Oo=o(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function Jt({idp:e,tokenUrl:t,init:r,missingTokenHint:n}){let i;try{i=await Yt(()=>fetch(t,r),{maxAttempts:3})}catch(p){throw new h(`Failed to fetch access token from ${t}`,{cause:p})}if(!i.ok){let p=await i.text();throw new z(`Failed to get token from ${e}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:t,responseBody:p})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new h(`Unexpected response from ${e} authentication (invalid JSON):
|
|
9
|
+
${s}`,{hint:n})}if(!Oo(a))throw new h(`No access token in ${e} authentication response:
|
|
10
|
+
${s}`,{hint:n});return a.access_token}o(Jt,"fetchOAuthToken");var Uo=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),r={};for(let[n,i]of Object.entries(t))if(typeof i=="string"){let s=n.toLowerCase().replace(/_/g,"-");r[s]=i}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),_o=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Uo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Lo=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),No=o((e,t)=>Jt({idp:"CDF",tokenUrl:"https://auth.cognite.com/oauth2/token",init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${t}`)}`,"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"),Ko=o((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let r=Lo(e);if(!r)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`);return`https://${r}.cognitedata.com/.default`},"resolveEntraScope"),jo=o((e,t,r,n,i)=>{let s=Ko(n,i);return Jt({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,grant_type:"client_credentials",...s?{scope:s}:{}})},missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."})},"getTokenEntra"),Xe=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:r,deploySecretName:n,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p}=e,c=_o(n);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return jo(r,c,s,a,p)}return No(r,c)},"getToken");async function ce(e,t,r=process.env,n){let i=await Xe(e,r),s=r.COGNITE_BASE_URL??e.baseUrl,a=(n??(p=>new Mo(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(ce,"getSdk");import zo from"os";import Wo from"path";import Xo from"open";import{buildAuthorizationUrl as Zo,calculatePKCECodeChallenge as Qo,discovery as ei,None as ti,randomPKCECodeVerifier as ri,randomState as ni}from"openid-client";import Ho from"https";import{authorizationCodeGrant as Vo}from"openid-client";function zt(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(zt,"escapeHtml");function Ze(e,t,r){let n=zt(t),i=zt(r);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
11
11
|
<h1>${n}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
12
12
|
@keyframes checkmark {
|
|
13
13
|
0% { transform: scale(0); }
|
|
@@ -16,31 +16,31 @@ ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token
|
|
|
16
16
|
}
|
|
17
17
|
h1 { animation: checkmark 0.5s ease-out; }
|
|
18
18
|
</style>`:""}
|
|
19
|
-
</body></html>`}o(
|
|
20
|
-
`),r.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let n=await
|
|
19
|
+
</body></html>`}o(Ze,"generateHtml");async function Bo(e,t,r,n,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(r,a,{pkceCodeVerifier:n,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Ze("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(Ze("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Bo,"handleCallback");function Go(e){let t=e/6e4,r=Math.round(t*10)/10;return`${r} ${r===1?"minute":"minutes"}`}o(Go,"formatTimeoutMinutes");function Wt(e,t,r,n,i,s={createServer:Ho.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Vo}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,y)=>{try{let g=await Bo(m,y,r,n,i,s);g.shouldClose&&(d(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){d(),p(g instanceof Error?g:new Error(String(g)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Go(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}o(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${m.message}`),p(m)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Wt,"startCallbackServer");import{mkdirSync as qo}from"fs";import{loadLocalCertificates as Yo}from"@cognite/app-sdk/https";var Jo={loadLocalCertificates:Yo,mkdirSync:qo,logger:console};async function Xt(e,t=Jo){t.mkdirSync(e,{recursive:!0});let{cert:r,key:n,source:i}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new h(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:r,key:n}}o(Xt,"getOrCreateCertificates");var oi={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Wo.join(zo.homedir(),".cdf-login")},ii={open:Xo,getOrCreateCertificates:Xt,startCallbackServer:Wt,discovery:ei,buildAuthorizationUrl:Zo,randomPKCECodeVerifier:ri,calculatePKCECodeChallenge:Qo,randomState:ni,logger:console};async function Qt(e,t=oi,r){return r===void 0?Zt(e,t,ii):Zt(e,t,r)}o(Qt,"login");async function si(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,ti())}catch(r){throw new h(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}o(si,"fetchOpenIdConfig");async function Zt(e,t,r){r.logger.log(`\u{1F510} Starting CDF login flow...
|
|
20
|
+
`),r.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let n=await si(r,t),i=r.randomPKCECodeVerifier(),s=await r.calculatePKCECodeChallenge(i),a=r.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(p.organization_hint=e);let c=r.buildAuthorizationUrl(n,p).toString(),l=await r.getOrCreateCertificates(t.certDir);e&&r.logger.log(`\u{1F3E2} Organization: ${e}`),r.logger.log(`\u{1F680} Opening browser for authentication...
|
|
21
21
|
`);try{await r.open(c)}catch(d){let m=d instanceof Error?d.message:String(d);r.logger.error("\u274C Failed to open browser automatically."),r.logger.error(` Reason: ${m}`),r.logger.error(`Please open this URL manually:
|
|
22
|
-
`),r.logger.error(c),r.logger.error("")}return r.startCallbackServer(t,l,n,i,a)}o(
|
|
22
|
+
`),r.logger.error(c),r.logger.error("")}return r.startCallbackServer(t,l,n,i,a)}o(Zt,"loginImpl");async function $(e,t,r={}){let{login:n=Qt,getSdk:i=ce,createClient:s=o(a=>new ai(a),"createClient")}=r;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await n(a),c=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>p.access_token,"getToken")});return await c.authenticate(),c}return i(e,t.appId)}o($,"getClientForDeployment");import er from"enquirer";var tr="Enter custom target...";function rr(e,t){let r=t.map((n,i)=>` ${i}: ${n.org}/${n.project}`).join(`
|
|
23
23
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
24
|
-
${r}`)}o(
|
|
24
|
+
${r}`)}o(rr,"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 n=e[Number.parseInt(t)];if(n)return n;rr(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;rr(t,e)}o(x,"findDeployment");function T(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(T,"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 r=[...e.deployments.map(s=>`${s.org}/${s.project}`),tr],{selected:n}=await er.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==tr){let s=e.deployments.find(a=>`${a.org}/${a.project}`===n);if(s)return s;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await er.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(R,"resolveDeployment");import{existsSync as pi}from"fs";import{resolve as ci}from"path";import{config as li}from"dotenv";function F(e,t={existsSync:pi,config:li}){let r=ci(e,".env");t.existsSync(r)&&(console.log(`Loading environment variables from ${r}`),t.config({path:r}))}o(F,"loadEnvFile");function O(e){e.infra!=="appsApi"&&(console.error(`
|
|
25
25
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
26
26
|
|
|
27
27
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
28
28
|
the old CDF Application Registry. This deploy path has been removed.
|
|
29
29
|
|
|
30
30
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
31
|
-
`),process.exit(1))}o(
|
|
31
|
+
`),process.exit(1))}o(O,"assertAppHostingInfra");async function di(e){let t=process.cwd();F(t);let r=C(t);O(r);let n=e.interactive?await R(r,e):x(r.deployments,e.deployment);if(!e.interactive){let d=T(n);if(d.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await $(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new k(i),{externalId:a,versionTag:p}=r,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`)}o(di,"handleActivate");function nr(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",`
|
|
32
32
|
Examples:
|
|
33
33
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
34
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>
|
|
35
|
-
`),initial:!1};async function
|
|
36
|
-
`),s=`link .specify/memory/constitution.md in specifyDir=${n}`,
|
|
34
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>di(r))}o(nr,"registerActivateCommand");import{basename as vr,dirname as qi,normalize as Yi,resolve as xe}from"path";import{fileURLToPath as Ji,pathToFileURL as zi}from"url";import{Logger as Wi,runner as Xi}from"hygen";import{execFileSync as le}from"child_process";function ve(e={}){let{execFileSync:t=le}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(ve,"isGitInstalled");function Ce(e,t={}){let{execFileSync:r=le}=t;try{return r("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ce,"isInsideGitRepo");function or(e,t={}){let{execFileSync:r=le}=t;r("git",["-C",e,"init"],{stdio:"pipe"}),r("git",["-C",e,"add","."],{stdio:"pipe"}),r("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(or,"gitInitAndCommit");function ir(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(ir,"gitUserName");function sr(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(sr,"gitUserEmail");import{safeParse as mi}from"valibot";function de(e,t){return r=>{let n=mi(t,r);return n.success?!0:`${e} ${n.issues[0].message}`}}o(de,"toPromptValidator");var ar={name:de("App name",qe),displayName:de("Display name",Ge),baseUrl:de("Base URL",Ye),org:de("Org",Je),project:de("Project",ze)};function ui(e,t){return e?async r=>{let n=t(r);return n===!0?e(r):n}:t}o(ui,"composeValidators");function Ee(e){return e.map(t=>{if(!(t.name in ar))return t;let r=ar[t.name];return{...t,validate:ui(t.validate,r)}})}o(Ee,"applySchemaValidators");import{basename as pr}from"path";import cr from"enquirer";function Qe(e){return e.replace(/[A-Z]/g,(t,r)=>r===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(Qe,"kebabCase");var gi={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(`
|
|
35
|
+
`),initial:!1};async function fi(e,t,r){return e!==void 0?e:t?!!(await r([gi])).useSpecKit:!1}o(fi,"resolveSpecKit");function yi(e){return typeof e=="function"}o(yi,"isFunctionInitial");function lr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(lr,"normalizeCluster");function dr({isCurrentDir:e,dirName:t,onAppName:r,onUseSpecKit:n,presets:i={},specKit:s,prompt:a=cr.prompt.bind(cr)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(v=>v[1]!==void 0)),l=Object.keys(c).length>0,d=e?pr(process.cwd()):t?pr(t):null,m=l&&d!==null,y=!m&&d?p.map(v=>v.name==="name"?{...v,initial:d}:v):p,g=Ee(y),u=m&&d?{...c,name:d}:c,w=new Set(Object.keys(u)),S=g.filter(v=>!w.has(v.name)),b=S.findIndex(v=>v.name==="baseUrl"),f;if(m){let v=lr(u.cluster),H=o(E=>yi(E.initial)?E.initial():E.initial,"resolveInitial"),re=o(E=>{if(E.name==="baseUrl")return`https://${v}.cognitedata.com`;let q=H(E);if(q===void 0)throw new Error(`Non-interactive mode: --${Qe(E.name)} has no default. Pass it as a flag.`);return q},"deriveValue");f=Object.fromEntries(S.map(E=>[E.name,re(E)]))}else if(b!==-1){let v=S.filter(D=>D.name!=="baseUrl"),H=v.length>0?await a(v):{},re=typeof H.cluster=="string"?H.cluster:"",q=`https://${lr(re||u.cluster)}.cognitedata.com`,Y=S[b],J=await a([{...Y,initial:q}]);f={...H,...J}}else f=S.length>0?await a(S):{};let L={...u,...f},A=typeof L.name=="string"?L.name:"";A&&r(A);let pe=await fi(s,!m&&S.length>0,a);return n?.(pe),{...L,name:A,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:pe}},"prompt")})}o(dr,"createAppPrompter");async function mr(e,t,r){let n=[];Object.values(t).some(s=>s!==void 0)&&r!==null&&n.push({key:"name",value:r,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&n.push({key:s,value:a,label:`--${Qe(s)}`});for(let{key:s,value:a,label:p}of n){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(mr,"validatePresets");import{cpSync as et,existsSync as Ei,mkdirSync as tt,writeFileSync as ki}from"fs";import{dirname as be,posix as bi,resolve as U}from"path";import{fileURLToPath as gr}from"url";import{copyFileSync as hi,symlinkSync as Si}from"fs";import{dirname as wi,join as vi}from"path";function Ci(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Ci,"errno");function ur(e){return e instanceof Error?e.message:String(e)}o(ur,"messageOf");function ke({target:e,linkPath:t,label:r,symlink:n=Si,copyFile:i=hi}){try{return n(e,t),!0}catch(s){let a=Ci(s);if(a==="EEXIST")return!0;let p=ur(s);if(a==="EPERM"||a==="EACCES")try{let c=vi(wi(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${r} 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 ${r} symlink: ${p} (copy fallback also failed: ${ur(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${r} symlink:`,p),!1}}o(ke,"linkOrCopyOrWarn");var Pi=U(be(gr(import.meta.url)),"..","..","_vendor","spec-kit"),xi=U(be(gr(import.meta.url)),"..","..","_cognite-spec-extensions"),Ai={branch_numbering:"sequential"},Di=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],Ii=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function fr({appDir:e,vendorDir:t=Pi,cogniteExtensionsDir:r=xi}){let n=U(e,".specify"),i=U(n,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of Di){let l=U(e,c);s=`copy ${p} to ${c}`,tt(be(l),{recursive:!0}),et(U(t,p),l,{recursive:!0})}for(let{from:p,to:c}of Ii){let l=U(e,c);s=`copy cognite extension ${p} to ${c}`,tt(be(l),{recursive:!0}),et(U(r,p),l,{recursive:!0})}let a=U(n,"extensions.yml");Ei(a)||(s="write .specify/extensions.yml",et(U(r,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${n}`,ki(U(n,"init-options.json"),`${JSON.stringify(Ai,null,2)}
|
|
36
|
+
`),s=`link .specify/memory/constitution.md in specifyDir=${n}`,tt(i,{recursive:!0}),ke({target:bi.join("..","..","AGENTS.md"),linkPath:U(i,"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})}}o(fr,"installSpecKit");import{execFileSync as Pe}from"child_process";import{mkdtempSync as $i,readdirSync as Ti,rmSync as Ri}from"fs";import{createRequire as Fi}from"module";import{tmpdir as Oi}from"os";import{join as Ui,resolve as yr}from"path";import{InvalidArgumentError as _i}from"commander";import Li from"enquirer";var hr="cognitedata/builder-skills",rt=["claude-code","cursor","github-copilot","opencode","codex"],Ni=Fi(import.meta.url).resolve("skills/bin/cli.mjs");function nt(e,t={}){try{Pe(process.execPath,[Ni,...e],{stdio:"inherit",cwd:process.cwd(),...t})}catch(r){throw new h(`Skills CLI failed (${e.join(" ")})`,{cause:r,hint:"Check your internet connection and that git is installed, then try again."})}}o(nt,"execSkillsCli");function Ki(){return rt.map(e=>["add",hr,"-a",e,"--skill","*","-y"])}o(Ki,"pullAllArgsPerAgent");var ji=1e4;async function Sr(e,t={}){let r=t.exec??nt,n=t.timeout??ji,i=t.readdir??(p=>Ti(p));for(let p of Ki())try{r(p,{cwd:e,timeout:n,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[yr(e,".claude","skills"),yr(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(Sr,"pullAllSkillsInto");function Mi(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new _i("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Mi,"validateSource");function Hi(e){let t=$i(Ui(Oi(),"skills-"));try{try{Pe("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 r;try{r=Pe("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{r=Pe("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return r.toString().trim().split(/\r?\n/).filter(n=>!!n&&!n.startsWith("."))}finally{Ri(t,{recursive:!0,force:!0})}}o(Hi,"listRemoteSkills");async function Vi(e,t={}){let r=o(p=>Li.prompt(p),"defaultPrompt"),{listSkills:n=Hi,prompt:i=r}=t,s=n(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(Vi,"pickSkillsInteractive");function Bi(e,t,r){let n=["add",e.source,"-a",t];return e.skill?n.push("--skill",e.skill):r&&r.length>0?n.push("--skill",...r,"-y"):n.push("--skill","*","-y"),e.global&&n.push("--global"),n}o(Bi,"buildPullArgs");async function Gi(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Vi(e.source)}catch(n){let i=n instanceof Error?n.message:String(n);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let r=!1;for(let n of rt)try{nt(Bi(e,n,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${n}: ${s}`),r=!0}r?(console.log(`
|
|
37
37
|
Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
|
|
38
|
-
Skills pulled successfully`)}o(
|
|
39
|
-
Supports: ${
|
|
38
|
+
Skills pulled successfully`)}o(Gi,"handlePull");function wr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
|
|
39
|
+
Supports: ${rt.join(", ")}`).addHelpText("after",`
|
|
40
40
|
Examples:
|
|
41
41
|
npx @cognite/cli apps skills pull Pull all skills
|
|
42
42
|
npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
|
|
43
|
-
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",
|
|
43
|
+
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",Mi,hr).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(Gi),t.command("list").description("List installed skills").action(()=>{nt(["list"])}),t}o(wr,"registerSkillsCommand");var Cr=xe(qi(Ji(import.meta.url)),"..","..","_templates");async function Zi(){let e=xe(Cr,"app","new","prompt.js");return(await import(zi(e).href)).default}o(Zi,"loadPromptDefs");function Qi(e,t){return!e||t?null:Yi(e)}o(Qi,"resolveDirName");function es(e,t,r){if(e)return{cwd:process.cwd(),display:"."};let n=t??r;if(!n)throw new Error("App creation completed without a target directory or name.");return{cwd:xe(process.cwd(),n),display:n}}o(es,"resolveAppLocation");function ts(e,t,r){let n=` npm install
|
|
44
44
|
npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=r?`
|
|
45
45
|
To start spec-driven development:
|
|
46
46
|
Run /speckit.specify in Claude Code or Cursor and describe your app.
|
|
@@ -67,7 +67,7 @@ ${i}
|
|
|
67
67
|
cd "${t}"
|
|
68
68
|
${s}
|
|
69
69
|
${p}
|
|
70
|
-
`)}o(
|
|
70
|
+
`)}o(ts,"printSuccessMessage");async function rs(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await Sr(e)}catch(t){let r=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",r)}}o(rs,"pullSkillsInto");function ns(e,t={}){let{isGitInstalled:r=ve,isInsideGitRepo:n=Ce,gitInitAndCommit:i=or}=t;if(!r()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!n(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(ns,"maybeInitGit");async function os(e,t){let r=e==="."||e==="./",n=Qi(e,r),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Zi(),c=Ee(p),l=r?vr(process.cwd()):n?vr(n):null;await mr(c,a,l);let d=dr({isCurrentDir:r,dirName:n,onAppName:o(y=>{i=y},"onAppName"),onUseSpecKit:o(y=>{s=y},"onUseSpecKit"),presets:a,specKit:t.specKit});await Xi(["app","new"],{templates:Cr,cwd:process.cwd(),logger:new Wi(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=es(r,n,i);ke({target:"AGENTS.md",linkPath:xe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&fr({appDir:m.cwd}),await rs(m.cwd),ns(m.cwd),ts(r,m.display,s)}o(os,"handleCreate");function Er(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",`
|
|
71
71
|
Non-interactive use (CI, scripts, AI agents):
|
|
72
72
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
73
73
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -80,22 +80,22 @@ Examples:
|
|
|
80
80
|
--display-name "My App" --description "My app" \\
|
|
81
81
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
82
82
|
--base-url https://greenfield.cognitedata.com
|
|
83
|
-
Fully non-interactive`).action(
|
|
83
|
+
Fully non-interactive`).action(os)}o(Er,"registerCreateCommand");import is from"path";async function ss(e,t,r){let n=await $(e,{interactive:t.interactive,appId:r,orgHint:t.org});return new k(n)}o(ss,"defaultGetApiClient");async function as(e,t,r={}){let{loadEnvFile:n=F,loadAppConfig:i=C,getApiClient:s=ss}=r,a=is.resolve(process.cwd(),e);n(a);let p=i(a);O(p);let c=t.interactive?await R(p,t):x(p.deployments,t.deployment);if(!t.interactive){let y=T(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.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`)}o(as,"handleDeactivate");function kr(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",`
|
|
84
84
|
Examples:
|
|
85
85
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
86
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,r)=>
|
|
87
|
-
`).filter(Boolean),i=o(a=>a.split("/").some(p=>
|
|
86
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,r)=>as(t,r))}o(kr,"registerDeactivateCommand");import{mkdir as gs,readFile as fs}from"fs/promises";import{basename as ys,dirname as hs}from"path";import{execFileSync as Ae}from"child_process";import B from"fs";import P from"path";import{parseAndValidateManifestConfig as ps}from"@cognite/app-sdk/vite";import{BlobReader as cs,Uint8ArrayWriter as ls,ZipWriter as ds}from"@zip.js/zip.js";var ot="package.json",it="package-lock.json",br="manifest.json",st=".cognite",ms=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],at=class at{constructor(t="dist"){this.distPath=P.isAbsolute(t)?t:P.join(process.cwd(),t),this.appRoot=P.dirname(this.distPath)}validateBuildDirectory(){if(!B.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=P.join(this.appRoot,ot);if(!B.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let r=P.join(this.appRoot,it);if(!B.existsSync(r))throw new Error(`"${r}" not found. It is required for deployment.`)}async createZip(t="app.zip",r=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let n=new ds(new ls,{level:9}),i=o(async(c,l)=>{await n.add(l,new cs(await B.openAsBlob(c))),r&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await B.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=P.join(c,d.name);d.isDirectory()?await s(m):await i(m,P.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=P.join(this.appRoot,ot);await i(c,P.posix.join(st,ot));let l=P.join(this.appRoot,br);if(B.existsSync(l)){let m=B.readFileSync(l,"utf-8");ps(m,l),await i(l,P.posix.join(st,br))}let d=P.join(this.appRoot,it);await i(d,P.posix.join(st,it)),a=await n.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await B.promises.writeFile(t,a)}catch(c){throw new h(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let r;try{r=Ae("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 n=Ae("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=n?n.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(r,s);try{Ae("git",["-C",r,"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=(B.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${P.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,r){let n=Ae("git",["-C",t,"ls-tree","-r","--name-only",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
87
|
+
`).filter(Boolean),i=o(a=>a.split("/").some(p=>ms.some(c=>c.test(p))),"isSensitive"),s=n.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
88
88
|
`+s.map(a=>` ${a}`).join(`
|
|
89
89
|
`)+`
|
|
90
|
-
Hint: git rm --cached <file>`)}};o(
|
|
91
|
-
`))}o(
|
|
90
|
+
Hint: git rm --cached <file>`)}};o(at,"ApplicationPackager");var Q=at;import us from"path";var Pr=".cognite-bundles";function xr(e,t){return`${e}-${t}.zip`}o(xr,"bundleFileName");function ee(e,t,r){return us.join(e,Pr,xr(t,r))}o(ee,"bundlePath");async function De(e,t,r,n){let{externalId:i,name:s,description:a,versionTag:p}=t,c=ee(r,i,p);await gs(hs(c),{recursive:!0}),await new Q(`${r}/dist`).createZip(c,!0);let l;try{l=await fs(c)}catch(d){throw new h(`Failed to read bundle file: ${c}`,{cause:d})}await new k(e).deploy(i,s,a,p,l,ys(c),n)}o(De,"packageAndUpload");var pt=o(async(e,t,r)=>{let n=await ce(e,r);await De(n,t,r,e.published)},"deploy");import{existsSync as Ss,readFileSync as ws}from"fs";var Ar=[".dev.sig",".cert.sig"];function me(e,t={}){let r=t.existsSync??Ss,n=t.readFileSync??((s,a)=>ws(s,a)),i=[];for(let s of Ar){let a=`${e}${s}`;if(!r(a))continue;let p=n(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(me,"discoverSignatures");import{execSync as vs}from"child_process";function ct(e,t=!0,r={execSync:vs}){console.log("\u{1F4E6} Building app with npm...");try{r.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(n){throw new h(`npm run build failed in ${e}`,{cause:n,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}o(ct,"buildApp");function Dr(e,t){let{org:r,project:n,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${r}.fusion.cognite.com/${n}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(Dr,"generateFusionUrl");function Ir(e,t,r){let n=r?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=r?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",n,"=".repeat(n.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
|
|
91
|
+
`))}o(Ir,"printDeployInfo");function $r(e,t){console.log(`
|
|
92
92
|
\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 r=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
|
|
93
93
|
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(`
|
|
94
|
-
To submit for certification: npx @cognite/cli apps submit`);let n=
|
|
94
|
+
To submit for certification: npx @cognite/cli apps submit`);let n=Dr(t,e);n&&console.log(`
|
|
95
95
|
\u{1F517} Open your app:
|
|
96
|
-
${n}`)}o(
|
|
97
|
-
\u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r)
|
|
98
|
-
\u{1F4E4} Deploying to ${t.project}...`),await De(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r,!1)
|
|
96
|
+
${n}`)}o($r,"printDeployResult");async function Cs(e,t,r,n,i){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.`);Ir(e,t,!1),n.skipBuild||ct(r),console.log(`
|
|
97
|
+
\u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r),$r(e,t)}o(Cs,"handleDeployNonInteractive");async function Es(e,t,r,n){Ir(e,t,!0),n.skipBuild||ct(r);let i=await $(t,{interactive:!0,appId:e.externalId,orgHint:n.org});console.log(`
|
|
98
|
+
\u{1F4E4} Deploying to ${t.project}...`),await De(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r,!1),$r(e,t)}o(Es,"handleDeployInteractive");async function ks(e,t=process.cwd(),r={}){let{loadEnvFile:n=F,loadAppConfig:i=C,deploy:s=pt}=r;n(t);let a=i(t);if(O(a),e.interactive){let c=await R(a,e);await Es(a,c,t,e);return}let p=x(a.deployments,e.deployment);await Cs(a,p,t,e,s)}o(ks,"handleDeploy");function Tr(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",`
|
|
99
99
|
Environment (non-interactive):
|
|
100
100
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
101
101
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -109,79 +109,79 @@ Examples:
|
|
|
109
109
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
110
110
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
111
111
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
112
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>
|
|
112
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>ks(t))}o(Tr,"registerDeployCommand");async function bs(e,t,r){let n=await $(e,{interactive:t.interactive,appId:r.externalId,orgHint:t.org});return new k(n)}o(bs,"defaultBuildApiClient");async function Ps(e,t={}){let r=t.loadEnvFile??F,n=t.loadAppConfig??C,i=t.buildApiClient??bs,s=t.discoverSignatures??me,a=process.cwd();r(a);let p=n(a);O(p);let c=e.interactive?await R(p,e):x(p.deployments,e.deployment);if(!e.interactive){let u=T(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 i(c,e,p),{externalId:d,versionTag:m}=p,y;try{y=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(y.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${y.lifecycleState} (terminal).`);let g=s(ee(a,d,m));g.length>0&&await l.submitSignatures(d,m,g),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.")}o(Ps,"handlePublish");function Rr(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",`
|
|
113
113
|
Examples:
|
|
114
114
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
115
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>
|
|
115
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>Ps(r))}o(Rr,"registerPublishCommand");import{spawnSync as xs}from"child_process";import{mkdirSync as As}from"fs";import{resolve as lt}from"path";var Ds=["localhost","local.cognite.ai","*.local.cognite.ai"],Is={info:o(e=>{process.stdout.write(`${e}
|
|
116
116
|
`)},"info"),error:o(e=>{process.stderr.write(`${e}
|
|
117
|
-
`)},"error")}
|
|
117
|
+
`)},"error")},$s={spawnSync:xs,mkdirSync:As,logger:Is};function Ts(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(Ts,"hasMkcert");function Rs({certDir:e=lt(process.cwd(),"certificates/mkcert"),domains:t=Ds,deps:r={}}={}){let n={...$s,...r},{spawnSync:i,mkdirSync:s,logger:a}=n;if(!Ts(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=lt(e,"localhost.pem"),l=lt(e,"localhost-key.pem");if(i("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}}o(Rs,"setupHttps");function Fs(e){Rs({certDir:e.certDir})}o(Fs,"handleSetupHttps");function Fr(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",`
|
|
118
118
|
Examples:
|
|
119
119
|
npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
|
|
120
|
-
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>
|
|
121
|
-
${e}`)}}o(
|
|
122
|
-
${e}`)}}o(_r,"revealInFileManager");var
|
|
120
|
+
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>Fs(t))}o(Fr,"registerSetupHttpsCommand");import{createReadStream as ya,existsSync as ha,writeFileSync as Sa}from"fs";import{basename as wa,dirname as va,join as Ca,resolve as St}from"path";import{parseScope as Ea,signBundle as ka,validateScopes as ba}from"@cognite/app-sdk/codesigning";import{existsSync as ua,readFileSync as ga}from"fs";import{execFile as _s}from"child_process";import{promisify as Ls}from"util";import{execFileSync as Or}from"child_process";import{platform as Os}from"os";import Us from"path";function K(e,t={}){let{platform:r=Os}=t;switch(r()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(K,"isOS");function Ur(e,t={}){let{exec:r=Or,log:n=console.log}=t,[i,s]=K("macos",t)?["open",[e]]:K("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{r(i,s)}catch{n(`Could not open browser \u2014 open manually:
|
|
121
|
+
${e}`)}}o(Ur,"openInBrowser");function _r(e,t={}){let{exec:r=Or,log:n=console.log}=t,[i,s]=K("macos",t)?["open",["-R",e]]:K("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Us.dirname(e)]];try{r(i,s)}catch{n(`Could not open file manager \u2014 files are at:
|
|
122
|
+
${e}`)}}o(_r,"revealInFileManager");var Nr="cognite-flows",Ns=Ls(_s),Kr=o((e,t)=>Ns(e,t),"defaultExecFile"),Ks=-25300,js=Ks&255;function Ms(e){if(!(e instanceof Error)||!("code"in e)||e.code!==js)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Ms,"isKeychainNotFoundError");async function jr(e,t,r={}){if(!K("macos",r))throw new Error("Keychain storage is only supported on macOS");let{execFile:n=Kr}=r;await n("security",["add-generic-password","-a",e,"-s",Nr,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(jr,"storeKeyInKeychain");async function Ie(e,t={}){if(!K("macos",t))return null;let{execFile:r=Kr}=t;try{let{stdout:n}=await r("security",["find-generic-password","-a",e,"-s",Nr,"-w"]);return Buffer.from(n.trim(),"base64").toString("utf-8")}catch(n){if(Ms(n))return null;throw n}}o(Ie,"readKeyFromKeychain");import{homedir as Hs}from"os";import{join as Mr}from"path";function _(e={}){let{env:t=process.env,homedir:r=Hs}=e,n=t.COGNITE_CLI_HOME?.trim()||Mr(r(),".cognite-cli");return{home:n,keysDir:Mr(n,"keys")}}o(_,"getConfig");import{pbkdf2 as Gs,randomBytes as qs}from"crypto";import{promisify as Ys}from"util";import{CompactEncrypt as Js,base64url as Hr,compactDecrypt as zs}from"jose";var Vs=new TextEncoder,Bs=new TextDecoder,dt={encode:o(e=>Vs.encode(e),"encode"),decode:o(e=>Bs.decode(e),"decode")};var Ws=Ys(Gs),gt=6e5,Xs="sha512",mt="PBKDF2-HMAC-SHA512",ut=16,$e="A256GCM",Zs=32,Te=2e6;async function Vr(e,t,r){return await Ws(e,t,r,Zs,Xs)}o(Vr,"deriveKey");async function Br(e,t,r=gt){if(!Number.isInteger(r)||r<1||r>Te)throw new Error(`Invalid iterations: must be an integer between 1 and ${Te}`);let n=qs(ut),i=await Vr(t,n,r);return await new Js(dt.encode(e)).setProtectedHeader({alg:"dir",enc:$e,kdf:mt,kdf_iter:r,kdf_salt:Hr.encode(n)}).encrypt(i)}o(Br,"encryptStringAsJwe");async function Gr(e,t){let{plaintext:r}=await zs(e,async n=>{if(!e.length)throw new Error("Unexpected JWE empty value");if(t.length<15)throw new Error(`Invalid passphrase it should be at least ${15} but got ${t.length}`);if(n.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(n.alg)}"; only "dir" is supported`);if(n.enc!==$e)throw new Error(`Unexpected JWE enc "${String(n.enc)}"; only "${$e}" is supported`);if(n.kdf!==mt)throw new Error(`Unexpected KDF "${String(n.kdf)}"; only "${mt}" is supported`);let i=Number(n.kdf_iter);if(!Number.isInteger(i)||i<1||i>Te)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Te}`);if(typeof n.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=Hr.decode(n.kdf_salt);if(s.length!==ut)throw new Error(`Invalid kdf_salt length in JWE header: expected ${ut} bytes, got ${s.length}`);return await Vr(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[$e]});return dt.decode(r)}o(Gr,"decryptJweAsString");function Qs(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Qs,"isJweCompact");var qr=Qs;import{existsSync as ea,readdirSync as ta,readFileSync as ra}from"fs";import{join as ft}from"path";var ne=".pub.pem",yt=".key.jwe",ht=".meta.json";function Re(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(Re,"formatLocalKeySource");function na(e){return{existsSync:e.existsSync??ea,readdirSync:e.readdirSync??ta,readFileSync:e.readFileSync??((t,r)=>ra(t,r)),isOS:e.isOS??(t=>K(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Ie(t))}}o(na,"resolveDeps");function oa(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(oa,"readEmailFromMeta");function ia(e,t){return t.existsSync(e)?t.readdirSync(e).filter(r=>r.endsWith(ne)):[]}o(ia,"publicKeyEntries");function sa(e){return e.slice(0,-ne.length)}o(sa,"kidFromPublicKeyFilename");async function aa(e,t,r){if(r.isOS("macos")&&await r.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let n=ft(t,`${e}${yt}`);return r.existsSync(n)?{kind:"encrypted-file",path:n}:{kind:"public-only"}}o(aa,"resolveSource");async function Fe(e=_().keysDir,t={}){let r=na(t),n=new Set,i=ia(e,r).flatMap(s=>{let a=sa(s);return!a||n.has(a)?[]:(n.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await aa(s,e,r),c=ft(e,`${s}${ht}`),l;try{l=oa(r.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:ft(e,a),email:l}}))}o(Fe,"discoverLocalKeys");import pa from"enquirer";async function ca(e){return pa.prompt(e)}o(ca,"defaultPrompt");async function Yr(e,t={}){let{prompt:r=ca}=t,{passphrase:n}=await r({type:"password",name:"passphrase",message:e});return n}o(Yr,"promptPassphrase");import da from"enquirer";import{statSync as la}from"fs";function Jr(e,t=la){return e.map(r=>({key:r,mtime:t(r.publicKeyPath).mtimeMs})).sort((r,n)=>n.mtime-r.mtime).map(({key:r})=>r)}o(Jr,"sortByMtime");async function ma(e){return da.prompt(e)}o(ma,"defaultPrompt");async function zr(e,t={}){if(e.length===1)return e[0];let{prompt:r=ma,sortByMtime:n=Jr}=t,i=n(e),s=i[0],{choice:a}=await r({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 r({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,Re(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(zr,"promptSigningIdentity");function fa(e){return{existsSync:e.existsSync??ua,readFileSync:e.readFileSync??((t,r)=>ga(t,r)),readKeyFromKeychain:e.readKeyFromKeychain??Ie,decryptJweAsString:e.decryptJweAsString??Gr,discoverLocalKeys:e.discoverLocalKeys??Fe,keysDir:e.keysDir??_().keysDir,promptPassphrase:e.promptPassphrase??Yr,promptSigningIdentity:e.promptSigningIdentity??zr}}o(fa,"resolveDeps");async function Wr(e,t={}){let r=fa(t);if(e.keyPath){if(!r.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=r.readFileSync(e.keyPath,"utf-8").trim();if(qr(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await r.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await r.decryptJweAsString(s,a),kid:e.kid}}return{privateKeyPem:s,kid:e.kid}}let n=await r.discoverLocalKeys(r.keysDir);if(n.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=n.find(s=>s.kid===e.kid);else if(e.interactive)i=await r.promptSigningIdentity(n);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await r.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await r.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await r.decryptJweAsString(r.readFileSync(i.source.path,"utf-8"),s),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(Wr,"resolvePrivateKey");var Pa=o(async(e,t,r,n,i)=>{let s=await $(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new k(s).submitSignatures(t,r,n)},"defaultSubmitSignatures");function xa(e){let t=ya(e);return new ReadableStream({start(r){t.on("data",n=>{let i=typeof n=="string"?Buffer.from(n):n;r.enqueue(new Uint8Array(i))}),t.on("end",()=>r.close()),t.on("error",n=>r.error(n))},cancel(){t.destroy()}})}o(xa,"createWebStreamFromFile");function Aa(e){return{existsSync:e.existsSync??ha,writeFileSync:e.writeFileSync??Sa,createBundleStream:e.createBundleStream??xa,signBundle:e.signBundle??ka,parseScope:e.parseScope??Ea,validateScopes:e.validateScopes??ba,loadAppConfig:e.loadAppConfig??C,resolvePrivateKey:e.resolvePrivateKey??(t=>Wr(t)),submitSignatures:e.submitSignatures??Pa,discoverSignatures:e.discoverSignatures??me}}o(Aa,"resolveDeps");async function Xr(e,t,r={},n=process.cwd()){let i=Aa(r),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(n);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(f=>({org:f.org,project:f.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?St(n,e):ee(n,s,a);if(!i.existsSync(l)){let f=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}${f}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
|
|
123
123
|
${d.join(`
|
|
124
|
-
`)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?
|
|
125
|
-
Payload:`,JSON.stringify(u.payload,null,2));let
|
|
126
|
-
To publish: npx @cognite/cli apps publish .`)}o(
|
|
124
|
+
`)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?St(n,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),g=i.createBundleStream(l),u=await i.signBundle({privateKeyPem:m,kid:y,appId:s,version:a,bundleStream:g,role:t.asCertifier?"certifier":"developer",scopes:p}),w=t.output?St(n,t.output):Ca(va(l),`${wa(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(w,u.token,"utf-8"),console.log(`\u2705 Signed: ${w}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(f=>`${f.org}/${f.project}`).join(", ")}`),t.verbose&&console.log(`
|
|
125
|
+
Payload:`,JSON.stringify(u.payload,null,2));let S=Array.from(new Set([...i.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 f=T(b);if(f.length>0)throw new Error(`Deployment ${b.org}/${b.project} is missing ${f.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(b,s,a,S,t),console.log(`
|
|
126
|
+
To publish: npx @cognite/cli apps publish .`)}o(Xr,"handleSign");function Zr(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((r,n)=>{let i={...n,appid:n.identifier??n.appid,scope:n.requirements??n.scope};return Xr(r,i,t)})}o(Zr,"registerSignCommand");function Da(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(Da,"describeStatus");function Ia(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let r of e){let n=r.status==="VALID"?"\u2705":"\u274C",i=new Date(r.signatureIat).toISOString();t.push(` ${n} ${r.signerKid} (${r.signerRole}, signed ${i}) \u2014 ${r.status}`)}return t}o(Ia,"formatSignatures");async function $a(e){let t=process.cwd();F(t);let r=C(t);O(r);let n=e.interactive?await R(r,e):x(r.deployments,e.deployment);if(!e.interactive){let a=T(n);if(a.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await $(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new k(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let a=await s.getVersion(r.externalId,r.versionTag);console.log(`Status: ${Da(a)}`);let p=await Ta(s,r.externalId,r.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Ia(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}}o($a,"handleStatus");async function Ta(e,t,r){try{return await e.listSignatures(t,r)}catch(n){if(W(n)&&n.status===404||n instanceof Error&&/status code: 404/.test(n.message))return"endpoint-unavailable";throw n}}o(Ta,"fetchSignatures");function Qr(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",`
|
|
127
127
|
Examples:
|
|
128
128
|
npx @cognite/cli apps status . Status using env-var auth
|
|
129
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)
|
|
130
|
-
`))}</pre>`,p=
|
|
131
|
-
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(
|
|
129
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)=>$a(r))}o(Qr,"registerStatusCommand");import{execFileSync as Ct}from"child_process";import vt from"fs";import ue from"path";import Ua from"readline";var en="https://cognite.zendesk.com",Ra="360001234312",Fa="tf_360015295097",Oa="cognite_flows_certifications";function tn(e,t,r){let n=new URLSearchParams({ticket_form_id:Ra,tf_priority:"normal",tf_subject:e,[Fa]:Oa,tf_description:t});return`${r}/hc/en-us/requests/new?${n}`}o(tn,"buildUrl");function rn(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}o(rn,"escapeHtml");function wt(e){return e.map(rn).join("<br>")}o(wt,"toHtml");function nn(e,t=en){let{appName:r,externalId:n,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${r}`,`App external ID: ${n}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${n}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return tn(`App Review Request: ${r}`,wt(l.filter(d=>d!==void 0)),t)}o(nn,"buildAppReviewUrl");function on(e,t,r,n,i=en){let s=wt(["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: ${r}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${rn(n.replace(/\r\n/g,`
|
|
130
|
+
`))}</pre>`,p=wt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return tn(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(on,"buildKeyRegistrationUrl");function _a(){return new Promise(e=>{let t=Ua.createInterface({input:process.stdin,output:process.stdout});t.question(`
|
|
131
|
+
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(_a,"defaultPressEnter");var La=[{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 Na(e){let t=La.filter(({pattern:r})=>Ct("git",["-C",e,"ls-files","--",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let r=t.map(({label:n,skill:i})=>` ${n} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
|
|
132
132
|
|
|
133
133
|
`+r.join(`
|
|
134
|
-
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(
|
|
134
|
+
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(Na,"assertArtifactsCommitted");async function Ka(e=process.cwd(),t={}){let{openInBrowser:r=Ur,revealInFileManager:n=_r,pressEnter:i=_a,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!ve())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!Ce(e))throw new Error("Not a git repository. Run this command from your app's root directory.");F(e);let a=C(e);O(a),Na(e);let p=ue.join(e,"dist","submit");vt.mkdirSync(p,{recursive:!0});let c=Ct("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Ct("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.
|
|
135
135
|
|
|
136
|
-
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=ue.join(p,d);await new
|
|
137
|
-
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(
|
|
136
|
+
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=ue.join(p,d);await new Q(ue.join(e,"dist")).createSourceArchive(m);let g=`${a.externalId}-${a.versionTag}.zip`,u=ue.join(e,".cognite-bundles",g),w=!1;vt.existsSync(u)&&(vt.copyFileSync(u,ue.join(p,g)),w=!0);let S=nn({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:ir(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
|
|
137
|
+
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(w?` ${g} \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(`
|
|
138
138
|
Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
|
|
139
|
-
\u{1F517} ${
|
|
139
|
+
\u{1F517} ${S}`),s()&&(await i(),r(S),n(m))}o(Ka,"handleSubmit");function sn(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
|
|
140
140
|
Examples:
|
|
141
|
-
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>
|
|
142
|
-
`,"passphraseMismatchMsg"),
|
|
141
|
+
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Ka())}o(sn,"registerSubmitCommand");function an(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Er(t),Tr(t),Qr(t),Rr(t),nr(t),kr(t),Fr(t),sn(t),wr(t),Zr(t),t}o(an,"registerAppsCommand");import{existsSync as Za,mkdirSync as Qa,writeFileSync as ep}from"fs";import{dirname as Dt,join as ye}from"path";import{generateSigningKeyPair as tp}from"@cognite/app-sdk/codesigning";import rp from"open";import bt from"enquirer";import{email as ja,pipe as Ma,safeParse as Ha,string as Va}from"valibot";var Ba=Ma(Va(),ja());function oe(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!Ha(Ba,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(oe,"parseEmail");function ie(e,t="--expires"){let r=Number(e);if(!Number.isInteger(r)||r<1||r>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return r}o(ie,"parseExpiryMonths");var Oe=3,pn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",cn=`Key expiry in months (${1}-${12})`,ln="Email address for the registry entry",dn=`Passphrase for the encrypted private key (min ${15} chars)`,mn="Confirm passphrase",un=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),gn=o(e=>`Passphrases do not match (attempt ${e}/${Oe}).
|
|
142
|
+
`,"passphraseMismatchMsg"),fn=`Passphrase confirmation failed after ${Oe} attempts`,yn=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),hn="How would you like to submit your key registration?",Sn="Open in browser",wn="Copy link to clipboard";async function Ue(e){return bt.prompt(e)}o(Ue,"defaultPrompt");function Pt(e){return t=>{try{return e(t),!0}catch(r){return r instanceof Error?r.message:"Invalid"}}}o(Pt,"parserAsValidator");var qa=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function ge(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!qa.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}o(ge,"parseKid");async function vn(e={}){let{prompt:t=Ue}=e,{kid:r}=await t({type:"input",name:"kid",message:pn,validate:Pt(ge)});return ge(r)}o(vn,"promptKid");async function Cn(e={}){let{prompt:t=o(n=>bt.prompt(n),"prompt")}=e,{action:r}=await t({type:"select",name:"action",message:hn,choices:[{name:"browser",message:Sn},{name:"clipboard",message:wn}]});if(r!=="browser"&&r!=="clipboard")throw new Error(`Unexpected Zendesk action: ${r}`);return r}o(Cn,"promptZendeskAction");async function En(e={}){let{prompt:t=Ue}=e,{months:r}=await t({type:"input",name:"months",message:cn,initial:String(6),validate:Pt(n=>ie(n,"expiry"))});return ie(r,"expiry")}o(En,"promptExpiryMonths");async function kn(e={}){let{prompt:t=Ue,gitUserEmail:r=sr}=e,{email:n}=await t({type:"input",name:"email",message:ln,initial:r(),validate:Pt(i=>oe(i,"email"))});return oe(n,"email")}o(kn,"promptEmail");async function bn(e={}){let{prompt:t=Ue,stderr:r=process.stderr}=e;for(let n=1;n<=Oe;n+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:dn,validate:o(a=>a.length>=15?!0:un(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:mn});if(i===s)return i;r.write(gn(n))}throw new Error(fn)}o(bn,"promptPassphrase");async function Pn(e,t={}){let{prompt:r=o(i=>bt.prompt(i),"prompt")}=t,{confirmed:n}=await r({type:"confirm",name:"confirmed",message:yn(e),initial:!1});return n}o(Pn,"promptConfirmOverwrite");function xn(e,t){let r=e.getUTCFullYear(),n=e.getUTCMonth()+t,i=new Date(Date.UTC(r,n+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(r,n,s))}o(xn,"addMonthsClamped");function xt(e){return e.toISOString().slice(0,10)}o(xt,"formatIsoDate");function An(e=new Date){return xt(e)}o(An,"todayIso");import Ya,{Chalk as Ja}from"chalk";var fe=new Ja({level:0});function Dn(e){return e.isTTY?Ya:fe}o(Dn,"chalkForStream");var _e=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),In=32,$n=44,Tn=60,za="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Wa(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==$n&&t.length!==Tn)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${$n} (raw) or ${Tn} (X.509-wrapped)`);let r=Buffer.from(t,"base64");if(r.length===_e.length+In&&r.subarray(0,_e.length).equals(_e))return r.subarray(_e.length).toString("base64");if(r.length===In)return r.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${r.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(Wa,"pemBodyOneLine");function At(e,t=fe,r=new Date){let n=Rn(e.issuedAt??An(r)),i=Rn(e.expires),s=Wa(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
|
|
143
143
|
`,"kv"),c="";return c+=`
|
|
144
|
-
${t.bold("Add this entry to")} ${t.magenta(
|
|
144
|
+
${t.bold("Add this entry to")} ${t.magenta(za)} ${t.bold("under")} ${t.cyan("publicKeys:")}
|
|
145
145
|
|
|
146
146
|
`,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
147
|
-
`,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(n)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(
|
|
147
|
+
`,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(n)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(At,"renderRegistryYamlBlock");function Rn(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let r=new Date(t);if(Number.isNaN(r.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return r.toISOString()}o(Rn,"toIsoInstant");import Xa from"clipboardy";function Fn(e){return Xa.write(e)}o(Fn,"copyToClipboard");function np(e){return{writeFileSync:e.writeFileSync??ep,mkdirSync:e.mkdirSync??Qa,existsSync:e.existsSync??Za,generateSigningKeyPair:e.generateSigningKeyPair??tp,encryptStringAsJwe:e.encryptStringAsJwe??Br,storeKeyInKeychain:e.storeKeyInKeychain??jr,isOS:e.isOS??(t=>K(t)),promptKid:e.promptKid??vn,promptExpiryMonths:e.promptExpiryMonths??En,promptEmail:e.promptEmail??kn,promptPassphrase:e.promptPassphrase??bn,promptConfirmOverwrite:e.promptConfirmOverwrite??Pn,discoverLocalKeys:e.discoverLocalKeys??(()=>Fe()),promptZendeskAction:e.promptZendeskAction??Cn,openUrl:e.openUrl??(t=>rp(t)),copyToClipboard:e.copyToClipboard??Fn}}o(np,"resolveDeps");function Un(e,t={}){let r=np(t),n=e.command("keys").description("Manage code signing keys");n.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 macOS Keychain 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(i=>ap(i,r)),n.command("list").description("List local signing identities and their storage location").action(()=>op(r))}o(Un,"registerKeysCommand");async function op(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
148
148
|
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${_().keysDir}).
|
|
149
|
-
`);return}let r=["KID","SOURCE","EMAIL"],n=t.map(a=>[a.kid,
|
|
149
|
+
`);return}let r=["KID","SOURCE","EMAIL"],n=t.map(a=>[a.kid,Re(a.source),a.email??"\u2014"]),i=r.map((a,p)=>Math.max(a.length,...n.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(r)}
|
|
150
150
|
`);for(let a of n)process.stdout.write(`${s(a)}
|
|
151
|
-
`)}o(
|
|
152
|
-
`))}let
|
|
153
|
-
`);return}let M;e.email!==void 0?M=
|
|
151
|
+
`)}o(op,"handleList");function On(e,t,r){let n=ye(_().keysDir,`${e}${ne}`);return r.mkdirSync(Dt(n),{recursive:!0}),r.writeFileSync(n,t),n}o(On,"writePublicKey");async function ip(e,t,r,n,i,{force:s=!1}={}){let a=n??ye(_().keysDir,`${e}${yt}`);if(i.mkdirSync(Dt(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,r);return i.writeFileSync(a,p,{mode:384}),a}o(ip,"writeEncryptedPrivateKey");function sp(e,t,r){let n=[];if(e.expires===void 0)n.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{ie(e.expires)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)n.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=ge(e.kid),s=ye(_().keysDir,`${i}${ne}`);r(s)&&!e.force&&n.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)n.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{oe(e.email,"--email")}catch(i){n.push(i instanceof Error?i.message:String(i))}return t||n.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),n}o(sp,"collectNonInteractiveErrors");async function ap(e,t,r=new Date){let{isOS:n,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:y,promptConfirmOverwrite:g}=t,u=e.interactive??!1,w=e.keychain!==!1&&n("macos")&&!e.output;if(!u){let D=sp(e,w,i);if(D.length>0)throw new Error(D.join(`
|
|
152
|
+
`))}let S;e.expires!==void 0?S=ie(e.expires):S=await l();let b=xt(xn(r,S)),f;e.kid!==void 0?f=ge(e.kid):f=await d();let L=ye(_().keysDir,`${f}${ne}`),A=i(L);if(A&&!e.force&&!await g(f)){process.stderr.write(`Aborted.
|
|
153
|
+
`);return}let M;e.email!==void 0?M=oe(e.email,"--email"):M=await m();let pe=w?{kind:"keychain"}:{kind:"file",passphrase:await y()};process.stderr.write(`
|
|
154
154
|
Generating Ed25519 keypair...
|
|
155
155
|
|
|
156
|
-
`);let{privateKeyPem:
|
|
156
|
+
`);let{privateKeyPem:v,publicKeyPem:H}=await p(f);if(pe.kind==="keychain"){await c(f,v);let D=On(f,H,t);process.stderr.write(`Public key: ${D}
|
|
157
157
|
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${f})
|
|
158
|
-
`)}else{let
|
|
159
|
-
`),process.stderr.write(`Private key: ${
|
|
158
|
+
`)}else{let D=await ip(f,v,pe.passphrase,e.output,t,{force:A}),no=On(f,H,t);process.stderr.write(`Public key: ${no}
|
|
159
|
+
`),process.stderr.write(`Private key: ${D} (JWE, AES-256-GCM, PBKDF2-SHA512 x${gt.toLocaleString()})
|
|
160
160
|
`),n("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
161
|
-
`)}let
|
|
162
|
-
Signing identity (kid): ${
|
|
163
|
-
`),process.stderr.write(`Expires: ${
|
|
164
|
-
`);let
|
|
161
|
+
`)}let re=ye(_().keysDir,`${f}${ht}`);s(Dt(re),{recursive:!0}),a(re,JSON.stringify({email:M}));let E=Dn(process.stderr);process.stderr.write(`
|
|
162
|
+
Signing identity (kid): ${E.green(f)}
|
|
163
|
+
`),process.stderr.write(`Expires: ${b} (${S} month${S===1?"":"s"} from today)
|
|
164
|
+
`);let q={kid:f,publicKeyPem:H,email:M,expires:b};u||(process.stderr.write(`
|
|
165
165
|
Key registration data:
|
|
166
166
|
|
|
167
|
-
`),process.stderr.write(
|
|
168
|
-
${
|
|
167
|
+
`),process.stderr.write(At(q,E,r)));let Y=on(f,M,b,At(q,fe,r));process.stderr.write(`
|
|
168
|
+
${E.bold("Next:")}
|
|
169
169
|
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
170
|
-
`);let J;if(e.copyLink?J="clipboard":u?J=await t.promptZendeskAction():J=null,J==="browser")try{await t.openUrl(
|
|
171
|
-
`)}catch{process.stderr.write(` URL: ${
|
|
172
|
-
`)}else if(J==="clipboard"){let
|
|
173
|
-
`:` URL: ${
|
|
174
|
-
`)}else process.stderr.write(` URL: ${
|
|
170
|
+
`);let J;if(e.copyLink?J="clipboard":u?J=await t.promptZendeskAction():J=null,J==="browser")try{await t.openUrl(Y),process.stderr.write(` Opening in browser...
|
|
171
|
+
`)}catch{process.stderr.write(` URL: ${Y}
|
|
172
|
+
`)}else if(J==="clipboard"){let D=!1;try{await t.copyToClipboard(Y),D=!0}catch{}process.stderr.write(D&&!e.copyLink?` Link copied to clipboard.
|
|
173
|
+
`:` URL: ${Y}
|
|
174
|
+
`)}else process.stderr.write(` URL: ${Y}
|
|
175
175
|
`);process.stderr.write(`
|
|
176
176
|
2. Once your key is approved, sign your Dune app:
|
|
177
|
-
`),process.stderr.write(` ${
|
|
178
|
-
`)}o(
|
|
179
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{
|
|
180
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(
|
|
181
|
-
`),
|
|
182
|
-
`);let g=o(()=>{},"finish"),u=new Promise(
|
|
183
|
-
`)}}}o(Yn,"createTelemetry");var vp
|
|
184
|
-
`);return
|
|
185
|
-
${
|
|
186
|
-
`)},"onOutdated")})});
|
|
187
|
-
Cancelled.`),process.exit(130)),(!(e instanceof
|
|
177
|
+
`),process.stderr.write(` ${E.cyan(`cognite sign -s ${f}`)}
|
|
178
|
+
`)}o(ap,"handleGenerate");import{performance as _n}from"perf_hooks";var Ln=1e3,Le;function pp(){Le=_n.now()}o(pp,"markActionStart");function cp(){Le=void 0}o(cp,"resetActionStart");function lp(){if(Le!==void 0)return Math.max(0,Math.round(_n.now()-Le))}o(lp,"snapshotActionDurationMs");function Nn(){let e=lp();return cp(),{...e!==void 0&&{actionDurationMs:e}}}o(Nn,"takePerformanceFields");var dp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function mp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>typeof r=="boolean"?[t,r]:dp.has(t)?[t,r]:[t,"[REDACTED]"]))}o(mp,"sanitize");function up(e){let t=[],r=e;for(;r;)r.parent&&t.unshift(r.name()),r=r.parent;return t.join(" ")}o(up,"getCommandPath");function Kn(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Kn,"tryLoadAppConfig");function It(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(It,"commandFromArgv");function jn(e,t,r=C){e.hook("preAction",()=>{pp()}),e.hook("postAction",async(n,i)=>{try{let s={command:up(i),options:mp(i.opts()),success:!0,...Kn(r),...Nn()};t.track("Flows.CLI.Command",{...s}),await t.flush(Ln)}catch{}})}o(jn,"instrument");async function Mn(e,t,r=C){try{let n={command:It(t),options:{},success:!1,...Kn(r),...Nn()};e.track("Flows.CLI.Command",{...n}),await e.flush(Ln)}catch{}}o(Mn,"trackFailure");var gp="ERR_USE_AFTER_CLOSE";function Vn(e){return e instanceof Error&&"code"in e&&e.code===gp}o(Vn,"isReadlineClosedError");function fp(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(fp,"isPlainObject");function $t(e){return e==null||Vn(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&fp(e)&&Object.keys(e).length===0)}o($t,"isPromptCancel");var Hn=!1;function Bn(){Hn||(Hn=!0,process.on("uncaughtException",e=>{Vn(e)&&(console.error(`
|
|
179
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{$t(e)&&(console.error(`
|
|
180
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(Bn,"installCancelHandler");import{homedir as vp,userInfo as Cp}from"os";import Gn from"mixpanel";var yp="5c4d853e7c3b77b1eb4468d5329b278c",he="cognite-cli",hp=2e3,qn={env:process.env,init:Gn.init.bind(Gn)},Sp={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Tt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Tt,"isTelemetryDisabled");function wp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(wp,"isDebug");function Yn(e={}){let t=e.env??qn.env,r=e.init??qn.init,n=e.packageName,i=e.cliVersion,s=wp(t);if(Tt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
181
|
+
`),Sp;let a,p=new Set;function c(){if(a)return a;try{return a=r(yp,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let y={...d,applicationId:he,...n&&{packageName:n},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(y)}
|
|
182
|
+
`);let g=o(()=>{},"finish"),u=new Promise(w=>{g=w});p.add(u);try{m.track(l,y,g)}catch{g()}u.finally(()=>p.delete(u))},async flush(l=hp){if(p.size===0)return;let d,m=new Promise(y=>{d=setTimeout(y,l),d.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{d&&clearTimeout(d)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
|
|
183
|
+
`)}}}o(Yn,"createTelemetry");var Ep=vp(),kp=(()=>{try{return Cp().username}catch{return""}})();function se(e,t=Ep){if(!t||t==="/")return e;let r=e.replaceAll(t,"~"),n=t.replaceAll("\\","/");return n!==t&&(r=r.replaceAll(n,"~")),r=r.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),r=r.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),r}o(se,"redactHomedir");function bp(e,t=kp){if(!t||t.length<3)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp("(^|[\\/\\s:])"+r+"(?=[\\/\\s:.@]|$)","g");return e.replace(n,"$1<user>")}o(bp,"redactUsername");var Pp=1e3,xp="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Ap={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Dp(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Dp,"buildRelease");var Ip="192.0.2.0";function $p(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:se(t.filename)},...t.abs_path!==void 0&&{abs_path:se(t.abs_path)},...t.module!==void 0&&{module:se(t.module)}}))}o($p,"scrubStackFrames");function Rt(e){return bp(se(e))}o(Rt,"redactPii");function Tp(e){let t={...e.user,email:void 0,username:void 0,ip_address:Ip,id:void 0},r=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Rt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:$p(s.stacktrace.frames)}}})),n=e.contexts?.cli,i=n!==void 0?Object.fromEntries(Object.entries(n).map(([s,a])=>[s,typeof a=="string"?Rt(a):a])):void 0;return{...e,message:e.message!==void 0?Rt(e.message):e.message,user:t,server_name:void 0,...r!==void 0&&{exception:{...e.exception,values:r}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(Tp,"scrubPii");function Jn(e={}){let t=e.env??process.env;if(Tt(t))return Ap;let r=Dp(e),n="production",i=null,s=null;function a(){return{dsn:xp,release:r,environment:n,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:he},contexts:{cli:{applicationId:he,node:process.version,platform:process.platform}}},beforeSend:Tp}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Rp(c,l))}catch{}},async flush(c=Pp){try{if(!i)return;await i.flush(c)}catch{}}}}o(Jn,"createErrorReporter");function Rp(e,t){let r={level:"fatal"},n={applicationId:he,node:process.version,platform:process.platform};if(t?.command&&(r.tags={command:t.command},n.command=t.command),Lt(e)&&(e.hint&&(n.hint=e.hint),e.helpUrl&&(n.helpUrl=e.helpUrl),n.shouldReport=e.shouldReport),r.contexts={cli:n},Nt(e)&&(r.contexts.http={url:e.requestUrl!==void 0?se(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);r.extra={responseBody:se(i)}}return r}o(Rp,"buildCaptureContext");import{mkdirSync as Fp,readFileSync as Op,writeFileSync as Up}from"fs";import{homedir as _p}from"os";import{resolve as Ne}from"path";import{debuglog as Lp}from"util";import{lt as Np,parse as zn}from"semver";var Kp="https://registry.npmjs.org/@cognite/cli/latest",jp=1500,Wn="upgrade-check.json",Xn=Ne(process.env.XDG_CACHE_HOME||Ne(_p(),".cache"),"@cognite","cli"),Ft=Lp("cognite-flows");function Mp(e,t){return!e||!t||!zn(e)||!zn(t)?!1:Np(e,t)}o(Mp,"isOutdated");async function Hp({timeout:e=jp,registryUrl:t=Kp,fetchImpl:r=globalThis.fetch}={}){if(typeof r!="function")return null;try{let n=await r(t,{signal:AbortSignal.timeout(e)});if(!n?.ok)return null;let i=await n.json();return typeof i?.version=="string"?i.version:null}catch(n){return Ft("fetchLatestVersion failed (%s): %O",t,n),null}}o(Hp,"fetchLatestVersion");function Vp(e=Xn,t=864e5){try{let r=Op(Ne(e,Wn),"utf-8"),n=JSON.parse(r);return typeof n.latest!="string"||typeof n.fetchedAt!="number"||Date.now()-n.fetchedAt>t?null:{latest:n.latest,fetchedAt:n.fetchedAt}}catch(r){return Ft("readUpgradeCheckCache failed (%s): %O",e,r),null}}o(Vp,"readUpgradeCheckCache");function Bp(e,t){try{Fp(e,{recursive:!0});let r={latest:t,fetchedAt:Date.now()};Up(Ne(e,Wn),JSON.stringify(r))}catch(r){Ft("writeUpgradeCheckCache failed (%s): %O",e,r)}}o(Bp,"writeUpgradeCheckCache");async function Gp({cacheDir:e=Xn,...t}={}){let r=await Hp(t);r&&Bp(e,r)}o(Gp,"startBackgroundUpgradeCheck");function Zn(e,{onOutdated:t,cacheDir:r,...n}={}){let i=Vp(r);if(i){Mp(e,i.latest)&&t?.(e,i.latest);return}Gp({cacheDir:r,...n})}o(Zn,"preActionUpgradeCheck");import{default as Hf,chalkStderr as Qn}from"chalk";function eo(e,t){let r=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],n=Math.max(...r.map(p=>[...p].length))+2,i="\u2500".repeat(n),s=o(p=>`\u2502 ${p}${" ".repeat(n-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...r.map(s),`\u2514${i}\u2518`].join(`
|
|
184
|
+
`);return Qn.bold.yellow(a)}o(eo,"formatUpgradeWarning");function Jp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Jp,"isDep0040Warning");var Ut=process,zp=Ut.emit.bind(Ut);Ut.emit=function(e,...t){return e==="warning"&&Jp(t[0])?!1:zp(e,...t)};Bn();var ae=new Yp;ae.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.5.1").showHelpAfterError().configureOutput({writeOut:o(e=>qp(1,e),"writeOut")});ae.hook("preAction",()=>{Zn("1.5.1",{onOutdated:o((e,t)=>{console.warn(`
|
|
185
|
+
${eo(e,t)}
|
|
186
|
+
`)},"onOutdated")})});an(ae);Un(ae);var ro=Yn({packageName:"@cognite/cli",cliVersion:"1.5.1"}),to=Jn({packageName:"@cognite/cli",cliVersion:"1.5.1"});jn(ae,ro);var Ot=process.argv.slice(2);ae.parseAsync(Ot,{from:"user"}).catch(async e=>{await Mn(ro,Ot),$t(e)&&(console.error(`
|
|
187
|
+
Cancelled.`),process.exit(130)),(!(e instanceof h)||e.shouldReport)&&(await to.captureError(e,{command:It(Ot)}),await to.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof h&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-MZWFUPT4.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-MZWFUPT4.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
|
package/package.json
CHANGED
package/dist/chunk-5ABVQYYD.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
var ie=Object.defineProperty;var i=(n,e)=>ie(n,"name",{value:e,configurable:!0});import{mkdir as _e,readFile as Fe}from"fs/promises";import{basename as Oe,dirname as Le}from"path";var D=class D extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:ue(e.cause)}}};i(D,"HintedError");var w=D;var J="https://docs.cognite.com/cdf/access/",ae="https://status.cognite.com";function ce(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:J};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:J};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:ae};default:return{}}}i(ce,"defaultHintForStatus");var U=class U extends w{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ce(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var x=U;function pe(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.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 e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.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 e.port?`Port ${e.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(pe,"hintForErrno");function ue(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=pe(r.code,r);if(o!==void 0)return o;e=r.cause}}i(ue,"hintForCause");var K="https://docs.cognite.com/cdf/access/";function d(n){return n!==null&&typeof n=="object"}i(d,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(C,"isHttpError");function le(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
-
See: ${K}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
-
See: ${K}`;default:return}}i(le,"httpStatusHint");function y(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=le(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
-
${t}`),{cause:e}):null}i(y,"enrichedHttpError");function de(n){if(!d(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(d(t)){let r=t.error;if(d(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}i(de,"findMissingArray");function ge(n,e){if(!C(n)||n.status!==400)return!1;let t=de(n);return t?t.some(r=>d(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(ge,"isMissingExternalIdError");function N(n,e){return C(n)&&n.status===404||ge(n,e)}i(N,"isNotFoundError");var X=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Z=["ACTIVE","PREVIEW"],V=class V extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};i(V,"AppVersionNotFoundError");var b=V;function R(n,e){return n.includes(e)}i(R,"includesValue");function fe(n){return R(X,n)}i(fe,"isAppVersionLifecycleState");function he(n){return R(Z,n)}i(he,"isAppVersionAlias");function me(n){return typeof n.version=="string"&&fe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||he(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(me,"isAppVersion");function W(n){if(!d(n))throw new Error("Invalid version response: not an object");if(!me(n))throw new Error("Invalid version response: missing or malformed fields");return n}i(W,"parseAppVersion");var _=class _{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(o){throw y(o)??o}}async uploadVersion(e,t,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",t),a.append("entryPath",s);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,u=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${c}`,h=new AbortController,oe=setTimeout(()=>h.abort(),300*1e3),E;try{E=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:a,signal:h.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(oe)}if(!E.ok){let g=await E.text(),S;try{S=JSON.parse(g)}catch{}let I=g;if(d(S)){let A=S.error;if(typeof A=="string")I=A;else if(d(A)){let k=A.message,z=A.code;I=typeof k=="string"?k:z!=null?`Unknown error (code: ${z})`:g}else{let k=S.message;I=typeof k=="string"?k:g}}let Y=E.headers.get("x-request-id"),se=Y?` | X-Request-ID: ${Y}`:"";throw new x(`Upload failed: ${E.status} \u2014 ${I}${se}`,{httpStatusCode:E.status,requestUrl:m,responseBody:d(S)?S:g})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return W(a.data)}catch(a){throw N(a,[e,t])?new b(e,t):y(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/active`;try{let o=await this.client.get(r);return W(o.data)}catch(o){if(N(o,[e]))return null;throw y(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:t}})}catch(s){throw y(s)??s}}async submitSignatures(e,t,r){let o=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw y(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Se(a.data)}catch(a){throw y(a)??a}}};i(_,"AppHostingApi");var T=_,ye=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ee=["developer","certifier"];function Se(n){if(!d(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=we(t);return r?[r]:[]})}i(Se,"parseStoredSignatures");function we(n){if(!d(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!R(Ee,t)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!R(ye,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(we,"parseStoredSignature");var F=class F{constructor(e){this.api=new T(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,o,s){return this.api.uploadVersion(e,t,r,o,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(o){if(C(o)&&o.status===409){console.log(`\u2705 App '${e}' already exists`);return}throw o}}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let o=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(e,t,r,o,s,a,p=!1){console.log(`
|
|
5
|
-
\u{1F680} Deploying application via App Hosting API...
|
|
6
|
-
`);try{await this.ensureApp(e,t,r),await this.uploadVersion(e,o,s,a),p&&await this.publishAndActivate(e,o),console.log(`
|
|
7
|
-
\u2705 Deployment successful!`)}catch(c){let u=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${u}`),{cause:c})}}};i(F,"AppHostingClient");var v=F;import{execFileSync as $}from"child_process";import f from"fs";import l from"path";import{parseAndValidateManifestConfig as Ae}from"@cognite/app-sdk/vite";import{BlobReader as ke,Uint8ArrayWriter as Ce,ZipWriter as ve}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Q="manifest.json",B=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],H=class H{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!f.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,O);if(!f.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,L);if(!f.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new ve(new Ce,{level:9}),o=i(async(c,u)=>{await r.add(u,new ke(await f.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=i(async c=>{let u=await f.promises.readdir(c,{withFileTypes:!0});for(let m of u){let h=l.join(c,m.name);m.isDirectory()?await s(h):await o(h,l.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=l.join(this.appRoot,O);await o(c,l.posix.join(B,O));let u=l.join(this.appRoot,Q);if(f.existsSync(u)){let h=f.readFileSync(u,"utf-8");Ae(h,u),await o(u,l.posix.join(B,Q))}let m=l.join(this.appRoot,L);await o(m,l.posix.join(B,L)),a=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}await f.promises.writeFile(e,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=$("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=$("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(t,s);try{$("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${u}`)}let p=(f.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=$("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
8
|
-
`).filter(Boolean),o=i(a=>a.split("/").some(p=>Pe.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:
|
|
9
|
-
`+s.map(a=>` ${a}`).join(`
|
|
10
|
-
`)+`
|
|
11
|
-
Hint: git rm --cached <file>`)}};i(H,"ApplicationPackager");var P=H;import Ie from"path";var ee=".cognite-bundles";function te(n,e){return`${n}-${e}.zip`}i(te,"bundleFileName");function j(n,e,t){return Ie.join(n,ee,te(e,t))}i(j,"bundlePath");import{CogniteClient as Ve}from"@cognite/sdk";function xe(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(xe,"exponentialBackoffWithJitter");function be(n){return new Promise(e=>setTimeout(e,n))}i(be,"sleep");async function M(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??xe;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let p=o(s);e.onAttemptFail?.(a,s,p),await be(p),s++}}i(M,"retryAsync");var Re=i(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=o}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Te=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Re()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),$e=i(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let e=n.replace(/^https?:\/\//,"");return e=e.split("/")[0],e=e.split(":")[0],e=e.replace(/\.cognitedata\.com$/,""),e}},"extractClusterFromUrl"),De=i(async(n,e)=>{let t=`Basic ${btoa(`${n}:${e}`)}`,r="https://auth.cognite.com/oauth2/token",o={grant_type:"client_credentials"},s;try{s=await M(()=>fetch(r,{method:"POST",headers:{Authorization:t,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(o)}),{maxAttempts:3})}catch(p){throw new w(`Failed to fetch access token from ${r}`,{cause:p})}if(!s.ok){let p=await s.text();throw new Error(`Failed to get token from CDF: ${s.status} ${s.statusText}
|
|
12
|
-
${p}`)}let a=await s.json();if(!a.access_token)throw new Error("No access token returned from CDF authentication");return a.access_token},"getTokenCdf"),Ue=i((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let t=$e(n);if(!t)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);return`https://${t}.cognitedata.com/.default`},"resolveEntraScope"),Ne=i(async(n,e,t,r,o)=>{let s=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,a=Ue(r,o),p;try{p=await M(()=>fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,grant_type:"client_credentials",...a?{scope:a}:{}})}),{maxAttempts:3})}catch(u){throw new w(`Failed to fetch access token from ${s}`,{cause:u})}if(!p.ok){let u=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
|
|
13
|
-
${u}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),q=i(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p}=n,c=Te(r);if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Ne(t,c,s,a,p)}return De(t,c)},"getToken");async function G(n,e,t=process.env,r){let o=await q(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new Ve(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}i(G,"getSdk");async function ne(n,e,t,r){let{externalId:o,name:s,description:a,versionTag:p}=e,c=j(t,o,p);await _e(Le(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u=await Fe(c);await new v(n).deploy(o,s,a,p,u,Oe(c),r)}i(ne,"packageAndUpload");var Be=i(async(n,e,t)=>{let r=await G(n,t);await ne(r,e,t,n.published)},"deploy");import{existsSync as He,readFileSync as je}from"fs";var re=[".dev.sig",".cert.sig"];function Me(n,e={}){let t=e.existsSync??He,r=e.readFileSync??((s,a)=>je(s,a)),o=[];for(let s of re){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Me,"discoverSignatures");export{v as a,P as b,ee as c,te as d,j as e,q as f,G as g,ne as h,Be as i,re as j,Me as k};
|