@cognite/cli 1.3.2-alpha.https1 → 1.3.2-alpha.winurl1
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.
|
@@ -3,20 +3,17 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>vite.config.ts'
|
|
|
3
3
|
---
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
|
|
6
|
-
import {
|
|
7
|
-
fusionOpenPlugin,
|
|
8
|
-
manifestCspPlugin,
|
|
9
|
-
mkcertPlugin,
|
|
10
|
-
} from '@cognite/app-sdk/vite';
|
|
6
|
+
import { fusionOpenPlugin, manifestCspPlugin } from '@cognite/app-sdk/vite';
|
|
11
7
|
import tailwindcss from '@tailwindcss/vite';
|
|
12
8
|
import react from '@vitejs/plugin-react';
|
|
13
9
|
import { defineConfig } from 'vite';
|
|
10
|
+
import mkcert from 'vite-plugin-mkcert';
|
|
14
11
|
|
|
15
12
|
export default defineConfig({
|
|
16
13
|
base: './',
|
|
17
14
|
// manifestCspPlugin() must stay first — its middleware sets the
|
|
18
15
|
// Content-Security-Policy header before any HTML response is sent.
|
|
19
|
-
plugins: [manifestCspPlugin(), react(),
|
|
16
|
+
plugins: [manifestCspPlugin(), react(), mkcert(), fusionOpenPlugin(), tailwindcss()],
|
|
20
17
|
resolve: {
|
|
21
18
|
alias: {
|
|
22
19
|
'@': path.resolve(__dirname, './src'),
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
---
|
|
2
|
+
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>patches/@cognite+app-sdk+0.5.1.patch'
|
|
3
|
+
---
|
|
4
|
+
diff --git a/node_modules/@cognite/app-sdk/dist/vite/fusion-open-plugin.js b/node_modules/@cognite/app-sdk/dist/vite/fusion-open-plugin.js
|
|
5
|
+
index a43509c..3518d90 100644
|
|
6
|
+
--- a/node_modules/@cognite/app-sdk/dist/vite/fusion-open-plugin.js
|
|
7
|
+
+++ b/node_modules/@cognite/app-sdk/dist/vite/fusion-open-plugin.js
|
|
8
|
+
@@ -3,7 +3,11 @@ import l from "node:fs";
|
|
9
|
+
import m from "node:path";
|
|
10
|
+
import { FLOWS_SUBAPP_PATH as u } from "./constants.js";
|
|
11
|
+
const g = (o) => {
|
|
12
|
+
- const e = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
13
|
+
+ if (process.platform === "win32") {
|
|
14
|
+
+ d("cmd", ["/c", "start", "", o], { stdio: "ignore", detached: !0 }).unref();
|
|
15
|
+
+ return;
|
|
16
|
+
+ }
|
|
17
|
+
+ const e = process.platform === "darwin" ? "open" : "xdg-open";
|
|
18
|
+
d(e, [o], { stdio: "ignore", detached: !0 }).unref();
|
|
19
|
+
}, h = () => ({
|
|
20
|
+
name: "fusion-open",
|
|
@@ -23,7 +23,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
23
23
|
"lint:fix": "eslint . --fix --ext .js,.mjs,.cjs,.ts,.tsx",
|
|
24
24
|
"deploy": "npx @cognite/cli@latest apps deploy --interactive",
|
|
25
25
|
"activate": "npx @cognite/cli@latest apps activate --interactive",
|
|
26
|
-
"
|
|
26
|
+
"postinstall": "patch-package"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@cognite/aura": "^0.1.7",
|
|
@@ -56,11 +56,13 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
56
56
|
"eslint-plugin-react-refresh": "^0.5.2",
|
|
57
57
|
"globals": "^16.5.0",
|
|
58
58
|
"happy-dom": "^20.9.0",
|
|
59
|
+
"patch-package": "^8.0.1",
|
|
59
60
|
"postcss": "^8.5.6",
|
|
60
61
|
"tailwindcss": "^4.1.17",
|
|
61
62
|
"typescript": "^5.0.0",
|
|
62
63
|
"typescript-eslint": "^8.46.4",
|
|
63
64
|
"vite": "7.3.2",
|
|
65
|
+
"vite-plugin-mkcert": "^1.17.9",
|
|
64
66
|
"vitest": "^2.1.8"
|
|
65
67
|
}
|
|
66
68
|
}
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as o,e as gt}from"../chunk-A5ASLC6T.js";import{writeSync as
|
|
2
|
+
import{a as o,e as gt}from"../chunk-A5ASLC6T.js";import{writeSync as ca}from"fs";import{Command as la}from"commander";import{createReadStream as Go,existsSync as Jo,readFileSync as Yo,writeFileSync as qo}from"fs";import{basename as zo,dirname as Wo,join as Xo,resolve as he}from"path";import{hashDevSignature as Zo,parseScope as Qo,signBundle as ei,validateScopes as ti}from"@cognite/app-sdk/codesigning";var ft="https://docs.cognite.com/cdf/access/";function K(e){return e!==null&&typeof e=="object"}o(K,"isRecord");function X(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(X,"isHttpError");function hr(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
3
3
|
See: ${ft}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
4
|
-
See: ${ft}`;default:return}}o(
|
|
5
|
-
${
|
|
4
|
+
See: ${ft}`;default:return}}o(hr,"httpStatusHint");function M(e){let t=e instanceof Error?e:new Error(String(e));if(!X(t))return null;let n=hr(t.status);return n?Object.assign(new Error(`${t.message}
|
|
5
|
+
${n}`),{cause:t}):null}o(M,"enrichedHttpError");function Sr(e){if(!K(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(K(n)){let r=n.error;if(K(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(Sr,"findMissingArray");function wr(e,t){if(!X(e)||e.status!==400)return!1;let n=Sr(e);return n?n.some(r=>K(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(wr,"isMissingExternalIdError");function Ie(e,t){return X(e)&&e.status===404||wr(e,t)}o(Ie,"isNotFoundError");var ht=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],St=["ACTIVE","PREVIEW"],$e=class $e extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o($e,"AppVersionNotFoundError");var T=$e;function wt(e,t){return e.includes(t)}o(wt,"includesValue");function vr(e){return wt(ht,e)}o(vr,"isAppVersionLifecycleState");function Cr(e){return wt(St,e)}o(Cr,"isAppVersionAlias");function Pr(e){return typeof e.version=="string"&&vr(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||Cr(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Pr,"isAppVersion");function yt(e){if(!K(e))throw new Error("Invalid version response: not an object");if(!Pr(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(yt,"parseAppVersion");var Fe=class Fe{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(i){throw M(i)??i}}async uploadVersion(t,n,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",n),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),d=`${this.client.getBaseUrl()}${c}`,m=new AbortController,g=setTimeout(()=>m.abort(),300*1e3),u;try{u=await fetch(d,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:m.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error("Upload timed out after 5 minutes"):f}finally{clearTimeout(g)}if(!u.ok){let f=await u.text(),S=f;try{let y=JSON.parse(f);if(K(y)){let C=y.error;if(typeof C=="string")S=C;else if(K(C)){let $=C.message,w=C.code;S=typeof $=="string"?$:w!=null?`Unknown error (code: ${w})`:f}else{let $=y.message;S=typeof $=="string"?$:f}}}catch{}let v=u.headers.get("x-request-id"),h=v?` | X-Request-ID: ${v}`:"",b=Object.assign(new Error(`Upload failed: ${u.status} \u2014 ${S}${h}`),{status:u.status});throw M(b)??b}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),i=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return yt(a.data)}catch(a){throw Ie(a,[t,n])?new T(t,n):M(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let i=await this.client.get(r);return yt(i.data)}catch(i){if(Ie(i,[t]))return null;throw M(i)??i}}async updateVersions(t,n){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:n}})}catch(s){throw M(s)??s}}async submitSignatures(t,n,r){let i=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw M(p)??p}}};o(Fe,"AppHostingApi");var de=Fe;var Te=class Te{constructor(t){this.api=new de(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,i,s){return this.api.uploadVersion(t,n,r,i,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(i){if(X(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async submitSignatures(t,n,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,r),console.log("\u2705 Signatures stored"))}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let i=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,n,r,i,s,a,p=!1){console.log(`
|
|
6
6
|
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
-
`);try{await this.ensureApp(t,r
|
|
8
|
-
\u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};o(Te,"AppHostingClient");var P=Te;import
|
|
9
|
-
${
|
|
10
|
-
${l}`)}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"),je=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:
|
|
11
|
-
<h1>${
|
|
7
|
+
`);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
|
|
8
|
+
\u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};o(Te,"AppHostingClient");var P=Te;import Er from"path";var vt=".cognite-bundles";function Ct(e,t){return`${e}-${t}.zip`}o(Ct,"bundleFileName");function V(e,t,n){return Er.join(e,vt,Ct(t,n))}o(V,"bundlePath");import{existsSync as br,readFileSync as kr}from"fs";var Pt=[".dev.sig",".cert.sig"];function Z(e,t={}){let n=t.existsSync??br,r=t.readFileSync??((s,a)=>kr(s,a)),i=[];for(let s of Pt){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(Z,"discoverSignatures");import{existsSync as Ur,readFileSync as Kr}from"fs";import{resolve as Lr}from"path";import{array as xr,boolean as Ar,check as Et,forward as bt,literal as Dr,maxLength as Ir,minLength as $r,nonEmpty as z,object as kt,optional as H,picklist as Fr,pipe as L,safeParse as Tr,string as O,url as Or}from"valibot";var Oe=L(O(),z("must not be empty")),Re=L(O(),z("must not be empty"),Ir(256,"must be 256 characters or fewer")),_e=L(O(),z("must not be empty"),Or("must be a valid URL")),Ue=L(O(),z("must not be empty")),Ke=L(O(),z("must not be empty")),Rr=L(kt({org:Ue,project:Ke,baseUrl:_e,deployClientId:H(O(),""),deploySecretName:H(O(),""),published:H(Ar(),!1),idpType:H(Fr(["cdf","entra_id"]),"cdf"),tenantId:H(O())}),bt(Et(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),bt(Et(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),_r=kt({name:Oe,externalId:Re,versionTag:L(O(),z("must not be empty")),description:H(O(),""),deployments:L(xr(Rr),$r(1,"must contain at least one deployment")),infra:H(Dr("appsApi"))});function Le(e){let t=Tr(_r,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",i=r?`"${r}" `:"";throw new Error(`app.json: ${i}${n.message}`)}o(Le,"validateAppConfig");function E(e,t={}){let{validator:n=Le,existsSync:r=Ur,readFileSync:i=Kr}=t,s=Lr(e,"app.json");if(!r(s))throw new Error("No app.json found in current directory. Make sure you're running this command from your app's root directory.");let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}o(E,"loadAppConfig");import{CogniteClient as po}from"@cognite/sdk";import{CogniteClient as Br}from"@cognite/sdk";var jr=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,i]of Object.entries(t))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=i}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Nr=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=jr()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),Mr=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"),Vr=o(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let s=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
|
|
9
|
+
${s}`)}let i=await r.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),Hr=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=Mr(r);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let s=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${i}.cognitedata.com/.default`,p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!p.ok){let l=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
|
|
10
|
+
${l}`)}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"),je=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a}=e,p=Nr(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Hr(n,p,s,a)}return Vr(n,p)},"getToken");async function Q(e,t,n=process.env,r){let i=await je(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Br(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(Q,"getSdk");import Xr from"os";import Zr from"path";import Qr from"open";import{buildAuthorizationUrl as eo,calculatePKCECodeChallenge as to,discovery as no,None as ro,randomPKCECodeVerifier as oo,randomState as io}from"openid-client";import Gr from"https";import{authorizationCodeGrant as Jr}from"openid-client";function xt(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(xt,"escapeHtml");function Ne(e,t,n){let r=xt(t),i=xt(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
11
|
+
<h1>${r}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
12
12
|
@keyframes checkmark {
|
|
13
13
|
0% { transform: scale(0); }
|
|
14
14
|
50% { transform: scale(1.2); }
|
|
@@ -16,29 +16,32 @@ ${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(Ne,"generateHtml");async function
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
`)
|
|
19
|
+
</body></html>`}o(Ne,"generateHtml");async function Yr(e,t,n,r,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Ne("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(Ne("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Yr,"handleCallback");function qr(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(qr,"formatTimeoutMinutes");function At(e,t,n,r,i,s={createServer:Gr.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Jr}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,g)=>{try{let u=await Yr(m,g,n,r,i,s);u.shouldClose&&(d(),u.error?p(u.error):u.tokens?a(u.tokens):p(new Error("No tokens received")))}catch(u){d(),p(u instanceof Error?u:new Error(String(u)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${qr(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(At,"startCallbackServer");import{execFileSync as zr}from"child_process";import Me from"fs";import Dt from"path";function It(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(It,"loadCertificates");function Wr(e,t,n,r){console.log("\u{1F510} Generating self-signed certificate for HTTPS..."),r.existsSync(e)||r.mkdirSync(e,{recursive:!0});try{return r.execFileSync("openssl",["req","-x509","-newkey","rsa:2048","-nodes","-sha256","-subj","/CN=localhost","-keyout",t,"-out",n,"-days","365"],{stdio:["ignore","pipe","ignore"]}),console.log("\u2705 Certificate generated and saved locally"),It(t,n,r)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
|
|
20
|
+
On macOS: openssl is pre-installed
|
|
21
|
+
On Linux: sudo apt-get install openssl
|
|
22
|
+
On Windows: Install OpenSSL or use WSL`)}}o(Wr,"generateCertificate");function $t(e,t={existsSync:Me.existsSync,readFileSync:o(n=>Me.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{Me.mkdirSync(n,r)},"mkdirSync"),execFileSync:zr}){let n=Dt.join(e,"localhost-key.pem"),r=Dt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?It(n,r,t):Wr(e,n,r,t)}o($t,"getOrCreateCertificates");var so={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Zr.join(Xr.homedir(),".cdf-login")},ao={open:Qr,getOrCreateCertificates:$t,startCallbackServer:At,discovery:no,buildAuthorizationUrl:eo,randomPKCECodeVerifier:oo,calculatePKCECodeChallenge:to,randomState:io,logger:console};async function Tt(e,t=so,n){return n===void 0?Ft(e,t,ao):Ft(e,t,n)}o(Tt,"login");async function Ft(e,t,n){n.logger.log(`\u{1F510} Starting CDF login flow...
|
|
23
|
+
`),n.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let r=await n.discovery(new URL(t.authority),t.clientId,void 0,ro()),i=n.randomPKCECodeVerifier(),s=await n.calculatePKCECodeChallenge(i),a=n.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=n.buildAuthorizationUrl(r,p).toString(),l=n.getOrCreateCertificates(t.certDir);e&&n.logger.log(`\u{1F3E2} Organization: ${e}`),n.logger.log(`\u{1F680} Opening browser for authentication...
|
|
24
|
+
`);try{await n.open(c)}catch(d){let m=d instanceof Error?d.message:String(d);n.logger.error("\u274C Failed to open browser automatically."),n.logger.error(` Reason: ${m}`),n.logger.error(`Please open this URL manually:
|
|
25
|
+
`),n.logger.error(c),n.logger.error("")}return n.startCallbackServer(t,l,r,i,a)}o(Ft,"loginImpl");async function A(e,t,n={}){let{login:r=Tt,getSdk:i=Q,createClient:s=o(a=>new po(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(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(A,"getClientForDeployment");import Ot from"enquirer";var Rt="Enter custom target...";function _t(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
|
|
23
26
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
24
|
-
${r}`)}o(Ot,"deploymentNotFoundError");function b(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;Ot(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;Ot(t,e)}o(b,"findDeployment");function D(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(D,"getMissingCredentials");async function I(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 b(e.deployments,t.deployment);let r=[...e.deployments.map(a=>`${a.org}/${a.project}`),Tt],{selected:n}=await Ft.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==Tt){let a=e.deployments.find(s=>`${s.org}/${s.project}`===n);if(a)return a;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await Ft.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(a=>a?!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(I,"resolveDeployment");import{existsSync as Ho,readFileSync as Vo}from"fs";import{execFile as lo}from"child_process";import{promisify as mo}from"util";import{platform as co}from"os";function B(e,t={}){let{platform:r=co}=t;switch(r()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(B,"isOS");var _t="cognite-flows",uo=mo(lo),Ut=o((e,t)=>uo(e,t),"defaultExecFile"),go=-25300,fo=go&255;function yo(e){if(!(e instanceof Error)||!("code"in e)||e.code!==fo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(yo,"isKeychainNotFoundError");async function Lt(e,t,r={}){if(!B("macos",r))throw new Error("Keychain storage is only supported on macOS");let{execFile:n=Ut}=r;await n("security",["add-generic-password","-a",e,"-s",_t,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Lt,"storeKeyInKeychain");async function me(e,t={}){if(!B("macos",t))return null;let{execFile:r=Ut}=t;try{let{stdout:n}=await r("security",["find-generic-password","-a",e,"-s",_t,"-w"]);return Buffer.from(n.trim(),"base64").toString("utf-8")}catch(n){if(yo(n))return null;throw n}}o(me,"readKeyFromKeychain");import{pbkdf2 as wo,randomBytes as vo}from"crypto";import{promisify as Co}from"util";import{CompactEncrypt as Po,base64url as Kt,compactDecrypt as Eo}from"jose";var ho=new TextEncoder,So=new TextDecoder,Me={encode:o(e=>ho.encode(e),"encode"),decode:o(e=>So.decode(e),"decode")};var ko=Co(wo),Be=6e5,bo="sha512",He="PBKDF2-HMAC-SHA512",Ve=16,ue="A256GCM",xo=32,ge=2e6;async function jt(e,t,r){return await ko(e,t,r,xo,bo)}o(jt,"deriveKey");async function Nt(e,t,r=Be){if(!Number.isInteger(r)||r<1||r>ge)throw new Error(`Invalid iterations: must be an integer between 1 and ${ge}`);let n=vo(Ve),i=await jt(t,n,r);return await new Po(Me.encode(e)).setProtectedHeader({alg:"dir",enc:ue,kdf:He,kdf_iter:r,kdf_salt:Kt.encode(n)}).encrypt(i)}o(Nt,"encryptStringAsJwe");async function Mt(e,t){let{plaintext:r}=await Eo(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!==ue)throw new Error(`Unexpected JWE enc "${String(n.enc)}"; only "${ue}" is supported`);if(n.kdf!==He)throw new Error(`Unexpected KDF "${String(n.kdf)}"; only "${He}" is supported`);let i=Number(n.kdf_iter);if(!Number.isInteger(i)||i<1||i>ge)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${ge}`);if(typeof n.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Kt.decode(n.kdf_salt);if(a.length!==Ve)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Ve} bytes, got ${a.length}`);return await jt(t,a,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[ue]});return Me.decode(r)}o(Mt,"decryptJweAsString");function Ao(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Ao,"isJweCompact");var Ht=Ao;import{existsSync as Io,readdirSync as $o,readFileSync as Fo}from"fs";import{join as Ge}from"path";import{homedir as Do}from"os";import{join as Vt}from"path";function F(e={}){let{env:t=process.env,homedir:r=Do}=e,n=t.COGNITE_CLI_HOME?.trim()||Vt(r(),".cognite-cli");return{home:n,keysDir:Vt(n,"keys")}}o(F,"getConfig");var ee=".pub.pem",Je=".key.jwe",Ye=".meta.json";function fe(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(fe,"formatLocalKeySource");function To(e){return{existsSync:e.existsSync??Io,readdirSync:e.readdirSync??$o,readFileSync:e.readFileSync??((t,r)=>Fo(t,r)),isOS:e.isOS??(t=>B(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>me(t))}}o(To,"resolveDeps");function Oo(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(Oo,"readEmailFromMeta");function Ro(e,t){return t.existsSync(e)?t.readdirSync(e).filter(r=>r.endsWith(ee)):[]}o(Ro,"publicKeyEntries");function _o(e){return e.slice(0,-ee.length)}o(_o,"kidFromPublicKeyFilename");async function Uo(e,t,r){if(r.isOS("macos")&&await r.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let n=Ge(t,`${e}${Je}`);return r.existsSync(n)?{kind:"encrypted-file",path:n}:{kind:"public-only"}}o(Uo,"resolveSource");async function ye(e=F().keysDir,t={}){let r=To(t),n=new Set,i=Ro(e,r).flatMap(a=>{let s=_o(a);return!s||n.has(s)?[]:(n.add(s),[{kid:s,entry:a}])});return Promise.all(i.map(async({kid:a,entry:s})=>{let p=await Uo(a,e,r),c=Ge(e,`${a}${Ye}`),l;try{l=Oo(r.readFileSync(c,"utf8"))}catch{}return{kid:a,source:p,publicKeyPath:Ge(e,s),email:l}}))}o(ye,"discoverLocalKeys");import Lo from"enquirer";async function Ko(e){return Lo.prompt(e)}o(Ko,"defaultPrompt");async function Bt(e,t={}){let{prompt:r=Ko}=t,{passphrase:n}=await r({type:"password",name:"passphrase",message:e});return n}o(Bt,"promptPassphrase");import No from"enquirer";import{statSync as jo}from"fs";function Gt(e,t=jo){return e.map(r=>({key:r,mtime:t(r.publicKeyPath).mtimeMs})).sort((r,n)=>n.mtime-r.mtime).map(({key:r})=>r)}o(Gt,"sortByMtime");async function Mo(e){return No.prompt(e)}o(Mo,"defaultPrompt");async function Jt(e,t={}){if(e.length===1)return e[0];let{prompt:r=Mo,sortByMtime:n=Gt}=t,i=n(e),a=i[0],{choice:s}=await r({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${a.kid}`},{name:"pick",message:"Pick from list"}]});if(s==="latest")return a;if(s==="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,fe(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: "${s}"`)}o(Jt,"promptSigningIdentity");function Bo(e){return{existsSync:e.existsSync??Ho,readFileSync:e.readFileSync??((t,r)=>Vo(t,r)),readKeyFromKeychain:e.readKeyFromKeychain??me,decryptJweAsString:e.decryptJweAsString??Mt,discoverLocalKeys:e.discoverLocalKeys??ye,keysDir:e.keysDir??F().keysDir,promptPassphrase:e.promptPassphrase??Bt,promptSigningIdentity:e.promptSigningIdentity??Jt}}o(Bo,"resolveDeps");async function Yt(e,t={}){let r=Bo(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 a=r.readFileSync(e.keyPath,"utf-8").trim();if(Ht(a)){let s=await r.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await r.decryptJweAsString(a,s),kid:e.kid}}return{privateKeyPem:a,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=e.kid?n.find(a=>a.kid===e.kid):await r.promptSigningIdentity(n);if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let a=await r.readKeyFromKeychain(i.kid);if(!a)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:a,kid:i.kid}}case"encrypted-file":{let a=await r.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await r.decryptJweAsString(r.readFileSync(i.source.path,"utf-8"),a),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(Yt,"resolvePrivateKey");var ri=o(async(e,t,r,n,i)=>{let a=await A(e,{interactive:i.interactive??!1,appId:t,orgHint:i.org});await new P(a).submitSignatures(t,r,n)},"defaultSubmitSignatures");function ni(e){let t=Go(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(ni,"createWebStreamFromFile");function oi(e){return{existsSync:e.existsSync??Jo,readFileSync:e.readFileSync??((t,r)=>Yo(t,r)),writeFileSync:e.writeFileSync??qo,createBundleStream:e.createBundleStream??ni,signBundle:e.signBundle??ei,hashDevSignature:e.hashDevSignature??Zo,parseScope:e.parseScope??Qo,validateScopes:e.validateScopes??ti,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>Yt(t)),submitSignatures:e.submitSignatures??ri,discoverSignatures:e.discoverSignatures??Z}}o(oi,"resolveDeps");async function qt(e,t,r={},n=process.cwd()){let i=oi(r),a=t.appid,s=t.appVersion,p=[],c=i.loadAppConfig(n);if(a=a??c.externalId,s=s??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(y=>({org:y.org,project:y.project})),!a)throw new Error("--appid is required (or set externalId in app.json)");if(!s)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?he(n,e):H(n,a,s);if(!i.existsSync(l)){let y=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}${y}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
|
|
27
|
+
${n}`)}o(_t,"deploymentNotFoundError");function k(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;_t(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;_t(t,e)}o(k,"findDeployment");function D(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o(D,"getMissingCredentials");async function I(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 k(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),Rt],{selected:r}=await Ot.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==Rt){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await Ot.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(I,"resolveDeployment");import{existsSync as Vo,readFileSync as Ho}from"fs";import{execFile as lo}from"child_process";import{promisify as mo}from"util";import{platform as co}from"os";function B(e,t={}){let{platform:n=co}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(B,"isOS");var Kt="cognite-flows",uo=mo(lo),Lt=o((e,t)=>uo(e,t),"defaultExecFile"),go=-25300,fo=go&255;function yo(e){if(!(e instanceof Error)||!("code"in e)||e.code!==fo)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(yo,"isKeychainNotFoundError");async function jt(e,t,n={}){if(!B("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Lt}=n;await r("security",["add-generic-password","-a",e,"-s",Kt,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(jt,"storeKeyInKeychain");async function me(e,t={}){if(!B("macos",t))return null;let{execFile:n=Lt}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Kt,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if(yo(r))return null;throw r}}o(me,"readKeyFromKeychain");import{pbkdf2 as wo,randomBytes as vo}from"crypto";import{promisify as Co}from"util";import{CompactEncrypt as Po,base64url as Nt,compactDecrypt as Eo}from"jose";var ho=new TextEncoder,So=new TextDecoder,Ve={encode:o(e=>ho.encode(e),"encode"),decode:o(e=>So.decode(e),"decode")};var bo=Co(wo),Ge=6e5,ko="sha512",He="PBKDF2-HMAC-SHA512",Be=16,ue="A256GCM",xo=32,ge=2e6;async function Mt(e,t,n){return await bo(e,t,n,xo,ko)}o(Mt,"deriveKey");async function Vt(e,t,n=Ge){if(!Number.isInteger(n)||n<1||n>ge)throw new Error(`Invalid iterations: must be an integer between 1 and ${ge}`);let r=vo(Be),i=await Mt(t,r,n);return await new Po(Ve.encode(e)).setProtectedHeader({alg:"dir",enc:ue,kdf:He,kdf_iter:n,kdf_salt:Nt.encode(r)}).encrypt(i)}o(Vt,"encryptStringAsJwe");async function Ht(e,t){let{plaintext:n}=await Eo(e,async r=>{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(r.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(r.alg)}"; only "dir" is supported`);if(r.enc!==ue)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${ue}" is supported`);if(r.kdf!==He)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${He}" is supported`);let i=Number(r.kdf_iter);if(!Number.isInteger(i)||i<1||i>ge)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${ge}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=Nt.decode(r.kdf_salt);if(s.length!==Be)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Be} bytes, got ${s.length}`);return await Mt(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[ue]});return Ve.decode(n)}o(Ht,"decryptJweAsString");function Ao(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Ao,"isJweCompact");var Bt=Ao;import{existsSync as Io,readdirSync as $o,readFileSync as Fo}from"fs";import{join as Je}from"path";import{homedir as Do}from"os";import{join as Gt}from"path";function F(e={}){let{env:t=process.env,homedir:n=Do}=e,r=t.COGNITE_CLI_HOME?.trim()||Gt(n(),".cognite-cli");return{home:r,keysDir:Gt(r,"keys")}}o(F,"getConfig");var ee=".pub.pem",Ye=".key.jwe",qe=".meta.json";function fe(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(fe,"formatLocalKeySource");function To(e){return{existsSync:e.existsSync??Io,readdirSync:e.readdirSync??$o,readFileSync:e.readFileSync??((t,n)=>Fo(t,n)),isOS:e.isOS??(t=>B(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>me(t))}}o(To,"resolveDeps");function Oo(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(Oo,"readEmailFromMeta");function Ro(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(ee)):[]}o(Ro,"publicKeyEntries");function _o(e){return e.slice(0,-ee.length)}o(_o,"kidFromPublicKeyFilename");async function Uo(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=Je(t,`${e}${Ye}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}o(Uo,"resolveSource");async function ye(e=F().keysDir,t={}){let n=To(t),r=new Set,i=Ro(e,n).flatMap(s=>{let a=_o(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await Uo(s,e,n),c=Je(e,`${s}${qe}`),l;try{l=Oo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:Je(e,a),email:l}}))}o(ye,"discoverLocalKeys");import Ko from"enquirer";async function Lo(e){return Ko.prompt(e)}o(Lo,"defaultPrompt");async function Jt(e,t={}){let{prompt:n=Lo}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return r}o(Jt,"promptPassphrase");import No from"enquirer";import{statSync as jo}from"fs";function Yt(e,t=jo){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}o(Yt,"sortByMtime");async function Mo(e){return No.prompt(e)}o(Mo,"defaultPrompt");async function qt(e,t={}){if(e.length===1)return e[0];let{prompt:n=Mo,sortByMtime:r=Yt}=t,i=r(e),s=i[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await n({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,fe(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(qt,"promptSigningIdentity");function Bo(e){return{existsSync:e.existsSync??Vo,readFileSync:e.readFileSync??((t,n)=>Ho(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??me,decryptJweAsString:e.decryptJweAsString??Ht,discoverLocalKeys:e.discoverLocalKeys??ye,keysDir:e.keysDir??F().keysDir,promptPassphrase:e.promptPassphrase??Jt,promptSigningIdentity:e.promptSigningIdentity??qt}}o(Bo,"resolveDeps");async function zt(e,t={}){let n=Bo(t);if(e.keyPath){if(!n.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=n.readFileSync(e.keyPath,"utf-8").trim();if(Bt(s)){let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await n.decryptJweAsString(s,a),kid:e.kid}}return{privateKeyPem:s,kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i=e.kid?r.find(s=>s.kid===e.kid):await n.promptSigningIdentity(r);if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await n.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{let s=await n.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await n.decryptJweAsString(n.readFileSync(i.source.path,"utf-8"),s),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(zt,"resolvePrivateKey");var ni=o(async(e,t,n,r,i)=>{let s=await A(e,{interactive:i.interactive??!1,appId:t,orgHint:i.org});await new P(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function ri(e){let t=Go(e);return new ReadableStream({start(n){t.on("data",r=>{let i=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(i))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}o(ri,"createWebStreamFromFile");function oi(e){return{existsSync:e.existsSync??Jo,readFileSync:e.readFileSync??((t,n)=>Yo(t,n)),writeFileSync:e.writeFileSync??qo,createBundleStream:e.createBundleStream??ri,signBundle:e.signBundle??ei,hashDevSignature:e.hashDevSignature??Zo,parseScope:e.parseScope??Qo,validateScopes:e.validateScopes??ti,loadAppConfig:e.loadAppConfig??E,resolvePrivateKey:e.resolvePrivateKey??(t=>zt(t)),submitSignatures:e.submitSignatures??ni,discoverSignatures:e.discoverSignatures??Z}}o(oi,"resolveDeps");async function Wt(e,t,n={},r=process.cwd()){let i=oi(n),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(y=>({org:y.org,project:y.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?he(r,e):V(r,s,a);if(!i.existsSync(l)){let y=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}${y}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
|
|
25
28
|
${d.join(`
|
|
26
|
-
`)}`);let{privateKeyPem:m,kid:g}=await i.resolvePrivateKey({keyPath:t.key?he(
|
|
27
|
-
Payload:`,JSON.stringify(S.payload,null,2));let h=Array.from(new Set([...i.discoverSignatures(l),S.token])),
|
|
28
|
-
To publish: npx @cognite/cli apps publish .`)}o(
|
|
29
|
+
`)}`);let{privateKeyPem:m,kid:g}=await i.resolvePrivateKey({keyPath:t.key?he(r,t.key):void 0,kid:t.signingIdentity}),u;if(t.devSig){let y=he(r,t.devSig);if(!i.existsSync(y))throw new Error(`Dev signature file not found: ${y}`);let C=i.readFileSync(y,"utf-8").trim();u=await i.hashDevSignature(C)}let f=i.createBundleStream(l),S=await i.signBundle({privateKeyPem:m,kid:g,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p,devSignatureSha256:u}),v=t.output?he(r,t.output):Xo(Wo(l),`${zo(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(v,S.token,"utf-8"),console.log(`\u2705 Signed: ${v}`),console.log(` kid: ${S.kid}`),console.log(` bundle: ${S.payload.bundleSha256}`),console.log(` scopes: ${S.payload.scopes.map(y=>`${y.org}/${y.project}`).join(", ")}`),t.verbose&&console.log(`
|
|
30
|
+
Payload:`,JSON.stringify(S.payload,null,2));let h=Array.from(new Set([...i.discoverSignatures(l),S.token])),b=t.interactive?await I(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):k(c.deployments,t.deployment);if(!t.interactive){let y=D(b);if(y.length>0)throw new Error(`Deployment ${b.org}/${b.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps sign --interactive\` for browser-based authentication instead.`)}await i.submitSignatures(b,s,a,h,t),console.log(`
|
|
31
|
+
To publish: npx @cognite/cli apps publish .`)}o(Wt,"handleSign");function Xt(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","After signing, submit the signature to App Hosting using browser-based auth",!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)").action((n,r)=>{let i={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return Wt(n,i,t)})}o(Xt,"registerSignCommand");import{existsSync as ii}from"fs";import{resolve as si}from"path";import{config as ai}from"dotenv";function R(e,t={existsSync:ii,config:ai}){let n=si(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(R,"loadEnvFile");function _(e){e.infra!=="appsApi"&&(console.error(`
|
|
29
32
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
30
33
|
|
|
31
34
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
32
35
|
the old CDF Application Registry. This deploy path has been removed.
|
|
33
36
|
|
|
34
37
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
35
|
-
`),process.exit(1))}o(_,"assertAppHostingInfra");async function pi(e){let t=process.cwd();R(t);let
|
|
38
|
+
`),process.exit(1))}o(_,"assertAppHostingInfra");async function pi(e){let t=process.cwd();R(t);let n=E(t);_(n);let r=e.interactive?await I(n,e):k(n.deployments,e.deployment);if(!e.interactive){let d=D(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await A(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof T?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(pi,"handleActivate");function Zt(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",`
|
|
36
39
|
Examples:
|
|
37
40
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
38
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,
|
|
39
|
-
`),initial:!1};async function mi(e){return!!(await e([di])).useSpecKit}o(mi,"promptForSpecKit");async function ui(e,t,
|
|
40
|
-
`),i=`link .specify/memory/constitution.md in specifyDir=${
|
|
41
|
-
npm run dev`,i="To deploy your app:",
|
|
41
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>pi(n))}o(Zt,"registerActivateCommand");import{readdirSync as ki}from"fs";import{basename as gn,dirname as xi,normalize as Ai,resolve as ne}from"path";import{fileURLToPath as Di,pathToFileURL as Ii}from"url";import{Logger as $i,runner as Fi}from"hygen";import{execFileSync as Se}from"child_process";function Qt(e={}){let{execFileSync:t=Se}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(Qt,"isGitInstalled");function en(e,t={}){let{execFileSync:n=Se}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(en,"isInsideGitRepo");function tn(e,t={}){let{execFileSync:n=Se}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(tn,"gitInitAndCommit");function nn(e={}){let{execFileSync:t=Se}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(nn,"gitUserEmail");import{safeParse as ci}from"valibot";function te(e,t){return n=>{let r=ci(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(te,"toPromptValidator");var rn={name:te("App name",Re),displayName:te("Display name",Oe),baseUrl:te("Base URL",_e),org:te("Org",Ue),project:te("Project",Ke)};function li(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(li,"composeValidators");function we(e){return e.map(t=>{if(!(t.name in rn))return t;let n=rn[t.name];return{...t,validate:li(t.validate,n)}})}o(we,"applySchemaValidators");import{basename as sn}from"path";import an from"enquirer";function on(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(on,"kebabCase");var di={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(`
|
|
42
|
+
`),initial:!1};async function mi(e){return!!(await e([di])).useSpecKit}o(mi,"promptForSpecKit");async function ui(e,t,n){return e!==void 0?e:t?mi(n):!1}o(ui,"resolveSpecKit");function pn({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=an.prompt.bind(an)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(w=>w[1]!==void 0)),l=Object.keys(c).length>0,d=e?sn(process.cwd()):t?sn(t):null,m=l&&d!==null,g=!m&&d?p.map(w=>w.name==="name"?{...w,initial:d}:w):p,u=we(g),f=m?{...c,name:d}:c,S=new Set(Object.keys(f)),v=u.filter(w=>!S.has(w.name)),h=v.findIndex(w=>w.name==="baseUrl"),b;if(h!==-1){let w=v.filter(yr=>yr.name!=="baseUrl"),N=w.length>0?await a(w):{},ce=typeof N.cluster=="string"?N.cluster:"",Y=typeof f.cluster=="string"?f.cluster:"",le=`https://${(ce||Y).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,U=v[h],De=await a([{...U,initial:le}]);b={...N,...De}}else b=v.length>0?await a(v):{};let y={...f,...b},C=typeof y.name=="string"?y.name:"";C&&n(C);let $=await ui(s,v.length>0,a);return r?.($),{...y,name:C,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:$}},"prompt")})}o(pn,"createAppPrompter");async function cn(e,t,n){let r=[];Object.values(t).some(s=>s!==void 0)&&n!==null&&r.push({key:"name",value:n,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&r.push({key:s,value:a,label:`--${on(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(cn,"validatePresets");import{cpSync as wi,mkdirSync as dn,writeFileSync as vi}from"fs";import{dirname as mn,resolve as J}from"path";import{fileURLToPath as Ci}from"url";import{copyFileSync as gi,symlinkSync as fi}from"fs";import{dirname as yi,join as hi}from"path";function Si(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Si,"errno");function ln(e){return e instanceof Error?e.message:String(e)}o(ln,"messageOf");function ve({target:e,linkPath:t,label:n,symlink:r=fi,copyFile:i=gi}){try{return r(e,t),!0}catch(s){let a=Si(s);if(a==="EEXIST")return!0;let p=ln(s);if(a==="EPERM"||a==="EACCES")try{let c=hi(yi(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${p} (copy fallback also failed: ${ln(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o(ve,"linkOrCopyOrWarn");var Pi=J(mn(Ci(import.meta.url)),"..","..","_vendor","spec-kit"),Ei={branch_numbering:"sequential"},bi=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function un({appDir:e,vendorDir:t=Pi}){let n=J(e,".specify"),r=J(n,"memory"),i=`prepare spec-kit install for appDir=${e}`;try{for(let{from:s,to:a}of bi){let p=J(e,a);i=`copy ${s} to ${a}`,dn(mn(p),{recursive:!0}),wi(J(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,vi(J(n,"init-options.json"),`${JSON.stringify(Ei,null,2)}
|
|
43
|
+
`),i=`link .specify/memory/constitution.md in specifyDir=${n}`,dn(r,{recursive:!0}),ve({target:"../../AGENTS.md",linkPath:J(r,"constitution.md"),label:".specify/memory/constitution.md"})}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`installSpecKit failed while ${i} (appDir=${e}, vendorDir=${t}): ${a}`,{cause:s})}}o(un,"installSpecKit");var fn=ne(xi(Di(import.meta.url)),"..","..","_templates");async function Ti(){let e=ne(fn,"app","new","prompt.js");return(await import(Ii(e).href)).default}o(Ti,"loadPromptDefs");function Oi(e,t){return!e||t?null:Ai(e)}o(Oi,"resolveDirName");function Ri(e,t,n){if(e)return{cwd:process.cwd(),display:"."};let r=t??n;if(!r)throw new Error("App creation completed without a target directory or name.");return{cwd:ne(process.cwd(),r),display:r}}o(Ri,"resolveAppLocation");function _i(e,t,n){let r=` npm install
|
|
44
|
+
npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
|
|
42
45
|
To start spec-driven development:
|
|
43
46
|
Run /speckit.specify in Claude Code or Cursor and describe your app.
|
|
44
47
|
`:"",p=` # Or fully non-interactive (deploys first target from app.json):
|
|
@@ -46,10 +49,10 @@ To start spec-driven development:
|
|
|
46
49
|
\u2705 App created successfully in current directory!
|
|
47
50
|
|
|
48
51
|
Next steps:
|
|
49
|
-
${
|
|
50
|
-
${
|
|
52
|
+
${r}
|
|
53
|
+
${a}
|
|
51
54
|
${i}
|
|
52
|
-
${
|
|
55
|
+
${s}
|
|
53
56
|
${p}
|
|
54
57
|
`);return}console.log(`
|
|
55
58
|
\u2705 App created successfully!
|
|
@@ -58,14 +61,14 @@ To open in Cursor:
|
|
|
58
61
|
cursor "${t}"
|
|
59
62
|
Or:
|
|
60
63
|
cd "${t}"
|
|
61
|
-
${
|
|
62
|
-
${
|
|
64
|
+
${r}
|
|
65
|
+
${a}
|
|
63
66
|
${i}
|
|
64
67
|
cd "${t}"
|
|
65
|
-
${
|
|
68
|
+
${s}
|
|
66
69
|
${p}
|
|
67
|
-
`)}o(_i,"printSuccessMessage");async function Ui(e){try{let{execSkillsCli:t,pullAllArgs:
|
|
68
|
-
${
|
|
70
|
+
`)}o(_i,"printSuccessMessage");async function Ui(e){try{let{execSkillsCli:t,pullAllArgs:n}=await import("../skills-GQ5TZKCM.js");console.log("\u{1F9E0} Pulling skills into your app..."),t(n(),{cwd:e,timeout:3e4,stdio:["pipe","pipe","inherit"]});let r=ne(e,".agents","skills"),i=0;try{i=ki(r).length}catch{console.warn(`Skills directory not found after pull \u2014 no skills may have been installed (expected: ${r})`)}let s=i>0?`${i} skills`:"skills";console.log(`\u2705 Installed ${s} successfully to
|
|
71
|
+
${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(Ui,"pullSkillsInto");function Ki(e,t={}){let{isGitInstalled:n=Qt,isInsideGitRepo:r=en,gitInitAndCommit:i=tn}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(Ki,"maybeInitGit");async function Li(e,t){let n=e==="."||e==="./",r=Oi(e,n),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Ti(),c=we(p),l=n?gn(process.cwd()):r?gn(r):null;await cn(c,a,l);let d=pn({isCurrentDir:n,dirName:r,onAppName:o(g=>{i=g},"onAppName"),onUseSpecKit:o(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await Fi(["app","new"],{templates:fn,cwd:process.cwd(),logger:new $i(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Ri(n,r,i);ve({target:"AGENTS.md",linkPath:ne(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&un({appDir:m.cwd}),await Ui(m.cwd),Ki(m.cwd),_i(n,m.display,s)}o(Li,"handleCreate");function yn(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",`
|
|
69
72
|
Non-interactive use (CI, scripts, AI agents):
|
|
70
73
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
71
74
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -78,17 +81,17 @@ Examples:
|
|
|
78
81
|
--display-name "My App" --description "My app" \\
|
|
79
82
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
80
83
|
--base-url https://greenfield.cognitedata.com
|
|
81
|
-
Fully non-interactive`).action(
|
|
84
|
+
Fully non-interactive`).action(Li)}o(yn,"registerCreateCommand");import ji from"path";async function Ni(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new P(r)}o(Ni,"defaultGetApiClient");async function Mi(e,t,n={}){let{loadEnvFile:r=R,loadAppConfig:i=E,getApiClient:s=Ni}=n,a=ji.resolve(process.cwd(),e);r(a);let p=i(a);_(p);let c=t.interactive?await I(p,t):k(p.deployments,t.deployment);if(!t.interactive){let g=D(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let l=await s(c,t,p.externalId),{externalId:d}=p,m=await l.getActiveVersion(d);if(!m){console.log(` ${d} has no active version \u2014 nothing to deactivate.`);return}await l.deactivateVersion(d,m.version),console.log(`\u2713 Deactivated ${d} @ ${m.version} \u2014 active alias removed`)}o(Mi,"handleDeactivate");function hn(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",`
|
|
82
85
|
Examples:
|
|
83
86
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
84
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,
|
|
85
|
-
`))}o(
|
|
86
|
-
\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
|
|
87
|
-
To sign: npx @cognite/cli apps sign --interactive${
|
|
87
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Mi(t,n))}o(hn,"registerDeactivateCommand");import{mkdir as Ji,readFile as Yi}from"fs/promises";import{basename as qi,dirname as zi}from"path";import j from"fs";import x from"path";import{parseAndValidateManifestConfig as Vi}from"@cognite/app-sdk/vite";import{BlobReader as Hi,Uint8ArrayWriter as Bi,ZipWriter as Gi}from"@zip.js/zip.js";var ze="package.json",We="package-lock.json",Sn="manifest.json",Xe=".cognite",Ze=class Ze{constructor(t="dist"){this.distPath=x.isAbsolute(t)?t:x.join(process.cwd(),t),this.appRoot=x.dirname(this.distPath)}validateBuildDirectory(){if(!j.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=x.join(this.appRoot,ze);if(!j.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=x.join(this.appRoot,We);if(!j.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new Gi(new Bi,{level:9}),i=o(async(c,l)=>{await r.add(l,new Hi(await j.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await j.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=x.join(c,d.name);d.isDirectory()?await s(m):await i(m,x.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=x.join(this.appRoot,ze);await i(c,x.posix.join(Xe,ze));let l=x.join(this.appRoot,Sn);if(j.existsSync(l)){let m=j.readFileSync(l,"utf-8");Vi(m,l),await i(l,x.posix.join(Xe,Sn))}let d=x.join(this.appRoot,We);await i(d,x.posix.join(Xe,We)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await j.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}};o(Ze,"ApplicationPackager");var re=Ze;async function Ce(e,t,n,r){let{externalId:i,name:s,description:a,versionTag:p}=t,c=V(n,i,p);await Ji(zi(c),{recursive:!0}),await new re(`${n}/dist`).createZip(c,!0);let l=await Yi(c);await new P(e).deploy(i,s,a,p,l,qi(c),r)}o(Ce,"packageAndUpload");var Qe=o(async(e,t,n)=>{let r=await Q(e,n);await Ce(r,t,n,e.published)},"deploy");import{execSync as Wi}from"child_process";function et(e,t=!0,n={execSync:Wi}){console.log("\u{1F4E6} Building app with npm..."),n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(et,"buildApp");function wn(e,t){let{org:n,project:r,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(wn,"generateFusionUrl");function vn(e,t,n){let r=n?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=n?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",r,"=".repeat(r.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
|
|
88
|
+
`))}o(vn,"printDeployInfo");function Cn(e,t){console.log(`
|
|
89
|
+
\u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let n=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
|
|
90
|
+
To sign: npx @cognite/cli apps sign --interactive${n}`),console.log(`To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=wn(t,e);r&&console.log(`
|
|
88
91
|
\u{1F517} Open your app:
|
|
89
|
-
${
|
|
90
|
-
\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},
|
|
91
|
-
\u{1F4E4} Deploying to ${t.project}...`),await Ce(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},
|
|
92
|
+
${r}`)}o(Cn,"printDeployResult");async function Xi(e,t,n,r,i){let s=D(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.`);vn(e,t,!1),r.skipBuild||et(n),console.log(`
|
|
93
|
+
\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},n),Cn(e,t)}o(Xi,"handleDeployNonInteractive");async function Zi(e,t,n,r){vn(e,t,!0),r.skipBuild||et(n);let i=await A(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
|
|
94
|
+
\u{1F4E4} Deploying to ${t.project}...`),await Ce(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n,!1),Cn(e,t)}o(Zi,"handleDeployInteractive");async function Qi(e,t=process.cwd(),n={}){let{loadEnvFile:r=R,loadAppConfig:i=E,deploy:s=Qe}=n;r(t);let a=i(t);if(_(a),e.interactive){let c=await I(a,e);await Zi(a,c,t,e);return}let p=k(a.deployments,e.deployment);await Xi(a,p,t,e,s)}o(Qi,"handleDeploy");function Pn(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",`
|
|
92
95
|
Environment (non-interactive):
|
|
93
96
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
94
97
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -102,42 +105,37 @@ Examples:
|
|
|
102
105
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
103
106
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
104
107
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
105
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Qi(t))}o(
|
|
108
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Qi(t))}o(Pn,"registerDeployCommand");async function es(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new P(r)}o(es,"defaultBuildApiClient");async function ts(e,t={}){let n=t.loadEnvFile??R,r=t.loadAppConfig??E,i=t.buildApiClient??es,s=t.discoverSignatures??Z,a=process.cwd();n(a);let p=r(a);_(p);let c=e.interactive?await I(p,e):k(p.deployments,e.deployment);if(!e.interactive){let f=D(c);if(f.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${f.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,g;try{g=await l.getVersion(d,m)}catch(f){throw f instanceof T?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}if(g.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(g.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(g.lifecycleState==="DEPRECATED"||g.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${g.lifecycleState} (terminal).`);let u=s(V(a,d,m));u.length>0&&await l.submitSignatures(d,m,u),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(ts,"handlePublish");function En(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",`
|
|
106
109
|
Examples:
|
|
107
110
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
108
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,
|
|
109
|
-
`)},"info"),error:o(e=>{process.stderr.write(`${e}
|
|
110
|
-
`)},"error")},ss={spawnSync:rs,mkdirSync:ns,logger:is};function as(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(as,"hasMkcert");function ps({certDir:e=et(process.cwd(),"certificates/mkcert"),domains:t=os,deps:r={}}={}){let n={...ss,...r},{spawnSync:i,mkdirSync:a,logger:s}=n;if(!as(i))throw s.error("Error: mkcert is not installed."),s.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),s.error("On Windows: choco install mkcert (or scoop install mkcert)"),s.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");a(e,{recursive:!0});let c=et(e,"localhost.pem"),l=et(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 s.info(""),s.info("Certificates generated:"),s.info(` cert: ${c}`),s.info(` key: ${l}`),{certFile:c,keyFile:l}}o(ps,"setupHttps");function cs(e){ps({certDir:e.certDir})}o(cs,"handleSetupHttps");function Cr(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",`
|
|
111
|
-
Examples:
|
|
112
|
-
npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
|
|
113
|
-
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>cs(t))}o(Cr,"registerSetupHttpsCommand");function ls(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(ls,"describeStatus");async function ds(e){let t=process.cwd();R(t);let r=E(t);_(r);let n=e.interactive?await I(r,e):b(r.deployments,e.deployment);if(!e.interactive){let s=D(n);if(s.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await A(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),a=new P(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let s=await a.getVersion(r.externalId,r.versionTag),p=ls(s);console.log(`Status: ${p}`),s.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(s){if(s instanceof T){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw s}}o(ds,"handleStatus");function Pr(e){return e.command("status").description("Show the deployment status 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",`
|
|
111
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>ts(n))}o(En,"registerPublishCommand");function ns(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(ns,"describeStatus");async function rs(e){let t=process.cwd();R(t);let n=E(t);_(n);let r=e.interactive?await I(n,e):k(n.deployments,e.deployment);if(!e.interactive){let a=D(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await A(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new P(i);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag),p=ns(a);console.log(`Status: ${p}`),a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof T){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(rs,"handleStatus");function bn(e){return e.command("status").description("Show the deployment status 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",`
|
|
114
112
|
Examples:
|
|
115
113
|
npx @cognite/cli apps status . Status using env-var auth
|
|
116
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,
|
|
114
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>rs(n))}o(bn,"registerStatusCommand");function kn(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return yn(t),Pn(t),bn(t),En(t),Zt(t),hn(t),gt(t),Xt(t),t}o(kn,"registerAppsCommand");import{existsSync as Es,mkdirSync as bs,writeFileSync as ks}from"fs";import{dirname as at,join as ke}from"path";import{generateSigningKeyPair as xs}from"@cognite/app-sdk/codesigning";import As from"open";function xn(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,i=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(n,r,s))}o(xn,"addMonthsClamped");function tt(e){return e.toISOString().slice(0,10)}o(tt,"formatIsoDate");function An(e=new Date){return tt(e)}o(An,"todayIso");import os,{Chalk as is}from"chalk";var oe=new is({level:0});function Dn(e){return e.isTTY?os:oe}o(Dn,"chalkForStream");function ss(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(ss,"pemBodyOneLine");function nt(e,t=oe,n=new Date){let r=e.issuedAt??An(n),i=ss(e.publicKeyPem),s=" ",a=o((c,l)=>`${s}${t.cyan(c)}${t.dim(":")} ${l}
|
|
117
115
|
`,"kv"),p="";return p+=`
|
|
118
116
|
${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
|
|
119
117
|
|
|
120
118
|
`,p+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
121
|
-
`,p+=
|
|
119
|
+
`,p+=a("public_key",t.green(i)),p+=a("email",t.yellow(e.email)),p+=a("capabilities",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),p+=a("issued_at",t.green(r)),p+=a("expires",t.green(e.expires)),p+=a("revoked_at",t.dim("null")),p}o(nt,"renderRegistryEntry");import as from"clipboardy";function In(e){return as.write(e)}o(In,"copyToClipboard");import{email as ps,pipe as cs,safeParse as ls,string as ds}from"valibot";var ms=cs(ds(),ps());function ie(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!ls(ms,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(ie,"parseEmail");function se(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}o(se,"parseExpiryMonths");var us="https://cognite.zendesk.com",gs="360001234312",fs="tf_360015295097",ys="cognite_flows",hs="360004885031";function Ss(e,t){let n=new URLSearchParams({locale:"en-us",brand_id:hs,return_to:e});return`${t}/access?${n}`}o(Ss,"withLogin");function ws(e,t,n){let r=new URLSearchParams({ticket_form_id:gs,tf_priority:"normal",tf_subject:e,[fs]:ys,tf_description:t});return Ss(`${n}/hc/en-us/requests/new?${r}`,n)}o(ws,"buildUrl");function vs(e){return e.join("<br>")}o(vs,"toHtml");function $n(e,t,n,r,i=us){return ws(`Public Key Registration: ${t}`,vs(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to signing-keys.yaml:","",...r.replace(/\r\n/g,`
|
|
122
120
|
`).split(`
|
|
123
|
-
`),"","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]),i)}o(
|
|
124
|
-
`,"passphraseMismatchMsg"),
|
|
121
|
+
`),"","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]),i)}o($n,"buildKeyRegistrationUrl");import it from"enquirer";var Pe=3,Fn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Tn=`Key expiry in months (${1}-${12})`,On="Email address for the registry entry",Rn=`Passphrase for the encrypted private key (min ${15} chars)`,_n="Confirm passphrase",Un=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Kn=o(e=>`Passphrases do not match (attempt ${e}/${Pe}).
|
|
122
|
+
`,"passphraseMismatchMsg"),Ln=`Passphrase confirmation failed after ${Pe} attempts`,jn=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Nn="How would you like to submit your key registration?",Mn="Open in browser",Vn="Copy link to clipboard";async function be(e){return it.prompt(e)}o(be,"defaultPrompt");function st(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(st,"parserAsValidator");var Ps=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function Ee(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(!Ps.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(Ee,"parseKid");async function Hn(e={}){let{prompt:t=be}=e,{kid:n}=await t({type:"input",name:"kid",message:Fn,validate:st(Ee)});return Ee(n)}o(Hn,"promptKid");async function Bn(e={}){let{prompt:t=o(r=>it.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Nn,choices:[{name:"browser",message:Mn},{name:"clipboard",message:Vn}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}o(Bn,"promptZendeskAction");async function Gn(e={}){let{prompt:t=be}=e,{months:n}=await t({type:"input",name:"months",message:Tn,initial:String(6),validate:st(r=>se(r,"expiry"))});return se(n,"expiry")}o(Gn,"promptExpiryMonths");async function Jn(e={}){let{prompt:t=be,gitUserEmail:n=nn}=e,{email:r}=await t({type:"input",name:"email",message:On,initial:n(),validate:st(i=>ie(i,"email"))});return ie(r,"email")}o(Jn,"promptEmail");async function Yn(e={}){let{prompt:t=be,stderr:n=process.stderr}=e;for(let r=1;r<=Pe;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:Rn,validate:o(a=>a.length>=15?!0:Un(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:_n});if(i===s)return i;n.write(Kn(r))}throw new Error(Ln)}o(Yn,"promptPassphrase");async function qn(e,t={}){let{prompt:n=o(i=>it.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:jn(e),initial:!1});return r}o(qn,"promptConfirmOverwrite");function Ds(e){return{writeFileSync:e.writeFileSync??ks,mkdirSync:e.mkdirSync??bs,existsSync:e.existsSync??Es,generateSigningKeyPair:e.generateSigningKeyPair??xs,encryptStringAsJwe:e.encryptStringAsJwe??Vt,storeKeyInKeychain:e.storeKeyInKeychain??jt,isOS:e.isOS??(t=>B(t)),promptKid:e.promptKid??Hn,promptExpiryMonths:e.promptExpiryMonths??Gn,promptEmail:e.promptEmail??Jn,promptPassphrase:e.promptPassphrase??Yn,promptConfirmOverwrite:e.promptConfirmOverwrite??qn,discoverLocalKeys:e.discoverLocalKeys??(()=>ye()),promptZendeskAction:e.promptZendeskAction??Bn,openUrl:e.openUrl??(t=>As(t)),copyToClipboard:e.copyToClipboard??In,isInteractive:e.isInteractive??(()=>process.stdout.isTTY===!0)}}o(Ds,"resolveDeps");function Wn(e,t={}){let n=Ds(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip macOS Keychain and write a passphrase-encrypted private key under ${F().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").action(i=>Fs(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Is(n))}o(Wn,"registerKeysCommand");async function Is(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
125
123
|
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${F().keysDir}).
|
|
126
|
-
`);return}let
|
|
127
|
-
`);for(let
|
|
128
|
-
`)}o(
|
|
124
|
+
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,fe(a.source),a.email??"\u2014"]),i=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
|
|
125
|
+
`);for(let a of r)process.stdout.write(`${s(a)}
|
|
126
|
+
`)}o(Is,"handleList");function zn(e,t,n){let r=ke(F().keysDir,`${e}${ee}`);return n.mkdirSync(at(r),{recursive:!0}),n.writeFileSync(r,t),r}o(zn,"writePublicKey");async function $s(e,t,n,r,i,{force:s=!1}={}){let a=r??ke(F().keysDir,`${e}${Ye}`);if(i.mkdirSync(at(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,n);return i.writeFileSync(a,p,{mode:384}),a}o($s,"writeEncryptedPrivateKey");async function Fs(e,t,n=new Date){let{isOS:r,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:g,promptConfirmOverwrite:u}=t,f=e.keychain!==!1&&r("macos")&&!e.output,S=e.expires!==void 0?se(e.expires):await l(),v=tt(xn(n,S)),h=e.kid!==void 0?Ee(e.kid):await d(),b=ke(F().keysDir,`${h}${ee}`),y=i(b);if(y&&!e.force&&!await u(h)){process.stderr.write(`Aborted.
|
|
129
127
|
`);return}let C=e.email!==void 0?ie(e.email,"--email"):await m(),$=f?null:await g();process.stderr.write(`
|
|
130
128
|
Generating Ed25519 keypair...
|
|
131
129
|
|
|
132
|
-
`);let{privateKeyPem:w,publicKeyPem:N}=await p(h);if(f){await c(h,w);let U=
|
|
130
|
+
`);let{privateKeyPem:w,publicKeyPem:N}=await p(h);if(f){await c(h,w);let U=zn(h,N,t);process.stderr.write(`Public key: ${U}
|
|
133
131
|
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${h})
|
|
134
|
-
`)}else{if($===null)throw new Error("passphrase is required when not using Keychain");let U=await
|
|
135
|
-
`),process.stderr.write(`Private key: ${U} (JWE, AES-256-GCM, PBKDF2-SHA512 x${
|
|
136
|
-
`),
|
|
137
|
-
`)}let ce=
|
|
132
|
+
`)}else{if($===null)throw new Error("passphrase is required when not using Keychain");let U=await $s(h,w,$,e.output,t,{force:y}),De=zn(h,N,t);process.stderr.write(`Public key: ${De}
|
|
133
|
+
`),process.stderr.write(`Private key: ${U} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Ge.toLocaleString()})
|
|
134
|
+
`),r("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
135
|
+
`)}let ce=ke(F().keysDir,`${h}${qe}`);s(at(ce),{recursive:!0}),a(ce,JSON.stringify({email:C}));let Y=Dn(process.stderr);process.stderr.write(`
|
|
138
136
|
Signing identity (kid): ${Y.green(h)}
|
|
139
137
|
`),process.stderr.write(`Expires: ${v} (${S} month${S===1?"":"s"} from today)
|
|
140
|
-
`);let Ae={kid:h,publicKeyPem:N,email:C,expires:v};process.stderr.write(
|
|
138
|
+
`);let Ae={kid:h,publicKeyPem:N,email:C,expires:v};process.stderr.write(nt(Ae,Y,n));let q=$n(h,C,v,nt(Ae,oe,n));process.stderr.write(`
|
|
141
139
|
${Y.bold("Next:")}
|
|
142
140
|
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
143
141
|
`);let le=e.copyLink?"clipboard":t.isInteractive()?await t.promptZendeskAction():null;if(le==="browser")try{await t.openUrl(q),process.stderr.write(` Opening in browser...
|
|
@@ -148,13 +146,13 @@ ${Y.bold("Next:")}
|
|
|
148
146
|
`);process.stderr.write(`
|
|
149
147
|
2. Once your key is approved, sign your Dune app:
|
|
150
148
|
`),process.stderr.write(` ${Y.cyan(`cognite sign -s ${h}`)}
|
|
151
|
-
`)}o(
|
|
149
|
+
`)}o(Fs,"handleGenerate");var Xn=1e3,Ts=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function Os(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Ts.has(t)?[t,n]:[t,"[REDACTED]"]))}o(Os,"sanitize");function Rs(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(Rs,"getCommandPath");function Zn(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Zn,"tryLoadAppConfig");function pt(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(pt,"commandFromArgv");function Qn(e,t,n=E){e.hook("postAction",async(r,i)=>{try{let s={command:Rs(i),options:Os(i.opts()),success:!0,...Zn(n)};t.track("Flows.CLI.Command",{...s}),await t.flush(Xn)}catch{}})}o(Qn,"instrument");async function er(e,t,n=E){try{let r={command:pt(t),options:{},success:!1,...Zn(n)};e.track("Flows.CLI.Command",{...r}),await e.flush(Xn)}catch{}}o(er,"trackFailure");var _s="ERR_USE_AFTER_CLOSE";function nr(e){return e instanceof Error&&"code"in e&&e.code===_s}o(nr,"isReadlineClosedError");function Us(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Us,"isPlainObject");function ct(e){return e==null||nr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Us(e)&&Object.keys(e).length===0)}o(ct,"isPromptCancel");var tr=!1;function rr(){tr||(tr=!0,process.on("uncaughtException",e=>{nr(e)&&(console.error(`
|
|
152
150
|
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{ct(e)&&(console.error(`
|
|
153
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(
|
|
154
|
-
`),
|
|
155
|
-
`);let u=o(()=>{},"finish"),f=new Promise(S=>{u=S});p.add(f);try{m.track(l,g,u)}catch{u()}f.finally(()=>p.delete(f))},async flush(l=
|
|
156
|
-
`)}}}o(
|
|
157
|
-
`);return
|
|
158
|
-
${
|
|
159
|
-
`)},"onOutdated")})});
|
|
160
|
-
Cancelled.`),process.exit(130)),await
|
|
151
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(rr,"installCancelHandler");import{homedir as Ms}from"os";import or from"mixpanel";var Ks="5c4d853e7c3b77b1eb4468d5329b278c",ae="cognite-cli",Ls=2e3,ir={env:process.env,init:or.init.bind(or)},js={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function lt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(lt,"isTelemetryDisabled");function Ns(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(Ns,"isDebug");function sr(e={}){let t=e.env??ir.env,n=e.init??ir.init,r=e.packageName,i=e.cliVersion,s=Ns(t);if(lt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
152
|
+
`),js;let a,p=new Set;function c(){if(a)return a;try{return a=n(Ks,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let g={...d,applicationId:ae,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(g)}
|
|
153
|
+
`);let u=o(()=>{},"finish"),f=new Promise(S=>{u=S});p.add(f);try{m.track(l,g,u)}catch{u()}f.finally(()=>p.delete(f))},async flush(l=Ls){if(p.size===0)return;let d,m=new Promise(g=>{d=setTimeout(g,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)
|
|
154
|
+
`)}}}o(sr,"createTelemetry");var Vs=Ms();function pe(e,t=Vs){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}o(pe,"redactHomedir");var Hs=1e3,Bs="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Gs={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function Js(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(Js,"buildRelease");var Ys="192.0.2.0";function qs(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:pe(t.filename)},...t.abs_path!==void 0&&{abs_path:pe(t.abs_path)},...t.module!==void 0&&{module:pe(t.module)}}))}o(qs,"scrubStackFrames");function zs(e){let t={...e.user,email:void 0,username:void 0,ip_address:Ys,id:void 0},n=e.exception?.values?.map(r=>({...r,value:r.value!==void 0?pe(r.value):r.value,...r.stacktrace!==void 0&&{stacktrace:{...r.stacktrace,frames:qs(r.stacktrace.frames)}}}));return{...e,message:e.message!==void 0?pe(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}}}}o(zs,"scrubPii");function ar(e={}){let t=e.env??process.env;if(lt(t))return Gs;let n=Js(e),r="production",i=null,s=null;function a(){return{dsn:Bs,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:ae},contexts:{cli:{applicationId:ae,node:process.version,platform:process.platform}}},beforeSend:zs}}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;let m={level:"fatal"};l?.command&&(m.tags={command:l.command},m.contexts={cli:{applicationId:ae,node:process.version,platform:process.platform,command:l.command}}),d.captureException(c,m)}catch{}},async flush(c=Hs){try{if(!i)return;await i.flush(c)}catch{}}}}o(ar,"createErrorReporter");import{mkdirSync as Ws,readFileSync as Xs,writeFileSync as Zs}from"fs";import{homedir as Qs}from"os";import{resolve as xe}from"path";import{debuglog as ea}from"util";import{lt as ta,parse as pr}from"semver";var na="https://registry.npmjs.org/@cognite/cli/latest",ra=1500,cr="upgrade-check.json",lr=xe(process.env.XDG_CACHE_HOME||xe(Qs(),".cache"),"@cognite","cli"),dt=ea("cognite-flows");function oa(e,t){return!e||!t||!pr(e)||!pr(t)?!1:ta(e,t)}o(oa,"isOutdated");async function ia({timeout:e=ra,registryUrl:t=na,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let i=await r.json();return typeof i?.version=="string"?i.version:null}catch(r){return dt("fetchLatestVersion failed (%s): %O",t,r),null}}o(ia,"fetchLatestVersion");function sa(e=lr,t=864e5){try{let n=Xs(xe(e,cr),"utf-8"),r=JSON.parse(n);return typeof r.latest!="string"||typeof r.fetchedAt!="number"||Date.now()-r.fetchedAt>t?null:{latest:r.latest,fetchedAt:r.fetchedAt}}catch(n){return dt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(sa,"readUpgradeCheckCache");function aa(e,t){try{Ws(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Zs(xe(e,cr),JSON.stringify(n))}catch(n){dt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(aa,"writeUpgradeCheckCache");async function pa({cacheDir:e=lr,...t}={}){let n=await ia(t);n&&aa(e,n)}o(pa,"startBackgroundUpgradeCheck");function dr(e,{onOutdated:t,cacheDir:n,...r}={}){let i=sa(n);if(i){oa(e,i.latest)&&t?.(e,i.latest);return}pa({cacheDir:n,...r})}o(dr,"preActionUpgradeCheck");import{default as lu,chalkStderr as mr}from"chalk";function ur(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,i="\u2500".repeat(r),s=o(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...n.map(s),`\u2514${i}\u2518`].join(`
|
|
155
|
+
`);return mr.bold.yellow(a)}o(ur,"formatUpgradeWarning");function da(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(da,"isDep0040Warning");var ut=process,ma=ut.emit.bind(ut);ut.emit=function(e,...t){return e==="warning"&&da(t[0])?!1:ma(e,...t)};rr();var W=new la;W.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.3.2-alpha.winurl1").showHelpAfterError().configureOutput({writeOut:o(e=>ca(1,e),"writeOut")});W.hook("preAction",()=>{dr("1.3.2-alpha.winurl1",{onOutdated:o((e,t)=>{console.warn(`
|
|
156
|
+
${ur(e,t)}
|
|
157
|
+
`)},"onOutdated")})});kn(W);Wn(W);var fr=sr({packageName:"@cognite/cli",cliVersion:"1.3.2-alpha.winurl1"}),gr=ar({packageName:"@cognite/cli",cliVersion:"1.3.2-alpha.winurl1"});Qn(W,fr);var mt=process.argv.slice(2);W.parseAsync(mt,{from:"user"}).catch(async e=>{await er(fr,mt),ct(e)&&(console.error(`
|
|
158
|
+
Cancelled.`),process.exit(130)),await gr.captureError(e,{command:pt(mt)}),await gr.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
|