@cognite/cli 1.3.2 → 1.3.3-alpha-zendesk
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_templates/app/new/root/gitignore.ejs.t +3 -0
- package/dist/chunk-5R5NRM2C.js +13 -0
- package/dist/cli/cli.js +91 -62
- package/dist/deploy/index.d.ts +78 -22
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +4 -3
- package/dist/chunk-QOJVLP7E.js +0 -9
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
var et=Object.defineProperty;var s=(n,t)=>et(n,"name",{value:t,configurable:!0});import{mkdir as Et,readFile as St}from"fs/promises";import{basename as Pt,dirname as vt}from"path";var J="https://docs.cognite.com/cdf/access/";function y(n){return n!==null&&typeof n=="object"}s(y,"isRecord");function P(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(P,"isHttpError");function nt(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${J}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${J}`;default:return}}s(nt,"httpStatusHint");function w(n){let t=n instanceof Error?n:new Error(String(n));if(!P(t))return null;let e=nt(t.status);return e?Object.assign(new Error(`${t.message}
|
|
4
|
+
${e}`),{cause:t}):null}s(w,"enrichedHttpError");function rt(n){if(!y(n))return null;let t=n.missing;if(Array.isArray(t))return t;let e=n.data;if(y(e)){let r=e.error;if(y(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(e.missing))return e.missing}return null}s(rt,"findMissingArray");function ot(n,t){if(!P(n)||n.status!==400)return!1;let e=rt(n);return e?e.some(r=>y(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(ot,"isMissingExternalIdError");function b(n,t){return P(n)&&n.status===404||ot(n,t)}s(b,"isNotFoundError");var q=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Y=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,e){super(`Version ${e} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=e}};s(I,"AppVersionNotFoundError");var C=I;function G(n,t){return n.includes(t)}s(G,"includesValue");function st(n){return G(q,n)}s(st,"isAppVersionLifecycleState");function it(n){return G(Y,n)}s(it,"isAppVersionAlias");function at(n){return typeof n.version=="string"&&st(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||it(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(at,"isAppVersion");function z(n){if(!y(n))throw new Error("Invalid version response: not an object");if(!at(n))throw new Error("Invalid version response: missing or malformed fields");return n}s(z,"parseAppVersion");var R=class R{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,e,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:e,description:r}]}})}catch(o){throw w(o)??o}}async uploadVersion(t,e,r,o,a="index.html"){console.log(`\u{1F4E4} Uploading version ${e}...`);let i=new FormData;i.append("file",new Blob([new Uint8Array(r)]),o),i.append("version",e),i.append("entryPath",a);let c=encodeURIComponent(t),p=`${this.appsBasePath}/${c}/versions`,l=await this.client.authenticate(),A=`${this.client.getBaseUrl()}${p}`,m=new AbortController,d=setTimeout(()=>m.abort(),300*1e3),g;try{g=await fetch(A,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:i,signal:m.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new Error("Upload timed out after 5 minutes"):h}finally{clearTimeout(d)}if(!g.ok){let h=await g.text(),k=h;try{let V=JSON.parse(h);if(y(V)){let E=V.error;if(typeof E=="string")k=E;else if(y(E)){let S=E.message,M=E.code;k=typeof S=="string"?S:M!=null?`Unknown error (code: ${M})`:h}else{let S=V.message;k=typeof S=="string"?S:h}}}catch{}let j=g.headers.get("x-request-id"),tt=j?` | X-Request-ID: ${j}`:"",H=Object.assign(new Error(`Upload failed: ${g.status} \u2014 ${k}${tt}`),{status:g.status});throw w(H)??H}console.log(`\u2705 Version ${e} uploaded`)}async getVersion(t,e){let r=encodeURIComponent(t),o=encodeURIComponent(e),a=`${this.appsBasePath}/${r}/versions/${o}`;try{let i=await this.client.get(a);return z(i.data)}catch(i){throw b(i,[t,e])?new C(t,e):w(i)??i}}async getActiveVersion(t){let e=encodeURIComponent(t),r=`${this.appsBasePath}/${e}/active`;try{let o=await this.client.get(r);return z(o.data)}catch(o){if(b(o,[t]))return null;throw w(o)??o}}async updateVersions(t,e){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:e}})}catch(a){throw w(a)??a}}async submitSignatures(t,e,r){let o=encodeURIComponent(t),a=encodeURIComponent(e),i=`${this.appsBasePath}/${o}/versions/${a}/signatures`;try{await this.client.post(i,{data:{items:r}})}catch(c){throw w(c)??c}}};s(R,"AppHostingApi");var $=R;var T=class T{constructor(t){this.api=new $(t)}getVersion(t,e){return this.api.getVersion(t,e)}uploadVersion(t,e,r,o,a){return this.api.uploadVersion(t,e,r,o,a)}async ensureApp(t,e,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,e,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(P(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async submitSignatures(t,e,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${e}...`),await this.api.submitSignatures(t,e,r),console.log("\u2705 Signatures stored"))}async publishVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,e){console.log(`\u{1F680} Publishing and activating version ${e}...`),await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${e} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{alias:{setNull:!0}}}])}async activateVersion(t,e){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==e?r.version:void 0;return await this.api.updateVersions(t,[{version:e,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,e,r,o,a,i,c=!1){console.log(`
|
|
5
|
+
\u{1F680} Deploying application via App Hosting API...
|
|
6
|
+
`);try{await this.ensureApp(t,e,r),await this.uploadVersion(t,o,a,i),c&&await this.publishAndActivate(t,o),console.log(`
|
|
7
|
+
\u2705 Deployment successful!`)}catch(p){let l=p instanceof Error?p.message:String(p);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:p})}}};s(T,"AppHostingClient");var v=T;import{execFileSync as D}from"child_process";import f from"fs";import u from"path";import{parseAndValidateManifestConfig as ct}from"@cognite/app-sdk/vite";import{BlobReader as pt,Uint8ArrayWriter as lt,ZipWriter as dt}from"@zip.js/zip.js";var F="package.json",U="package-lock.json",K="manifest.json",_=".cognite",ut=[/^\.env(\..+)?$/,/^\.secrets?$/,/\.(key|pem|p12|pfx|jks|crt)$/i],N=class N{constructor(t="dist"){this.distPath=u.isAbsolute(t)?t:u.join(process.cwd(),t),this.appRoot=u.dirname(this.distPath)}validateBuildDirectory(){if(!f.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=u.join(this.appRoot,F);if(!f.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let e=u.join(this.appRoot,U);if(!f.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`)}async createZip(t="app.zip",e=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new dt(new lt,{level:9}),o=s(async(p,l)=>{await r.add(l,new pt(await f.openAsBlob(p))),e&&console.log(` \u{1F4C4} ${l}`)},"addFile"),a=s(async p=>{let l=await f.promises.readdir(p,{withFileTypes:!0});for(let A of l){let m=u.join(p,A.name);A.isDirectory()?await a(m):await o(m,u.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),i;try{await a(this.distPath);let p=u.join(this.appRoot,F);await o(p,u.posix.join(_,F));let l=u.join(this.appRoot,K);if(f.existsSync(l)){let m=f.readFileSync(l,"utf-8");ct(m,l),await o(l,u.posix.join(_,K))}let A=u.join(this.appRoot,U);await o(A,u.posix.join(_,U)),i=await r.close()}catch(p){let l=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${l}`)}await f.promises.writeFile(t,i);let c=(i.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${c} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let e;try{e=D("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(d){throw d instanceof Error&&"code"in d&&d.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=f.realpathSync(e),o=f.realpathSync(this.appRoot),a=u.relative(r,o)||".",i=a.replace(/\\/g,"/"),c=a==="."?"":`${i}/`,l=D("git",["-C",e,"ls-files","--",i],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
8
|
+
`).filter(Boolean).map(d=>c?d.slice(c.length):d).filter(d=>ut.some(g=>g.test(u.basename(d))));if(l.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
9
|
+
`+l.map(d=>` ${d}`).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
Hint: git rm --cached <file>`);try{D("git",["-C",e,"archive","--format=zip",`--output=${t}`,"HEAD","--",i])}catch(d){let g=d instanceof Error?d.message:String(d);throw new Error(`Failed to create source archive: ${g}`)}let m=(f.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${u.basename(t)} (${m} MB)`),t}};s(N,"ApplicationPackager");var x=N;import gt from"path";var W=".cognite-bundles";function X(n,t){return`${n}-${t}.zip`}s(X,"bundleFileName");function L(n,t,e){return gt.join(n,W,X(t,e))}s(L,"bundlePath");import{CogniteClient as wt}from"@cognite/sdk";var ft=s(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let t=JSON.parse(n),e={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let a=r.toLowerCase().replace(/_/g,"-");e[a]=o}return e}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),mt=s(n=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=ft()[n]),t||(t=process.env[n]),!t)throw new Error(`Secret not found in environment: ${n}`);return t},"getSecretFromEnv"),ht=s(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=n.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),yt=s(async(n,t)=>{let e=`Basic ${btoa(`${n}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:e,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let a=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
|
|
12
|
+
${a}`)}let o=await r.json();if(!o.access_token)throw new Error("No access token returned from CDF authentication");return o.access_token},"getTokenCdf"),At=s(async(n,t,e,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=ht(r);if(!o)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let a=`https://login.microsoftonline.com/${e}/oauth2/v2.0/token`,i=`https://${o}.cognitedata.com/.default`,c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:t,scope:i,grant_type:"client_credentials"})});if(!c.ok){let l=await c.text();throw new Error(`Failed to get token from Entra ID: ${c.status} ${c.statusText}
|
|
13
|
+
${l}`)}let p=await c.json();if(!p.access_token)throw new Error("No access token returned from Entra ID authentication");return p.access_token},"getTokenEntra"),O=s(async(n,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:e,deploySecretName:r,idpType:o="cdf",tenantId:a,baseUrl:i}=n,c=mt(r);if(o==="entra_id"){if(!a)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return At(e,c,a,i)}return yt(e,c)},"getToken");async function B(n,t,e=process.env,r){let o=await O(n,e),a=e.COGNITE_BASE_URL??n.baseUrl,i=(r??(c=>new wt(c)))({appId:t,project:n.project,baseUrl:a,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await i.authenticate(),i}s(B,"getSdk");async function Z(n,t,e,r){let{externalId:o,name:a,description:i,versionTag:c}=t,p=L(e,o,c);await Et(vt(p),{recursive:!0}),await new x(`${e}/dist`).createZip(p,!0);let l=await St(p);await new v(n).deploy(o,a,i,c,l,Pt(p),r)}s(Z,"packageAndUpload");var xt=s(async(n,t,e)=>{let r=await B(n,e);await Z(r,t,e,n.published)},"deploy");import{existsSync as kt,readFileSync as Ct}from"fs";var Q=[".dev.sig",".cert.sig"];function $t(n,t={}){let e=t.existsSync??kt,r=t.readFileSync??((a,i)=>Ct(a,i)),o=[];for(let a of Q){let i=`${n}${a}`;if(!e(i))continue;let c=r(i,"utf8").trim();c.length>0&&o.push(c)}return o}s($t,"discoverSignatures");export{v as a,x as b,W as c,X as d,L as e,O as f,B as g,Z as h,xt as i,Q as j,$t as k};
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as o,e as
|
|
3
|
-
See: ${
|
|
4
|
-
See: ${
|
|
5
|
-
${n}`),{cause:t}):null}o(
|
|
2
|
+
import{a as o,e as vt}from"../chunk-A5ASLC6T.js";import{writeSync as ba}from"fs";import{Command as ka}from"commander";import{createReadStream as ii,existsSync as si,readFileSync as ai,writeFileSync as pi}from"fs";import{basename as ci,dirname as li,join as di,resolve as ve}from"path";import{hashDevSignature as mi,parseScope as ui,signBundle as gi,validateScopes as fi}from"@cognite/app-sdk/codesigning";var wt="https://docs.cognite.com/cdf/access/";function L(e){return e!==null&&typeof e=="object"}o(L,"isRecord");function Z(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(Z,"isHttpError");function Fr(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
3
|
+
See: ${wt}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
4
|
+
See: ${wt}`;default:return}}o(Fr,"httpStatusHint");function M(e){let t=e instanceof Error?e:new Error(String(e));if(!Z(t))return null;let n=Fr(t.status);return n?Object.assign(new Error(`${t.message}
|
|
5
|
+
${n}`),{cause:t}):null}o(M,"enrichedHttpError");function Tr(e){if(!L(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(L(n)){let r=n.error;if(L(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}o(Tr,"findMissingArray");function Rr(e,t){if(!Z(e)||e.status!==400)return!1;let n=Tr(e);return n?n.some(r=>L(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}o(Rr,"isMissingExternalIdError");function $e(e,t){return Z(e)&&e.status===404||Rr(e,t)}o($e,"isNotFoundError");var Et=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Pt=["ACTIVE","PREVIEW"],Fe=class Fe extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};o(Fe,"AppVersionNotFoundError");var _=Fe;function bt(e,t){return e.includes(t)}o(bt,"includesValue");function Or(e){return bt(Et,e)}o(Or,"isAppVersionLifecycleState");function _r(e){return bt(Pt,e)}o(_r,"isAppVersionAlias");function Ur(e){return typeof e.version=="string"&&Or(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||_r(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(Ur,"isAppVersion");function Ct(e){if(!L(e))throw new Error("Invalid version response: not an object");if(!Ur(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Ct,"parseAppVersion");var Te=class Te{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,u=setTimeout(()=>m.abort(),300*1e3),g;try{g=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(u)}if(!g.ok){let f=await g.text(),S=f;try{let y=JSON.parse(f);if(L(y)){let P=y.error;if(typeof P=="string")S=P;else if(L(P)){let T=P.message,v=P.code;S=typeof T=="string"?T:v!=null?`Unknown error (code: ${v})`:f}else{let T=y.message;S=typeof T=="string"?T:f}}}catch{}let C=g.headers.get("x-request-id"),h=C?` | X-Request-ID: ${C}`:"",k=Object.assign(new Error(`Upload failed: ${g.status} \u2014 ${S}${h}`),{status:g.status});throw M(k)??k}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 Ct(a.data)}catch(a){throw $e(a,[t,n])?new _(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 Ct(i.data)}catch(i){if($e(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(Te,"AppHostingApi");var ue=Te;var Re=class Re{constructor(t){this.api=new ue(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(Z(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,n,r),await this.uploadVersion(t,i,a
|
|
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(
|
|
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"),
|
|
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(Re,"AppHostingClient");var b=Re;import Kr from"path";var kt=".cognite-bundles";function xt(e,t){return`${e}-${t}.zip`}o(xt,"bundleFileName");function V(e,t,n){return Kr.join(e,kt,xt(t,n))}o(V,"bundlePath");import{existsSync as Lr,readFileSync as jr}from"fs";var At=[".dev.sig",".cert.sig"];function Q(e,t={}){let n=t.existsSync??Lr,r=t.readFileSync??((s,a)=>jr(s,a)),i=[];for(let s of At){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(Q,"discoverSignatures");import{existsSync as Wr,readFileSync as Xr}from"fs";import{resolve as Zr}from"path";import{array as Nr,boolean as Mr,check as Dt,forward as It,literal as Vr,maxLength as Hr,minLength as Br,nonEmpty as W,object as $t,optional as H,picklist as Gr,pipe as j,safeParse as Jr,string as U,url as Yr}from"valibot";var Oe=j(U(),W("must not be empty")),_e=j(U(),W("must not be empty"),Hr(256,"must be 256 characters or fewer")),Ue=j(U(),W("must not be empty"),Yr("must be a valid URL")),Ke=j(U(),W("must not be empty")),Le=j(U(),W("must not be empty")),qr=j($t({org:Ke,project:Le,baseUrl:Ue,deployClientId:H(U(),""),deploySecretName:H(U(),""),published:H(Mr(),!1),idpType:H(Gr(["cdf","entra_id"]),"cdf"),tenantId:H(U())}),It(Dt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),It(Dt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),zr=$t({name:Oe,externalId:_e,versionTag:j(U(),W("must not be empty")),description:H(U(),""),deployments:j(Nr(qr),Br(1,"must contain at least one deployment")),infra:H(Vr("appsApi"))});function je(e){let t=Jr(zr,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(je,"validateAppConfig");function w(e,t={}){let{validator:n=je,existsSync:r=Wr,readFileSync:i=Xr}=t,s=Zr(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(w,"loadAppConfig");import{CogniteClient as Po}from"@cognite/sdk";import{CogniteClient as oo}from"@cognite/sdk";var Qr=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"),eo=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Qr()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),to=o(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),no=o(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"),ro=o(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=to(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"),Ne=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=eo(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return ro(n,p,s,a)}return no(n,p)},"getToken");async function ee(e,t,n=process.env,r){let i=await Ne(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new oo(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(ee,"getSdk");import mo from"os";import uo from"path";import go from"open";import{buildAuthorizationUrl as fo,calculatePKCECodeChallenge as yo,discovery as ho,None as So,randomPKCECodeVerifier as vo,randomState as wo}from"openid-client";import io from"https";import{authorizationCodeGrant as so}from"openid-client";function Ft(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}o(Ft,"escapeHtml");function Me(e,t,n){let r=Ft(t),i=Ft(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
11
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); }
|
|
@@ -16,28 +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(
|
|
19
|
+
</body></html>`}o(Me,"generateHtml");async function ao(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(Me("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(Me("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(ao,"handleCallback");function po(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}o(po,"formatTimeoutMinutes");function Tt(e,t,n,r,i,s={createServer:io.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:so}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,u)=>{try{let g=await ao(m,u,n,r,i,s);g.shouldClose&&(d(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){d(),p(g instanceof Error?g:new Error(String(g)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${po(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(Tt,"startCallbackServer");import{execFileSync as co}from"child_process";import Ve from"fs";import Rt from"path";function Ot(e,t,n){return{key:n.readFileSync(e),cert:n.readFileSync(t)}}o(Ot,"loadCertificates");function lo(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"),Ot(t,n,r)}catch{throw new Error(`Failed to generate self-signed certificate. Make sure openssl is installed.
|
|
20
20
|
On macOS: openssl is pre-installed
|
|
21
21
|
On Linux: sudo apt-get install openssl
|
|
22
|
-
On Windows: Install OpenSSL or use WSL`)}}o(
|
|
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,
|
|
24
|
-
`);try{await n.open(c)}catch(
|
|
25
|
-
`),n.logger.error(c),n.logger.error("")}return n.startCallbackServer(t,l,r,i,
|
|
22
|
+
On Windows: Install OpenSSL or use WSL`)}}o(lo,"generateCertificate");function _t(e,t={existsSync:Ve.existsSync,readFileSync:o(n=>Ve.readFileSync(n),"readFileSync"),mkdirSync:o((n,r)=>{Ve.mkdirSync(n,r)},"mkdirSync"),execFileSync:co}){let n=Rt.join(e,"localhost-key.pem"),r=Rt.join(e,"localhost-cert.pem");return t.existsSync(n)&&t.existsSync(r)?Ot(n,r,t):lo(e,n,r,t)}o(_t,"getOrCreateCertificates");var Co={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:uo.join(mo.homedir(),".cdf-login")},Eo={open:go,getOrCreateCertificates:_t,startCallbackServer:Tt,discovery:ho,buildAuthorizationUrl:fo,randomPKCECodeVerifier:vo,calculatePKCECodeChallenge:yo,randomState:wo,logger:console};async function Kt(e,t=Co,n){return n===void 0?Ut(e,t,Eo):Ut(e,t,n)}o(Kt,"login");async function Ut(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,So()),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(Ut,"loginImpl");async function A(e,t,n={}){let{login:r=Kt,getSdk:i=ee,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 Lt from"enquirer";var jt="Enter custom target...";function Nt(e,t){let n=t.map((r,i)=>` ${i}: ${r.org}/${r.project}`).join(`
|
|
26
26
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
27
|
-
${n}`)}o(ft,"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 r=e[Number.parseInt(t)];if(r)return r;ft(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;ft(t,e)}o(b,"findDeployment");function $(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o($,"getMissingCredentials");async function T(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return b(e.deployments,t.deployment);let n=[...e.deployments.map(a=>`${a.org}/${a.project}`),gt],{selected:r}=await ut.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==gt){let a=e.deployments.find(s=>`${s.org}/${s.project}`===r);if(a)return a;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let i=await ut.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(T,"resolveDeployment");import{existsSync as Rr}from"fs";import{resolve as _r}from"path";import{config as Ur}from"dotenv";function F(e,t={existsSync:Rr,config:Ur}){let n=_r(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o(F,"loadEnvFile");function O(e){e.infra!=="appsApi"&&(console.error(`
|
|
27
|
+
${n}`)}o(Nt,"deploymentNotFoundError");function x(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let r=e[Number.parseInt(t)];if(r)return r;Nt(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;Nt(t,e)}o(x,"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 x(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),jt],{selected:r}=await Lt.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==jt){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 Lt.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 ni,readFileSync as ri}from"fs";import{execFile as ko}from"child_process";import{promisify as xo}from"util";import{execFileSync as Mt}from"child_process";import{platform as He}from"os";import bo from"path";function B(e,t={}){let{platform:n=He}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(B,"isOS");function Vt(e,t={}){let{exec:n=Mt,platform:r=He}=t;try{let i=r();i==="darwin"?n("open",[e]):i==="win32"?n("cmd",["/c","start","",e]):n("xdg-open",[e])}catch{}}o(Vt,"openInBrowser");function Ht(e,t={}){let{exec:n=Mt,platform:r=He}=t;try{let i=r();i==="darwin"?n("open",["-R",e]):i==="win32"?n("explorer",[`/select,${e}`]):n("xdg-open",[bo.dirname(e)])}catch{}}o(Ht,"revealInFileManager");var Gt="cognite-flows",Ao=xo(ko),Jt=o((e,t)=>Ao(e,t),"defaultExecFile"),Do=-25300,Io=Do&255;function $o(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Io)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o($o,"isKeychainNotFoundError");async function Yt(e,t,n={}){if(!B("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:r=Jt}=n;await r("security",["add-generic-password","-a",e,"-s",Gt,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Yt,"storeKeyInKeychain");async function ge(e,t={}){if(!B("macos",t))return null;let{execFile:n=Jt}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",Gt,"-w"]);return Buffer.from(r.trim(),"base64").toString("utf-8")}catch(r){if($o(r))return null;throw r}}o(ge,"readKeyFromKeychain");import{pbkdf2 as Ro,randomBytes as Oo}from"crypto";import{promisify as _o}from"util";import{CompactEncrypt as Uo,base64url as qt,compactDecrypt as Ko}from"jose";var Fo=new TextEncoder,To=new TextDecoder,Be={encode:o(e=>Fo.encode(e),"encode"),decode:o(e=>To.decode(e),"decode")};var Lo=_o(Ro),Ye=6e5,jo="sha512",Ge="PBKDF2-HMAC-SHA512",Je=16,fe="A256GCM",No=32,ye=2e6;async function zt(e,t,n){return await Lo(e,t,n,No,jo)}o(zt,"deriveKey");async function Wt(e,t,n=Ye){if(!Number.isInteger(n)||n<1||n>ye)throw new Error(`Invalid iterations: must be an integer between 1 and ${ye}`);let r=Oo(Je),i=await zt(t,r,n);return await new Uo(Be.encode(e)).setProtectedHeader({alg:"dir",enc:fe,kdf:Ge,kdf_iter:n,kdf_salt:qt.encode(r)}).encrypt(i)}o(Wt,"encryptStringAsJwe");async function Xt(e,t){let{plaintext:n}=await Ko(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!==fe)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${fe}" is supported`);if(r.kdf!==Ge)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Ge}" is supported`);let i=Number(r.kdf_iter);if(!Number.isInteger(i)||i<1||i>ye)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${ye}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=qt.decode(r.kdf_salt);if(s.length!==Je)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Je} bytes, got ${s.length}`);return await zt(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[fe]});return Be.decode(n)}o(Xt,"decryptJweAsString");function Mo(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Mo,"isJweCompact");var Zt=Mo;import{existsSync as Ho,readdirSync as Bo,readFileSync as Go}from"fs";import{join as qe}from"path";import{homedir as Vo}from"os";import{join as Qt}from"path";function R(e={}){let{env:t=process.env,homedir:n=Vo}=e,r=t.COGNITE_CLI_HOME?.trim()||Qt(n(),".cognite-cli");return{home:r,keysDir:Qt(r,"keys")}}o(R,"getConfig");var te=".pub.pem",ze=".key.jwe",We=".meta.json";function he(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(he,"formatLocalKeySource");function Jo(e){return{existsSync:e.existsSync??Ho,readdirSync:e.readdirSync??Bo,readFileSync:e.readFileSync??((t,n)=>Go(t,n)),isOS:e.isOS??(t=>B(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>ge(t))}}o(Jo,"resolveDeps");function Yo(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(Yo,"readEmailFromMeta");function qo(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(te)):[]}o(qo,"publicKeyEntries");function zo(e){return e.slice(0,-te.length)}o(zo,"kidFromPublicKeyFilename");async function Wo(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let r=qe(t,`${e}${ze}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}o(Wo,"resolveSource");async function Se(e=R().keysDir,t={}){let n=Jo(t),r=new Set,i=qo(e,n).flatMap(s=>{let a=zo(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 Wo(s,e,n),c=qe(e,`${s}${We}`),l;try{l=Yo(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:qe(e,a),email:l}}))}o(Se,"discoverLocalKeys");import Xo from"enquirer";async function Zo(e){return Xo.prompt(e)}o(Zo,"defaultPrompt");async function en(e,t={}){let{prompt:n=Zo}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return r}o(en,"promptPassphrase");import ei from"enquirer";import{statSync as Qo}from"fs";function tn(e,t=Qo){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}o(tn,"sortByMtime");async function ti(e){return ei.prompt(e)}o(ti,"defaultPrompt");async function nn(e,t={}){if(e.length===1)return e[0];let{prompt:n=ti,sortByMtime:r=tn}=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,he(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(nn,"promptSigningIdentity");function oi(e){return{existsSync:e.existsSync??ni,readFileSync:e.readFileSync??((t,n)=>ri(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??ge,decryptJweAsString:e.decryptJweAsString??Xt,discoverLocalKeys:e.discoverLocalKeys??Se,keysDir:e.keysDir??R().keysDir,promptPassphrase:e.promptPassphrase??en,promptSigningIdentity:e.promptSigningIdentity??nn}}o(oi,"resolveDeps");async function rn(e,t={}){let n=oi(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(Zt(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(rn,"resolvePrivateKey");var yi=o(async(e,t,n,r,i)=>{let s=await A(e,{interactive:i.interactive??!1,appId:t,orgHint:i.org});await new b(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function hi(e){let t=ii(e);return new ReadableStream({start(n){t.on("data",r=>n.enqueue(new Uint8Array(r))),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}o(hi,"createWebStreamFromFile");function Si(e){return{existsSync:e.existsSync??si,readFileSync:e.readFileSync??((t,n)=>ai(t,n)),writeFileSync:e.writeFileSync??pi,createBundleStream:e.createBundleStream??hi,signBundle:e.signBundle??gi,hashDevSignature:e.hashDevSignature??mi,parseScope:e.parseScope??ui,validateScopes:e.validateScopes??fi,loadAppConfig:e.loadAppConfig??w,resolvePrivateKey:e.resolvePrivateKey??(t=>rn(t)),submitSignatures:e.submitSignatures??yi,discoverSignatures:e.discoverSignatures??Q}}o(Si,"resolveDeps");async function on(e,t,n={},r=process.cwd()){let i=Si(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?ve(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:
|
|
28
|
+
${d.join(`
|
|
29
|
+
`)}`);let{privateKeyPem:m,kid:u}=await i.resolvePrivateKey({keyPath:t.key?ve(r,t.key):void 0,kid:t.signingIdentity}),g;if(t.devSig){let y=ve(r,t.devSig);if(!i.existsSync(y))throw new Error(`Dev signature file not found: ${y}`);let P=i.readFileSync(y,"utf-8").trim();g=await i.hashDevSignature(P)}let f=i.createBundleStream(l),S=await i.signBundle({privateKeyPem:m,kid:u,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p,devSignatureSha256:g}),C=t.output?ve(r,t.output):di(li(l),`${ci(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(C,S.token,"utf-8"),console.log(`\u2705 Signed: ${C}`),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])),k=t.interactive?await I(c,{interactive:!0,deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):x(c.deployments,t.deployment);if(!t.interactive){let y=D(k);if(y.length>0)throw new Error(`Deployment ${k.org}/${k.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps sign --interactive\` for browser-based authentication instead.`)}await i.submitSignatures(k,s,a,h,t),console.log(`
|
|
31
|
+
To publish: npx @cognite/cli apps publish .`)}o(on,"handleSign");function sn(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 on(n,i,t)})}o(sn,"registerSignCommand");import{existsSync as vi}from"fs";import{resolve as wi}from"path";import{config as Ci}from"dotenv";function $(e,t={existsSync:vi,config:Ci}){let n=wi(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}o($,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
|
|
28
32
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
29
33
|
|
|
30
34
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
31
35
|
the old CDF Application Registry. This deploy path has been removed.
|
|
32
36
|
|
|
33
37
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
34
|
-
`),process.exit(1))}o(
|
|
38
|
+
`),process.exit(1))}o(F,"assertAppHostingInfra");async function Ei(e){let t=process.cwd();$(t);let n=w(t);F(n);let r=e.interactive?await I(n,e):x(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 b(i),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof _?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(Ei,"handleActivate");function an(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",`
|
|
35
39
|
Examples:
|
|
36
40
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
37
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>
|
|
38
|
-
`),initial:!1};async function
|
|
39
|
-
`),i=`link .specify/memory/constitution.md in specifyDir=${n}`,
|
|
40
|
-
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)=>Ei(n))}o(an,"registerActivateCommand");import{readdirSync as ji}from"fs";import{basename as Pn,dirname as Ni,normalize as Mi,resolve as oe}from"path";import{fileURLToPath as Vi,pathToFileURL as Hi}from"url";import{Logger as Bi,runner as Gi}from"hygen";import{execFileSync as ne}from"child_process";function pn(e={}){let{execFileSync:t=ne}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(pn,"isGitInstalled");function cn(e,t={}){let{execFileSync:n=ne}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(cn,"isInsideGitRepo");function ln(e,t={}){let{execFileSync:n=ne}=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(ln,"gitInitAndCommit");function dn(e={}){let{execFileSync:t=ne}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(dn,"gitUserName");function mn(e={}){let{execFileSync:t=ne}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(mn,"gitUserEmail");import{safeParse as Pi}from"valibot";function re(e,t){return n=>{let r=Pi(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}o(re,"toPromptValidator");var un={name:re("App name",_e),displayName:re("Display name",Oe),baseUrl:re("Base URL",Ue),org:re("Org",Ke),project:re("Project",Le)};function bi(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}o(bi,"composeValidators");function we(e){return e.map(t=>{if(!(t.name in un))return t;let n=un[t.name];return{...t,validate:bi(t.validate,n)}})}o(we,"applySchemaValidators");import{basename as fn}from"path";import yn from"enquirer";function gn(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(gn,"kebabCase");var ki={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 xi(e){return!!(await e([ki])).useSpecKit}o(xi,"promptForSpecKit");async function Ai(e,t,n){return e!==void 0?e:t?xi(n):!1}o(Ai,"resolveSpecKit");function hn({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:i={},specKit:s,prompt:a=yn.prompt.bind(yn)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(v=>v[1]!==void 0)),l=Object.keys(c).length>0,d=e?fn(process.cwd()):t?fn(t):null,m=l&&d!==null,u=!m&&d?p.map(v=>v.name==="name"?{...v,initial:d}:v):p,g=we(u),f=m?{...c,name:d}:c,S=new Set(Object.keys(f)),C=g.filter(v=>!S.has(v.name)),h=C.findIndex(v=>v.name==="baseUrl"),k;if(h!==-1){let v=C.filter($r=>$r.name!=="baseUrl"),N=v.length>0?await a(v):{},de=typeof N.cluster=="string"?N.cluster:"",q=typeof f.cluster=="string"?f.cluster:"",me=`https://${(de||q).trim().replace(/\/+$/,"")||"api"}.cognitedata.com`,K=C[h],Ie=await a([{...K,initial:me}]);k={...N,...Ie}}else k=C.length>0?await a(C):{};let y={...f,...k},P=typeof y.name=="string"?y.name:"";P&&n(P);let T=await Ai(s,C.length>0,a);return r?.(T),{...y,name:P,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:T}},"prompt")})}o(hn,"createAppPrompter");async function Sn(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:`--${gn(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(Sn,"validatePresets");import{cpSync as Ri,mkdirSync as wn,writeFileSync as Oi}from"fs";import{dirname as Cn,resolve as J}from"path";import{fileURLToPath as _i}from"url";import{copyFileSync as Di,symlinkSync as Ii}from"fs";import{dirname as $i,join as Fi}from"path";function Ti(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Ti,"errno");function vn(e){return e instanceof Error?e.message:String(e)}o(vn,"messageOf");function Ce({target:e,linkPath:t,label:n,symlink:r=Ii,copyFile:i=Di}){try{return r(e,t),!0}catch(s){let a=Ti(s);if(a==="EEXIST")return!0;let p=vn(s);if(a==="EPERM"||a==="EACCES")try{let c=Fi($i(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: ${vn(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}o(Ce,"linkOrCopyOrWarn");var Ui=J(Cn(_i(import.meta.url)),"..","..","_vendor","spec-kit"),Ki={branch_numbering:"sequential"},Li=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}];function En({appDir:e,vendorDir:t=Ui}){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 Li){let p=J(e,a);i=`copy ${s} to ${a}`,wn(Cn(p),{recursive:!0}),Ri(J(t,s),p,{recursive:!0})}i=`write init-options.json under specifyDir=${n}`,Oi(J(n,"init-options.json"),`${JSON.stringify(Ki,null,2)}
|
|
43
|
+
`),i=`link .specify/memory/constitution.md in specifyDir=${n}`,wn(r,{recursive:!0}),Ce({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(En,"installSpecKit");var bn=oe(Ni(Vi(import.meta.url)),"..","..","_templates");async function Ji(){let e=oe(bn,"app","new","prompt.js");return(await import(Hi(e).href)).default}o(Ji,"loadPromptDefs");function Yi(e,t){return!e||t?null:Mi(e)}o(Yi,"resolveDirName");function qi(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:oe(process.cwd(),r),display:r}}o(qi,"resolveAppLocation");function zi(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?`
|
|
41
45
|
To start spec-driven development:
|
|
42
46
|
Run /speckit.specify in Claude Code or Cursor and describe your app.
|
|
43
47
|
`:"",p=` # Or fully non-interactive (deploys first target from app.json):
|
|
@@ -46,9 +50,9 @@ To start spec-driven development:
|
|
|
46
50
|
|
|
47
51
|
Next steps:
|
|
48
52
|
${r}
|
|
49
|
-
${
|
|
53
|
+
${a}
|
|
50
54
|
${i}
|
|
51
|
-
${
|
|
55
|
+
${s}
|
|
52
56
|
${p}
|
|
53
57
|
`);return}console.log(`
|
|
54
58
|
\u2705 App created successfully!
|
|
@@ -58,13 +62,13 @@ To open in Cursor:
|
|
|
58
62
|
Or:
|
|
59
63
|
cd "${t}"
|
|
60
64
|
${r}
|
|
61
|
-
${
|
|
65
|
+
${a}
|
|
62
66
|
${i}
|
|
63
67
|
cd "${t}"
|
|
64
|
-
${
|
|
68
|
+
${s}
|
|
65
69
|
${p}
|
|
66
|
-
`)}o(
|
|
67
|
-
${r}`)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}o(
|
|
70
|
+
`)}o(zi,"printSuccessMessage");async function Wi(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=oe(e,".agents","skills"),i=0;try{i=ji(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(Wi,"pullSkillsInto");function Xi(e,t={}){let{isGitInstalled:n=pn,isInsideGitRepo:r=cn,gitInitAndCommit:i=ln}=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(Xi,"maybeInitGit");async function Zi(e,t){let n=e==="."||e==="./",r=Yi(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 Ji(),c=we(p),l=n?Pn(process.cwd()):r?Pn(r):null;await Sn(c,a,l);let d=hn({isCurrentDir:n,dirName:r,onAppName:o(u=>{i=u},"onAppName"),onUseSpecKit:o(u=>{s=u},"onUseSpecKit"),presets:a,specKit:t.specKit});await Gi(["app","new"],{templates:bn,cwd:process.cwd(),logger:new Bi(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=qi(n,r,i);Ce({target:"AGENTS.md",linkPath:oe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&En({appDir:m.cwd}),await Wi(m.cwd),Xi(m.cwd),zi(n,m.display,s)}o(Zi,"handleCreate");function kn(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",`
|
|
68
72
|
Non-interactive use (CI, scripts, AI agents):
|
|
69
73
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
70
74
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -77,17 +81,21 @@ Examples:
|
|
|
77
81
|
--display-name "My App" --description "My app" \\
|
|
78
82
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
79
83
|
--base-url https://greenfield.cognitedata.com
|
|
80
|
-
Fully non-interactive`).action(
|
|
84
|
+
Fully non-interactive`).action(Zi)}o(kn,"registerCreateCommand");import Qi from"path";async function es(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new b(r)}o(es,"defaultGetApiClient");async function ts(e,t,n={}){let{loadEnvFile:r=$,loadAppConfig:i=w,getApiClient:s=es}=n,a=Qi.resolve(process.cwd(),e);r(a);let p=i(a);F(p);let c=t.interactive?await I(p,t):x(p.deployments,t.deployment);if(!t.interactive){let u=D(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.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(ts,"handleDeactivate");function xn(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",`
|
|
81
85
|
Examples:
|
|
82
86
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
83
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>
|
|
84
|
-
`))
|
|
87
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>ts(t,n))}o(xn,"registerDeactivateCommand");import{mkdir as as,readFile as ps}from"fs/promises";import{basename as cs,dirname as ls}from"path";import{execFileSync as Xe}from"child_process";import O from"fs";import E from"path";import{parseAndValidateManifestConfig as ns}from"@cognite/app-sdk/vite";import{BlobReader as rs,Uint8ArrayWriter as os,ZipWriter as is}from"@zip.js/zip.js";var Ze="package.json",Qe="package-lock.json",An="manifest.json",et=".cognite",ss=[/^\.env(\..+)?$/,/^\.secrets?$/,/\.(key|pem|p12|pfx|jks|crt)$/i],tt=class tt{constructor(t="dist"){this.distPath=E.isAbsolute(t)?t:E.join(process.cwd(),t),this.appRoot=E.dirname(this.distPath)}validateBuildDirectory(){if(!O.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=E.join(this.appRoot,Ze);if(!O.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=E.join(this.appRoot,Qe);if(!O.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 is(new os,{level:9}),i=o(async(c,l)=>{await r.add(l,new rs(await O.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await O.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=E.join(c,d.name);d.isDirectory()?await s(m):await i(m,E.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=E.join(this.appRoot,Ze);await i(c,E.posix.join(et,Ze));let l=E.join(this.appRoot,An);if(O.existsSync(l)){let m=O.readFileSync(l,"utf-8");ns(m,l),await i(l,E.posix.join(et,An))}let d=E.join(this.appRoot,Qe);await i(d,E.posix.join(et,Qe)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await O.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=Xe("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(u){throw u instanceof Error&&"code"in u&&u.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=O.realpathSync(n),i=O.realpathSync(this.appRoot),s=E.relative(r,i)||".",a=s.replace(/\\/g,"/"),p=s==="."?"":`${a}/`,l=Xe("git",["-C",n,"ls-files","--",a],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
88
|
+
`).filter(Boolean).map(u=>p?u.slice(p.length):u).filter(u=>ss.some(g=>g.test(E.basename(u))));if(l.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
89
|
+
`+l.map(u=>` ${u}`).join(`
|
|
90
|
+
`)+`
|
|
91
|
+
Hint: git rm --cached <file>`);try{Xe("git",["-C",n,"archive","--format=zip",`--output=${t}`,"HEAD","--",a])}catch(u){let g=u instanceof Error?u.message:String(u);throw new Error(`Failed to create source archive: ${g}`)}let m=(O.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${E.basename(t)} (${m} MB)`),t}};o(tt,"ApplicationPackager");var Y=tt;async function Ee(e,t,n,r){let{externalId:i,name:s,description:a,versionTag:p}=t,c=V(n,i,p);await as(ls(c),{recursive:!0}),await new Y(`${n}/dist`).createZip(c,!0);let l=await ps(c);await new b(e).deploy(i,s,a,p,l,cs(c),r)}o(Ee,"packageAndUpload");var nt=o(async(e,t,n)=>{let r=await ee(e,n);await Ee(r,t,n,e.published)},"deploy");import{execSync as ds}from"child_process";function rt(e,t=!0,n={execSync:ds}){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(rt,"buildApp");function Dn(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(Dn,"generateFusionUrl");function In(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(`
|
|
92
|
+
`))}o(In,"printDeployInfo");function $n(e,t){console.log(`
|
|
85
93
|
\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(`
|
|
86
|
-
To publish: npx @cognite/cli apps publish .${n}`),console.log(`To activate: npx @cognite/cli apps activate .${n}`);let r=
|
|
94
|
+
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=Dn(t,e);r&&console.log(`
|
|
87
95
|
\u{1F517} Open your app:
|
|
88
|
-
${r}`)}o(
|
|
89
|
-
\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)
|
|
90
|
-
\u{1F4E4} Deploying to ${t.project}...`)
|
|
96
|
+
${r}`)}o($n,"printDeployResult");async function ms(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.`);In(e,t,!1),r.skipBuild||rt(n),console.log(`
|
|
97
|
+
\u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n),$n(e,t)}o(ms,"handleDeployNonInteractive");async function us(e,t,n,r){In(e,t,!0),r.skipBuild||rt(n);let i=await A(t,{interactive:!0,appId:e.externalId,orgHint:r.org});console.log(`
|
|
98
|
+
\u{1F4E4} Deploying to ${t.project}...`),await Ee(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},n,!1),$n(e,t)}o(us,"handleDeployInteractive");async function gs(e,t=process.cwd(),n={}){let{loadEnvFile:r=$,loadAppConfig:i=w,deploy:s=nt}=n;r(t);let a=i(t);if(F(a),e.interactive){let c=await I(a,e);await us(a,c,t,e);return}let p=x(a.deployments,e.deployment);await ms(a,p,t,e,s)}o(gs,"handleDeploy");function Fn(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",`
|
|
91
99
|
Environment (non-interactive):
|
|
92
100
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
93
101
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -101,43 +109,64 @@ Examples:
|
|
|
101
109
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
102
110
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
103
111
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
104
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>
|
|
112
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>gs(t))}o(Fn,"registerDeployCommand");async function fs(e,t,n){let r=await A(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new b(r)}o(fs,"defaultBuildApiClient");async function ys(e,t={}){let n=t.loadEnvFile??$,r=t.loadAppConfig??w,i=t.buildApiClient??fs,s=t.discoverSignatures??Q,a=process.cwd();n(a);let p=r(a);F(p);let c=e.interactive?await I(p,e):x(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,u;try{u=await l.getVersion(d,m)}catch(f){throw f instanceof _?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):f}if(u.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(u.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(u.lifecycleState==="DEPRECATED"||u.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${u.lifecycleState} (terminal).`);let g=s(V(a,d,m));g.length>0&&await l.submitSignatures(d,m,g),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(ys,"handlePublish");function Tn(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",`
|
|
105
113
|
Examples:
|
|
106
114
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
107
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)
|
|
115
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>ys(n))}o(Tn,"registerPublishCommand");function hs(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(hs,"describeStatus");async function Ss(e){let t=process.cwd();$(t);let n=w(t);F(n);let r=e.interactive?await I(n,e):x(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 b(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=hs(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 _){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(Ss,"handleStatus");function Rn(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",`
|
|
108
116
|
Examples:
|
|
109
117
|
npx @cognite/cli apps status . Status using env-var auth
|
|
110
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>
|
|
118
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Ss(n))}o(Rn,"registerStatusCommand");import{execFileSync as it}from"child_process";import ot from"fs";import ie from"path";var On="https://cognite.zendesk.com",vs="360001234312",ws="tf_360015295097",Cs="cognite_flows",Es="360004885031";function Ps(e,t){let n=new URLSearchParams({locale:"en-us",brand_id:Es,return_to:e});return`${t}/access?${n}`}o(Ps,"withLogin");function _n(e,t,n){let r=new URLSearchParams({ticket_form_id:vs,tf_priority:"normal",tf_subject:e,[ws]:Cs,tf_description:t});return Ps(`${n}/hc/en-us/requests/new?${r}`,n)}o(_n,"buildUrl");function Un(e){return e.join("<br>")}o(Un,"toHtml");function Kn(e,t=On){let{appName:n,externalId:r,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${r}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${r}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return _n(`App Review Request: ${n}`,Un(l.filter(d=>d!==void 0)),t)}o(Kn,"buildAppReviewUrl");function Ln(e,t,n,r,i=On){return _n(`Public Key Registration: ${t}`,Un(["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,`
|
|
119
|
+
`).split(`
|
|
120
|
+
`),"","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]),i)}o(Ln,"buildKeyRegistrationUrl");var bs=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function ks(e){let t=bs.filter(({pattern:n})=>it("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:r,skill:i})=>` ${r} \u2192 run \`${i}\``);throw new Error(`Certification files are missing or not committed. Run the required skills first:
|
|
121
|
+
|
|
122
|
+
`+n.join(`
|
|
123
|
+
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(ks,"assertArtifactsCommitted");async function xs(e=process.cwd(),t={}){let{openInBrowser:n=Vt,revealInFileManager:r=Ht}=t;$(e);let i=w(e);F(i),ks(e);let s=ie.join(e,"dist","submit");ot.mkdirSync(s,{recursive:!0});let a=it("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(it("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
|
|
124
|
+
|
|
125
|
+
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let c=`src-${a}.zip`,l=ie.join(s,c);await new Y(ie.join(e,"dist")).createSourceArchive(l);let m=`${i.externalId}-${i.versionTag}.zip`,u=ie.join(e,".cognite-bundles",m),g=!1;ot.existsSync(u)&&(ot.copyFileSync(u,ie.join(s,m)),g=!0);let f=Kn({appName:i.name,externalId:i.externalId,versionTag:i.versionTag,archiveName:c,developerName:dn(),cdfProject:i.deployments[0].project,cdfCluster:i.deployments[0].baseUrl});console.log(`
|
|
126
|
+
\u2705 Certification package ready: dist/submit/`),console.log(` ${c} \u2014 source archive (commit ${a})`),console.log(g?` ${m} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
|
|
127
|
+
Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
|
|
128
|
+
\u{1F517} ${f}`),n(f),r(l)}o(xs,"handleSubmit");function jn(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
|
|
129
|
+
Examples:
|
|
130
|
+
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>xs())}o(jn,"registerSubmitCommand");function Nn(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return kn(t),Fn(t),Rn(t),Tn(t),an(t),xn(t),jn(t),vt(t),sn(t),t}o(Nn,"registerAppsCommand");import{existsSync as Ls,mkdirSync as js,writeFileSync as Ns}from"fs";import{dirname as mt,join as xe}from"path";import{generateSigningKeyPair as Ms}from"@cognite/app-sdk/codesigning";import Vs from"open";function Mn(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(Mn,"addMonthsClamped");function st(e){return e.toISOString().slice(0,10)}o(st,"formatIsoDate");function Vn(e=new Date){return st(e)}o(Vn,"todayIso");import As,{Chalk as Ds}from"chalk";var se=new Ds({level:0});function Hn(e){return e.isTTY?As:se}o(Hn,"chalkForStream");function Is(e){return e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"")}o(Is,"pemBodyOneLine");function at(e,t=se,n=new Date){let r=e.issuedAt??Vn(n),i=Is(e.publicKeyPem),s=" ",a=o((c,l)=>`${s}${t.cyan(c)}${t.dim(":")} ${l}
|
|
111
131
|
`,"kv"),p="";return p+=`
|
|
112
132
|
${t.bold("Add this entry to")} ${t.magenta("services/app-hosting/config/signing-keys.yaml")} ${t.bold("under")} ${t.cyan("public_keys:")}
|
|
113
133
|
|
|
114
134
|
`,p+=`${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
115
|
-
`,p+=
|
|
116
|
-
`,"passphraseMismatchMsg"),
|
|
117
|
-
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${
|
|
118
|
-
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(
|
|
119
|
-
`);for(let
|
|
120
|
-
`)}o(
|
|
121
|
-
`);return}let P=e.email!==void 0?
|
|
135
|
+
`,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(at,"renderRegistryEntry");import $s from"clipboardy";function Bn(e){return $s.write(e)}o(Bn,"copyToClipboard");import{email as Fs,pipe as Ts,safeParse as Rs,string as Os}from"valibot";var _s=Ts(Os(),Fs());function ae(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Rs(_s,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}o(ae,"parseEmail");function pe(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}o(pe,"parseExpiryMonths");import lt from"enquirer";var Pe=3,Gn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",Jn=`Key expiry in months (${1}-${12})`,Yn="Email address for the registry entry",qn=`Passphrase for the encrypted private key (min ${15} chars)`,zn="Confirm passphrase",Wn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Xn=o(e=>`Passphrases do not match (attempt ${e}/${Pe}).
|
|
136
|
+
`,"passphraseMismatchMsg"),Zn=`Passphrase confirmation failed after ${Pe} attempts`,Qn=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),er="How would you like to submit your key registration?",tr="Open in browser",nr="Copy link to clipboard";async function ke(e){return lt.prompt(e)}o(ke,"defaultPrompt");function dt(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}o(dt,"parserAsValidator");var Ks=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function be(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(!Ks.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(be,"parseKid");async function rr(e={}){let{prompt:t=ke}=e,{kid:n}=await t({type:"input",name:"kid",message:Gn,validate:dt(be)});return be(n)}o(rr,"promptKid");async function or(e={}){let{prompt:t=o(r=>lt.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:er,choices:[{name:"browser",message:tr},{name:"clipboard",message:nr}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}o(or,"promptZendeskAction");async function ir(e={}){let{prompt:t=ke}=e,{months:n}=await t({type:"input",name:"months",message:Jn,initial:String(6),validate:dt(r=>pe(r,"expiry"))});return pe(n,"expiry")}o(ir,"promptExpiryMonths");async function sr(e={}){let{prompt:t=ke,gitUserEmail:n=mn}=e,{email:r}=await t({type:"input",name:"email",message:Yn,initial:n(),validate:dt(i=>ae(i,"email"))});return ae(r,"email")}o(sr,"promptEmail");async function ar(e={}){let{prompt:t=ke,stderr:n=process.stderr}=e;for(let r=1;r<=Pe;r+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:qn,validate:o(a=>a.length>=15?!0:Wn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:zn});if(i===s)return i;n.write(Xn(r))}throw new Error(Zn)}o(ar,"promptPassphrase");async function pr(e,t={}){let{prompt:n=o(i=>lt.prompt(i),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:Qn(e),initial:!1});return r}o(pr,"promptConfirmOverwrite");function Hs(e){return{writeFileSync:e.writeFileSync??Ns,mkdirSync:e.mkdirSync??js,existsSync:e.existsSync??Ls,generateSigningKeyPair:e.generateSigningKeyPair??Ms,encryptStringAsJwe:e.encryptStringAsJwe??Wt,storeKeyInKeychain:e.storeKeyInKeychain??Yt,isOS:e.isOS??(t=>B(t)),promptKid:e.promptKid??rr,promptExpiryMonths:e.promptExpiryMonths??ir,promptEmail:e.promptEmail??sr,promptPassphrase:e.promptPassphrase??ar,promptConfirmOverwrite:e.promptConfirmOverwrite??pr,discoverLocalKeys:e.discoverLocalKeys??(()=>Se()),promptZendeskAction:e.promptZendeskAction??or,openUrl:e.openUrl??(t=>Vs(t)),copyToClipboard:e.copyToClipboard??Bn,isInteractive:e.isInteractive??(()=>process.stdout.isTTY===!0)}}o(Hs,"resolveDeps");function lr(e,t={}){let n=Hs(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 ${R().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=>Js(i,n)),r.command("list").description("List local signing identities and their storage location").action(()=>Bs(n))}o(lr,"registerKeysCommand");async function Bs(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
137
|
+
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${R().keysDir}).
|
|
138
|
+
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,he(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)}
|
|
139
|
+
`);for(let a of r)process.stdout.write(`${s(a)}
|
|
140
|
+
`)}o(Bs,"handleList");function cr(e,t,n){let r=xe(R().keysDir,`${e}${te}`);return n.mkdirSync(mt(r),{recursive:!0}),n.writeFileSync(r,t),r}o(cr,"writePublicKey");async function Gs(e,t,n,r,i,{force:s=!1}={}){let a=r??xe(R().keysDir,`${e}${ze}`);if(i.mkdirSync(mt(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(Gs,"writeEncryptedPrivateKey");async function Js(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:u,promptConfirmOverwrite:g}=t,f=e.keychain!==!1&&r("macos")&&!e.output,S=e.expires!==void 0?pe(e.expires):await l(),C=st(Mn(n,S)),h=e.kid!==void 0?be(e.kid):await d(),k=xe(R().keysDir,`${h}${te}`),y=i(k);if(y&&!e.force&&!await g(h)){process.stderr.write(`Aborted.
|
|
141
|
+
`);return}let P=e.email!==void 0?ae(e.email,"--email"):await m(),T=f?null:await u();process.stderr.write(`
|
|
122
142
|
Generating Ed25519 keypair...
|
|
123
143
|
|
|
124
|
-
`);let{privateKeyPem:
|
|
125
|
-
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${
|
|
126
|
-
`)}else{if(
|
|
127
|
-
`),process.stderr.write(`Private key: ${
|
|
128
|
-
`),r()||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
129
|
-
`)}let
|
|
130
|
-
Signing identity (kid): ${
|
|
131
|
-
`),process.stderr.write(`Expires: ${
|
|
132
|
-
`)
|
|
133
|
-
${
|
|
134
|
-
`)
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
`)
|
|
138
|
-
|
|
139
|
-
`)}
|
|
140
|
-
`);
|
|
141
|
-
|
|
142
|
-
`)
|
|
143
|
-
|
|
144
|
+
`);let{privateKeyPem:v,publicKeyPem:N}=await p(h);if(f){await c(h,v);let K=cr(h,N,t);process.stderr.write(`Public key: ${K}
|
|
145
|
+
`),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${h})
|
|
146
|
+
`)}else{if(T===null)throw new Error("passphrase is required when not using Keychain");let K=await Gs(h,v,T,e.output,t,{force:y}),Ie=cr(h,N,t);process.stderr.write(`Public key: ${Ie}
|
|
147
|
+
`),process.stderr.write(`Private key: ${K} (JWE, AES-256-GCM, PBKDF2-SHA512 x${Ye.toLocaleString()})
|
|
148
|
+
`),r("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
|
|
149
|
+
`)}let de=xe(R().keysDir,`${h}${We}`);s(mt(de),{recursive:!0}),a(de,JSON.stringify({email:P}));let q=Hn(process.stderr);process.stderr.write(`
|
|
150
|
+
Signing identity (kid): ${q.green(h)}
|
|
151
|
+
`),process.stderr.write(`Expires: ${C} (${S} month${S===1?"":"s"} from today)
|
|
152
|
+
`);let De={kid:h,publicKeyPem:N,email:P,expires:C};process.stderr.write(at(De,q,n));let z=Ln(h,P,C,at(De,se,n));process.stderr.write(`
|
|
153
|
+
${q.bold("Next:")}
|
|
154
|
+
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
155
|
+
`);let me=e.copyLink?"clipboard":t.isInteractive()?await t.promptZendeskAction():null;if(me==="browser")try{await t.openUrl(z),process.stderr.write(` Opening in browser...
|
|
156
|
+
`)}catch{process.stderr.write(` URL: ${z}
|
|
157
|
+
`)}else if(me==="clipboard"){let K=!1;try{await t.copyToClipboard(z),K=!0}catch{}process.stderr.write(K&&!e.copyLink?` Link copied to clipboard.
|
|
158
|
+
`:` URL: ${z}
|
|
159
|
+
`)}else process.stderr.write(` URL: ${z}
|
|
160
|
+
`);process.stderr.write(`
|
|
161
|
+
2. Once your key is approved, sign your Dune app:
|
|
162
|
+
`),process.stderr.write(` ${q.cyan(`cognite sign -s ${h}`)}
|
|
163
|
+
`)}o(Js,"handleGenerate");var dr=1e3,Ys=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function qs(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Ys.has(t)?[t,n]:[t,"[REDACTED]"]))}o(qs,"sanitize");function zs(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}o(zs,"getCommandPath");function mr(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(mr,"tryLoadAppConfig");function ut(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o(ut,"commandFromArgv");function ur(e,t,n=w){e.hook("postAction",async(r,i)=>{try{let s={command:zs(i),options:qs(i.opts()),success:!0,...mr(n)};t.track("Flows.CLI.Command",s),await t.flush(dr)}catch{}})}o(ur,"instrument");async function gr(e,t,n=w){try{let r={command:ut(t),options:{},success:!1,...mr(n)};e.track("Flows.CLI.Command",r),await e.flush(dr)}catch{}}o(gr,"trackFailure");var Ws="ERR_USE_AFTER_CLOSE";function yr(e){return e instanceof Error&&"code"in e&&e.code===Ws}o(yr,"isReadlineClosedError");function Xs(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(Xs,"isPlainObject");function gt(e){return e==null||yr(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Xs(e)&&Object.keys(e).length===0)}o(gt,"isPromptCancel");var fr=!1;function hr(){fr||(fr=!0,process.on("uncaughtException",e=>{yr(e)&&(console.error(`
|
|
164
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{gt(e)&&(console.error(`
|
|
165
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(hr,"installCancelHandler");import{homedir as na}from"os";import Sr from"mixpanel";var Zs="5c4d853e7c3b77b1eb4468d5329b278c",ce="cognite-cli",Qs=2e3,vr={env:process.env,init:Sr.init.bind(Sr)},ea={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function ft(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(ft,"isTelemetryDisabled");function ta(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(ta,"isDebug");function wr(e={}){let t=e.env??vr.env,n=e.init??vr.init,r=e.packageName,i=e.cliVersion,s=ta(t);if(ft(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
166
|
+
`),ea;let a,p=new Set;function c(){if(a)return a;try{return a=n(Zs,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let u={...d,applicationId:ce,...r&&{packageName:r},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(u)}
|
|
167
|
+
`);let g=o(()=>{},"finish"),f=new Promise(S=>{g=S});p.add(f);try{m.track(l,u,g)}catch{g()}f.finally(()=>p.delete(f))},async flush(l=Qs){if(p.size===0)return;let d,m=new Promise(u=>{d=setTimeout(u,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)
|
|
168
|
+
`)}}}o(wr,"createTelemetry");var ra=na();function le(e,t=ra){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(le,"redactHomedir");var oa=1e3,ia="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",sa={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function aa(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(aa,"buildRelease");var pa="192.0.2.0";function ca(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:le(t.filename)},...t.abs_path!==void 0&&{abs_path:le(t.abs_path)},...t.module!==void 0&&{module:le(t.module)}}))}o(ca,"scrubStackFrames");function la(e){let t={...e.user,email:void 0,username:void 0,ip_address:pa,id:void 0},n=e.exception?.values?.map(r=>({...r,value:r.value!==void 0?le(r.value):r.value,...r.stacktrace!==void 0&&{stacktrace:{...r.stacktrace,frames:ca(r.stacktrace.frames)}}}));return{...e,message:e.message!==void 0?le(e.message):e.message,user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}}}}o(la,"scrubPii");function Cr(e={}){let t=e.env??process.env;if(ft(t))return sa;let n=aa(e),r="production",i=null,s=null;function a(){return{dsn:ia,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:ce},contexts:{cli:{applicationId:ce,node:process.version,platform:process.platform}}},beforeSend:la}}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:ce,node:process.version,platform:process.platform,command:l.command}}),d.captureException(c,m)}catch{}},async flush(c=oa){try{if(!i)return;await i.flush(c)}catch{}}}}o(Cr,"createErrorReporter");import{mkdirSync as da,readFileSync as ma,writeFileSync as ua}from"fs";import{homedir as ga}from"os";import{resolve as Ae}from"path";import{debuglog as fa}from"util";import{lt as ya,parse as Er}from"semver";var ha="https://registry.npmjs.org/@cognite/cli/latest",Sa=1500,Pr="upgrade-check.json",br=Ae(process.env.XDG_CACHE_HOME||Ae(ga(),".cache"),"@cognite","cli"),yt=fa("cognite-flows");function va(e,t){return!e||!t||!Er(e)||!Er(t)?!1:ya(e,t)}o(va,"isOutdated");async function wa({timeout:e=Sa,registryUrl:t=ha,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 yt("fetchLatestVersion failed (%s): %O",t,r),null}}o(wa,"fetchLatestVersion");function Ca(e=br,t=864e5){try{let n=ma(Ae(e,Pr),"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 yt("readUpgradeCheckCache failed (%s): %O",e,n),null}}o(Ca,"readUpgradeCheckCache");function Ea(e,t){try{da(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};ua(Ae(e,Pr),JSON.stringify(n))}catch(n){yt("writeUpgradeCheckCache failed (%s): %O",e,n)}}o(Ea,"writeUpgradeCheckCache");async function Pa({cacheDir:e=br,...t}={}){let n=await wa(t);n&&Ea(e,n)}o(Pa,"startBackgroundUpgradeCheck");function kr(e,{onOutdated:t,cacheDir:n,...r}={}){let i=Ca(n);if(i){va(e,i.latest)&&t?.(e,i.latest);return}Pa({cacheDir:n,...r})}o(kr,"preActionUpgradeCheck");import{default as Mu,chalkStderr as xr}from"chalk";function Ar(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(`
|
|
169
|
+
`);return xr.bold.yellow(a)}o(Ar,"formatUpgradeWarning");function xa(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(xa,"isDep0040Warning");var St=process,Aa=St.emit.bind(St);St.emit=function(e,...t){return e==="warning"&&xa(t[0])?!1:Aa(e,...t)};hr();var X=new ka;X.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.3.3-alpha-zendesk").showHelpAfterError().configureOutput({writeOut:o(e=>ba(1,e),"writeOut")});X.hook("preAction",()=>{kr("1.3.3-alpha-zendesk",{onOutdated:o((e,t)=>{console.warn(`
|
|
170
|
+
${Ar(e,t)}
|
|
171
|
+
`)},"onOutdated")})});Nn(X);lr(X);var Ir=wr({packageName:"@cognite/cli",cliVersion:"1.3.3-alpha-zendesk"}),Dr=Cr({packageName:"@cognite/cli",cliVersion:"1.3.3-alpha-zendesk"});ur(X,Ir);var ht=process.argv.slice(2);X.parseAsync(ht,{from:"user"}).catch(async e=>{await gr(Ir,ht),gt(e)&&(console.error(`
|
|
172
|
+
Cancelled.`),process.exit(130)),await Dr.captureError(e,{command:ut(ht)}),await Dr.flush(),console.error(e instanceof Error?`\u274C ${e.message}`:e),process.exit(1)});
|
package/dist/deploy/index.d.ts
CHANGED
|
@@ -1,26 +1,5 @@
|
|
|
1
1
|
import { CogniteClient, ClientOptions } from '@cognite/sdk';
|
|
2
2
|
|
|
3
|
-
type Deployment = {
|
|
4
|
-
org: string;
|
|
5
|
-
project: string;
|
|
6
|
-
baseUrl: string;
|
|
7
|
-
deployClientId: string;
|
|
8
|
-
deploySecretName: string;
|
|
9
|
-
published: boolean;
|
|
10
|
-
/** Identity provider type. Defaults to "cdf" if not specified */
|
|
11
|
-
idpType?: "cdf" | "entra_id";
|
|
12
|
-
/** Tenant ID for Entra ID authentication. Required when idpType is "entra_id" */
|
|
13
|
-
tenantId?: string;
|
|
14
|
-
};
|
|
15
|
-
type App = {
|
|
16
|
-
externalId: string;
|
|
17
|
-
name: string;
|
|
18
|
-
description: string;
|
|
19
|
-
versionTag: string;
|
|
20
|
-
};
|
|
21
|
-
|
|
22
|
-
declare const deploy: (deployment: Deployment, app: App, folder: string) => Promise<void>;
|
|
23
|
-
|
|
24
3
|
/**
|
|
25
4
|
* App Hosting HTTP API layer.
|
|
26
5
|
*
|
|
@@ -56,6 +35,13 @@ declare class AppHostingClient {
|
|
|
56
35
|
* success so the call is safe to repeat.
|
|
57
36
|
*/
|
|
58
37
|
ensureApp(externalId: string, name: string, description: string): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Submit verified compact-JWS signatures for a version uploaded earlier.
|
|
40
|
+
* No-op when `items` is empty so callers can wire it unconditionally.
|
|
41
|
+
* The backend accepts and stores well-formed tokens; tier-policy
|
|
42
|
+
* verification happens on the subsequent publish step.
|
|
43
|
+
*/
|
|
44
|
+
submitSignatures(appExternalId: string, version: string, items: string[]): Promise<void>;
|
|
59
45
|
/** Transition a version from DRAFT to PUBLISHED. */
|
|
60
46
|
publishVersion(appExternalId: string, version: string): Promise<void>;
|
|
61
47
|
/** Publish the version and immediately set it as the ACTIVE alias. */
|
|
@@ -85,6 +71,42 @@ declare class AppHostingClient {
|
|
|
85
71
|
deploy(appExternalId: string, name: string, description: string, versionTag: string, fileContent: Buffer, fileName: string, published?: boolean): Promise<void>;
|
|
86
72
|
}
|
|
87
73
|
|
|
74
|
+
type Deployment = {
|
|
75
|
+
org: string;
|
|
76
|
+
project: string;
|
|
77
|
+
baseUrl: string;
|
|
78
|
+
deployClientId: string;
|
|
79
|
+
deploySecretName: string;
|
|
80
|
+
published: boolean;
|
|
81
|
+
/** Identity provider type. Defaults to "cdf" if not specified */
|
|
82
|
+
idpType?: 'cdf' | 'entra_id';
|
|
83
|
+
/** Tenant ID for Entra ID authentication. Required when idpType is "entra_id" */
|
|
84
|
+
tenantId?: string;
|
|
85
|
+
};
|
|
86
|
+
type App = {
|
|
87
|
+
externalId: string;
|
|
88
|
+
name: string;
|
|
89
|
+
description: string;
|
|
90
|
+
versionTag: string;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Package `dist/` into `<folder>/.cognite-bundles/<externalId>-<versionTag>.zip`
|
|
95
|
+
* and upload it via an already-authenticated `AppHostingClient`. Both deploy
|
|
96
|
+
* entry points (programmatic `deploy()` and the CLI's interactive path) reuse
|
|
97
|
+
* this so packaging/upload behaviour stays in one place.
|
|
98
|
+
*
|
|
99
|
+
* The bundle file is intentionally left on disk so the follow-on
|
|
100
|
+
* `cognite apps sign` + `cognite apps publish` flow can operate on the
|
|
101
|
+
* exact bytes the backend received.
|
|
102
|
+
*/
|
|
103
|
+
declare function packageAndUpload(client: AppHostingApiClient, app: App, folder: string, published: boolean): Promise<void>;
|
|
104
|
+
/**
|
|
105
|
+
* Programmatic deploy used by CI scripts: resolves an SDK from the
|
|
106
|
+
* deployment's env-var credentials, then runs `packageAndUpload`.
|
|
107
|
+
*/
|
|
108
|
+
declare const deploy: (deployment: Deployment, app: App, folder: string) => Promise<void>;
|
|
109
|
+
|
|
88
110
|
/**
|
|
89
111
|
* Application Packaging
|
|
90
112
|
*
|
|
@@ -96,6 +118,7 @@ declare class ApplicationPackager {
|
|
|
96
118
|
constructor(distDirectory?: string);
|
|
97
119
|
validateBuildDirectory(): void;
|
|
98
120
|
createZip(outputFilename?: string, verbose?: boolean): Promise<string>;
|
|
121
|
+
createSourceArchive(outputPath: string): Promise<string>;
|
|
99
122
|
}
|
|
100
123
|
|
|
101
124
|
type Authenticatable = Pick<CogniteClient, 'authenticate'>;
|
|
@@ -111,4 +134,37 @@ declare function getSdk<C extends Authenticatable>(deployment: Deployment, folde
|
|
|
111
134
|
*/
|
|
112
135
|
declare const getToken: (deployment: Deployment, env?: NodeJS.ProcessEnv) => Promise<string>;
|
|
113
136
|
|
|
114
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Sibling-file discovery for bundle signatures written by `cognite sign`.
|
|
139
|
+
*
|
|
140
|
+
* <bundle>.dev.sig — developer signature
|
|
141
|
+
* <bundle>.cert.sig — certifier counter-signature (`--as-certifier`)
|
|
142
|
+
*
|
|
143
|
+
* Tokens are passed verbatim to the App Hosting `/signatures` endpoint; the
|
|
144
|
+
* backend verifies them against its key registry and tier policy.
|
|
145
|
+
*
|
|
146
|
+
* Collaborators are injected via `deps` so tests can stub fs without `vi.mock`.
|
|
147
|
+
*/
|
|
148
|
+
declare const SIGNATURE_SUFFIXES: readonly [".dev.sig", ".cert.sig"];
|
|
149
|
+
type DiscoverSignaturesDeps = {
|
|
150
|
+
existsSync?: (path: string) => boolean;
|
|
151
|
+
readFileSync?: (path: string, encoding: 'utf8') => string;
|
|
152
|
+
};
|
|
153
|
+
declare function discoverSignatures(bundlePath: string, deps?: DiscoverSignaturesDeps): string[];
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Stable on-disk location for a packaged app bundle, keyed on app + version.
|
|
157
|
+
*
|
|
158
|
+
* `cognite apps deploy` writes the zip here and leaves it in place, so the
|
|
159
|
+
* subsequent `cognite apps sign` + `cognite apps publish` steps operate on
|
|
160
|
+
* the *exact bytes* that were uploaded — the bundle SHA in the signed
|
|
161
|
+
* payload matches what the backend has on hand.
|
|
162
|
+
*
|
|
163
|
+
* Lives under a single gitignored folder (`.cognite-bundles/`) so signed
|
|
164
|
+
* artefacts don't accidentally land in version control.
|
|
165
|
+
*/
|
|
166
|
+
declare const BUNDLE_DIR = ".cognite-bundles";
|
|
167
|
+
declare function bundleFileName(externalId: string, versionTag: string): string;
|
|
168
|
+
declare function bundlePath(cwd: string, externalId: string, versionTag: string): string;
|
|
169
|
+
|
|
170
|
+
export { type App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, type Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken, packageAndUpload };
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-5R5NRM2C.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { App, AppHostingClient, ApplicationPackager, Deployment, deploy, getSdk, getToken } from './deploy/index.js';
|
|
1
|
+
export { App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken, packageAndUpload } from './deploy/index.js';
|
|
2
2
|
import '@cognite/sdk';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f,e as m}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-5R5NRM2C.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cognite/cli",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.3-alpha-zendesk",
|
|
4
4
|
"description": "CLI for Cognite Data Fusion",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"author": "Cognite",
|
|
@@ -49,6 +49,7 @@
|
|
|
49
49
|
"@sentry/node": "^10.51.0",
|
|
50
50
|
"@zip.js/zip.js": "^2.7.0",
|
|
51
51
|
"chalk": "^5.6.2",
|
|
52
|
+
"clipboardy": "5.3.1",
|
|
52
53
|
"commander": "^14.0.3",
|
|
53
54
|
"dotenv": "^17.4.2",
|
|
54
55
|
"enquirer": "^2.4.1",
|
|
@@ -75,14 +76,14 @@
|
|
|
75
76
|
}
|
|
76
77
|
},
|
|
77
78
|
"devDependencies": {
|
|
78
|
-
"@types/ejs": "^3.1.5",
|
|
79
|
-
"ejs": "^3.1.10",
|
|
80
79
|
"@mswjs/http-middleware": "^0.10.3",
|
|
80
|
+
"@types/ejs": "^3.1.5",
|
|
81
81
|
"@types/express": "^5.0.6",
|
|
82
82
|
"@types/node": "^24.10.1",
|
|
83
83
|
"@types/react": "^19.2.6",
|
|
84
84
|
"@types/react-dom": "^19.2.3",
|
|
85
85
|
"@types/semver": "^7.7.0",
|
|
86
|
+
"ejs": "^3.1.10",
|
|
86
87
|
"express": "^5.2.1",
|
|
87
88
|
"msw": "^2.13.6",
|
|
88
89
|
"react": "^19.2.6",
|
package/dist/chunk-QOJVLP7E.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
var W=Object.defineProperty;var s=(e,t)=>W(e,"name",{value:t,configurable:!0});import Y from"fs";import gt from"path";var F="https://docs.cognite.com/cdf/access/";function m(e){return e!==null&&typeof e=="object"}s(m,"isRecord");function P(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}s(P,"isHttpError");function Z(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
-
See: ${F}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
-
See: ${F}`;default:return}}s(Z,"httpStatusHint");function A(e){let t=e instanceof Error?e:new Error(String(e));if(!P(t))return null;let n=Z(t.status);return n?Object.assign(new Error(`${t.message}
|
|
4
|
-
${n}`),{cause:t}):null}s(A,"enrichedHttpError");function X(e){if(!m(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(m(n)){let r=n.error;if(m(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}s(X,"findMissingArray");function Q(e,t){if(!P(e)||e.status!==400)return!1;let n=X(e);return n?n.some(r=>m(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(Q,"isMissingExternalIdError");function $(e,t){return P(e)&&e.status===404||Q(e,t)}s($,"isNotFoundError");var M=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],J=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};s(I,"AppVersionNotFoundError");var k=I;function q(e,t){return e.includes(t)}s(q,"includesValue");function tt(e){return q(M,e)}s(tt,"isAppVersionLifecycleState");function et(e){return q(J,e)}s(et,"isAppVersionAlias");function nt(e){return typeof e.version=="string"&&tt(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||et(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}s(nt,"isAppVersion");function H(e){if(!m(e))throw new Error("Invalid version response: not an object");if(!nt(e))throw new Error("Invalid version response: missing or malformed fields");return e}s(H,"parseAppVersion");var T=class T{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw A(o)??o}}async uploadVersion(t,n,r,o,i="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",n),a.append("entryPath",i);let l=encodeURIComponent(t),c=`${this.appsBasePath}/${l}/versions`,p=await this.client.authenticate(),g=`${this.client.getBaseUrl()}${c}`,u=new AbortController,G=setTimeout(()=>u.abort(),300*1e3),h;try{h=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${p}`},body:a,signal:u.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error("Upload timed out after 5 minutes"):f}finally{clearTimeout(G)}if(!h.ok){let f=await h.text(),V=f;try{let x=JSON.parse(f);if(m(x)){let w=x.error;if(typeof w=="string")V=w;else if(m(w)){let E=w.message,B=w.code;V=typeof E=="string"?E:B!=null?`Unknown error (code: ${B})`:f}else{let E=x.message;V=typeof E=="string"?E:f}}}catch{}let j=h.headers.get("x-request-id"),K=j?` | X-Request-ID: ${j}`:"",N=Object.assign(new Error(`Upload failed: ${h.status} \u2014 ${V}${K}`),{status:h.status});throw A(N)??N}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),i=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(i);return H(a.data)}catch(a){throw $(a,[t,n])?new k(t,n):A(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let o=await this.client.get(r);return H(o.data)}catch(o){if($(o,[t]))return null;throw A(o)??o}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(i){throw A(i)??i}}};s(T,"AppHostingApi");var v=T;var b=class b{constructor(t){this.api=new v(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,i){return this.api.uploadVersion(t,n,r,o,i)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(P(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,i,a,l=!1){console.log(`
|
|
5
|
-
\u{1F680} Deploying application via App Hosting API...
|
|
6
|
-
`);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,o,i,a),l&&await this.publishAndActivate(t,o),console.log(`
|
|
7
|
-
\u2705 Deployment successful!`)}catch(c){let p=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${p}`),{cause:c})}}};s(b,"AppHostingClient");var S=b;import y from"fs";import d from"path";import{parseAndValidateManifestConfig as rt}from"@cognite/app-sdk/vite";import{BlobReader as ot,Uint8ArrayWriter as st,ZipWriter as it}from"@zip.js/zip.js";var R="package.json",D="package-lock.json",z="manifest.json",_=".cognite",L=class L{constructor(t="dist"){this.distPath=d.isAbsolute(t)?t:d.join(process.cwd(),t),this.appRoot=d.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=d.join(this.appRoot,R);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=d.join(this.appRoot,D);if(!y.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 it(new st,{level:9}),o=s(async(c,p)=>{await r.add(p,new ot(await y.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),i=s(async c=>{let p=await y.promises.readdir(c,{withFileTypes:!0});for(let g of p){let u=d.join(c,g.name);g.isDirectory()?await i(u):await o(u,d.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await i(this.distPath);let c=d.join(this.appRoot,R);await o(c,d.posix.join(_,R));let p=d.join(this.appRoot,z);if(y.existsSync(p)){let u=y.readFileSync(p,"utf-8");rt(u,p),await o(p,d.posix.join(_,z))}let g=d.join(this.appRoot,D);await o(g,d.posix.join(_,D)),a=await r.close()}catch(c){let p=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${p}`)}await y.promises.writeFile(t,a);let l=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${l} MB)`),t}};s(L,"ApplicationPackager");var C=L;import{CogniteClient as ut}from"@cognite/sdk";var at=s(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=r.toLowerCase().replace(/_/g,"-");n[i]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),ct=s(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=at()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),pt=s(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"),lt=s(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 i=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
|
|
8
|
-
${i}`)}let o=await r.json();if(!o.access_token)throw new Error("No access token returned from CDF authentication");return o.access_token},"getTokenCdf"),dt=s(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=pt(r);if(!o)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let i=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${o}.cognitedata.com/.default`,l=await fetch(i,{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(!l.ok){let p=await l.text();throw new Error(`Failed to get token from Entra ID: ${l.status} ${l.statusText}
|
|
9
|
-
${p}`)}let c=await l.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),O=s(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:i,baseUrl:a}=e,l=ct(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return dt(n,l,i,a)}return lt(n,l)},"getToken");async function U(e,t,n=process.env,r){let o=await O(e,n),i=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(l=>new ut(l)))({appId:t,project:e.project,baseUrl:i,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}s(U,"getSdk");var ft=s(async(e,t,n)=>{let r=await new C(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:o,name:i,description:a,versionTag:l}=t,c=await U(e,n),p=new S(c),g=Y.readFileSync(r),u=gt.basename(r);await p.deploy(o,i,a,l,g,u,e.published)}finally{try{Y.unlinkSync(r)}catch{}}},"deploy");export{S as a,C as b,O as c,U as d,ft as e};
|