@cognite/cli 1.7.0 → 1.8.0-alpha.sdk-gen
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/agents/create/README_TEMPLATE.md +66 -0
- package/_templates/app/new/config/vitest.config.ts.ejs.t +3 -2
- package/_templates/app/new/root/.npmrc.ejs.t +1 -1
- package/_templates/app/new/root/AGENTS.md.ejs.t +62 -12
- package/_templates/app/new/root/SPEC.md.ejs.t +17 -15
- package/_templates/app/new/root/app.json.ejs.t +1 -0
- package/_templates/app/new/root/manifest.json.ejs.t +6 -1
- package/_templates/app/new/root/package.json.ejs.t +4 -1
- package/_templates/app/new/src/App.test.tsx.ejs.t +32 -2
- package/_templates/app/new/src/App.tsx.ejs.t +54 -5
- package/_templates/app/new/src/main.tsx.ejs.t +0 -70
- package/dist/chunk-ATR2SGLU.js +1 -0
- package/dist/chunk-M3FWAJ4N.js +12 -0
- package/dist/chunk-PZ2YS5FR.js +1 -0
- package/dist/cli/cli.js +241 -101
- package/dist/deploy/index.d.ts +37 -10
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/sdk-runtime/index.d.ts +371 -0
- package/dist/sdk-runtime/index.js +1 -0
- package/package.json +18 -4
- package/dist/chunk-74X2P7OO.js +0 -12
package/dist/cli/cli.js
CHANGED
|
@@ -1,26 +1,104 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var $o=Object.defineProperty;var Zt=e=>{throw TypeError(e)};var o=(e,t)=>$o(e,"name",{value:t,configurable:!0});var Qt=(e,t,r)=>t.has(e)||Zt("Cannot "+r);var er=(e,t,r)=>(Qt(e,t,"read from private field"),r?r.call(e):t.get(e)),tr=(e,t,r)=>t.has(e)?Zt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),rr=(e,t,r,n)=>(Qt(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);import{writeSync as _c}from"fs";import{Command as Lc}from"commander";var Xe=class Xe extends Error{constructor(t,r={}){super(t),this.name="HintedError",r.cause!==void 0&&(this.cause=r.cause);let n=this.deriveDefaults(r);this.hint=r.hint??n.hint,this.helpUrl=r.helpUrl??n.helpUrl,this.shouldReport=r.shouldReport??!0}deriveDefaults(t){return{hint:Oo(t.cause)}}};o(Xe,"HintedError");var g=Xe;function or(e){return e instanceof g}o(or,"isHintedError");var nr="https://docs.cognite.com/cdf/access/",To="https://status.cognite.com";function Ro(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:nr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:nr};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:To};default:return{}}}o(Ro,"defaultHintForStatus");var Ze=class Ze extends g{constructor(t,r){super(t,r),this.name="HintedHttpError",this.httpStatusCode=r.httpStatusCode,this.requestUrl=r.requestUrl,this.responseBody=r.responseBody}deriveDefaults(t){let{httpStatusCode:r}=t,n=Ro(r),i=super.deriveDefaults(t);return{hint:n.hint??i.hint,helpUrl:n.helpUrl}}};o(Ze,"HintedHttpError");var te=Ze;function ir(e){return e instanceof te}o(ir,"isHintedHttpError");function Fo(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Fo,"hintForErrno");function Oo(e){let t=e,r=new Set;for(;t!=null&&!r.has(t)&&(r.add(t),typeof t=="object");){let n=t,i=Fo(n.code,n);if(i!==void 0)return i;t=n.cause}}o(Oo,"hintForCause");import{existsSync as vi,readFileSync as Ci}from"fs";import{join as Ei,resolve as Fe}from"path";import{verifyBundle as ki}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as bi}from"jose";import rt from"enquirer";import{email as Uo,pipe as _o,safeParse as Lo,string as No}from"valibot";var Ko=_o(No(),Uo());function ae(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!Lo(Ko,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(ae,"parseEmail");function pe(e,t="--expires"){let r=Number(e);if(!Number.isInteger(r)||r<1||r>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return r}o(pe,"parseExpiryMonths");import{execFileSync as ge}from"child_process";function be(e={}){let{execFileSync:t=ge}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(be,"isGitInstalled");function Pe(e,t={}){let{execFileSync:r=ge}=t;try{return r("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Pe,"isInsideGitRepo");function sr(e,t={}){let{execFileSync:r=ge}=t;r("git",["-C",e,"init"],{stdio:"pipe"}),r("git",["-C",e,"add","."],{stdio:"pipe"}),r("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(sr,"gitInitAndCommit");function ar(e={}){let{execFileSync:t=ge}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(ar,"gitUserName");function pr(e={}){let{execFileSync:t=ge}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(pr,"gitUserEmail");import{inspect as Mo}from"util";var Qe="[REDACTED]",fe,xe=class xe{constructor(t){tr(this,fe);rr(this,fe,t)}toString(){return Qe}toJSON(){return Qe}[Mo.custom](){return Qe}expose(){return er(this,fe)}static from(t){return new xe(t)}};fe=new WeakMap,o(xe,"SensitiveString");var v=xe;var Ae=3,cr="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",lr=`Key expiry in months (${1}-${12})`,dr="Email address for the registry entry",mr=`Passphrase for the encrypted private key (min ${15} chars)`,ur="Confirm passphrase",gr=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),fr=o(e=>`Passphrases do not match (attempt ${e}/${Ae}).
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
var Qs=Object.defineProperty;var ur=e=>{throw TypeError(e)};var i=(e,t)=>Qs(e,"name",{value:t,configurable:!0});var gr=(e,t,n)=>t.has(e)||ur("Cannot "+n);var fr=(e,t,n)=>(gr(e,t,"read from private field"),n?n.call(e):t.get(e)),yr=(e,t,n)=>t.has(e)?ur("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),hr=(e,t,n,r)=>(gr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{writeSync as ng}from"fs";import{Command as rg}from"commander";var Yt=class Yt extends Error{constructor(t,n={}){super(t),this.name="HintedError",n.cause!==void 0&&(this.cause=n.cause);let r=this.deriveDefaults(n);this.hint=n.hint??r.hint,this.helpUrl=n.helpUrl??r.helpUrl,this.shouldReport=n.shouldReport??!0}deriveDefaults(t){return{hint:Ws(t.cause)}}};i(Yt,"HintedError");var h=Yt;function Sr(e){return e instanceof h}i(Sr,"isHintedError");var wr="https://docs.cognite.com/cdf/access/",zs="https://status.cognite.com";function Js(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:wr};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:wr};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:zs};default:return{}}}i(Js,"defaultHintForStatus");var Wt=class Wt extends h{constructor(t,n){super(t,n),this.name="HintedHttpError",this.httpStatusCode=n.httpStatusCode,this.requestUrl=n.requestUrl,this.responseBody=n.responseBody}deriveDefaults(t){let{httpStatusCode:n}=t,r=Js(n),o=super.deriveDefaults(t);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(Wt,"HintedHttpError");var fe=Wt;function vr(e){return e instanceof fe}i(vr,"isHintedHttpError");function Ys(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}i(Ys,"hintForErrno");function Ws(e){let t=e,n=new Set;for(;t!=null&&!n.has(t)&&(n.add(t),typeof t=="object");){let r=t,o=Ys(r.code,r);if(o!==void 0)return o;t=r.cause}}i(Ws,"hintForCause");import{existsSync as Tc,readFileSync as Fc,writeFileSync as Oc}from"fs";import{resolve as Pn}from"path";import{fileURLToPath as Lc}from"url";import{CogniteClient as Nc}from"@cognite/sdk";import Dn from"enquirer";import{mkdirSync as Qa,readFileSync as za,rmSync as Ja,writeFileSync as dt}from"fs";import{resolve as se}from"path";import{generate as ei}from"@graphql-codegen/cli";import{GraphQLSchema as Oa,GraphQLObjectType as La,GraphQLNonNull as Q,GraphQLList as De,GraphQLString as ve,GraphQLInt as Na,GraphQLInputObjectType as Qr,printSchema as _a}from"graphql";function tt(e){return{space:e.space,externalId:e.externalId,version:e.version}}i(tt,"toSharedViewId");function Zs(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}i(Zs,"dmsTypeToGraphQL");function Cr(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?e.type.source?{kind:"directRelationList",targetView:tt(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:tt(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let r=t.values;if(typeof r=="object"&&r!==null)for(let[o,s]of Object.entries(r))n[o]={name:typeof s=="object"&&s!==null&&"name"in s?String(s.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,o.name??r]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?Zs(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:tt(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:tt(e.source),direction:t}}return{kind:"scalar"}}i(Cr,"parsePropertyDescriptor");var kr=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var Xs=new Set(["String","Int","Float","DateTime","Date"]);function xr(e){return e.kind==="directRelation"||e.kind==="directRelationList"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:kr.has(e.graphqlType??"String")}i(xr,"isFilterableDescriptor");function Er(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:kr.has(e.graphqlType??"String")}i(Er,"isSortableDescriptor");function br(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&Xs.has(e.graphqlType??"")}i(br,"hasInOpDescriptor");function Pr(e){return e.kind==="scalar"&&e.isList===!0}i(Pr,"hasListOpsDescriptor");var Dr=/^[A-Za-z_][A-Za-z0-9_]*$/;function Ir(e){return Dr.test(e)}i(Ir,"isSafeExternalId");function Zt(e,t){if(!Ir(e))throw new Error(`Unsafe externalId for ${t}: "${e}" \u2014 must match ${Dr}. externalIds are interpolated into file paths and emitted TypeScript source and must contain only ASCII letters, digits, and underscore (and not start with a digit).`)}i(Zt,"assertSafeExternalId");var Ar=/^[a-z][a-z0-9_-]*$/;function ye(e){if(!Ar.test(e))throw new Error(`Unsafe SDK name: "${e}" \u2014 must match ${Ar}. SDK names become folders under src/generated_sdks/ and must contain only lowercase ASCII letters, digits, hyphen, and underscore.`)}i(ye,"assertSafeSdkName");function re(e){return e.usedFor!=="edge"}i(re,"isNodeOrAll");function be(e){return{query:`query${e}`,getById:`get${e}ById`,count:`count${e}`,search:`search${e}`,aggregate:`aggregate${e}`}}i(be,"viewOperationNames");function $r(e){let t=new Set;return e.filter(n=>t.has(n.externalId)?!1:(t.add(n.externalId),!0))}i($r,"dedupeByExternalId");function J(e){return Object.entries(e.properties).map(([t,n])=>[t,Cr(n),n.description])}i(J,"parsedProperties");function Rr(e){return e.map(t=>({...t,properties:Object.fromEntries(Object.entries(t.properties).map(([n,r])=>[n,ea(r)]))}))}i(Rr,"viewsForGeneratedFile");function ea(e){if("source"in e)return e;let{type:t}=e;if(!t||t.type!=="enum")return e;let{list:n,maxListSize:r,...o}=t;return{...e,type:o}}i(ea,"stripDeprecatedEnumList");function Tr(e){let t=e.filter(re),n=new Map,r=new Map;for(let o of t){let s=new Map;for(let[p,c]of J(o))s.set(p,c);let a={view:{space:o.space,externalId:o.externalId,version:o.version},properties:s};n.set(`${o.space}:${o.externalId}`,a),r.set(o.externalId,a)}return{view(o){let s=n.get(`${o.space}:${o.externalId}`)??r.get(o.externalId);if(!s)throw new Error(`SchemaKnowledge: no view for "${o.space}:${o.externalId}"`);return s},property(o,s){return(n.get(`${o.space}:${o.externalId}`)??r.get(o.externalId))?.properties.get(s)}}}i(Tr,"buildSchemaKnowledge");import{GraphQLObjectType as Fr,GraphQLNonNull as Me,GraphQLString as tn,GraphQLFloat as it,GraphQLList as aa,GraphQLEnumType as pa}from"graphql";import{GraphQLScalarType as ie,Kind as K}from"graphql";function nt(e){switch(e.kind){case K.STRING:case K.BOOLEAN:return e.value;case K.INT:return parseInt(e.value,10);case K.FLOAT:return parseFloat(e.value);case K.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=nt(n.value);return t}case K.LIST:return e.values.map(nt);case K.NULL:return null;default:return null}}i(nt,"parseLiteralJSON");var ta=new ie({name:"DateTime",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.STRING?e.value:null,"parseLiteral")}),na=new ie({name:"Date",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.STRING?e.value:null,"parseLiteral")}),Xt=new ie({name:"JSON",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:nt}),ra=new ie({name:"CogniteTimeSeriesReference",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.STRING?e.value:null,"parseLiteral")}),ia=new ie({name:"CogniteFileReference",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.STRING?e.value:null,"parseLiteral")}),oa=new ie({name:"CogniteSequenceReference",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.STRING?e.value:null,"parseLiteral")}),rt=new ie({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:i(e=>e.kind===K.INT?parseInt(e.value,10):null,"parseLiteral")}),sa=new ie({name:"DirectRelationList",description:"A list of direct-relation node references ({ space, externalId }).",serialize:i(e=>e,"serialize"),parseValue:i(e=>e,"parseValue"),parseLiteral:nt}),oe={DateTime:ta,Date:na,JSON:Xt,CogniteTimeSeriesReference:ra,CogniteFileReference:ia,CogniteSequenceReference:oa,ListLimit:rt,DirectRelationList:sa},en={DateTime:"string",Date:"string",JSON:"unknown",CogniteTimeSeriesReference:"string",CogniteFileReference:"string",CogniteSequenceReference:"string",ListLimit:"number",DirectRelationList:"Array<{ space: string; externalId: string }>"};var ca=new pa({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),Or={function:{type:new Me(ca)},property:{type:tn},interval:{type:it}},la=new Fr({name:"HistogramBucket",fields:{start:{type:new Me(it)},count:{type:new Me(it)}}}),Lr=new Fr({name:"AggregateResult",fields:{aggregate:{type:new Me(tn)},property:{type:tn},value:{type:it},buckets:{type:new aa(new Me(la))},group:{type:Xt}}});import{GraphQLObjectType as rn,GraphQLNonNull as Pe,GraphQLList as da,GraphQLString as nn,GraphQLBoolean as ma}from"graphql";var ua=new rn({name:"PageInfo",fields:{endCursor:{type:nn},hasNextPage:{type:new Pe(ma)}}}),ot=new rn({name:"NodeReference",fields:{space:{type:new Pe(nn)},externalId:{type:new Pe(nn)}}});function st(e,t){return new rn({name:`${e}Connection`,fields:{items:{type:new Pe(new da(new Pe(t)))},pageInfo:{type:new Pe(ua)}}})}i(st,"makeConnectionType");import{GraphQLInputObjectType as Se,GraphQLList as _,GraphQLNonNull as pt,GraphQLString as he,GraphQLBoolean as N,GraphQLFloat as va,GraphQLInt as Ca}from"graphql";import{GraphQLObjectType as ga,GraphQLNonNull as Nr,GraphQLList as fa,GraphQLString as at,GraphQLBoolean as ya,GraphQLInt as Ur,GraphQLFloat as ha,GraphQLEnumType as wa}from"graphql";function _r(e){return e==="String"?at:e==="Boolean"?ya:e==="Int"?Ur:e==="Float"?ha:oe[e]??at}i(_r,"scalarForName");function Mr(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}i(Mr,"createTypeContext");function Sa(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}i(Sa,"sanitizeEnumValue");function on(e,t,n,r){let o=n.enumRegistry.get(e);if(o)return o;let s=new wa({name:e,values:Object.fromEntries(t.map(a=>[Sa(a),{value:a,description:r?.[a]}]))});return n.enumRegistry.set(e,s),s}i(on,"getOrCreateEnumType");function Vr(e,t){return new ga({name:e.externalId,description:e.description??e.name,fields:i(()=>{let n={space:{type:new Nr(at)},externalId:{type:new Nr(at)}};for(let[r,o,s]of J(e))if(o.kind==="scalar")o.isList?n[r]={type:new fa(_r(o.graphqlType??"String")),description:s}:n[r]={type:_r(o.graphqlType??"String"),description:s};else if(o.kind==="enum"){let a=`${e.externalId}${r.charAt(0).toUpperCase()}${r.slice(1)}`;n[r]={type:on(a,o.values,t,o.valueNames),description:s}}else if(o.kind==="directRelation"){let a=t.typeRegistry.get(o.targetView.externalId)??ot;n[r]={type:a,description:s}}else if(o.kind==="directRelationList")n[r]={type:oe.DirectRelationList,description:s};else if(o.kind==="reverseList"||o.kind==="edge"){let a=o.kind==="reverseList"?o.sourceView.externalId:o.targetView.externalId,p=t.typeRegistry.get(a)??ot,c=t.connectionRegistry.get(a);c||(c=st(a,p),t.connectionRegistry.set(a,c)),n[r]={type:c,description:s,args:{limit:{type:Ur}}}}else if(o.kind==="reverseDirect"){let a=t.typeRegistry.get(o.sourceView.externalId)??ot;n[r]={type:a,description:s}}return n},"fields")})}i(Vr,"generateViewObjectType");function Ae(e,t,n){let r={isNull:{type:N},exists:{type:N},eq:{type:t}};return n.hasIn&&(r.in={type:new _(t)}),n.hasPrefix&&(r.prefix={type:he}),n.hasRange&&(r.gte={type:t},r.gt={type:t},r.lte={type:t},r.lt={type:t}),n.hasListOps&&(r.containsAny={type:new _(t)},r.containsAll={type:new _(t)},r.overlaps={type:new _(t)}),new Se({name:e,fields:r})}i(Ae,"makeScalarFilter");var sn=Ae("StringFilter",he,{hasIn:!0,hasPrefix:!0}),ka=Ae("BooleanFilter",N,{}),xa=Ae("IntFilter",Ca,{hasIn:!0,hasRange:!0}),Ea=Ae("FloatFilter",va,{hasIn:!0,hasRange:!0}),ba=Ae("DateTimeFilter",oe.DateTime,{hasIn:!0,hasRange:!0}),Pa=Ae("DateFilter",oe.Date,{hasIn:!0,hasRange:!0}),Aa=new Se({name:"StringListFilter",fields:{isNull:{type:N},exists:{type:N},containsAny:{type:new _(he)},containsAll:{type:new _(he)},overlaps:{type:new _(he)}}}),we=new Se({name:"DirectRelationRef",fields:{space:{type:new pt(he)},externalId:{type:new pt(he)}}}),Da=new Se({name:"DirectRelationFilter",fields:{isNull:{type:N},exists:{type:N},eq:{type:we},in:{type:new _(we)}}}),Ia=new Se({name:"DirectRelationListFilter",fields:{isNull:{type:N},exists:{type:N},containsAny:{type:new _(new pt(we))},containsAll:{type:new _(new pt(we))}}});function $a(e){switch(e){case"String":return sn;case"Boolean":return ka;case"Int":return xa;case"Float":return Ea;case"DateTime":return ba;case"Date":return Pa;default:return sn}}i($a,"scalarFilterForName");var jr=["space","externalId"];function Kr(e,t,n){let r=t.get(e.externalId),o={};for(let a of jr)o[a]={type:sn};let s=new Set(jr);for(let[a,p]of J(e)){if(s.has(a))continue;let c=xr(p),l=Pr(p);if(!(!c&&!l))if(p.kind==="directRelation"){let d={isNull:{type:N},exists:{type:N},eq:{type:we},in:{type:new _(we)}};br(p)&&(d.in={type:new _(we)});let m=t.get(p.targetView.externalId);m&&(d.nested={type:m}),o[a]=m?{type:new Se({name:`_${e.externalId}_${a}_Filter`,fields:d})}:{type:Da}}else if(p.kind==="directRelationList")o[a]={type:Ia};else if(p.kind==="enum"){let d=`${e.externalId}${a.charAt(0).toUpperCase()}${a.slice(1)}`,m=on(d,p.values,n),g=n.enumFilterRegistry.get(d);g||(g=new Se({name:`${d}Filter`,fields:{isNull:{type:N},exists:{type:N},eq:{type:m},in:{type:new _(m)}}}),n.enumFilterRegistry.set(d,g)),o[a]={type:g}}else if(l)o[a]={type:Aa};else{let d=p.kind==="scalar"?p.graphqlType??"String":"String",m=$a(d);m&&(o[a]={type:m})}}return{...o,hasData:{type:N},matchAll:{type:N},_and:{type:new _(r)},_or:{type:new _(r)},_not:{type:r}}}i(Kr,"generateFilterFields");import{GraphQLEnumType as Br,GraphQLInputObjectType as Hr,GraphQLList as Ra,GraphQLNonNull as ct,GraphQLString as Ta,GraphQLBoolean as Fa}from"graphql";var lt=new Br({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function Gr(e){let t=[];for(let[r,o]of J(e))Er(o)&&t.push(r);if(t.length===0)return null;let n=new Br({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(r=>[r,{value:r}]))});return new Hr({name:`${e.externalId}Sort`,fields:{field:{type:new ct(n)},direction:{type:new ct(lt)},nullsFirst:{type:Fa}}})}i(Gr,"generateSortInput");var qr=new Hr({name:"SearchSort",fields:{property:{type:new ct(new Ra(new ct(Ta)))},direction:{type:lt}}});function zr(e){let t=e.filter(re),n=Mr(t);for(let l of t){let d=Vr(l,n);n.typeRegistry.set(l.externalId,d)}let r=new Map;for(let l of t){let d=new Qr({name:`${l.externalId}Filter`,fields:i(()=>Kr(l,r,n),"fields")});r.set(l.externalId,d)}let o={};for(let l of t){let d=l.externalId,m=be(d),g=n.typeRegistry.get(d),f=n.connectionRegistry.get(d);f||(f=st(d,g),n.connectionRegistry.set(d,f));let u=r.get(d),y=Gr(l),S={limit:{type:rt},cursor:{type:ve},filter:{type:u}};y&&(S.sort={type:new De(y)}),o[m.query]={type:new Q(f),args:S},o[m.getById]={type:g,args:{space:{type:new Q(ve)},externalId:{type:new Q(ve)}}},o[m.count]={type:new Q(Na),args:{filter:{type:u}}},o[m.search]={type:new Q(f),args:{query:{type:ve},limit:{type:rt},filter:{type:u},sort:{type:new De(new Q(qr))},properties:{type:new De(new Q(ve))}}},o[m.aggregate]={type:new Q(new De(new Q(Lr))),args:{filter:{type:u},aggregates:{type:new De(new Q(new Qr({name:`${d}AggregateRequest`,fields:Or})))},groupBy:{type:new De(new Q(ve))},query:{type:ve}}}}let s=[];for(let[l,d]of n.typeRegistry)s.push({name:d.name,source:`typeRegistry[${l}]`});for(let[l,d]of n.connectionRegistry)s.push({name:d.name,source:`connectionRegistry[${l}]`});let a=new Map;for(let{name:l,source:d}of s)a.has(l)||a.set(l,[]),a.get(l).push(d);for(let[l,d]of a)if(d.length>1)throw new Error(`[dune] duplicate GraphQL type "${l}" from: ${d.join(", ")}`);let p=new Oa({query:new La({name:"Query",fields:o}),types:[lt,...Object.values(oe),...n.enumRegistry.values()]}),c=Tr(t);return{schema:p,sdl:_a(p),schemaKnowledge:c}}i(zr,"buildSchema");async function Jr(e,t){let r=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!r)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!r.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let o=r.views.map(a=>({space:a.space,externalId:a.externalId,version:a.version}));return(await t.views.retrieve(o,{includeInheritedProperties:!0})).items}i(Jr,"fetchViews");import{GraphQLObjectType as Ua,GraphQLNonNull as Ma,GraphQLList as Va,isScalarType as ja,isEnumType as Ka,parse as Ba,print as Ha}from"graphql";function an(e,t){let n=e.getType(t);if(!(n instanceof Ua))return[];let r=n.getFields(),o=[];for(let[s,a]of Object.entries(r)){let p=a.type;for(;p instanceof Ma||p instanceof Va;)p=p.ofType;(ja(p)||Ka(p))&&o.push(s)}return o}i(an,"scalarFieldsFor");function Ga(e,t){let n=an(e,t),r=["space","externalId"];for(let o of["name","description"])n.includes(o)&&r.push(o);return r.join(" ")}i(Ga,"minimalRelationFields");function Yr(e,t,n){let r=[];for(let[o,s]of J(e))if(s.kind==="directRelation"||s.kind==="reverseDirect"){let a=s.kind==="directRelation"?s.targetView.externalId:s.sourceView.externalId;if(n)r.push(`${o} { ${Ga(t,a)} }`);else{let c=["space","externalId",...an(t,a).filter(l=>l!=="space"&&l!=="externalId")];r.push(`${o} { ${c.join(" ")} }`)}}else!n&&(s.kind==="reverseList"||s.kind==="edge")&&r.push(`${o} { items { space externalId } pageInfo { hasNextPage endCursor } }`);return r}i(Yr,"relationFieldsFor");function Wr(e,t,n,r){return`query ${e}(${t}) {
|
|
3
|
+
${e}(${n}) {
|
|
4
|
+
items {
|
|
5
|
+
${r}
|
|
6
|
+
}
|
|
7
|
+
pageInfo { hasNextPage endCursor }
|
|
8
|
+
}
|
|
9
|
+
}`}i(Wr,"paginatedOp");function qa(e,t){let n=e.externalId,r=an(t,n),o=Yr(e,t,!0),s=Yr(e,t,!1),a=[...r,...o].join(`
|
|
10
|
+
`),p=[...r,...s].join(`
|
|
11
|
+
`),c=!!t.getType(`${n}Sort`),l=be(n),d=Wr(l.query,c?`$limit: ListLimit, $cursor: String, $filter: ${n}Filter, $sort: [${n}Sort!]`:`$limit: ListLimit, $cursor: String, $filter: ${n}Filter`,c?"limit: $limit, cursor: $cursor, filter: $filter, sort: $sort":"limit: $limit, cursor: $cursor, filter: $filter",a),m=Wr(l.search,`$query: String, $limit: ListLimit, $filter: ${n}Filter, $sort: [SearchSort!], $properties: [String!]`,"query: $query, limit: $limit, filter: $filter, sort: $sort, properties: $properties",a),g=`query ${l.getById}($space: String!, $externalId: String!) {
|
|
12
|
+
${l.getById}(space: $space, externalId: $externalId) {
|
|
13
|
+
${p}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
`,f=`query ${l.count}($filter: ${n}Filter) {
|
|
17
|
+
${l.count}(filter: $filter)
|
|
18
|
+
}`,u=`query ${l.aggregate}($filter: ${n}Filter, $aggregates: [${n}AggregateRequest!], $groupBy: [String!], $query: String) {
|
|
19
|
+
${l.aggregate}(filter: $filter, aggregates: $aggregates, groupBy: $groupBy, query: $query) {
|
|
20
|
+
aggregate
|
|
21
|
+
property
|
|
22
|
+
value
|
|
23
|
+
buckets { start count }
|
|
24
|
+
group
|
|
25
|
+
}
|
|
26
|
+
}`;return Ha(Ba([d,g,f,m,u].join(`
|
|
7
27
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
`)
|
|
28
|
+
`)))}i(qa,"generateViewOperations");function Zr(e,t){return e.filter(re).map(n=>qa(n,t)).join(`
|
|
29
|
+
|
|
30
|
+
`)}i(Zr,"generateOperations");var mt=`/* eslint-disable */
|
|
31
|
+
`;function Xr(e){dt(e,mt+za(e,"utf-8"),"utf-8")}i(Xr,"prependHeader");var ti="change-case-all#upperCaseFirst";function Ve(e){let t=be(e),n="{ items: [], pageInfo: { hasNextPage: false, endCursor: null } }";return[{method:t.query,op:"query",data:`Query${e}Query`,emptyResult:n},{method:t.getById,op:"getById",data:`Get${e}ByIdQuery`,emptyResult:"null"},{method:t.count,op:"count",data:`Count${e}Query`,emptyResult:"0"},{method:t.search,op:"search",data:`Search${e}Query`,emptyResult:n},{method:t.aggregate,op:"aggregate",data:`Aggregate${e}Query`,emptyResult:"[]"}]}i(Ve,"opsFor");function Ie(e){return e.charAt(0).toLowerCase()+e.slice(1)}i(Ie,"resourceKey");var Ya=i(e=>Ve(e).map(t=>t.data),"typeNamesFor");function Wa(e,t){let n=i(r=>r.match(/from '(\.\/[^']+)'/)?.[1]??"","path");return n(e).localeCompare(n(t),void 0,{sensitivity:"base"})}i(Wa,"byImportPath");function Za(e){let t=$r(e),n=new Set(t);for(let r of e)n.has(r)||console.warn(`[dune] dedup: dropped ${r.space}/${r.externalId} (duplicate externalId)`);return console.log(`[dune] views after dedup: ${t.length} (was ${e.length})`),t}i(Za,"dedupeWithLogging");function Xa(e,t){dt(se(e,"views.generated.ts"),`${mt}import type { ViewDefinition } from '@cognite/cli/sdk-runtime';
|
|
32
|
+
|
|
33
|
+
// Auto-generated \u2014 do not edit.
|
|
34
|
+
export const views: ViewDefinition[] = ${JSON.stringify(Rr(t),null,2)};
|
|
35
|
+
`,"utf-8")}i(Xa,"writeViewsFile");async function ep(e,t){await ei({schema:t,generates:{[se(e,"types.generated.ts")]:{plugins:["typescript"],config:{scalars:en,namingConvention:ti}}}},!0)}i(ep,"generateBaseTypes");async function tp(e,t,n,r){let o=Zr(r,n);await ei({schema:t,documents:o,generates:{[se(e,"operations.generated.ts")]:{plugins:["typescript-operations"],config:{scalars:en,namingConvention:ti}}}},!0)}i(tp,"generateOperationTypes");function np(e,t){let n=`${t}Filter`,r=e.data,o=e.method;switch(e.op){case"query":return` query: ListMethod<${r}, '${o}', QueryArgs, ${n}>;`;case"search":return` search: ListMethod<${r}, '${o}', SearchArgs, ${n}>;`;case"getById":return` getById: GetByIdMethod<${r}, '${o}'>;`;case"count":return` count: CountMethod<${r}, '${o}', ${n}>;`;case"aggregate":return` aggregate: AggregateMethod<${r}, '${o}', ${n}>;`}}i(np,"interfaceSig");function rp(e,t){let n=e.data,r=e.method,o=`Promise<${n}['${r}']>`;switch(e.op){case"query":return` query: (args: QueryArgs = {}): ${o} => dispatcher.query<ListItemOf<${n}['${r}']>>('${t}', args),`;case"search":return` search: (args: SearchArgs = {}): ${o} => dispatcher.search<ListItemOf<${n}['${r}']>>('${t}', args),`;case"getById":return` getById: (args: GetByIdArgs): ${o} => dispatcher.getById<NonNullable<${n}['${r}']>>('${t}', args),`;case"count":return` count: (args: CountArgs = {}): ${o} => dispatcher.count('${t}', args),`;case"aggregate":return` aggregate: (args: AggregateArgs = {}): ${o} => dispatcher.aggregate<ArrayElementOf<${n}['${r}']>>('${t}', args),`}}i(rp,"implLine");function ip(e,t){let n=t.flatMap(Ya),r=t.map(p=>`${p}Filter`),o=[`import type { ${n.join(", ")} } from './operations.generated';`,`import type { ${r.join(", ")} } from './types.generated';`,"import { views } from './views.generated';"].sort(Wa).join(`
|
|
36
|
+
`),s=t.map(p=>` ${Ie(p)}: {
|
|
37
|
+
${Ve(p).map(c=>np(c,p)).join(`
|
|
38
|
+
`)}
|
|
39
|
+
};`).join(`
|
|
40
|
+
`),a=t.map(p=>` ${Ie(p)}: {
|
|
41
|
+
${Ve(p).map(c=>rp(c,p)).join(`
|
|
42
|
+
`)}
|
|
43
|
+
},`).join(`
|
|
44
|
+
`);dt(se(e,"index.ts"),`${mt}import { createSdkRuntimeFromViews } from '@cognite/cli/sdk-runtime';
|
|
45
|
+
import type { AggregateArgs, AggregateMethod, ArrayElementOf, CountArgs, CountMethod, GetByIdArgs, GetByIdMethod, ListItemOf, ListMethod, QueryArgs, SearchArgs } from '@cognite/cli/sdk-runtime';
|
|
46
|
+
|
|
47
|
+
${o}
|
|
48
|
+
|
|
49
|
+
export * from './types.generated';
|
|
50
|
+
export type { ${n.join(", ")} } from './operations.generated';
|
|
51
|
+
|
|
52
|
+
/** Resource-namespaced SDK: sdk.<resource>.<query|getById|count|search|aggregate>(...). */
|
|
53
|
+
export interface Sdk {
|
|
54
|
+
${s}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Creates a fully-typed SDK backed by the SDK runtime. Each method translates its typed
|
|
59
|
+
* arguments into DMS API calls \u2014 no CDF GraphQL endpoint and no graphql-js are involved.
|
|
60
|
+
* \`select\` narrows the returned data; the return type reflects it as a Partial of the view.
|
|
61
|
+
*/
|
|
62
|
+
export function createSdk(client: Parameters<typeof createSdkRuntimeFromViews>[1]): Sdk {
|
|
63
|
+
const { dispatcher } = createSdkRuntimeFromViews(views, client);
|
|
64
|
+
return {
|
|
65
|
+
${a}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
`,"utf-8")}i(ip,"writeBarrel");function op(e){let t="{ space: string; externalId: string } & Record<string, unknown>",n="{ hasNextPage: boolean; endCursor: string | null }";switch(e.op){case"query":case"search":return` ${e.op}?: (args?: unknown) => Promise<{ items: Array<${t}>; pageInfo: ${n} }>;`;case"getById":return` getById?: (args?: unknown) => Promise<(${t}) | null>;`;case"count":return" count?: (args?: unknown) => Promise<number>;";case"aggregate":return" aggregate?: (args?: unknown) => Promise<unknown[]>;"}}i(op,"mockOverrideSig");function sp(e,t){let n=t.map(o=>` ${Ie(o)}?: {
|
|
69
|
+
${Ve(o).map(op).join(`
|
|
70
|
+
`)}
|
|
71
|
+
};`).join(`
|
|
72
|
+
`),r=t.map(o=>` ${Ie(o)}: {
|
|
73
|
+
`+Ve(o).map(s=>` ${s.op}: vi.fn(() => Promise.resolve(${s.emptyResult})),`).join(`
|
|
74
|
+
`)+`
|
|
75
|
+
...overrides.${Ie(o)},
|
|
76
|
+
} as unknown as Sdk['${Ie(o)}'],`).join(`
|
|
77
|
+
`);dt(se(e,"test-helpers.ts"),`${mt}import { vi } from 'vitest';
|
|
78
|
+
|
|
79
|
+
import type { Sdk } from './index';
|
|
80
|
+
|
|
81
|
+
type MockOverrides = {
|
|
82
|
+
${n}
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export function makeMockSdk(overrides: MockOverrides = {}): Sdk {
|
|
86
|
+
return {
|
|
87
|
+
${r}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
`,"utf-8")}i(sp,"writeTestHelpers");async function ni(e,t,n){return ap(await Jr(e,t),e.name,n)}i(ni,"generateSdk");async function ap(e,t,n){let r={name:t},o=Za(e);for(let d of o)Zt(d.externalId,"codegen view");ye(r.name);let{schema:s,sdl:a}=zr(o),p=o.filter(re),c=se(n,r.name);Ja(c,{recursive:!0,force:!0}),Qa(c,{recursive:!0}),Xa(c,p),await ep(c,a),await tp(c,a,s,p),Xr(se(c,"types.generated.ts")),Xr(se(c,"operations.generated.ts"));let l=p.map(d=>d.externalId).sort((d,m)=>d.localeCompare(m));return ip(c,l),sp(c,l),{sdkDir:c,viewCount:p.length}}i(ap,"generateSdkFromViews");import{existsSync as hp,readFileSync as wp}from"fs";import{resolve as Sp}from"path";import{array as ri,boolean as pp,check as $e,forward as Re,literal as cp,maxLength as lp,minLength as dp,nonEmpty as ae,object as ii,optional as X,picklist as mp,pipe as Y,safeParse as up,string as H,url as oi}from"valibot";var pn=Y(H(),ae("must not be empty")),cn=Y(H(),ae("must not be empty"),lp(256,"must be 256 characters or fewer")),ln=Y(H(),ae("must not be empty"),oi("must be a valid URL")),gp=Y(H(),ae("must not be empty"),oi("must be a valid URL")),dn=Y(H(),ae("must not be empty")),mn=Y(H(),ae("must not be empty")),fp=Y(ii({org:dn,project:mn,baseUrl:ln,deployClientId:X(H(),""),deploySecretName:X(H(),""),published:X(pp(),!1),idpType:X(mp(["cdf","entra_id","oauth"]),"cdf"),tenantId:X(H()),scopes:X(ri(Y(H(),ae("must not be empty")))),tokenUrl:X(gp)}),Re($e(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Re($e(e=>e.idpType!=="oauth"||!!e.tokenUrl,'must be set when idpType is "oauth"'),["tokenUrl"]),Re($e(e=>!e.tokenUrl||e.idpType==="oauth",'must only be set when idpType is "oauth"'),["tokenUrl"]),Re($e(e=>e.idpType!=="oauth"||!!e.deployClientId,'must be set when idpType is "oauth"'),["deployClientId"]),Re($e(e=>e.idpType!=="oauth"||!!e.deploySecretName,'must be set when idpType is "oauth"'),["deploySecretName"]),Re($e(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),yp=ii({name:pn,externalId:cn,versionTag:Y(H(),ae("must not be empty")),description:X(H(),""),deployments:Y(ri(fp),dp(1,"must contain at least one deployment")),infra:X(cp("appsApi"))});function un(e){let t=up(yp,e);if(t.success)return t.output;let n=t.issues[0],r=n.path?.map(s=>s.key).join(".")??"",o=r?`"${r}" `:"";throw new Error(`app.json: ${o}${n.message}`)}i(un,"validateAppConfig");function k(e,t={}){let{validator:n=un,existsSync:r=hp,readFileSync:o=wp}=t,s=Sp(e,"app.json");if(!r(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=o(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return n(p)}i(k,"loadAppConfig");import{CogniteClient as hc}from"@cognite/sdk";import{inspect as vp}from"util";var gn="[REDACTED]",je,ut=class ut{constructor(t){yr(this,je);hr(this,je,t)}toString(){return gn}toJSON(){return gn}[vp.custom](){return gn}expose(){return fr(this,je)}static from(t){return new ut(t)}};je=new WeakMap,i(ut,"SensitiveString");var x=ut;var si="https://docs.cognite.com/cdf/access/";function B(e){return e!==null&&typeof e=="object"}i(B,"isRecord");function Ce(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(Ce,"isHttpError");function Cp(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
91
|
+
See: ${si}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
92
|
+
See: ${si}`;default:return}}i(Cp,"httpStatusHint");function W(e){let t=e instanceof Error?e:new Error(String(e));if(!Ce(t))return null;let n=Cp(t.status);return n?Object.assign(new Error(`${t.message}
|
|
93
|
+
${n}`),{cause:t}):null}i(W,"enrichedHttpError");function kp(e){if(!B(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(B(n)){let r=n.error;if(B(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}i(kp,"findMissingArray");function xp(e,t){if(!Ce(e)||e.status!==400)return!1;let n=kp(e);return n?n.some(r=>B(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}i(xp,"isMissingExternalIdError");function gt(e,t){return Ce(e)&&e.status===404||xp(e,t)}i(gt,"isNotFoundError");var pi=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ci=["ACTIVE","PREVIEW"],fn=class fn extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};i(fn,"AppVersionNotFoundError");var G=fn,yn=class yn extends Error{constructor(t){super(`App ${t} not found`),this.name="AppNotFoundError",this.appExternalId=t}};i(yn,"AppNotFoundError");var Te=yn;function ft(e,t){return e.includes(t)}i(ft,"includesValue");function Ep(e){return ft(pi,e)}i(Ep,"isAppVersionLifecycleState");function bp(e){return ft(ci,e)}i(bp,"isAppVersionAlias");function Pp(e){return typeof e.version=="string"&&Ep(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||bp(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}i(Pp,"isAppVersion");function ai(e){if(!B(e)){let t=JSON.stringify(e)?.slice(0,200)??String(e);throw new Error(`Invalid version response: expected object, got ${t}`)}if(!Pp(e)){let t=JSON.stringify(e).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${t}`)}return e}i(ai,"parseAppVersion");function Ap(e){if(!B(e))throw new Error("Invalid app response: not an object");let{externalId:t,name:n,description:r}=e;if(typeof t!="string")throw new Error("Invalid app response: missing externalId");if(typeof n!="string")throw new Error("Invalid app response: missing name");if(r!=null&&typeof r!="string")throw new Error("Invalid app response: malformed description");return{externalId:t,name:n,description:typeof r=="string"?r:void 0}}i(Ap,"parseAppMetadata");var hn=class hn{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw W(o)??o}}async updateApps(t){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:t}})}catch(n){throw W(n)??n}}async getApp(t){let n=`${this.appsBasePath}/${encodeURIComponent(t)}`;try{let r=await this.client.get(n);return Ap(r.data)}catch(r){throw gt(r,[t])?new Te(t):W(r)??r}}async uploadVersion(t,n,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",n),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate();if(!l)throw new h("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let d=x.from(l),m=`${this.client.getBaseUrl()}${c}`,g=new AbortController,f=setTimeout(()=>g.abort(),300*1e3),u;try{u=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${d.expose()}`},body:a,signal:g.signal})}catch(y){throw y instanceof Error&&y.name==="AbortError"?new h("Upload timed out after 5 minutes",{hint:"The upload took longer than 5 minutes. Try again \u2014 if it keeps timing out, check your network speed or bundle size."}):new h(`Failed to upload version to ${m}`,{cause:y,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(f)}if(!u.ok){let y=await u.text(),S;try{S=JSON.parse(y)}catch{}let C=y;if(B(S)){let V=S.error;if(typeof V=="string")C=V;else if(B(V)){let A=V.message,E=V.code;C=typeof A=="string"?A:E!=null?`Unknown error (code: ${E})`:y}else{let A=S.message;C=typeof A=="string"?A:y}}let v=u.headers.get("x-request-id"),w=v?` | X-Request-ID: ${v}`:"",b=B(S)?S:y;throw new fe(`Upload failed: ${u.status} \u2014 ${C}${w}`,{httpStatusCode:u.status,requestUrl:m,responseBody:b})}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return ai(a.data)}catch(a){throw gt(a,[t,n])?new G(t,n):W(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/versions/list`;try{let o=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!B(o.data)||!Array.isArray(o.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=o.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return ai(s[0])}catch(o){if(gt(o,[t]))return null;throw W(o)??o}}async deleteVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/delete`;try{await this.client.post(o,{data:{items:n.map(s=>({version:s}))}})}catch(s){throw W(s)??s}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(s){throw W(s)??s}}async submitSignatures(t,n,r){let o=encodeURIComponent(t),s=encodeURIComponent(n),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw W(p)??p}}async listSignatures(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return $p(a.data)}catch(a){throw W(a)??a}}};i(hn,"AppHostingApi");var yt=hn,Dp=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ip=["developer","certifier"];function $p(e){if(!B(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(n=>{let r=Rp(n);return r?[r]:[]})}i($p,"parseStoredSignatures");function Rp(e){if(!B(e))return null;let{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!ft(Ip,n)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!ft(Dp,a)?null:{signerKid:t,signerRole:n,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(Rp,"parseStoredSignature");function wn(e,t){let n=[];e.name!==t.name&&n.push({field:"name",remote:e.name,local:t.name});let r=e.description??"";return r!==t.description&&n.push({field:"description",remote:r,local:t.description}),n}i(wn,"diffAppMetadata");function Tp(e){let t=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:n,remote:r,local:o}of e){let s=`${n}:`.padEnd(14);t.push(` ${s}"${r}" \u2192 "${o}"`)}return t.join(`
|
|
94
|
+
`)}i(Tp,"formatMetadataDriftError");var Sn=class Sn{constructor(t){this.api=new yt(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,s){return this.api.uploadVersion(t,n,r,o,s)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(Ce(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`),await this.checkMetadataDrift(t,n,r);return}throw o}}async checkMetadataDrift(t,n,r){let o;try{o=await this.getApp(t)}catch{return}let s=wn(o,{name:n,description:r});if(s.length!==0)throw new h(Tp(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(t){return this.api.getApp(t)}async updateAppMetadata(t,n,r){await this.api.updateApps([{externalId:t,update:{name:{set:n},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(t,n,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${n}...`),await this.api.submitSignatures(t,n,r),console.log("\u2705 Signatures stored"))}listSignatures(t,n){return this.api.listSignatures(t,n)}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{alias:{setNull:!0}}}])}async deleteVersion(t,n){await this.api.deleteVersions(t,[n])}async deprecateVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"ARCHIVED"}}}])}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,s,a,p=!1){console.log(`
|
|
17
95
|
\u{1F680} Deploying application via App Hosting API...
|
|
18
|
-
`),await this.ensureApp(t,r
|
|
19
|
-
\u2705 Deployment successful!`)}};
|
|
20
|
-
`),
|
|
21
|
-
`);let u=
|
|
22
|
-
`)}}}
|
|
23
|
-
<h1>${
|
|
96
|
+
`),await this.ensureApp(t,n,r),await this.uploadVersion(t,o,s,a),p&&await this.publishAndActivate(t,o),console.log(`
|
|
97
|
+
\u2705 Deployment successful!`)}};i(Sn,"AppHostingClient");var D=Sn;import{CogniteClient as Kp}from"@cognite/sdk";function Fp(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}i(Fp,"exponentialBackoffWithJitter");function Op(e){return new Promise(t=>setTimeout(t,e))}i(Op,"sleep");async function li(e,t={}){let n=t.maxAttempts??5,r=t.shouldRetry??(()=>!0),o=t.delayInMsCalculator??Fp;if(n<1)throw new Error("`maxAttempts` must be 1 or greater");if(n>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=n||!r(a))throw a;let p=o(s);t.onAttemptFail?.(a,s,p),await Op(p),s++}}i(li,"retryAsync");var Lp="https://auth.cognite.com/oauth2/token",Np=i(e=>typeof e=="object"&&e!==null&&"access_token"in e&&typeof e.access_token=="string","hasAccessToken");async function di({idp:e,tokenUrl:t,init:n,missingTokenHint:r}){let o;try{o=await li(()=>fetch(t,n),{maxAttempts:3})}catch(p){throw new h(`Failed to fetch access token from ${t}`,{cause:p})}if(!o.ok){let p=await o.text();throw new fe(`Failed to get token from ${e}: ${o.status} ${o.statusText}`,{httpStatusCode:o.status,requestUrl:t,responseBody:p})}let s=await o.text(),a;try{a=JSON.parse(s)}catch{throw new h(`Unexpected response from ${e} authentication (invalid JSON)`,{hint:r})}if(!Np(a))throw new h(`No access token in ${e} authentication response`,{hint:r});return x.from(a.access_token)}i(di,"fetchOAuthToken");var _p=i(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");n[s]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Up=i(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=_p()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return x.from(t)},"getSecretFromEnv"),Mp=i((e,t)=>{let n=t.expose();return di({idp:"CDF",tokenUrl:Lp,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${e}:${n}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),mi=i(({idp:e,tokenUrl:t,clientId:n,clientSecret:r,scopes:o,missingTokenHint:s})=>di({idp:e,tokenUrl:t,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:r,grant_type:"client_credentials",...o!==void 0?{scope:o.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Vp=i((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(e).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`)}},"resolveEntraScope"),jp=i((e,t,n,r,o)=>mi({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,clientId:e,clientSecret:t.expose(),scopes:o!==void 0?o:[Vp(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),vn=i(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return x.from(t.COGNITE_TOKEN);let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p,tokenUrl:c}=e,l=Up(r);if(o==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return mi({idp:"OAuth",tokenUrl:c,clientId:n,clientSecret:l.expose(),scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return jp(n,l,s,a,p)}return Mp(n,l)},"getToken");async function Fe(e,t,n=process.env,r){let o=await vn(e,n),s=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(p=>new Kp(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:i(async()=>o.expose(),"oidcTokenProvider")});return await a.authenticate(),a}i(Fe,"getSdk");import ic from"os";import oc from"path";import sc from"open";import{buildAuthorizationUrl as ac,calculatePKCECodeChallenge as pc,discovery as cc,None as lc,randomPKCECodeVerifier as dc,randomState as mc}from"openid-client";import ui from"mixpanel";var Bp="5c4d853e7c3b77b1eb4468d5329b278c",Ke="cognite-cli",Hp=2e3,gi={env:process.env,init:ui.init.bind(ui)},Gp={track:i(()=>{},"track"),flush:i(async()=>{},"flush")};function Cn(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}i(Cn,"isTelemetryDisabled");function qp(e=process.env){if(e.GITHUB_ACTIONS)return"github-actions";if(e.TF_BUILD)return"azure-devops";if(e.GITLAB_CI)return"gitlab-ci";if(e.CIRCLECI)return"circleci";if(e.TRAVIS)return"travis-ci";if(e.BUILDKITE)return"buildkite";if(e.DRONE)return"drone";if(e.SEMAPHORE)return"semaphore";if(e.TEAMCITY_VERSION)return"teamcity";if(e.APPVEYOR)return"appveyor";if(e.CODEBUILD_BUILD_ID)return"aws-codebuild";if(e.HEROKU_TEST_RUN_ID)return"heroku-ci";if(e.BITBUCKET_BUILD_NUMBER)return"bitbucket-pipelines";if(e.JENKINS_URL||e.JENKINS_HOME)return"jenkins";if(e.CI&&e.CI!=="false"&&e.CI!=="0")return"ci-generic"}i(qp,"detectCiEnvironment");function Qp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}i(Qp,"isDebug");function ht(e={}){let t=e.env??gi.env,n=e.init??gi.init,r=e.packageName,o=e.cliVersion,s=Qp(t),a=qp(t);if(Cn(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
|
|
98
|
+
`),Gp;let p,c=new Set;function l(){if(p)return p;try{return p=n(Bp,{geolocate:!1,keepAlive:!1}),p}catch{return}}return i(l,"getClient"),{track(d,m={}){let g=l();if(!g)return;let f={...m,applicationId:Ke,...r&&{packageName:r},...o&&{cliVersion:o},nodeVersion:process.version,platform:process.platform,...a&&{ciEnvironment:a}};s&&process.stderr.write(`[telemetry] track ${d} ${JSON.stringify(f)}
|
|
99
|
+
`);let u=i(()=>{},"finish"),y=new Promise(S=>{u=S});c.add(y);try{g.track(d,f,u)}catch{u()}y.finally(()=>c.delete(y))},async flush(d=Hp){if(c.size===0)return;let m,g=new Promise(f=>{m=setTimeout(f,d),m.unref?.()});try{await Promise.race([Promise.allSettled([...c]),g])}finally{m&&clearTimeout(m)}s&&process.stderr.write(`[telemetry] flush done (${c.size} still pending)
|
|
100
|
+
`)}}}i(ht,"createTelemetry");import Wp from"https";import{authorizationCodeGrant as Zp}from"openid-client";function fi(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}i(fi,"escapeHtml");function kn(e,t,n){let r=fi(t),o=fi(n);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
|
|
101
|
+
<h1>${r}</h1><p>${o}</p><p>You can close this window.</p>${e==="success"?`<style>
|
|
24
102
|
@keyframes checkmark {
|
|
25
103
|
0% { transform: scale(0); }
|
|
26
104
|
50% { transform: scale(1.2); }
|
|
@@ -28,42 +106,83 @@ Examples:
|
|
|
28
106
|
}
|
|
29
107
|
h1 { animation: checkmark 0.5s ease-out; }
|
|
30
108
|
</style>`:""}
|
|
31
|
-
</body></html>`}
|
|
32
|
-
`)
|
|
33
|
-
`);try{await
|
|
34
|
-
`),s.
|
|
109
|
+
</body></html>`}i(kn,"generateHtml");import Yp from"net";import{execFileSync as yi}from"child_process";import{platform as zp}from"os";import Jp from"path";function U(e,t={}){let{platform:n=zp}=t;switch(n()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}i(U,"isOS");function hi(e,t={}){let{exec:n=yi,log:r=console.log}=t,[o,s]=U("macos",t)?["open",[e]]:U("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{n(o,s)}catch{r(`Could not open browser \u2014 open manually:
|
|
110
|
+
${e}`)}}i(hi,"openInBrowser");function wi(e,t={}){let{exec:n=yi,log:r=console.log}=t,[o,s]=U("macos",t)?["open",["-R",e]]:U("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Jp.dirname(e)]];try{n(o,s)}catch{r(`Could not open file manager \u2014 files are at:
|
|
111
|
+
${e}`)}}i(wi,"revealInFileManager");function Si(e,t){return new Promise(n=>{let r=new Yp.Socket,o=i(s=>{r.removeAllListeners(),r.destroy(),n(s)},"done");r.setTimeout(500),r.once("connect",()=>o(!1)),r.once("timeout",()=>o(!0)),r.once("error",()=>o(!0)),r.connect(e,t)})}i(Si,"isHostPortFree");function St(e,t={}){return U("windows",t)?`Find the process: netstat -ano | findstr :${e} then kill it: taskkill /PID <pid> /F`:`Free port ${e} (e.g. lsof -ti :${e} | xargs kill) and retry.`}i(St,"freePortHint");async function vi(e){if(e<0)throw new Error(`Invalid port: ${e}`);return e===0?!0:(await Promise.all([Si(e,"127.0.0.1"),Si(e,"::1")])).every(Boolean)}i(vi,"isPortFree");async function Xp(e,t,n,r,o,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(n,a,{pkceCodeVerifier:r,expectedState:o});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(kn("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(kn("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}i(Xp,"handleCallback");function ec(e){let t=e/6e4,n=Math.round(t*10)/10;return`${n} ${n===1?"minute":"minutes"}`}i(ec,"formatTimeoutMinutes");function Ci(e,t,n,r,o,s={createServer:Wp.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Zp}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,g)=>{try{let f=await Xp(m,g,n,r,o,s);f.shouldClose&&(d(),f.error?p(f.error):f.tokens?a(f.tokens):p(new Error("No tokens received")))}catch(f){d(),p(f instanceof Error?f:new Error(String(f)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${ec(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}i(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"||m.code==="EACCES"?p(new h(`Port ${e.port} is already in use \u2014 the login callback server cannot start`,{cause:m,hint:St(e.port)})):p(new h(`Login callback server failed: ${m.message}`,{cause:m}))}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}i(Ci,"startCallbackServer");import{mkdirSync as tc}from"fs";import{loadLocalCertificates as nc}from"@cognite/app-sdk/https";var rc={loadLocalCertificates:nc,mkdirSync:tc,logger:console};async function ki(e,t=rc){t.mkdirSync(e,{recursive:!0});let{cert:n,key:r,source:o}=await t.loadLocalCertificates({certDir:e}).catch(s=>{throw new h(`Failed to load SSL certificates from ${e}`,{cause:s,hint:"Run `npx @cognite/cli apps setup-https` to create trusted local certificates."})});return o==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:n,key:r}}i(ki,"getOrCreateCertificates");var uc="openid profile email",gc={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:oc.join(ic.homedir(),".cdf-login")},fc={open:sc,getOrCreateCertificates:ki,startCallbackServer:Ci,isPortFree:vi,discovery:cc,buildAuthorizationUrl:ac,randomPKCECodeVerifier:dc,calculatePKCECodeChallenge:pc,randomState:mc,logger:console,telemetry:ht()};async function Ei(e,t=gc,n){return n===void 0?xi(e,t,fc):xi(e,t,n)}i(Ei,"login");async function yc(e,t){let{discovery:n}=e;try{return await n(new URL(t.authority),t.clientId,void 0,lc())}catch(r){throw new h(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}i(yc,"fetchOpenIdConfig");async function xi(e,t,n){let{isPortFree:r,telemetry:o,logger:s,randomPKCECodeVerifier:a,calculatePKCECodeChallenge:p,randomState:c,buildAuthorizationUrl:l,getOrCreateCertificates:d,open:m,startCallbackServer:g}=n;if(!await r(t.port))throw o?.track("Flows.CLI.PortInUse",{port:t.port}),new h(`Port ${t.port} is already in use \u2014 the login callback server cannot start`,{hint:St(t.port)});s.log(`\u{1F510} Starting CDF login flow...
|
|
112
|
+
`),s.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let u=await yc(n,t),y=a(),S=await p(y),C=c(),v={redirect_uri:t.redirectUri,scope:t.scope??uc,code_challenge:S,code_challenge_method:"S256",state:C};e&&(v.organization_hint=e);let w=l(u,v).toString(),b=await d(t.certDir);e&&s.log(`\u{1F3E2} Organization: ${e}`),s.log(`\u{1F680} Opening browser for authentication...
|
|
113
|
+
`);try{await m(w)}catch(V){let A=V instanceof Error?V.message:String(V);s.error("\u274C Failed to open browser automatically."),s.error(` Reason: ${A}`),s.error(`Please open this URL manually:
|
|
114
|
+
`),s.error(w),s.error("")}return g(t,b,u,y,C)}i(xi,"loginImpl");async function M(e,t,n={}){let{login:r=Ei,getSdk:o=Fe,createClient:s=i(a=>new hc(a),"createClient")}=n;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await r(a),c=x.from(p.access_token),l=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:i(async()=>c.expose(),"getToken")});return await l.authenticate(),l}return o(e,t.appId)}i(M,"getClientForDeployment");async function vt(e,t,n){let r=await M(e,{interactive:t.interactive,appId:n,orgHint:t.org});return new D(r)}i(vt,"buildAppHostingClient");import{existsSync as wc}from"fs";import{resolve as Sc}from"path";import{config as vc}from"dotenv";function P(e,t={existsSync:wc,config:vc}){let n=Sc(e,".env");t.existsSync(n)&&(console.log(`Loading environment variables from ${n}`),t.config({path:n}))}i(P,"loadEnvFile");import{readFileSync as Cc,writeFileSync as bi,renameSync as kc,existsSync as xc,mkdirSync as Ec}from"fs";import{resolve as Be}from"path";import{array as xn,object as Ai,optional as Pi,parse as bc,record as Pc,safeParse as Ac,string as ee,unknown as Dc}from"valibot";var Ic=Ai({space:ee(),externalId:ee(),version:ee()}),$c=Ai({name:ee(),dataModelSpace:ee(),dataModelExternalId:ee(),dataModelVersion:ee(),views:Pi(xn(Ic)),instanceSpaces:Pi(xn(ee()))}),Rc=Pc(ee(),Dc());function En(e){let t;try{t=Cc(e,"utf-8")}catch(r){throw r.code==="ENOENT"?new Error(`app.json not found at "${e}". Run this command from the root of a Cognite app.`):r}let n;try{n=JSON.parse(t)}catch(r){throw new Error(`app.json at "${e}" is not valid JSON: ${r.message}`)}return bc(Rc,n)}i(En,"readAppJson");function bn(e,t){let n=Be(e,"app.json"),o=En(n)["sdk-gen-alpha-version"];if(typeof o!="string"||o.length===0)throw new Error(`This app is not enabled for the SDK generator alpha.
|
|
115
|
+
app.json is missing "sdk-gen-alpha-version". The SDK generator is an alpha feature \u2014 scaffold a new app with the alpha CLI to use it.`);if(o!==t)throw new Error(`SDK generator alpha version mismatch.
|
|
116
|
+
app.json requires @cognite/cli@${o}, but you are running @cognite/cli@${t}.
|
|
117
|
+
Run the matching alpha instead: npx @cognite/cli@${o} apps sdk generate`)}i(bn,"assertSdkGenAlpha");function He(e){let t=Be(e,"app.json"),r=En(t).generatedSdks;if(r===void 0)return[];let o=Ac(xn($c),r);if(!o.success){let s=o.issues[0],a=s.path?.map(p=>p.key).join(".")??"";throw new Error(`app.json: generatedSdks${a?`.${a}`:""}: ${s.message}`)}return o.output}i(He,"readGeneratedSdks");function Di(e,t,n={}){ye(t.name);let r=Be(e,"app.json"),o=En(r),s=He(e),a=s.find(m=>m.name===t.name),p;if(a){if(!n.replace)throw new Error(`An SDK named "${t.name}" already exists in app.json. Pass { replace: true } to overwrite, or pick a different name.`);p=s.map(m=>m.name===t.name?t:m)}else p=[...s,t];let c=Be(e,".dune","sdk-configs");xc(c)||Ec(c,{recursive:!0});let l=Be(c,`${t.name}.json`);bi(l,JSON.stringify(t,null,2)+`
|
|
118
|
+
`),o.generatedSdks=p;let d=`${r}.tmp`;bi(d,JSON.stringify(o,null,2)+`
|
|
119
|
+
`),kc(d,r)}i(Di,"writeGeneratedSdkEntry");var In=class In extends Error{constructor(){super("Wizard cancelled by user")}};i(In,"WizardCancelled");var qe=In,Ge=Symbol("BACK"),_c=new RegExp("\x1B\\[[0-9;]*m","g");async function Ri(e,t){P(e);let n=k(e),r=n.deployments[0],o=await M(r,{interactive:t.interactive??!1,appId:n.externalId,orgHint:t.orgHint});if(t.interactive&&console.log(`\u2705 Authenticated
|
|
120
|
+
`),!(o instanceof Nc))throw new Error("[dune] getClientForDeployment did not return a CogniteClient");return o}i(Ri,"resolveClient");async function An(e,t,n){let r=t.map((p,c)=>({name:n(p,c),value:c})),o={type:"select",name:"answer",message:e,choices:r.map(p=>p.name)},{answer:s}=await Dn.prompt(o),a=r.findIndex(p=>p.name===s);return t[a]}i(An,"pick");async function Uc(e,t,n){let r=t.map((l,d)=>n(l,d)),o=new Map(r.map((l,d)=>[l,d])),s={type:"autocomplete",name:"answer",message:e,limit:12,choices:r},{answer:a}=await Dn.prompt(s);if(o.has(a))return t[o.get(a)];let p=i(l=>String(l).replace(_c,"").trim(),"clean"),c=p(a);for(let[l,d]of o)if(p(l)===c)return t[d];for(let[l,d]of o)if(p(l).includes(c)||c.includes(p(l)))return t[d];throw new Error(`Could not match selection "${a}" to any item`)}i(Uc,"searchPick");async function Mc(e,t=""){let n={type:"input",name:"answer",message:e,initial:t},{answer:r}=await Dn.prompt(n);return r}i(Mc,"ask");async function Vc(e,t={}){bn(e,"1.8.0-alpha.sdk-gen");let n=process.cwd();process.chdir(e);try{let r=await Ri(e,t),o={chosenModel:null,sdkName:null,replaceExisting:!1},s=[async()=>{console.log(`
|
|
121
|
+
\u{1F510} Fetching data models...`);let c=(await r.dataModels.list({limit:1e3,includeGlobal:!0})).items.map(l=>({space:l.space,externalId:l.externalId,version:l.version,name:l.name}));if(c.sort((l,d)=>`${l.space}/${l.externalId}`.localeCompare(`${d.space}/${d.externalId}`)),c.length===0)throw new Error("No data models found.");return console.log(`\u{1F50D} Found ${c.length} model(s). Type to search.
|
|
122
|
+
`),o.chosenModel=await Uc("\u{1F4E6} Select a data model:",c,l=>`${l.space} \u2192 ${l.externalId} / ${l.version}${l.name?` \u2014 ${l.name}`:""}`),!0},async()=>{let p=o.chosenModel.externalId.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9-_]/g,"-").toLowerCase(),c=await Mc(`
|
|
123
|
+
SDK name (folder under src/generated_sdks/, "back" to go back):`,p);if(c.toLowerCase()==="back")return Ge;try{ye(c)}catch(m){return console.log(`
|
|
124
|
+
\u26A0\uFE0F ${m instanceof Error?m.message:String(m)}
|
|
125
|
+
Please enter a valid name.
|
|
126
|
+
`),Ge}let d=He(e).find(m=>m.name===c);if(o.replaceExisting=!1,d){console.log(`
|
|
127
|
+
\u26A0\uFE0F An SDK named "${c}" already exists in app.json:`),console.log(` ${d.dataModelSpace} / ${d.dataModelExternalId} @ ${d.dataModelVersion}`);let m=await An("What would you like to do?",["Replace existing entry","Pick a different name","Cancel"],g=>g);if(m==="Cancel")throw new qe;if(m==="Pick a different name")return Ge;o.replaceExisting=!0}return o.sdkName=c,!0},async()=>{let p={name:o.sdkName,dataModelSpace:o.chosenModel.space,dataModelExternalId:o.chosenModel.externalId,dataModelVersion:String(o.chosenModel.version)};console.log(`
|
|
128
|
+
\u2500\u2500 Summary \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`),console.log(` Space: ${p.dataModelSpace}`),console.log(` Model: ${p.dataModelExternalId} @ ${p.dataModelVersion}`),console.log(" Views: all"),console.log(` SDK name: ${o.sdkName}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let c=await An("Write to app.json?",["Yes","Back","Cancel"],l=>l);if(c==="Back")return Ge;if(c==="Cancel")throw new qe;return Di(e,p,{replace:o.replaceExisting}),console.log(`
|
|
129
|
+
\u2705 Added "${p.name}" to app.json`),console.log(` Config saved to .dune/sdk-configs/${p.name}.json`),console.log(""),!0}],a=0;for(;a<s.length;)await s[a]()===Ge?(a=Math.max(0,a-1),console.log("")):a++;return{sdkName:o.sdkName,client:r}}finally{process.chdir(n)}}i(Vc,"runWizard");async function Ii(e,t,n,r={}){let o=n??process.cwd();bn(o,"1.8.0-alpha.sdk-gen");let s=He(o).find(m=>m.name===e);if(!s)throw new Error(`No SDK named "${e}" in generatedSdks`);let a=t??await Ri(o,r),p=Pn(o,"src/generated_sdks");console.log(`
|
|
130
|
+
\u2699\uFE0F Generating "${s.name}" (${s.dataModelSpace}/${s.dataModelExternalId}@${s.dataModelVersion})...`);let{sdkDir:c,viewCount:l}=await ni({name:s.name,space:s.dataModelSpace,dataModelExternalId:s.dataModelExternalId,dataModelVersion:s.dataModelVersion},a,p);console.log(`\u2705 Generated SDK for ${l} view(s) \u2192 ${c}`);let d=Pn(o,"package.json");if(Tc(d)){let m=JSON.parse(Fc(d,"utf-8"));if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`package.json at "${d}" is not a JSON object`);let g=m,f=typeof g.dependencies=="object"&&g.dependencies!==null?{...g.dependencies}:{},u=[],y=r.linkLocal?`file:${Pn(Lc(import.meta.url),"../../..")}`:"^1.8.0-alpha.sdk-gen";(!f["@cognite/cli"]||r.linkLocal)&&(f["@cognite/cli"]=y,u.push("@cognite/cli")),u.length>0&&(g.dependencies=f,Oc(d,JSON.stringify(g,null,2)+`
|
|
131
|
+
`,"utf-8"),console.log(`
|
|
132
|
+
\u{1F4E6} Updated package.json: ${u.join(", ")} (run npm install)`))}}i(Ii,"generate");function $i(e){return{interactive:e.interactive,orgHint:e.org,linkLocal:e.linkLocal}}i($i,"sdkCommandOptions");function Ti(e){e.command("sdk").summary("Add or regenerate typed GraphQL SDKs from CDF data models").description(`Add or regenerate typed GraphQL SDKs from CDF data models.
|
|
133
|
+
Run with --interactive for the guided wizard (pick a data model, update app.json, generate types).`).option("--interactive","Run the guided wizard (pick data model, update app.json, generate types)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").passThroughOptions().addHelpText("after",`
|
|
134
|
+
Examples:
|
|
135
|
+
npx @cognite/cli apps sdk --interactive Guided setup: pick a data model, add to app.json, generate types
|
|
136
|
+
npx @cognite/cli apps sdk generate Regenerate types for SDKs already in app.json
|
|
137
|
+
npx @cognite/cli apps sdk generate my-sdk Regenerate a specific SDK by name
|
|
138
|
+
|
|
139
|
+
Without --interactive, this command only shows help. Use --interactive for the guided wizard.
|
|
140
|
+
Non-interactive auth for generate uses the same env vars as apps deploy (COGNITE_TOKEN or deployment credentials).`).action(async function(n){if(!n.interactive){this.outputHelp();return}let r=process.cwd(),o=$i(n);try{let{sdkName:s,client:a}=await Vc(r,o);await Ii(s,a,r,o)}catch(s){if(s instanceof qe){console.log(`
|
|
141
|
+
Cancelled.
|
|
142
|
+
`),process.exitCode=0;return}throw s}}).command("generate [name]").description("Regenerate TypeScript types for an existing SDK from app.json").option("--interactive","Authenticate via browser login (same as apps deploy --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("--link-local","Point @cognite/cli at the local monorepo package (default: use published version from npm)").action(async(n,r)=>{let o=process.cwd(),s=$i(r),a=He(o);if(a.length===0)throw new Error('No generatedSdks entries found in app.json. Run "cognite apps sdk --interactive" first.');let p=n??(a.length===1?a[0].name:(await An("Which SDK to regenerate?",a,c=>c.name)).name);await Ii(p,void 0,o,s)})}i(Ti,"registerSdkCommand");import{existsSync as fl,readFileSync as yl}from"fs";import{join as hl,resolve as Rt}from"path";import{verifyBundle as wl}from"@cognite/app-sdk/codesigning";import{decodeProtectedHeader as Sl}from"jose";import Tn from"enquirer";import{email as jc,pipe as Kc,safeParse as Bc,string as Hc}from"valibot";var Gc=Kc(Hc(),jc());function Oe(e,t="email"){let n=e.trim();if(!n)throw new Error(`${t} is required`);if(!Bc(Gc,n).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return n}i(Oe,"parseEmail");function Le(e,t="--expires"){let n=Number(e);if(!Number.isInteger(n)||n<1||n>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return n}i(Le,"parseExpiryMonths");import{execFileSync as kt}from"child_process";import{execFileSync as qc}from"child_process";function Ct(e={}){let{execFileSync:t=qc}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}i(Ct,"isGitInstalled");function Z(e={}){if(!Ct(e))throw new h("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}i(Z,"throwIfGitMissing");function xt(e,t={}){let{execFileSync:n=kt}=t;try{return n("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}i(xt,"isInsideGitRepo");function Fi(e,t={}){let{execFileSync:n=kt}=t;n("git",["-C",e,"init"],{stdio:"pipe"}),n("git",["-C",e,"add","."],{stdio:"pipe"}),n("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}i(Fi,"gitInitAndCommit");function Oi(e={}){let{execFileSync:t=kt}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(Oi,"gitUserName");function Li(e={}){let{execFileSync:t=kt}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}i(Li,"gitUserEmail");var Et=3,Ni="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",_i=`Key expiry in months (${1}-${12})`,Ui="Email address for the registry entry",Mi=`Passphrase for the encrypted private key (min ${15} chars)`,Vi="Confirm passphrase",ji=i(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),Ki=i(e=>`Passphrases do not match (attempt ${e}/${Et}).
|
|
143
|
+
`,"passphraseMismatchMsg"),Bi=`Passphrase confirmation failed after ${Et} attempts`,Hi=i(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),Gi="How would you like to submit your key registration?",qi="Open in browser",Qi="Copy link to clipboard";async function bt(e){return Tn.prompt(e)}i(bt,"defaultPrompt");function Fn(e){return t=>{try{return e(t),!0}catch(n){return n instanceof Error?n.message:"Invalid"}}}i(Fn,"parserAsValidator");var zc=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function xe(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(!zc.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}i(xe,"parseKid");async function zi(e={}){let{prompt:t=bt}=e,{kid:n}=await t({type:"input",name:"kid",message:Ni,validate:Fn(xe)});return xe(n)}i(zi,"promptKid");async function Ji(e={}){let{prompt:t=i(r=>Tn.prompt(r),"prompt")}=e,{action:n}=await t({type:"select",name:"action",message:Gi,choices:[{name:"browser",message:qi},{name:"clipboard",message:Qi}]});if(n!=="browser"&&n!=="clipboard")throw new Error(`Unexpected Zendesk action: ${n}`);return n}i(Ji,"promptZendeskAction");async function Yi(e={}){let{prompt:t=bt}=e,{months:n}=await t({type:"input",name:"months",message:_i,initial:String(6),validate:Fn(r=>Le(r,"expiry"))});return Le(n,"expiry")}i(Yi,"promptExpiryMonths");async function Wi(e={}){let{prompt:t=bt,gitUserEmail:n=Li}=e,{email:r}=await t({type:"input",name:"email",message:Ui,initial:n(),validate:Fn(o=>Oe(o,"email"))});return Oe(r,"email")}i(Wi,"promptEmail");async function Zi(e={}){let{prompt:t=bt,stderr:n=process.stderr}=e;for(let r=1;r<=Et;r+=1){let{passphrase:o}=await t({type:"password",name:"passphrase",message:Mi,validate:i(a=>a.length>=15?!0:ji(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:Vi});if(o===s)return x.from(o);n.write(Ki(r))}throw new Error(Bi)}i(Zi,"promptPassphrase");async function Xi(e,t={}){let{prompt:n=i(o=>Tn.prompt(o),"prompt")}=t,{confirmed:r}=await n({type:"confirm",name:"confirmed",message:Hi(e),initial:!1});return r}i(Xi,"promptConfirmOverwrite");import{existsSync as ol,readdirSync as sl,readFileSync as al}from"fs";import{join as Ln}from"path";import{execFile as Jc}from"child_process";import{promisify as Yc}from"util";var eo="cognite-flows",Wc=Yc(Jc),to=i((e,t)=>Wc(e,t),"defaultExecFile"),Zc=-25300,Xc=Zc&255;function el(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Xc)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}i(el,"isKeychainNotFoundError");async function no(e,t,n={}){let r=t.expose();if(!U("macos",n))throw new Error("Keychain storage is only supported on macOS");let{execFile:o=to}=n;await o("security",["add-generic-password","-a",e,"-s",eo,"-w",Buffer.from(r,"utf-8").toString("base64"),"-U"])}i(no,"storeKeyInKeychain");async function Pt(e,t={}){if(!U("macos",t))return null;let{execFile:n=to}=t;try{let{stdout:r}=await n("security",["find-generic-password","-a",e,"-s",eo,"-w"]);return x.from(Buffer.from(r.trim(),"base64").toString("utf-8"))}catch(r){if(el(r))return null;throw r}}i(Pt,"readKeyFromKeychain");var io="cognite-cli-signing",tl="The native @napi-rs/keyring binary failed to load for this platform. Reinstall the CLI, or regenerate the key with `--output <path>` to use passphrase-encrypted file storage instead.",nl="Multiple Windows Credential Manager entries match this kid. Open Credential Manager (Control Panel \u2192 User Accounts \u2192 Credential Manager \u2192 Windows Credentials) and remove the duplicates.",ro="Windows Credential Manager failed unexpectedly. Regenerate the key with `--output <path>` to fall back to passphrase-encrypted file storage.";function rl(e){if(!(e instanceof Error))return ro;let t=e.message.toLowerCase();return t.includes("cannot find module")||t.includes("module_not_found")||t.includes("failed to load native binding")?tl:t.includes("ambiguous")?nl:ro}i(rl,"hintFor");function oo(e,t,n){return new h(`Failed to ${e} signing key for kid "${t}" in Windows Credential Manager`,{cause:n,hint:rl(n),shouldReport:!1})}i(oo,"wrapKeyringError");async function so(e,t){let{Entry:n}=await import("@napi-rs/keyring"),r=new n(e,t);return{setPassword:i(o=>r.setPassword(o),"setPassword"),getPassword:i(()=>r.getPassword(),"getPassword"),deleteCredential:i(()=>r.deleteCredential(),"deleteCredential")}}i(so,"defaultCreateEntry");async function ao(e,t,n={}){let{createEntry:r=so}=n,o=Buffer.from(t.expose(),"utf-8").toString("base64");try{(await r(io,e)).setPassword(o)}catch(s){throw oo("store",e,s)}}i(ao,"storeSigningKey");async function At(e,t={}){let{createEntry:n=so}=t;try{let o=(await n(io,e)).getPassword();return o===null?null:x.from(Buffer.from(o,"base64").toString("utf-8"))}catch(r){throw oo("read",e,r)}}i(At,"readSigningKey");import{homedir as il}from"os";import{join as On}from"path";function R(e={}){let{env:t=process.env,homedir:n=il}=e,r=t.COGNITE_CLI_HOME?.trim()||On(n(),".cognite-cli");return{home:r,keysDir:On(r,"keys"),sessionFile:On(r,"session.json")}}i(R,"getConfig");var pe=".pub.pem",Nn=".key.jwe",_n=".meta.json";function Dt(e){switch(e.kind){case"keychain":return"OS credential store";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}i(Dt,"formatLocalKeySource");function pl(e){return{existsSync:e.existsSync??ol,readdirSync:e.readdirSync??sl,readFileSync:e.readFileSync??((t,n)=>al(t,n)),isOS:e.isOS??(t=>U(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Pt(t)),readSigningKey:e.readSigningKey??(t=>At(t))}}i(pl,"resolveDeps");function cl(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}i(cl,"readEmailFromMeta");function ll(e,t){return t.existsSync(e)?t.readdirSync(e).filter(n=>n.endsWith(pe)):[]}i(ll,"publicKeyEntries");function dl(e){return e.slice(0,-pe.length)}i(dl,"kidFromPublicKeyFilename");async function ml(e,t,n){if(n.isOS("macos")&&await n.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};if(n.isOS("windows")&&await n.readSigningKey(e).catch(()=>null)!==null)return{kind:"keychain"};let r=Ln(t,`${e}${Nn}`);return n.existsSync(r)?{kind:"encrypted-file",path:r}:{kind:"public-only"}}i(ml,"resolveSource");async function It(e=R().keysDir,t={}){let n=pl(t),r=new Set,o=ll(e,n).flatMap(s=>{let a=dl(s);return!a||r.has(a)?[]:(r.add(a),[{kid:a,entry:s}])});return Promise.all(o.map(async({kid:s,entry:a})=>{let p=await ml(s,e,n),c=Ln(e,`${s}${_n}`),l;try{l=cl(n.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:Ln(e,a),email:l}}))}i(It,"discoverLocalKeys");import{createReadStream as ul}from"fs";function $t(e){let t=ul(e);return new ReadableStream({start(n){t.on("data",r=>{let o=typeof r=="string"?Buffer.from(r):r;n.enqueue(new Uint8Array(o))}),t.on("end",()=>n.close()),t.on("error",r=>n.error(r))},cancel(){t.destroy()}})}i($t,"createWebStreamFromFile");import gl from"path";var po=".cognite-bundles";function co(e,t){return`${e}-${t}.zip`}i(co,"bundleFileName");function q(e,t,n){return gl.join(e,po,co(t,n))}i(q,"bundlePath");var lo=[".dev.sig",".cert.sig",".sig"];function vl(e){return{existsSync:e.existsSync??fl,readFileSync:e.readFileSync??((t,n)=>yl(t,n)),createBundleStream:e.createBundleStream??$t,verifyBundle:e.verifyBundle??wl,loadAppConfig:e.loadAppConfig??k,defaultKeyDir:e.defaultKeyDir??(()=>R().keysDir)}}i(vl,"resolveDeps");function Cl(e,t){return lo.map(n=>`${e}${n}`).find(n=>t(n))}i(Cl,"findSiblingSignature");function kl(e){let t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}i(kl,"isCompactJws");function xl(e){try{let t=Sl(e);return typeof t.kid=="string"?t.kid:void 0}catch{return}}i(xl,"readKidFromToken");function El(e,t,n){let{existsSync:r,readFileSync:o}=n;try{xe(e)}catch(a){throw new h(a instanceof Error?a.message:String(a),{shouldReport:!1})}if(!r(t))throw new h(`Key directory not found: ${t}`,{shouldReport:!1});let s=hl(t,`${e}${pe}`);if(!r(s))throw new h(`No public key found for kid "${e}" in ${t}`,{shouldReport:!1});try{return o(s,"utf-8")}catch(a){throw new h(`Failed to read public key file: ${s}`,{cause:a,shouldReport:!1})}}i(El,"resolvePublicKeyForKid");function bl(e,t){let{payload:n,kid:r}=e;if(console.log(`Verified ${n.appId}@${n.version}`),console.log(` kid: ${r}`),console.log(` hash: ${n.bundleSha256}`),n.scopes&&n.scopes.length>0){let o=n.scopes.map(s=>`${s.org}/${s.project}`).join(", ");console.log(` scopes: ${o}`)}t&&console.log(JSON.stringify(n,null,2))}i(bl,"printResult");async function mo(e,t,n={},r=process.cwd()){let{existsSync:o,readFileSync:s,loadAppConfig:a,createBundleStream:p,verifyBundle:c,defaultKeyDir:l}=vl(n),d;if(e)d=Rt(r,e);else{let u;try{u=a(r)}catch(y){let S=y instanceof Error?y.message:String(y);throw new h(S,{cause:y,hint:"Run this command from a Cognite app directory (one with app.json), or pass [bundle] explicitly.",shouldReport:!1})}d=q(r,u.externalId,u.versionTag)}if(!o(d)){let u=e?void 0:"Default derived from app.json \u2014 pass [bundle] explicitly to override.";throw new h(`Bundle not found: ${d}`,{hint:u,shouldReport:!1})}let m=t.sig?Rt(r,t.sig):Cl(d,o);if(!m)throw new h("No signature file found.",{hint:`Pass --sig <path> or place one of ${lo.map(u=>`${d}${u}`).join(", ")} next to the bundle.`,shouldReport:!1});if(!o(m))throw new h(`Signature file not found: ${m}`,{shouldReport:!1});let g;try{g=s(m,"utf-8").trim()}catch(u){throw new h(`Failed to read signature file: ${m}`,{cause:u,shouldReport:!1})}if(!kl(g))throw new h(`Malformed JWS in ${m}`,{hint:"Expected a compact JWS (header.payload.signature \u2014 three base64url segments).",shouldReport:!1});let f;if(t.key){let u=Rt(r,t.key);if(!o(u))throw new h(`Public key not found: ${u}`,{shouldReport:!1});try{f=s(u,"utf-8")}catch(y){throw new h(`Failed to read public key file: ${u}`,{cause:y,shouldReport:!1})}}else{let u=t.keyDir?Rt(r,t.keyDir):l(),y=xl(g);if(!y)throw new h("Token header has no kid.",{hint:"Pass --key <path> to a public key PEM.",shouldReport:!1});f=El(y,u,{existsSync:o,readFileSync:s})}try{let u=await c({token:g,publicKeyPem:f,bundleStream:p(d)});bl(u,t.verbose??!1)}catch(u){let y=u instanceof Error?u.message:String(u);throw new h(`Bundle rejected: ${y}`,{shouldReport:!1})}}i(mo,"handleVerify");function uo(e,t={}){return e.command("verify [bundle]").description("Verify a signed app bundle locally (default: derived from app.json)").option("-s, --sig <path>","Path to the signature file (default: sibling .dev.sig / .cert.sig / .sig)").option("--key <path>","Path to a public key PEM file").option("--key-dir <path>","Directory of <kid>.pub.pem files \u2014 kid is read from the token header (default: $COGNITE_CLI_HOME/keys)").option("-v, --verbose","Print the full decoded payload after verification").addHelpText("after",`
|
|
144
|
+
Bundles are stored in .cognite-bundles/<externalId>-<versionTag>.zip by default.
|
|
145
|
+
|
|
146
|
+
Examples:
|
|
147
|
+
cognite apps verify Verify default bundle (path from app.json)
|
|
148
|
+
cognite apps verify .cognite-bundles/my-app-1.0.0.zip Verify a specific bundle
|
|
149
|
+
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --sig my-app-1.0.0.zip.dev.sig Verify with explicit signature
|
|
150
|
+
cognite apps verify .cognite-bundles/my-app-1.0.0.zip --key /path/to/pub.pem Verify with explicit public key`).action((n,r)=>mo(n,r,t))}i(uo,"registerVerifyCommand");import go from"enquirer";var fo="Enter custom target...";function yo(e,t){let n=t.map((r,o)=>` ${o}: ${r.org}/${r.project}`).join(`
|
|
35
151
|
`);throw new Error(`Deployment "${e}" not found. Available deployments:
|
|
36
|
-
${
|
|
152
|
+
${n}`)}i(yo,"deploymentNotFoundError");function I(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;yo(t,e)}let n=e.find(r=>r.project===t||`${r.org}/${r.project}`===t);if(n)return n;yo(t,e)}i(I,"findDeployment");function T(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}i(T,"getMissingCredentials");async function F(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return I(e.deployments,t.deployment);let n=[...e.deployments.map(s=>`${s.org}/${s.project}`),fo],{selected:r}=await go.prompt({type:"select",name:"selected",message:"Select deployment target",choices:n});if(r!==fo){let s=e.deployments.find(a=>`${a.org}/${a.project}`===r);if(s)return s;throw new Error(`Deployment "${r}" could not be resolved from app.json.`)}let o=await go.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:i(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:o.org||"",project:o.project,baseUrl:o.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}i(F,"resolveDeployment");function O(e){e.infra!=="appsApi"&&(console.error(`
|
|
37
153
|
\u26A0\uFE0F Legacy infrastructure is no longer supported.
|
|
38
154
|
|
|
39
155
|
Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
|
|
40
156
|
the old CDF Application Registry. This deploy path has been removed.
|
|
41
157
|
|
|
42
158
|
To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
|
|
43
|
-
`),process.exit(1))}
|
|
159
|
+
`),process.exit(1))}i(O,"assertAppHostingInfra");async function Pl(e){let t=process.cwd();P(t);let n=k(t);O(n);let r=e.interactive?await F(n,e):I(n.deployments,e.deployment);if(!e.interactive){let d=T(r);if(d.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let o=await M(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new D(o),{externalId:a,versionTag:p}=n,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof G?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}i(Pl,"handleActivate");function ho(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
44
160
|
Examples:
|
|
45
161
|
npx @cognite/cli apps activate . Activate using env-var auth
|
|
46
|
-
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,
|
|
47
|
-
`),initial:!1};async function
|
|
48
|
-
|
|
162
|
+
npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,n)=>Pl(n))}i(ho,"registerActivateCommand");import{basename as Fo,dirname as ad,normalize as pd,resolve as Nt}from"path";import{fileURLToPath as cd,pathToFileURL as ld}from"url";import{Logger as dd,runner as md}from"hygen";import{safeParse as Al}from"valibot";function Qe(e,t){return n=>{let r=Al(t,n);return r.success?!0:`${e} ${r.issues[0].message}`}}i(Qe,"toPromptValidator");var wo={name:Qe("App name",cn),displayName:Qe("Display name",pn),baseUrl:Qe("Base URL",ln),org:Qe("Org",dn),project:Qe("Project",mn)};function Dl(e,t){return e?async n=>{let r=t(n);return r===!0?e(n):r}:t}i(Dl,"composeValidators");function Tt(e){return e.map(t=>{if(!(t.name in wo))return t;let n=wo[t.name];return{...t,validate:Dl(t.validate,n)}})}i(Tt,"applySchemaValidators");import{basename as So}from"path";import vo from"enquirer";function Un(e){return e.replace(/[A-Z]/g,(t,n)=>n===0?t.toLowerCase():`-${t.toLowerCase()}`)}i(Un,"kebabCase");var Il={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code, Cursor, or GitHub Copilot. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
|
|
163
|
+
`),initial:!1};async function $l(e,t,n){return e!==void 0?e:t?!!(await n([Il])).useSpecKit:!1}i($l,"resolveSpecKit");function Rl(e){return typeof e=="function"}i(Rl,"isFunctionInitial");function Co(e){return(e??"").trim().replace(/\/+$/,"")||"api"}i(Co,"normalizeCluster");function ko({isCurrentDir:e,dirName:t,onAppName:n,onUseSpecKit:r,presets:o={},specKit:s,prompt:a=vo.prompt.bind(vo)}){return()=>({prompt:i(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(o).filter(E=>E[1]!==void 0)),l=Object.keys(c).length>0,d=e?So(process.cwd()):t?So(t):null,m=l&&d!==null,g=!m&&d?p.map(E=>E.name==="name"?{...E,initial:d}:E):p,f=Tt(g),u=m&&d?{...c,name:d}:c,y=new Set(Object.keys(u)),S=f.filter(E=>!y.has(E.name)),C=S.findIndex(E=>E.name==="baseUrl"),v;if(m){let E=Co(u.cluster),de=i(L=>Rl(L.initial)?L.initial():L.initial,"resolveInitial"),me=i(L=>{if(L.name==="baseUrl")return`https://${E}.cognitedata.com`;let ue=de(L);if(ue===void 0)throw new Error(`Non-interactive mode: --${Un(L.name)} has no default. Pass it as a flag.`);return ue},"deriveValue");v=Object.fromEntries(S.map(L=>[L.name,me(L)]))}else if(C!==-1){let E=S.filter(ge=>ge.name!=="baseUrl"),de=E.length>0?await a(E):{},me=typeof de.cluster=="string"?de.cluster:"",ue=`https://${Co(me||u.cluster)}.cognitedata.com`,Ee=S[C],et=await a([{...Ee,initial:ue}]);v={...de,...et}}else v=S.length>0?await a(S):{};let w={...u,...v},b=typeof w.name=="string"?w.name:"";b&&n(b);let A=await $l(s,!m&&S.length>0,a);return r?.(A),{...w,name:b,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:A}},"prompt")})}i(ko,"createAppPrompter");async function xo(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:`--${Un(s)}`});for(let{key:s,value:a,label:p}of r){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}i(xo,"validatePresets");import{cpSync as bo,existsSync as Po,mkdirSync as Ot,readdirSync as _l,readFileSync as Ul,writeFileSync as Mn}from"fs";import{basename as Ml,dirname as Vn,posix as Vl,resolve as $}from"path";import{fileURLToPath as Ao}from"url";import{copyFileSync as Tl,symlinkSync as Fl}from"fs";import{dirname as Ol,join as Ll}from"path";function Nl(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}i(Nl,"errno");function Eo(e){return e instanceof Error?e.message:String(e)}i(Eo,"messageOf");function Ft({target:e,linkPath:t,label:n,symlink:r=Fl,copyFile:o=Tl}){try{return r(e,t),!0}catch(s){let a=Nl(s);if(a==="EEXIST")return!0;let p=Eo(s);if(a==="EPERM"||a==="EACCES")try{let c=Ll(Ol(t),e);return o(c,t),console.log(`\u2139\uFE0F Wrote ${n} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${n} symlink: ${p} (copy fallback also failed: ${Eo(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${n} symlink:`,p),!1}}i(Ft,"linkOrCopyOrWarn");var jl=$(Vn(Ao(import.meta.url)),"..","..","_vendor","spec-kit"),Kl=$(Vn(Ao(import.meta.url)),"..","..","_cognite-spec-extensions"),Bl=["claude-code","cursor","github-copilot"],Hl={branch_numbering:"sequential"};function Do({appDir:e,vendorDir:t=jl,cogniteExtensionsDir:n=Kl,agents:r=Bl}){let o=$(e,".specify"),s=$(o,"memory"),a=new Set(r),p=`prepare spec-kit install for appDir=${e}`,l=[{srcRoot:t,from:"templates",to:".specify/templates"},{srcRoot:t,from:"scripts/bash",to:".specify/scripts/bash"},{srcRoot:t,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:t,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"commands",to:".claude/commands",agent:"claude-code"},{srcRoot:n,from:"commands",to:".cursor/commands",agent:"cursor"},{srcRoot:n,from:"templates",to:".specify/templates"}].filter(({agent:d})=>!d||a.has(d));try{for(let{srcRoot:m,from:g,to:f}of l){let u=$(e,f);p=`copy ${Ml(m)}/${g} to ${f}`,Ot(Vn(u),{recursive:!0}),bo($(m,g),u,{recursive:!0})}if(a.has("github-copilot")){let m=$(e,".github","agents"),g=$(e,".github","prompts");p="create .github/agents and .github/prompts dirs",Ot(m,{recursive:!0}),Ot(g,{recursive:!0});for(let f of[$(t,"commands"),$(n,"commands")])if(Po(f))for(let u of _l(f)){if(!u.endsWith(".md"))continue;let y=u.slice(0,-3);p=`copy ${u} to .github/agents/${y}.agent.md`,Mn($(m,`${y}.agent.md`),Ul($(f,u))),p=`write .github/prompts/${y}.prompt.md`,Mn($(g,`${y}.prompt.md`),`---
|
|
164
|
+
agent: ${y}
|
|
165
|
+
---
|
|
166
|
+
`)}}let d=$(o,"extensions.yml");Po(d)||(p="write .specify/extensions.yml",bo($(n,"extensions.yml"),d)),p=`write init-options.json under specifyDir=${o}`,Mn($(o,"init-options.json"),`${JSON.stringify(Hl,null,2)}
|
|
167
|
+
`),p=`link .specify/memory/constitution.md in specifyDir=${o}`,Ot(s,{recursive:!0}),Ft({target:Vl.join("..","..","AGENTS.md"),linkPath:$(s,"constitution.md"),label:".specify/memory/constitution.md"})}catch(d){let m=d instanceof Error?d.message:String(d);throw new Error(`installSpecKit failed while ${p} (appDir=${e}, vendorDir=${t}): ${m}`,{cause:d})}}i(Do,"installSpecKit");import{execFileSync as Lt}from"child_process";import{mkdtempSync as Gl,readdirSync as ql,rmSync as Ql}from"fs";import{createRequire as zl}from"module";import{tmpdir as Jl}from"os";import{join as Yl,resolve as Io}from"path";import{InvalidArgumentError as Wl}from"commander";import Zl from"enquirer";var $o="cognitedata/builder-skills",jn=["claude-code","cursor","github-copilot","opencode","codex"],Xl=zl(import.meta.url).resolve("skills/bin/cli.mjs");function Kn(e,t={}){try{Lt(process.execPath,[Xl,...e],{stdio:"inherit",cwd:process.cwd(),...t,env:{...process.env,...t.env,DISABLE_TELEMETRY:"1"}})}catch(n){throw Z(),new h(`Skills CLI failed (${e.join(" ")})`,{cause:n,hint:"Check your internet connection and try again."})}}i(Kn,"execSkillsCli");function ed(){return jn.map(e=>["add",$o,"-a",e,"--skill","*","-y"])}i(ed,"pullAllArgsPerAgent");var td=1e4;async function Ro(e,t={}){let n=t.exec??Kn;Z();let r=t.timeout??td,o=t.readdir??(p=>ql(p));for(let p of ed())try{n(p,{cwd:e,timeout:r,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[Io(e,".claude","skills"),Io(e,".agents","skills")])try{o(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}i(Ro,"pullAllSkillsInto");function nd(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Wl("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}i(nd,"validateSource");function rd(e){let t=Gl(Yl(Jl(),"skills-"));try{try{Lt("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch(r){throw Z(),new h(`Failed to clone skills repository "${e}".`,{hint:"Check your internet connection and try again.",shouldReport:!1,cause:r})}let n;try{n=Lt("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{n=Lt("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return n.toString().trim().split(/\r?\n/).filter(r=>!!r&&!r.startsWith("."))}finally{Ql(t,{recursive:!0,force:!0})}}i(rd,"listRemoteSkills");async function id(e,t={}){let n=i(p=>Zl.prompt(p),"defaultPrompt"),{listSkills:r=rd,prompt:o=n}=t,s=r(e),{selected:a}=await o({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}i(id,"pickSkillsInteractive");function od(e,t,n){let r=["add",e.source,"-a",t];return e.skill?r.push("--skill",e.skill):n&&n.length>0?r.push("--skill",...n,"-y"):r.push("--skill","*","-y"),e.global&&r.push("--global"),r}i(od,"buildPullArgs");async function sd(e){Z(),console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await id(e.source)}catch(r){if(r instanceof h)throw r;let o=r instanceof Error?r.message:String(r);console.error(`Failed to resolve skills interactively: ${o}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let n=!1;for(let r of jn)try{Kn(od(e,r,t))}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`\u26A0\uFE0F Could not pull skills for ${r}: ${s}`),n=!0}n?(console.log(`
|
|
49
168
|
Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
|
|
50
|
-
Skills pulled successfully`)}
|
|
51
|
-
Supports: ${
|
|
169
|
+
Skills pulled successfully`)}i(sd,"handlePull");function To(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
|
|
170
|
+
Supports: ${jn.join(", ")}`).addHelpText("after",`
|
|
52
171
|
Examples:
|
|
53
172
|
npx @cognite/cli apps skills pull Pull all skills
|
|
54
173
|
npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
|
|
55
|
-
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",
|
|
56
|
-
npm run dev`,
|
|
174
|
+
npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",nd,$o).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(sd),t.command("list").description("List installed skills").action(()=>{Kn(["list"])}),t}i(To,"registerSkillsCommand");var Oo=Nt(ad(cd(import.meta.url)),"..","..","_templates");async function ud(){let e=Nt(Oo,"app","new","prompt.js");return(await import(ld(e).href)).default}i(ud,"loadPromptDefs");function gd(e,t){return!e||t?null:pd(e)}i(gd,"resolveDirName");function fd(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:Nt(process.cwd(),r),display:r}}i(fd,"resolveAppLocation");function yd(e,t,n){let r=` npm install
|
|
175
|
+
npm run dev`,o="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=n?`
|
|
57
176
|
To start spec-driven development:
|
|
58
|
-
Run /speckit.specify in Claude Code or
|
|
177
|
+
Run /speckit.specify in Claude Code, Cursor, or GitHub Copilot and describe your app.
|
|
59
178
|
`:"",p=` # Or fully non-interactive (deploys first target from app.json):
|
|
60
179
|
npx @cognite/cli apps deploy`;if(e){console.log(`
|
|
61
180
|
\u2705 App created successfully in current directory!
|
|
62
181
|
|
|
63
182
|
Next steps:
|
|
64
|
-
${
|
|
183
|
+
${r}
|
|
65
184
|
${a}
|
|
66
|
-
${
|
|
185
|
+
${o}
|
|
67
186
|
${s}
|
|
68
187
|
${p}
|
|
69
188
|
`);return}console.log(`
|
|
@@ -73,13 +192,13 @@ To open in Cursor:
|
|
|
73
192
|
cursor "${t}"
|
|
74
193
|
Or:
|
|
75
194
|
cd "${t}"
|
|
76
|
-
${
|
|
195
|
+
${r}
|
|
77
196
|
${a}
|
|
78
|
-
${
|
|
197
|
+
${o}
|
|
79
198
|
cd "${t}"
|
|
80
199
|
${s}
|
|
81
200
|
${p}
|
|
82
|
-
`)}
|
|
201
|
+
`)}i(yd,"printSuccessMessage");async function hd(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await Ro(e)}catch(t){let n=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",n)}}i(hd,"pullSkillsInto");function wd(e,t={}){let{isGitInstalled:n=Ct,isInsideGitRepo:r=xt,gitInitAndCommit:o=Fi}=t;if(!n()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!r(e)){console.log("Initialising git repository...");try{o(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}i(wd,"maybeInitGit");async function Sd(e,t){let n=e==="."||e==="./",r=gd(e,n),o=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await ud(),c=Tt(p),l=n?Fo(process.cwd()):r?Fo(r):null;await xo(c,a,l);let d=ko({isCurrentDir:n,dirName:r,onAppName:i(g=>{o=g},"onAppName"),onUseSpecKit:i(g=>{s=g},"onUseSpecKit"),presets:a,specKit:t.specKit});await md(["app","new","--cliVersion","1.8.0-alpha.sdk-gen"],{templates:Oo,cwd:process.cwd(),logger:new dd(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=fd(n,r,o);Ft({target:"AGENTS.md",linkPath:Nt(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&Do({appDir:m.cwd}),await hd(m.cwd),wd(m.cwd),yd(n,m.display,s)}i(Sd,"handleCreate");function Lo(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
|
|
83
202
|
Non-interactive use (CI, scripts, AI agents):
|
|
84
203
|
Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
|
|
85
204
|
to skip every prompt. Missing flags fall back to the interactive prompt.
|
|
@@ -92,22 +211,30 @@ Examples:
|
|
|
92
211
|
--display-name "My App" --description "My app" \\
|
|
93
212
|
--org cog-atlas --project atlas-greenfield --cluster greenfield \\
|
|
94
213
|
--base-url https://greenfield.cognitedata.com
|
|
95
|
-
Fully non-interactive`).action(
|
|
214
|
+
Fully non-interactive`).action(Sd)}i(Lo,"registerCreateCommand");import vd from"path";async function Cd(e,t,n={}){let{loadEnvFile:r=P,loadAppConfig:o=k,getApiClient:s=vt}=n,a=vd.resolve(process.cwd(),e);r(a);let p=o(a);O(p);let c=t.interactive?await F(p,t):I(p.deployments,t.deployment);if(!t.interactive){let g=T(c);if(g.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${g.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let{externalId:l}=p,d=await s(c,t,l),m=await d.getActiveVersion(l);if(!m){console.log(` ${l} has no active version \u2014 nothing to deactivate.`);return}await d.deactivateVersion(l,m.version),console.log(`\u2713 Deactivated ${l} @ ${m.version} \u2014 active alias removed`)}i(Cd,"handleDeactivate");function No(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
96
215
|
Examples:
|
|
97
216
|
npx @cognite/cli apps deactivate . Deactivate using env-var auth
|
|
98
|
-
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,
|
|
99
|
-
`).
|
|
217
|
+
npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,n)=>Cd(t,n))}i(No,"registerDeactivateCommand");import kd from"path";import xd from"enquirer";async function Ed(e){let{confirmed:t}=await xd.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(Ed,"defaultConfirm");async function bd(e,t,n={}){let{loadEnvFile:r=P,loadAppConfig:o=k,getApiClient:s=vt,confirm:a=Ed}=n,p=kd.resolve(process.cwd(),e);r(p);let c=o(p);O(c);let l=t.interactive?await F(c,t):I(c.deployments,t.deployment);if(!t.interactive){let u=T(l);if(u.length>0)throw new h(`Deployment ${l.org}/${l.project} is missing ${u.join(" and ")} in app.json.`,{hint:"Use `npx @cognite/cli@latest apps delete --interactive` for browser-based authentication instead."})}let d=await s(l,t,c.externalId),{externalId:m,versionTag:g}=c,f;try{f=await d.getVersion(m,g)}catch(u){throw u instanceof G?new h(`Version ${g} of ${m} has not been deployed yet.`,{hint:"Run `npx @cognite/cli apps deploy` first."}):u}if(f.alias==="ACTIVE")throw new h(`Cannot archive ${m} @ ${g}: version is currently ACTIVE.`,{hint:"Run `npx @cognite/cli apps deactivate` first."});if(f.lifecycleState==="ARCHIVED"){console.log(` ${m} @ ${g} is already ARCHIVED \u2014 nothing to do.`);return}if(!t.force&&!await a(`Delete ${m} @ ${g}?`)){process.stderr.write(`Aborted.
|
|
218
|
+
`);return}if(f.lifecycleState==="DRAFT"){await d.deleteVersion(m,g),console.log(`\u2713 Deleted ${m} @ ${g} (DRAFT removed)`);return}f.lifecycleState==="PUBLISHED"&&(await d.deprecateVersion(m,g),console.log(`\u2713 Deprecated ${m} @ ${g} is now DEPRECATED`)),await d.archiveVersion(m,g),console.log(`\u2713 Archived ${m} @ ${g} is now ARCHIVED`)}i(bd,"handleDelete");function _o(e){return e.command("delete").description("Archive the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").option("-f, --force","Skip confirmation prompt",!1).addHelpText("after",`
|
|
219
|
+
Examples:
|
|
220
|
+
npx @cognite/cli apps delete . Archive using env-var auth
|
|
221
|
+
npx @cognite/cli apps delete . --interactive Archive using browser auth (no secrets needed)
|
|
222
|
+
npx @cognite/cli apps delete . --force Skip confirmation prompt`).action((t,n)=>bd(t,n))}i(_o,"registerDeleteCommand");import{existsSync as jd}from"fs";import{rm as Kd}from"fs/promises";import Vo from"enquirer";import{existsSync as Fd}from"fs";import{mkdir as Od,readFile as Ld}from"fs/promises";import{basename as Nd,dirname as _d}from"path";import{execFileSync as _t}from"child_process";import te from"fs";import j from"path";import{parseAndValidateManifestConfig as Pd}from"@cognite/app-sdk/vite";import{BlobReader as Ad,Uint8ArrayWriter as Dd,ZipWriter as Id}from"@zip.js/zip.js";var Bn="package.json",Hn="package-lock.json",Uo="manifest.json",Gn=".cognite",$d=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],qn=class qn{constructor(t="dist"){this.distPath=j.isAbsolute(t)?t:j.join(process.cwd(),t),this.appRoot=j.dirname(this.distPath)}validateBuildDirectory(){if(!te.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=j.join(this.appRoot,Bn);if(!te.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=j.join(this.appRoot,Hn);if(!te.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 Id(new Dd,{level:9}),o=i(async(c,l)=>{await r.add(l,new Ad(await te.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=i(async c=>{let l=await te.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=j.join(c,d.name);d.isDirectory()?await s(m):await o(m,j.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=j.join(this.appRoot,Bn);await o(c,j.posix.join(Gn,Bn));let l=j.join(this.appRoot,Uo);if(te.existsSync(l)){let m=te.readFileSync(l,"utf-8");Pd(m,l),await o(l,j.posix.join(Gn,Uo))}let d=j.join(this.appRoot,Hn);await o(d,j.posix.join(Gn,Hn)),a=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}try{await te.promises.writeFile(t,a)}catch(c){throw new h(`Failed to write bundle to ${t}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let n;try{n=_t("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw Z(),new h("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=_t("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",s=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(n,s);try{_t("git",["-C",n,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(te.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${j.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,n){let r=_t("git",["-C",t,"ls-tree","-r","--name-only",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
223
|
+
`).filter(Boolean),o=i(a=>a.split("/").some(p=>$d.some(c=>c.test(p))),"isSensitive"),s=r.filter(o);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
100
224
|
`+s.map(a=>` ${a}`).join(`
|
|
101
225
|
`)+`
|
|
102
|
-
Hint: git rm --cached <file>`)}};
|
|
103
|
-
|
|
104
|
-
|
|
226
|
+
Hint: git rm --cached <file>`)}};i(qn,"ApplicationPackager");var ne=qn;import{existsSync as Rd,readFileSync as Td}from"fs";var ce=[".dev.sig",".cert.sig"];function ze(e,t={}){let n=t.existsSync??Rd,r=t.readFileSync??((s,a)=>Td(s,a)),o=[];for(let s of ce){let a=`${e}${s}`;if(!n(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(ze,"discoverSignatures");async function Ut(e,t,{existsSync:n=Fd,mkdir:r=Od,createZip:o=i((s,a)=>new ne(s).createZip(a,!0),"createZipFn")}={}){let{externalId:s,versionTag:a}=e,p=q(t,s,a);if(n(p)){let l=ce.some(d=>n(`${p}${d}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new h(`Bundle already exists: ${p}`,{hint:l,shouldReport:!1})}await r(_d(p),{recursive:!0}),await o(`${t}/dist`,p)}i(Ut,"packageBundle");async function Je(e,t,n,r,{readFile:o=Ld,upload:s=i(async(a,p)=>new D(e).deploy(t.externalId,t.name,t.description,t.versionTag,a,p,r),"uploadFn")}={}){let a=q(n,t.externalId,t.versionTag),p;try{p=await o(a)}catch(c){throw new h(`Failed to read bundle file: ${a}`,{cause:c})}await s(p,Nd(a))}i(Je,"uploadBundle");var Qn=i(async(e,t,n)=>{let r=await Fe(e,n);await Ut(t,n),await Je(r,t,n,e.published)},"deploy"),zn=i(async(e,t,n)=>{let r=await Fe(e,n);await Je(r,t,n,e.published)},"deployBundle");import{execSync as Ud}from"child_process";function Mt(e,t=!0,n={execSync:Ud}){console.log("\u{1F4E6} Building app with npm...");try{n.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"})}catch(r){throw new h(`npm run build failed in ${e}`,{cause:r,hint:"Check the build output above for errors."})}console.log("\u2705 Build successful")}i(Mt,"buildApp");function Mo(e,t){let{org:n,project:r,baseUrl:o}=e,s;try{s=new URL(o).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${n}.fusion.cognite.com/${r}/flows-apps/app/${encodeURIComponent(a)}?${c}`}i(Mo,"generateFusionUrl");import Md,{Chalk as Vd}from"chalk";var Ye=new Vd({level:0});function Vt(e){return e.isTTY?Md:Ye}i(Vt,"chalkForStream");async function Bd(e){let{confirmed:t}=await Vo.prompt({type:"confirm",name:"confirmed",message:e,initial:!1});return t}i(Bd,"defaultConfirm");async function Hd(e,t){let{selected:n}=await Vo.prompt({type:"select",name:"selected",message:e,choices:t});return n}i(Hd,"defaultSelect");async function Gd(e){await Kd(e,{force:!0})}i(Gd,"defaultRm");function qd(e,t,n){return n(e)?t.skipBuild?"use-existing":process.stdout.isTTY?"prompt":"package-fresh":"package-fresh"}i(qd,"classifyExistingBundle");async function Qd(e,t){let{versionTag:n,hasSigs:r}=e,o=r?`A signed bundle for v${n} already exists. What would you like to do?`:`A bundle for v${n} already exists. What would you like to do?`,s=await t.select(o,[{name:"reuse",message:"Deploy the existing bundle without rebuilding"},{name:"rebuild",message:"Rebuild and deploy (overwrites the existing bundle)",...r?{hint:"\u2014 discards existing signatures"}:{}},{name:"cancel",message:"Cancel \u2014 do nothing"}]);if(s==="rebuild"&&r){let a=Vt(process.stderr);if(console.warn(a.bold.red(`
|
|
227
|
+
WARNING: this bundle is already signed.`)),console.warn(a.red(`Rebuilding overwrites the bundle and permanently discards its signatures (${ce.join(", ")}). You will have to re-sign before publishing.
|
|
228
|
+
`)),!await t.confirm("Rebuild anyway and discard the existing signatures?"))return"cancel"}return s==="reuse"?"reuse":s==="rebuild"?"rebuild":"cancel"}i(Qd,"promptBundleAction");async function zd(e,t){for(let n of[e,...ce.map(r=>`${e}${r}`)])t.existsSync(n)&&await t.rm(n)}i(zd,"removeBundleArtifacts");function jo(e){let{appConfig:t,deployment:n,interactive:r}=e,o=r?"Deploy (Interactive)":"Deploy",s=r?`${n.project} @ ${n.baseUrl}`:`${n.org}/${n.project}`;console.log(["",o,"=".repeat(o.length),`App: ${t.name} (${t.externalId})`,`Version: ${t.versionTag}`,`Target: ${s}`,""].join(`
|
|
229
|
+
`))}i(jo,"printDeployInfo");function Ko(e){let{appConfig:t,deployment:n}=e;console.log(`
|
|
230
|
+
Successfully deployed ${t.name} version ${t.versionTag} to ${n.org?`${n.org}/`:""}${n.project}`),console.log("App is deployed in draft mode");let r=t.deployments.length>1?` -d ${n.project}`:"";console.log(`
|
|
105
231
|
To sign: npx @cognite/cli apps sign --interactive${r}`),console.log(`To publish: npx @cognite/cli apps publish .${r}`),console.log(`To activate: npx @cognite/cli apps activate .${r}`),console.log(`
|
|
106
|
-
To submit for certification: npx @cognite/cli apps submit`);let
|
|
107
|
-
|
|
108
|
-
${
|
|
109
|
-
|
|
110
|
-
|
|
232
|
+
To submit for certification: npx @cognite/cli apps submit`);let o=Mo(n,t);o&&console.log(`
|
|
233
|
+
Open your app:
|
|
234
|
+
${o}`)}i(Ko,"printDeployResult");async function Jd(e,t){let{appConfig:n,deployment:r,cwd:o,options:s,useExistingBundle:a}=e,{deployFn:p,buildApp:c}=t,l=T(r);if(l.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${l.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);jo({appConfig:n,deployment:r,interactive:!1}),!s.skipBuild&&!a&&c(o),console.log(`
|
|
235
|
+
Deploying to ${r.org}/${r.project}...`),await p({...r,published:!1},{externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag},o),Ko({appConfig:n,deployment:r})}i(Jd,"handleDeployNonInteractive");async function Yd(e,t){let{appConfig:n,deployment:r,cwd:o,options:s,useExistingBundle:a}=e,{buildApp:p}=t;jo({appConfig:n,deployment:r,interactive:!0}),!s.skipBuild&&!a&&p(o);let c=await M(r,{interactive:!0,appId:n.externalId,orgHint:s.org});console.log(`
|
|
236
|
+
Deploying to ${r.project}...`);let l={externalId:n.externalId,name:n.name,description:n.description,versionTag:n.versionTag};a||await Ut(l,o),await Je(c,l,o,!1),Ko({appConfig:n,deployment:r})}i(Yd,"handleDeployInteractive");async function Wd(e,t=process.cwd(),n={}){let{loadEnvFile:r=P,loadAppConfig:o=k,deploy:s=Qn,deployBundle:a=zn,confirm:p=Bd,select:c=Hd,existsSync:l=jd,rm:d=Gd,buildApp:m=Mt}=n;r(t);let g=o(t);O(g);let f=q(t,g.externalId,g.versionTag),u=qd(f,e,l),y=u==="use-existing";if(u==="prompt"){let v=ce.some(b=>l(`${f}${b}`)),w=await Qd({versionTag:g.versionTag,hasSigs:v},{select:c,confirm:p});if(w==="cancel"){console.log(`
|
|
237
|
+
Deployment cancelled. Nothing was deployed.`);return}w==="reuse"?y=!0:await zd(f,{existsSync:l,rm:d})}if(e.interactive){let v=await F(g,e);await Yd({appConfig:g,deployment:v,cwd:t,options:e,useExistingBundle:y},{buildApp:m});return}let S=I(g.deployments,e.deployment);await Jd({appConfig:g,deployment:S,cwd:t,options:e,useExistingBundle:y},{deployFn:y?a:s,buildApp:m})}i(Wd,"handleDeploy");function Bo(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
111
238
|
Environment (non-interactive):
|
|
112
239
|
deployClientId and deploySecretName are configured per deployment in app.json.
|
|
113
240
|
deploySecretName is the name of the environment variable that holds the client
|
|
@@ -121,76 +248,89 @@ Examples:
|
|
|
121
248
|
npx @cognite/cli apps deploy -d my-project Deploy to project by name
|
|
122
249
|
npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
|
|
123
250
|
npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
|
|
124
|
-
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>
|
|
251
|
+
npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Wd(t))}i(Bo,"registerDeployCommand");import Bt from"fs";import im from"os";import le from"path";import om from"enquirer";import Jn from"fs";import jt from"path";import{BlobReader as Zd,Uint8ArrayWriter as Xd,ZipReader as em}from"@zip.js/zip.js";import We from"path";function Ho(e,t){let n=We.resolve(e),r=We.resolve(t),o=We.relative(n,r);return o===""||We.isAbsolute(o)?!1:o!==".."&&!o.startsWith(`..${We.sep}`)}i(Ho,"isSafePath");var tm=1e5,nm=2*1024**3;async function Go(e,t,n={}){let{openAsBlob:r=i(d=>Jn.openAsBlob(d),"openAsBlob"),mkdir:o=i((d,m)=>Jn.promises.mkdir(d,m),"mkdir"),writeFile:s=i((d,m)=>Jn.promises.writeFile(d,m),"writeFile"),maxEntries:a=tm,maxTotalBytes:p=nm}=n,c=await r(e),l=new em(new Zd(c));try{let d;try{d=await l.getEntries()}catch(f){throw new h(`Could not read bundle: ${jt.basename(e)} is not a valid zip file.`,{hint:"Make sure you are passing the correct bundle path.",shouldReport:!1,cause:f})}let m=0,g=0;for(let f of d){if(f.directory)continue;if(g++,g>a)throw new Error(`Zip contains too many entries (limit: ${a})`);if(m+=f.uncompressedSize,m>p)throw new Error(`Zip exceeds maximum allowed size (limit: ${Math.round(p/(1024*1024))} MB)`);if(jt.isAbsolute(f.filename))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let u=jt.join(t,f.filename);if(!Ho(t,u))throw new Error(`Malicious zip entry rejected: ${f.filename}`);let y=await f.getData(new Xd);await o(jt.dirname(u),{recursive:!0}),await s(u,y)}}finally{await l.close()}}i(Go,"extractZip");import{execFileSync as rm}from"child_process";function Qo(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}i(Qo,"isExitError");function qo(e){if(!Qo(e)||e.status!==1)throw e}i(qo,"swallowDiffExit");var Yn=class Yn{constructor(t={execFileSync:rm}){this.deps=t}isSupported(){try{return this.deps.execFileSync("git",["--version"],{stdio:"pipe"}),!0}catch{return!1}}isIdentical(t,n){try{return this.deps.execFileSync("git",["diff","--no-index","--quiet","--ignore-cr-at-eol",t,n]),!0}catch(r){if(Qo(r)&&r.status===1)return!1;throw r}}showStat(t,n){try{this.deps.execFileSync("git",["--no-pager","diff","--stat","--no-index","--ignore-cr-at-eol",t,n],{stdio:"inherit"})}catch(r){qo(r)}}showDiff(t,n,{usePager:r=!0}={}){let o=[];r||o.push("--no-pager"),o.push("diff","--word-diff=color","--no-index","--ignore-cr-at-eol",t,n);try{this.deps.execFileSync("git",o,{stdio:"inherit"})}catch(s){qo(s)}}};i(Yn,"GitDiffer");var Kt=Yn;var sm=i(async e=>(await om.prompt([{type:"confirm",name:"answer",message:e,initial:!1}])).answer,"defaultConfirm");async function am(e,t,n={}){let{cwd:r=process.cwd(),buildApp:o=Mt,createPackager:s=i(w=>new ne(w),"createPackager"),extractZip:a=Go,differ:p=new Kt,existsSync:c=i(w=>Bt.existsSync(w),"existsSync"),mkdtemp:l=i(w=>Bt.promises.mkdtemp(w),"mkdtemp"),mkdir:d=i(async(w,b)=>{await Bt.promises.mkdir(w,b)},"mkdir"),rm:m=i((w,b)=>Bt.promises.rm(w,b),"rm"),isInteractive:g=i(()=>!!(process.stdin.isTTY&&process.stdout.isTTY),"isInteractive"),confirm:f=sm,setExitCode:u=i(w=>{process.exitCode=w},"setExitCode")}=n;if(!p.isSupported())throw new h("git is required for the diff command",{hint:"Install git and ensure it is in your PATH.",shouldReport:!1});if(!c(e))throw new h(`Bundle not found: ${e}`,{hint:"Check the file path and try again.",shouldReport:!1});if(!t.skipBuild)await o(r);else{let w=le.join(r,"dist");if(!c(w))throw new h("dist directory not found.",{hint:"Run without --skip-build to build the app first, or run `pnpm build` manually.",shouldReport:!1})}let y=await l(le.join(im.tmpdir(),"cognite-diff-")),S=le.join(y,"ours.zip"),C=le.join(y,"ours"),v=le.join(y,"theirs");try{if(await d(C,{recursive:!0}),await d(v,{recursive:!0}),await s(le.join(r,"dist")).createZip(S),console.log(`
|
|
252
|
+
Extracting bundles...`),await a(S,C),await a(e,v),p.isIdentical(C,v)){console.log(`
|
|
253
|
+
Bundles are identical`);return}console.log(`
|
|
254
|
+
\u274C The local build at ${le.join(r,"dist")} differs from ${le.basename(e)}.`);let b=g();(t.showStat!==void 0?t.showStat:b&&await f("Show stat summary?"))&&p.showStat(C,v),(t.showDiff!==void 0?t.showDiff:b&&await f("Show full diff?"))&&p.showDiff(C,v,{usePager:t.pager}),u(1)}finally{await m(y,{recursive:!0,force:!0})}}i(am,"handleDiff");function zo(e){return e.command("diff <bundle>").description("Diff a trusted local build against an untrusted bundle zip").option("--skip-build","Skip rebuilding the app before diffing",!1).option("--no-pager","Disable the pager and print diff output directly").option("--show-stat","Show a compact stat summary when bundles differ").option("--show-diff","Show the full word diff when bundles differ").addHelpText("after",`
|
|
255
|
+
Builds the current source, packages it, then extracts both the local build
|
|
256
|
+
and the provided bundle to temporary directories and runs:
|
|
257
|
+
|
|
258
|
+
git diff --no-index <local-build> <bundle>
|
|
259
|
+
|
|
260
|
+
Exit code 0 means the bundles are identical; exit code 1 means they differ.
|
|
261
|
+
|
|
262
|
+
Examples:
|
|
263
|
+
npx @cognite/cli apps diff untrusted.zip
|
|
264
|
+
npx @cognite/cli apps diff untrusted.zip --skip-build
|
|
265
|
+
npx @cognite/cli apps diff untrusted.zip --show-stat --show-diff --no-pager`).action((t,n)=>am(t,n))}i(zo,"registerDiffCommand");function pm(e,t){console.log(""),console.log(`Updating metadata for '${e}':`);for(let{field:n,remote:r,local:o}of t){let s=`${n}:`.padEnd(13);console.log(` ${s}"${r}" \u2192 "${o||"(none)"}"`)}}i(pm,"printMetadataDiff");async function cm(e,t=process.cwd(),n={}){let{loadEnvFile:r=P,loadAppConfig:o=k,getClientForDeployment:s=M,createMetadataClient:a=i(y=>new D(y),"createMetadataClient"),getMissingCredentials:p=T}=n;r(t);let c=o(t);O(c);let l=e.interactive?await F(c,e):I(c.deployments,e.deployment);if(!e.interactive){let y=p(l);if(y.length>0)throw new Error(`Deployment ${l.org}/${l.project} is missing ${y.join(" and ")} in app.json. Use \`cognite apps metadata update --interactive\` for browser-based authentication instead.`)}let d=await s(l,{interactive:e.interactive,appId:c.externalId,orgHint:e.org}),m=a(d),g;try{g=await m.getApp(c.externalId)}catch(y){throw y instanceof Te?new Error(`App '${c.externalId}' is not deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):y}let f={name:c.name,description:c.description||""},u=wn(g,f);if(u.length===0){console.log(""),console.log(`Metadata for '${c.externalId}' already matches the deployed app \u2014 nothing to update.`),console.log("Edit name/description in app.json to change them.");return}pm(c.externalId,u),await m.updateAppMetadata(c.externalId,c.name,c.description),console.log(""),console.log(`\u2705 Metadata for '${c.externalId}' updated`)}i(cm,"handleUpdateMetadata");function Jo(e){let t=e.command("metadata").summary("Manage the deployed app's metadata").description("Manage the deployed app's metadata (name and description).");return t.command("update").description("Update the deployed app's name and description from app.json").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
125
266
|
Examples:
|
|
126
267
|
npx @cognite/cli apps metadata update . Push name/description using env-var auth
|
|
127
|
-
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((r
|
|
268
|
+
npx @cognite/cli apps metadata update . --interactive Push using browser auth (no secrets needed)`).action((n,r)=>cm(r)),t}i(Jo,"registerMetadataCommand");async function lm(e,t,n){let r=await M(e,{interactive:t.interactive,appId:n.externalId,orgHint:t.org});return new D(r)}i(lm,"defaultBuildApiClient");async function dm(e,t={}){let n=t.loadEnvFile??P,r=t.loadAppConfig??k,o=t.buildApiClient??lm,s=t.discoverSignatures??ze,a=process.cwd();n(a);let p=r(a);O(p);let c=e.interactive?await F(p,e):I(p.deployments,e.deployment);if(!e.interactive){let u=T(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await o(c,e,p),{externalId:d,versionTag:m}=p,g;try{g=await l.getVersion(d,m)}catch(u){throw u instanceof G?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):u}if(g.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(g.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(g.lifecycleState==="DEPRECATED"||g.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${g.lifecycleState} (terminal).`);let f=s(q(a,d,m));f.length>0&&await l.submitSignatures(d,m,f),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}i(dm,"handlePublish");function Yo(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
128
269
|
Examples:
|
|
129
270
|
npx @cognite/cli apps publish . Publish using env-var auth
|
|
130
|
-
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,
|
|
131
|
-
`)},"info"),error:
|
|
132
|
-
`)},"error")},
|
|
271
|
+
npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,n)=>dm(n))}i(Yo,"registerPublishCommand");import{spawnSync as mm}from"child_process";import{mkdirSync as um}from"fs";import{join as gm,resolve as Wo}from"path";var fm=["localhost","local.cognite.ai","*.local.cognite.ai"],ym={info:i(e=>{process.stdout.write(`${e}
|
|
272
|
+
`)},"info"),error:i(e=>{process.stderr.write(`${e}
|
|
273
|
+
`)},"error")},hm={spawnSync:mm,mkdirSync:um,logger:ym,getConfig:R};function wm(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}i(wm,"hasMkcert");function Sm({certDir:e,domains:t=fm,deps:n={}}={}){let r={...hm,...n},{spawnSync:o,mkdirSync:s,logger:a}=r,p=e??gm(r.getConfig().home,"certificates","mkcert");if(!wm(o))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),o("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(p,{recursive:!0});let l=Wo(p,"localhost.pem"),d=Wo(p,"localhost-key.pem");if(o("mkcert",["-cert-file",l,"-key-file",d,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${l}`),a.info(` key: ${d}`),{certFile:l,keyFile:d}}i(Sm,"setupHttps");function vm(e){Sm({certDir:e.certDir})}i(vm,"handleSetupHttps");function Zo(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ~/.cognite-cli/certificates/mkcert)").addHelpText("after",`
|
|
133
274
|
Examples:
|
|
134
|
-
npx @cognite/cli@latest apps setup-https Generate certs in
|
|
135
|
-
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>
|
|
275
|
+
npx @cognite/cli@latest apps setup-https Generate certs in ~/.cognite-cli/certificates/mkcert
|
|
276
|
+
npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>vm(t))}i(Zo,"registerSetupHttpsCommand");import{existsSync as Vm,writeFileSync as jm}from"fs";import{basename as Km,dirname as Bm,join as Hm,resolve as tr}from"path";import{parseScope as Gm,signBundle as qm,validateScopes as Qm}from"@cognite/app-sdk/codesigning";import{existsSync as _m,readFileSync as Um}from"fs";import{pbkdf2 as xm,randomBytes as Em}from"crypto";import{promisify as bm}from"util";import{CompactEncrypt as Pm,base64url as Xo,compactDecrypt as Am}from"jose";var Cm=new TextEncoder,km=new TextDecoder,Wn={encode:i(e=>Cm.encode(e),"encode"),decode:i(e=>km.decode(e),"decode")};var Dm=bm(xm),er=6e5,Im="sha512",Zn="PBKDF2-HMAC-SHA512",Xn=16,Ht="A256GCM",$m=32,Gt=2e6;async function es(e,t,n){return await Dm(e,t,n,$m,Im)}i(es,"deriveKey");async function ts(e,t,n=er){if(!Number.isInteger(n)||n<1||n>Gt)throw new Error(`Invalid iterations: must be an integer between 1 and ${Gt}`);let r=Em(Xn),o=await es(t.expose(),r,n);return await new Pm(Wn.encode(e.expose())).setProtectedHeader({alg:"dir",enc:Ht,kdf:Zn,kdf_iter:n,kdf_salt:Xo.encode(r)}).encrypt(o)}i(ts,"encryptStringAsJwe");async function ns(e,t){let{plaintext:n}=await Am(e,async r=>{if(!e.length)throw new Error("Unexpected JWE empty value");let o=t.expose();if(o.length<15)throw new Error(`Invalid passphrase: must be at least ${15} characters`);if(r.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(r.alg)}"; only "dir" is supported`);if(r.enc!==Ht)throw new Error(`Unexpected JWE enc "${String(r.enc)}"; only "${Ht}" is supported`);if(r.kdf!==Zn)throw new Error(`Unexpected KDF "${String(r.kdf)}"; only "${Zn}" is supported`);let s=Number(r.kdf_iter);if(!Number.isInteger(s)||s<1||s>Gt)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Gt}`);if(typeof r.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let a=Xo.decode(r.kdf_salt);if(a.length!==Xn)throw new Error(`Invalid kdf_salt length in JWE header: expected ${Xn} bytes, got ${a.length}`);return await es(o,a,s)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[Ht]});return Wn.decode(n)}i(ns,"decryptJweAsString");function Rm(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}i(Rm,"isJweCompact");var rs=Rm;import Tm from"enquirer";async function Fm(e){return Tm.prompt(e)}i(Fm,"defaultPrompt");async function is(e,t={}){let{prompt:n=Fm}=t,{passphrase:r}=await n({type:"password",name:"passphrase",message:e});return x.from(r)}i(is,"promptPassphrase");import Lm from"enquirer";import{statSync as Om}from"fs";function os(e,t=Om){return e.map(n=>({key:n,mtime:t(n.publicKeyPath).mtimeMs})).sort((n,r)=>r.mtime-n.mtime).map(({key:n})=>n)}i(os,"sortByMtime");async function Nm(e){return Lm.prompt(e)}i(Nm,"defaultPrompt");async function ss(e,t={}){if(e.length===1)return e[0];let{prompt:n=Nm,sortByMtime:r=os}=t,o=r(e),s=o[0],{choice:a}=await n({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await n({type:"select",name:"kid",message:"Select signing identity",choices:o.map(l=>({name:l.kid,message:[l.kid,l.email,Dt(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=o.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}i(ss,"promptSigningIdentity");function Mm(e){return{existsSync:e.existsSync??_m,readFileSync:e.readFileSync??((t,n)=>Um(t,n)),readKeyFromKeychain:e.readKeyFromKeychain??Pt,readSigningKey:e.readSigningKey??At,isOS:e.isOS??(t=>U(t)),decryptJweAsString:e.decryptJweAsString??ns,discoverLocalKeys:e.discoverLocalKeys??It,keysDir:e.keysDir??R().keysDir,promptPassphrase:e.promptPassphrase??is,promptSigningIdentity:e.promptSigningIdentity??ss}}i(Mm,"resolveDeps");async function as(e,t={}){let n=Mm(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(rs(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await n.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:x.from(await n.decryptJweAsString(s,a)),kid:e.kid}}return{privateKeyPem:x.from(s),kid:e.kid}}let r=await n.discoverLocalKeys(n.keysDir);if(r.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let o;if(e.kid)o=r.find(s=>s.kid===e.kid);else if(e.interactive)o=await n.promptSigningIdentity(r);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!o)throw new Error(`No key found with kid "${e.kid}"`);switch(o.source.kind){case"keychain":{let s=n.isOS("macos")?await n.readKeyFromKeychain(o.kid):await n.readSigningKey(o.kid);if(!s)throw new Error(`Key "${o.kid}" not found in OS credential store`);return{privateKeyPem:s,kid:o.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${o.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await n.promptPassphrase(`Passphrase for key ${o.kid}: `);return{privateKeyPem:x.from(await n.decryptJweAsString(n.readFileSync(o.source.path,"utf-8"),s)),kid:o.kid}}case"public-only":throw new Error(`Key "${o.kid}" has no private key on this machine (public-only).`)}}i(as,"resolvePrivateKey");var zm=i(async(e,t,n,r,o)=>{let s=await M(e,{interactive:o.browserAuth??!1,appId:t,orgHint:o.org});await new D(s).submitSignatures(t,n,r)},"defaultSubmitSignatures");function Jm(e){return{existsSync:e.existsSync??Vm,writeFileSync:e.writeFileSync??jm,createBundleStream:e.createBundleStream??$t,signBundle:e.signBundle??qm,parseScope:e.parseScope??Gm,validateScopes:e.validateScopes??Qm,loadAppConfig:e.loadAppConfig??k,resolvePrivateKey:e.resolvePrivateKey??(t=>as(t)),submitSignatures:e.submitSignatures??zm,discoverSignatures:e.discoverSignatures??ze}}i(Jm,"resolveDeps");async function ps(e,t,n={},r=process.cwd()){let o=Jm(n),s=t.appid,a=t.appVersion,p=[],c=o.loadAppConfig(r);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(o.parseScope):p=c.deployments.map(v=>({org:v.org,project:v.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?tr(r,e):q(r,s,a);if(!o.existsSync(l)){let v=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${v}`)}let d=o.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
|
|
136
277
|
${d.join(`
|
|
137
|
-
`)}`);let{privateKeyPem:m,kid:
|
|
138
|
-
Payload:`,JSON.stringify(u.payload,null,2));let
|
|
139
|
-
To publish: npx @cognite/cli apps publish .`)}
|
|
278
|
+
`)}`);let{privateKeyPem:m,kid:g}=await o.resolvePrivateKey({keyPath:t.key?tr(r,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),f=o.createBundleStream(l),u=await o.signBundle({privateKeyPem:m.expose(),kid:g,appId:s,version:a,bundleStream:f,role:t.asCertifier?"certifier":"developer",scopes:p}),y=t.output?tr(r,t.output):Hm(Bm(l),`${Km(l)}.${t.asCertifier?"cert":"dev"}.sig`);o.writeFileSync(y,u.token,"utf-8"),console.log(`\u2705 Signed: ${y}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(v=>`${v.org}/${v.project}`).join(", ")}`),t.verbose&&console.log(`
|
|
279
|
+
Payload:`,JSON.stringify(u.payload,null,2));let S=Array.from(new Set([...o.discoverSignatures(l),u.token])),C=t.interactive?await F(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):I(c.deployments,t.deployment);if(!t.browserAuth){let v=T(C);if(v.length>0)throw new Error(`Deployment ${C.org}/${C.project} is missing ${v.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await o.submitSignatures(C,s,a,S,t),console.log(`
|
|
280
|
+
To publish: npx @cognite/cli apps publish .`)}i(ps,"handleSign");function cs(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((n,r)=>{let o={...r,appid:r.identifier??r.appid,scope:r.requirements??r.scope};return ps(n,o,t)})}i(cs,"registerSignCommand");function Ym(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}i(Ym,"describeStatus");function Wm(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let n of e){let r=n.status==="VALID"?"\u2705":"\u274C",o=new Date(n.signatureIat).toISOString();t.push(` ${r} ${n.signerKid} (${n.signerRole}, signed ${o}) \u2014 ${n.status}`)}return t}i(Wm,"formatSignatures");async function Zm(e){let t=process.cwd();P(t);let n=k(t);O(n);let r=e.interactive?await F(n,e):I(n.deployments,e.deployment);if(!e.interactive){let a=T(r);if(a.length>0)throw new Error(`Deployment ${r.org}/${r.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let o=await M(r,{interactive:e.interactive,appId:n.externalId,orgHint:e.org}),s=new D(o);console.log(""),console.log(`App: ${n.name} (${n.externalId})`),console.log(`Version: ${n.versionTag} (local)`);try{let a=await s.getVersion(n.externalId,n.versionTag);console.log(`Status: ${Ym(a)}`);let p=await Xm(s,n.externalId,n.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Wm(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof G){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}i(Zm,"handleStatus");async function Xm(e,t,n){try{return await e.listSignatures(t,n)}catch(r){if(Ce(r)&&r.status===404||r instanceof Error&&/status code: 404/.test(r.message))return"endpoint-unavailable";throw r}}i(Xm,"fetchSignatures");function ls(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
|
|
140
281
|
Examples:
|
|
141
282
|
npx @cognite/cli apps status . Status using env-var auth
|
|
142
|
-
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,
|
|
143
|
-
`))}</pre>`,p=
|
|
144
|
-
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}
|
|
283
|
+
npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,n)=>Zm(n))}i(ls,"registerStatusCommand");import{execFileSync as ir}from"child_process";import rr from"fs";import Ze from"path";import ru from"readline";var ds="https://cognite.zendesk.com",eu="360001234312",tu="tf_360015295097",nu="cognite_flows_certifications";function ms(e,t,n){let r=new URLSearchParams({ticket_form_id:eu,tf_priority:"normal",tf_subject:e,[tu]:nu,tf_description:t});return`${n}/hc/en-us/requests/new?${r}`}i(ms,"buildUrl");function us(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}i(us,"escapeHtml");function nr(e){return e.map(us).join("<br>")}i(nr,"toHtml");function gs(e,t=ds){let{appName:n,externalId:r,versionTag:o,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${n}`,`App external ID: ${r}`,`Version: ${o}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${r}-${o}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return ms(`App Review Request: ${n}`,nr(l.filter(d=>d!==void 0)),t)}i(gs,"buildAppReviewUrl");function fs(e,t,n,r,o=ds){let s=nr(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${n}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${us(r.replace(/\r\n/g,`
|
|
284
|
+
`))}</pre>`,p=nr(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return ms(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,o)}i(fs,"buildKeyRegistrationUrl");function iu(){return new Promise(e=>{let t=ru.createInterface({input:process.stdin,output:process.stdout});t.question(`
|
|
285
|
+
Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}i(iu,"defaultPressEnter");var ou=[{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 su(e){let t=ou.filter(({pattern:n})=>ir("git",["-C",e,"ls-files","--",n],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let n=t.map(({label:r,skill:o})=>` ${r} \u2192 /${o}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
|
|
145
286
|
|
|
146
|
-
`+
|
|
147
|
-
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}
|
|
287
|
+
`+n.join(`
|
|
288
|
+
`)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}i(su,"assertArtifactsCommitted");async function au(e=process.cwd(),t={}){let{openInBrowser:n=hi,revealInFileManager:r=wi,pressEnter:o=iu,isInteractive:s=i(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(Z(),!xt(e))throw new Error("Not a git repository. Run this command from your app's root directory.");P(e);let a=k(e);O(a),su(e);let p=Ze.join(e,"dist","submit");rr.mkdirSync(p,{recursive:!0});let c=ir("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(ir("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
|
|
148
289
|
|
|
149
|
-
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=
|
|
150
|
-
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(
|
|
290
|
+
The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=Ze.join(p,d);await new ne(Ze.join(e,"dist")).createSourceArchive(m);let f=`${a.externalId}-${a.versionTag}.zip`,u=Ze.join(e,".cognite-bundles",f),y=!1;rr.existsSync(u)&&(rr.copyFileSync(u,Ze.join(p,f)),y=!0);let S=gs({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:Oi(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
|
|
291
|
+
\u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(y?` ${f} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
|
|
151
292
|
Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
|
|
152
|
-
\u{1F517} ${
|
|
293
|
+
\u{1F517} ${S}`),s()&&(await o(),n(S),r(m))}i(au,"handleSubmit");function ys(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
|
|
153
294
|
Examples:
|
|
154
|
-
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>
|
|
295
|
+
npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>au())}i(ys,"registerSubmitCommand");function hs(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Lo(t),Bo(t),zo(t),ls(t),Jo(t),Yo(t),ho(t),No(t),_o(t),Zo(t),ys(t),To(t),Ti(t),cs(t),uo(t),t}i(hs,"registerAppsCommand");import{existsSync as du,mkdirSync as mu,writeFileSync as uu}from"fs";import{dirname as ar,join as Xe}from"path";import{generateSigningKeyPair as gu}from"@cognite/app-sdk/codesigning";import fu from"open";function ws(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,o=new Date(Date.UTC(n,r+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),o);return new Date(Date.UTC(n,r,s))}i(ws,"addMonthsClamped");function or(e){return e.toISOString().slice(0,10)}i(or,"formatIsoDate");function Ss(e=new Date){return or(e)}i(Ss,"todayIso");var qt=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),vs=32,Cs=44,ks=60,pu="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function cu(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==Cs&&t.length!==ks)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${Cs} (raw) or ${ks} (X.509-wrapped)`);let n=Buffer.from(t,"base64");if(n.length===qt.length+vs&&n.subarray(0,qt.length).equals(qt))return n.subarray(qt.length).toString("base64");if(n.length===vs)return n.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${n.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}i(cu,"pemBodyOneLine");function sr(e,t=Ye,n=new Date){let r=xs(e.issuedAt??Ss(n)),o=xs(e.expires),s=cu(e.publicKeyPem),a=" ",p=i((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
|
|
155
296
|
`,"kv"),c="";return c+=`
|
|
156
|
-
${t.bold("Add this entry to")} ${t.magenta(
|
|
297
|
+
${t.bold("Add this entry to")} ${t.magenta(pu)} ${t.bold("under")} ${t.cyan("publicKeys:")}
|
|
157
298
|
|
|
158
299
|
`,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
|
|
159
|
-
`,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(
|
|
160
|
-
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${
|
|
161
|
-
`);return}let
|
|
162
|
-
`);for(let a of
|
|
163
|
-
`)}
|
|
164
|
-
`))}let
|
|
165
|
-
`);return}let
|
|
300
|
+
`,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(r)),c+=p("expiresAt",t.green(o)),c+=p("revokedAt",t.dim("null")),c}i(sr,"renderRegistryYamlBlock");function xs(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let n=new Date(t);if(Number.isNaN(n.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return n.toISOString()}i(xs,"toIsoInstant");import lu from"clipboardy";function Es(e){return lu.write(e)}i(Es,"copyToClipboard");function yu(e){return{writeFileSync:e.writeFileSync??uu,mkdirSync:e.mkdirSync??mu,existsSync:e.existsSync??du,generateSigningKeyPair:e.generateSigningKeyPair??gu,encryptStringAsJwe:e.encryptStringAsJwe??ts,storeKeyInKeychain:e.storeKeyInKeychain??no,storeSigningKey:e.storeSigningKey??ao,isOS:e.isOS??(t=>U(t)),promptKid:e.promptKid??zi,promptExpiryMonths:e.promptExpiryMonths??Yi,promptEmail:e.promptEmail??Wi,promptPassphrase:e.promptPassphrase??Zi,promptConfirmOverwrite:e.promptConfirmOverwrite??Xi,discoverLocalKeys:e.discoverLocalKeys??(()=>It()),promptZendeskAction:e.promptZendeskAction??Ji,openUrl:e.openUrl??(t=>fu(t)),copyToClipboard:e.copyToClipboard??Es}}i(yu,"resolveDeps");function Ps(e,t={}){let n=yu(t),r=e.command("keys").description("Manage code signing keys");r.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip the OS credential store (macOS Keychain / Windows Credential Manager) and write a passphrase-encrypted private key under ${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").option("--interactive","Prompt for any required flags that are not supplied",!1).action(o=>vu(o,n)),r.command("list").description("List local signing identities and their storage location").action(()=>hu(n))}i(Ps,"registerKeysCommand");async function hu(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
|
|
301
|
+
`),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${R().keysDir}).
|
|
302
|
+
`);return}let n=["KID","SOURCE","EMAIL"],r=t.map(a=>[a.kid,Dt(a.source),a.email??"\u2014"]),o=n.map((a,p)=>Math.max(a.length,...r.map(c=>c[p].length))),s=i(a=>a.map((p,c)=>p.padEnd(o[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(n)}
|
|
303
|
+
`);for(let a of r)process.stdout.write(`${s(a)}
|
|
304
|
+
`)}i(hu,"handleList");function bs(e,t,n){let r=Xe(R().keysDir,`${e}${pe}`);return n.mkdirSync(ar(r),{recursive:!0}),n.writeFileSync(r,t),r}i(bs,"writePublicKey");async function wu(e,t,n,r,o,{force:s=!1}={}){let a=r??Xe(R().keysDir,`${e}${Nn}`);if(o.mkdirSync(ar(a),{recursive:!0}),!s&&o.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await o.encryptStringAsJwe(t,n);return o.writeFileSync(a,p,{mode:384}),a}i(wu,"writeEncryptedPrivateKey");function Su(e,t,n){let r=[];if(e.expires===void 0)r.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{Le(e.expires)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.kid===void 0)r.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let o=xe(e.kid),s=Xe(R().keysDir,`${o}${pe}`);n(s)&&!e.force&&r.push(`Key "${o}" already exists. Use --force to overwrite without prompting.`)}catch(o){r.push(o instanceof Error?o.message:String(o))}if(e.email===void 0)r.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{Oe(e.email,"--email")}catch(o){r.push(o instanceof Error?o.message:String(o))}return t||r.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),r}i(Su,"collectNonInteractiveErrors");async function vu(e,t,n=new Date){let{isOS:r,existsSync:o,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,storeSigningKey:l,promptExpiryMonths:d,promptKid:m,promptEmail:g,promptPassphrase:f,promptConfirmOverwrite:u}=t,y=e.interactive??!1,S=e.keychain!==!1&&!e.output&&(r("macos")||r("windows"));if(!y){let z=Su(e,S,o);if(z.length>0)throw new Error(z.join(`
|
|
305
|
+
`))}let C;e.expires!==void 0?C=Le(e.expires):C=await d();let v=or(ws(n,C)),w;e.kid!==void 0?w=xe(e.kid):w=await m();let b=Xe(R().keysDir,`${w}${pe}`),V=o(b);if(V&&!e.force&&!await u(w)){process.stderr.write(`Aborted.
|
|
306
|
+
`);return}let A;e.email!==void 0?A=Oe(e.email,"--email"):A=await g();let E=S?{kind:"keychain"}:{kind:"file",passphrase:await f()};process.stderr.write(`
|
|
166
307
|
Generating Ed25519 keypair...
|
|
167
308
|
|
|
168
|
-
`);let{privateKeyPem:
|
|
169
|
-
`),process.stderr.write(`Private key:
|
|
170
|
-
`)}else{let
|
|
171
|
-
`),process.stderr.write(`Private key: ${
|
|
172
|
-
`),
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
`),process.stderr.write(`
|
|
176
|
-
`);let ke={kid:h,publicKeyPem:G,email:P,expires:E};u||(process.stderr.write(`
|
|
309
|
+
`);let{privateKeyPem:de,publicKeyPem:me}=await p(w),L=x.from(de);if(E.kind==="keychain"){r("macos")?await c(w,L):await l(w,L);let z=bs(w,me,t);process.stderr.write(`Public key: ${z}
|
|
310
|
+
`),process.stderr.write(`Private key: OS credential store (account: ${w})
|
|
311
|
+
`)}else{let z=await wu(w,L,E.passphrase,e.output,t,{force:V}),qs=bs(w,me,t);process.stderr.write(`Public key: ${qs}
|
|
312
|
+
`),process.stderr.write(`Private key: ${z} (JWE, AES-256-GCM, PBKDF2-SHA512 x${er.toLocaleString()})
|
|
313
|
+
`)}let ue=Xe(R().keysDir,`${w}${_n}`);s(ar(ue),{recursive:!0}),a(ue,JSON.stringify({email:A}));let Ee=Vt(process.stderr);process.stderr.write(`
|
|
314
|
+
Signing identity (kid): ${Ee.green(w)}
|
|
315
|
+
`),process.stderr.write(`Expires: ${v} (${C} month${C===1?"":"s"} from today)
|
|
316
|
+
`);let et={kid:w,publicKeyPem:me,email:A,expires:v};y||(process.stderr.write(`
|
|
177
317
|
Key registration data:
|
|
178
318
|
|
|
179
|
-
`),process.stderr.write(
|
|
180
|
-
${
|
|
319
|
+
`),process.stderr.write(sr(et,Ee,n)));let ge=fs(w,A,v,sr(et,Ye,n));process.stderr.write(`
|
|
320
|
+
${Ee.bold("Next:")}
|
|
181
321
|
`),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
|
|
182
|
-
`);let
|
|
183
|
-
`)}catch{process.stderr.write(` URL: ${
|
|
184
|
-
`)}else if(
|
|
185
|
-
`:` URL: ${
|
|
186
|
-
`)}else process.stderr.write(` URL: ${
|
|
322
|
+
`);let Ue;if(e.copyLink?Ue="clipboard":y?Ue=await t.promptZendeskAction():Ue=null,Ue==="browser")try{await t.openUrl(ge),process.stderr.write(` Opening in browser...
|
|
323
|
+
`)}catch{process.stderr.write(` URL: ${ge}
|
|
324
|
+
`)}else if(Ue==="clipboard"){let z=!1;try{await t.copyToClipboard(ge),z=!0}catch{}process.stderr.write(z&&!e.copyLink?` Link copied to clipboard.
|
|
325
|
+
`:` URL: ${ge}
|
|
326
|
+
`)}else process.stderr.write(` URL: ${ge}
|
|
187
327
|
`);process.stderr.write(`
|
|
188
328
|
2. Once your key is approved, sign your Dune app:
|
|
189
|
-
`),process.stderr.write(` ${
|
|
190
|
-
`)}
|
|
191
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{
|
|
192
|
-
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}
|
|
193
|
-
`);return
|
|
194
|
-
${
|
|
195
|
-
`)},"onOutdated")})});
|
|
196
|
-
Cancelled.`),process.exit(130)),(!(e instanceof
|
|
329
|
+
`),process.stderr.write(` ${Ee.cyan(`cognite sign -s ${w}`)}
|
|
330
|
+
`)}i(vu,"handleGenerate");import{performance as As}from"perf_hooks";var Ds=1e3,Qt;function Cu(){Qt=As.now()}i(Cu,"markActionStart");function ku(){Qt=void 0}i(ku,"resetActionStart");function xu(){if(Qt!==void 0)return Math.max(0,Math.round(As.now()-Qt))}i(xu,"snapshotActionDurationMs");function Is(){let e=xu();return ku(),{...e!==void 0&&{actionDurationMs:e}}}i(Is,"takePerformanceFields");var Eu=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function bu(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>typeof n=="boolean"?[t,n]:Eu.has(t)?[t,n]:[t,"[REDACTED]"]))}i(bu,"sanitize");function Pu(e){let t=[],n=e;for(;n;)n.parent&&t.unshift(n.name()),n=n.parent;return t.join(" ")}i(Pu,"getCommandPath");function $s(e){try{let t=e(process.cwd()),n=t.deployments[0];return{appName:t.name,appExternalId:t.externalId,appVersionTag:t.versionTag,...n&&{cogniteOrg:n.org,cogniteProject:n.project}}}catch{return{}}}i($s,"tryLoadAppConfig");function pr(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}i(pr,"commandFromArgv");function Rs(e,t,n=k){e.hook("preAction",()=>{Cu()}),e.hook("postAction",async(r,o)=>{try{let s={command:Pu(o),options:bu(o.opts()),success:!0,...$s(n),...Is()};t.track("Flows.CLI.Command",{...s}),await t.flush(Ds)}catch{}})}i(Rs,"instrument");async function Ts(e,t,n=k){try{let r={command:pr(t),options:{},success:!1,...$s(n),...Is()};e.track("Flows.CLI.Command",{...r}),await e.flush(Ds)}catch{}}i(Ts,"trackFailure");var Au="ERR_USE_AFTER_CLOSE";function Os(e){return e instanceof Error&&"code"in e&&e.code===Au}i(Os,"isReadlineClosedError");function Du(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}i(Du,"isPlainObject");function cr(e){return e==null||Os(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&Du(e)&&Object.keys(e).length===0)}i(cr,"isPromptCancel");var Fs=!1;function Ls(){Fs||(Fs=!0,process.on("uncaughtException",e=>{Os(e)&&(console.error(`
|
|
331
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{cr(e)&&(console.error(`
|
|
332
|
+
Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}i(Ls,"installCancelHandler");import{homedir as Iu,userInfo as $u}from"os";var Ru=Iu(),Tu=(()=>{try{return $u().username}catch{return""}})();function Ne(e,t=Ru){if(!t||t==="/")return e;let n=e.replaceAll(t,"~"),r=t.replaceAll("\\","/");return r!==t&&(n=n.replaceAll(r,"~")),n=n.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),n=n.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),n}i(Ne,"redactHomedir");function Fu(e,t=Tu){if(!t||t.length<3)return e;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp("(^|[\\/\\s:])"+n+"(?=[\\/\\s:.@]|$)","g");return e.replace(r,"$1<user>")}i(Fu,"redactUsername");var Ou=/(['"]?(?:access_token|accessToken|client_secret|clientSecret|refresh_token|refreshToken|password|token|passphrase)['"]?\s*:\s*)(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')/gi;function Ns(e){return e.replace(Ou,(t,n)=>{let r=t[n.length];return`${n}${r}[REDACTED]${r}`})}i(Ns,"redactCredentials");var Lu=1e3,Nu="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",_u={captureError:i(async()=>{},"captureError"),flush:i(async()=>{},"flush")};function Uu(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}i(Uu,"buildRelease");var Mu="192.0.2.0";function Vu(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:Ne(t.filename)},...t.abs_path!==void 0&&{abs_path:Ne(t.abs_path)},...t.module!==void 0&&{module:Ne(t.module)}}))}i(Vu,"scrubStackFrames");function zt(e){return Ns(Fu(Ne(e)))}i(zt,"redactPii");function ju(e){let t={...e.user,email:void 0,username:void 0,ip_address:Mu,id:void 0},n=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?zt(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Vu(s.stacktrace.frames)}}})),r=e.contexts?.cli,o=r!==void 0?Object.fromEntries(Object.entries(r).map(([s,a])=>[s,typeof a=="string"?zt(a):a])):void 0;return{...e,message:e.message!==void 0?zt(e.message):e.message,...typeof e.culprit=="string"&&{culprit:zt(e.culprit)},user:t,server_name:void 0,...n!==void 0&&{exception:{...e.exception,values:n}},...o!==void 0&&{contexts:{...e.contexts,cli:o}}}}i(ju,"scrubPii");function _s(e={}){let t=e.env??process.env;if(Cn(t))return _u;let n=Uu(e),r="production",o=null,s=null;function a(){return{dsn:Nu,release:n,environment:r,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:Ke},contexts:{cli:{applicationId:Ke,node:process.version,platform:process.platform}}},beforeSend:ju}}i(a,"buildInitOptions");async function p(){return o||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),o=c,c}catch{return null}})()),s)}return i(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Ku(c,l))}catch{}},async flush(c=Lu){try{if(!o)return;await o.flush(c)}catch{}}}}i(_s,"createErrorReporter");function Ku(e,t){let n={level:"fatal"},r={applicationId:Ke,node:process.version,platform:process.platform};if(t?.command&&(n.tags={command:t.command},r.command=t.command),Sr(e)&&(e.hint&&(r.hint=e.hint),e.helpUrl&&(r.helpUrl=e.helpUrl),r.shouldReport=e.shouldReport),n.contexts={cli:r},vr(e)&&(n.contexts.http={url:e.requestUrl!==void 0?Ne(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let o=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);n.extra={responseBody:Ns(Ne(o))}}return n}i(Ku,"buildCaptureContext");import{mkdirSync as Bu,readFileSync as Hu,writeFileSync as Gu}from"fs";import{homedir as qu}from"os";import{resolve as Jt}from"path";import{debuglog as Qu}from"util";import{lt as zu,parse as Us}from"semver";var Ju="https://registry.npmjs.org/@cognite/cli/latest",Yu=1500,Ms="upgrade-check.json",Vs=Jt(process.env.XDG_CACHE_HOME||Jt(qu(),".cache"),"@cognite","cli"),lr=Qu("cognite-flows");function Wu(e,t){return!e||!t||!Us(e)||!Us(t)?!1:zu(e,t)}i(Wu,"isOutdated");async function Zu({timeout:e=Yu,registryUrl:t=Ju,fetchImpl:n=globalThis.fetch}={}){if(typeof n!="function")return null;try{let r=await n(t,{signal:AbortSignal.timeout(e)});if(!r?.ok)return null;let o=await r.json();return typeof o?.version=="string"?o.version:null}catch(r){return lr("fetchLatestVersion failed (%s): %O",t,r),null}}i(Zu,"fetchLatestVersion");function Xu(e=Vs,t=864e5){try{let n=Hu(Jt(e,Ms),"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 lr("readUpgradeCheckCache failed (%s): %O",e,n),null}}i(Xu,"readUpgradeCheckCache");function eg(e,t){try{Bu(e,{recursive:!0});let n={latest:t,fetchedAt:Date.now()};Gu(Jt(e,Ms),JSON.stringify(n))}catch(n){lr("writeUpgradeCheckCache failed (%s): %O",e,n)}}i(eg,"writeUpgradeCheckCache");async function tg({cacheDir:e=Vs,...t}={}){let n=await Zu(t);n&&eg(e,n)}i(tg,"startBackgroundUpgradeCheck");function js(e,{onOutdated:t,cacheDir:n,...r}={}){let o=Xu(n);if(o){Wu(e,o.latest)&&t?.(e,o.latest);return}tg({cacheDir:n,...r})}i(js,"preActionUpgradeCheck");import{default as TE,chalkStderr as Ks}from"chalk";function Bs(e,t){let n=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],r=Math.max(...n.map(p=>[...p].length))+2,o="\u2500".repeat(r),s=i(p=>`\u2502 ${p}${" ".repeat(r-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${o}\u2510`,...n.map(s),`\u2514${o}\u2518`].join(`
|
|
333
|
+
`);return Ks.bold.yellow(a)}i(Bs,"formatUpgradeWarning");function ig(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}i(ig,"isDep0040Warning");var mr=process,og=mr.emit.bind(mr);mr.emit=function(e,...t){return e==="warning"&&ig(t[0])?!1:og(e,...t)};Ls();var _e=new rg;_e.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.8.0-alpha.sdk-gen").enablePositionalOptions().showHelpAfterError().configureOutput({writeOut:i(e=>ng(1,e),"writeOut")});_e.hook("preAction",()=>{js("1.8.0-alpha.sdk-gen",{onOutdated:i((e,t)=>{console.warn(`
|
|
334
|
+
${Bs(e,t)}
|
|
335
|
+
`)},"onOutdated")})});hs(_e);Ps(_e);var Gs=ht({packageName:"@cognite/cli",cliVersion:"1.8.0-alpha.sdk-gen"}),Hs=_s({packageName:"@cognite/cli",cliVersion:"1.8.0-alpha.sdk-gen"});Rs(_e,Gs);var dr=process.argv.slice(2);_e.parseAsync(dr,{from:"user"}).catch(async e=>{await Ts(Gs,dr),cr(e)&&(console.error(`
|
|
336
|
+
Cancelled.`),process.exit(130)),(!(e instanceof h)||e.shouldReport)&&(await Hs.captureError(e,{command:pr(dr)}),await Hs.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof h&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
|