@cognite/cli 1.7.1-alpha.1 → 1.8.0-alpha.263
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/README.md +5 -0
- package/_templates/agents/create/EVAL_CASES_TEMPLATE.yaml +77 -0
- package/_templates/agents/create/README_TEMPLATE.md +78 -0
- package/_templates/app/new/config/vitest.config.ts.ejs.t +3 -2
- package/_templates/app/new/root/AGENTS.md.ejs.t +3 -1
- package/_templates/app/new/root/package.json.ejs.t +10 -10
- package/_templates/app/new/src/App.test.tsx.ejs.t +33 -2
- package/_templates/app/new/src/App.tsx.ejs.t +64 -11
- package/dist/chunk-IYQSEWZ2.js +12 -0
- package/dist/cli/cli.js +120 -92
- package/dist/deploy/index.d.ts +43 -11
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +15 -8
- package/dist/chunk-74X2P7OO.js +0 -12
package/dist/deploy/index.d.ts
CHANGED
|
@@ -31,7 +31,7 @@ interface AppMetadata {
|
|
|
31
31
|
name: string;
|
|
32
32
|
description?: string;
|
|
33
33
|
}
|
|
34
|
-
declare const SIGNATURE_STATUSES: readonly ["VALID", "REVOKED", "EXPIRED", "SIGNED_BEFORE_KEY_ISSUED", "IAT_IN_FUTURE", "BUNDLE_TOO_OLD", "KEY_NOT_IN_REGISTRY"];
|
|
34
|
+
declare const SIGNATURE_STATUSES: readonly ["VALID", "REVOKED", "EXPIRED", "SIGNED_BEFORE_KEY_ISSUED", "IAT_IN_FUTURE", "BUNDLE_TOO_OLD", "KEY_NOT_IN_REGISTRY", "SCOPE_MISMATCH", "VERIFICATION_FAILED"];
|
|
35
35
|
type SignatureStatus = (typeof SIGNATURE_STATUSES)[number];
|
|
36
36
|
declare const SIGNER_ROLES: readonly ["developer", "certifier"];
|
|
37
37
|
type SignerRole = (typeof SIGNER_ROLES)[number];
|
|
@@ -86,6 +86,12 @@ declare class AppHostingClient {
|
|
|
86
86
|
getActiveVersion(appExternalId: string): Promise<AppVersion | null>;
|
|
87
87
|
/** Remove the ACTIVE alias from a version, taking it out of service without changing its lifecycle state. */
|
|
88
88
|
deactivateVersion(appExternalId: string, version: string): Promise<void>;
|
|
89
|
+
/** Hard-delete a version. Only DRAFT and ARCHIVED versions can be deleted. */
|
|
90
|
+
deleteVersion(appExternalId: string, version: string): Promise<void>;
|
|
91
|
+
/** PUBLISHED → DEPRECATED */
|
|
92
|
+
deprecateVersion(appExternalId: string, version: string): Promise<void>;
|
|
93
|
+
/** DEPRECATED → ARCHIVED */
|
|
94
|
+
archiveVersion(appExternalId: string, version: string): Promise<void>;
|
|
89
95
|
/**
|
|
90
96
|
* Set the ACTIVE alias on a version. Returns the version that was
|
|
91
97
|
* previously active (if any) so callers can surface "Superseded X"
|
|
@@ -133,22 +139,43 @@ type App = {
|
|
|
133
139
|
versionTag: string;
|
|
134
140
|
};
|
|
135
141
|
|
|
142
|
+
type PackageBundleDeps = {
|
|
143
|
+
existsSync?: (path: string) => boolean;
|
|
144
|
+
mkdir?: (path: string, options: {
|
|
145
|
+
recursive: boolean;
|
|
146
|
+
}) => Promise<unknown>;
|
|
147
|
+
createZip?: (distDir: string, zipFilename: string) => Promise<string>;
|
|
148
|
+
};
|
|
149
|
+
type UploadBundleDeps = {
|
|
150
|
+
readFile?: (path: string) => Promise<Buffer>;
|
|
151
|
+
upload?: (content: Buffer, fileName: string) => Promise<void>;
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* Zip `dist/` into `.cognite-bundles/<externalId>-<versionTag>.zip`.
|
|
155
|
+
*
|
|
156
|
+
* Throws if the bundle file already exists so an accidental overwrite never
|
|
157
|
+
* silently invalidates a previously-signed artefact. The CLI intercepts this
|
|
158
|
+
* condition _before_ the build and login steps; the guard here is the last
|
|
159
|
+
* line of defence for programmatic / CI callers.
|
|
160
|
+
*/
|
|
161
|
+
declare function packageBundle(app: App, folder: string, { existsSync, mkdir: mkdirFn, createZip: createZipFn, }?: PackageBundleDeps): Promise<void>;
|
|
136
162
|
/**
|
|
137
|
-
*
|
|
138
|
-
* and upload it via an already-authenticated `AppHostingClient`. Both deploy
|
|
139
|
-
* entry points (programmatic `deploy()` and the CLI's interactive path) reuse
|
|
140
|
-
* this so packaging/upload behaviour stays in one place.
|
|
163
|
+
* Read the bundle that is already on disk and upload it to App Hosting.
|
|
141
164
|
*
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
* exact bytes the backend received.
|
|
165
|
+
* Does not package anything — the caller is responsible for ensuring
|
|
166
|
+
* `.cognite-bundles/<externalId>-<versionTag>.zip` exists before calling.
|
|
145
167
|
*/
|
|
146
|
-
declare function
|
|
168
|
+
declare function uploadBundle(client: AppHostingApiClient, app: App, folder: string, published: boolean, { readFile: readFileFn, upload: uploadFn, }?: UploadBundleDeps): Promise<void>;
|
|
147
169
|
/**
|
|
148
170
|
* Programmatic deploy used by CI scripts: resolves an SDK from the
|
|
149
|
-
* deployment's env-var credentials,
|
|
171
|
+
* deployment's env-var credentials, packages `dist/`, and uploads.
|
|
150
172
|
*/
|
|
151
173
|
declare const deploy: (deployment: Deployment, app: App, folder: string) => Promise<void>;
|
|
174
|
+
/**
|
|
175
|
+
* Like `deploy` but skips packaging — uploads the existing bundle as-is.
|
|
176
|
+
* Used by the CLI when the user opts to reuse a previously-built bundle.
|
|
177
|
+
*/
|
|
178
|
+
declare const deployBundle: (deployment: Deployment, app: App, folder: string) => Promise<void>;
|
|
152
179
|
|
|
153
180
|
/**
|
|
154
181
|
* Application Packaging
|
|
@@ -185,6 +212,11 @@ declare class SensitiveString {
|
|
|
185
212
|
[inspect.custom](): string;
|
|
186
213
|
/** Returns the raw value. Only call this at a trusted boundary. */
|
|
187
214
|
expose(): string;
|
|
215
|
+
/**
|
|
216
|
+
* Value-equality with another secret, without exposing either. `expose()` is
|
|
217
|
+
* reserved for external boundaries, and an in-process comparison is not one.
|
|
218
|
+
*/
|
|
219
|
+
equals(other: SensitiveString): boolean;
|
|
188
220
|
/** Creates a {@link SensitiveString} wrapping `value`. */
|
|
189
221
|
static from(value: string): SensitiveString;
|
|
190
222
|
}
|
|
@@ -231,4 +263,4 @@ declare const BUNDLE_DIR = ".cognite-bundles";
|
|
|
231
263
|
declare function bundleFileName(externalId: string, versionTag: string): string;
|
|
232
264
|
declare function bundlePath(cwd: string, externalId: string, versionTag: string): string;
|
|
233
265
|
|
|
234
|
-
export { type App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, type Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken,
|
|
266
|
+
export { type App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, type Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, deployBundle, discoverSignatures, getSdk, getToken, packageBundle, uploadBundle };
|
package/dist/deploy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"../chunk-IYQSEWZ2.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,h as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,l as deploy,m as deployBundle,i as discoverSignatures,g as getSdk,f as getToken,j as packageBundle,k as uploadBundle};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, discoverSignatures, getSdk, getToken,
|
|
1
|
+
export { App, AppHostingClient, ApplicationPackager, BUNDLE_DIR, Deployment, SIGNATURE_SUFFIXES, bundleFileName, bundlePath, deploy, deployBundle, discoverSignatures, getSdk, getToken, packageBundle, uploadBundle } from './deploy/index.js';
|
|
2
2
|
import '@cognite/sdk';
|
|
3
3
|
import 'node:util';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-
|
|
1
|
+
import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c,l as d,m as g}from"./chunk-IYQSEWZ2.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,x as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,d as deploy,g as deployBundle,a as discoverSignatures,t as getSdk,p as getToken,b as packageBundle,c as uploadBundle};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cognite/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.0-alpha.263",
|
|
4
4
|
"description": "CLI for Cognite Data Fusion",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
6
6
|
"author": "Cognite",
|
|
@@ -40,31 +40,36 @@
|
|
|
40
40
|
"prepack": "pnpm run build",
|
|
41
41
|
"prepublishOnly": "pnpm run build",
|
|
42
42
|
"test": "vitest run",
|
|
43
|
+
"test:coverage": "vitest run --coverage",
|
|
43
44
|
"test:watch": "vitest",
|
|
44
45
|
"mock:server": "tsx cli/testing/msw/standalone.ts",
|
|
45
46
|
"mock:deploy": "cd ../../apps/mock-app && pnpm build && COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 node ../../packages/cli/dist/cli/cli.js deploy --skip-build",
|
|
46
47
|
"refresh-spec-kit": "bash scripts/refresh-spec-kit.sh"
|
|
47
48
|
},
|
|
48
49
|
"dependencies": {
|
|
49
|
-
"@
|
|
50
|
+
"@ai-sdk/provider": "^2.0.0",
|
|
51
|
+
"@arizeai/phoenix-evals": "^1.0.3",
|
|
52
|
+
"@cognite/app-sdk": "^0.8.0",
|
|
50
53
|
"@cognite/sdk": "^10.10.0",
|
|
51
54
|
"@napi-rs/keyring": "^1.3.0",
|
|
52
55
|
"@sentry/node": "^10.51.0",
|
|
53
56
|
"@zip.js/zip.js": "^2.7.0",
|
|
54
57
|
"chalk": "^5.6.2",
|
|
55
58
|
"clipboardy": "5.3.1",
|
|
56
|
-
"commander": "^
|
|
59
|
+
"commander": "^15.0.0",
|
|
57
60
|
"dotenv": "^17.4.2",
|
|
58
61
|
"enquirer": "^2.4.1",
|
|
59
62
|
"execa": "^5.1.1",
|
|
60
63
|
"hygen": "^6.2.11",
|
|
61
64
|
"jose": "^6.2.2",
|
|
62
|
-
"mixpanel": "^0.
|
|
65
|
+
"mixpanel": "^0.22.0",
|
|
63
66
|
"open": "^10.1.0",
|
|
64
67
|
"openid-client": "^6.8.3",
|
|
68
|
+
"proper-lockfile": "^4.1.2",
|
|
65
69
|
"semver": "^7.7.0",
|
|
66
70
|
"skills": "^1.4.3",
|
|
67
|
-
"valibot": "^1.3.1"
|
|
71
|
+
"valibot": "^1.3.1",
|
|
72
|
+
"yaml": "^2.9.0"
|
|
68
73
|
},
|
|
69
74
|
"peerDependencies": {
|
|
70
75
|
"react": ">=18.0.0",
|
|
@@ -83,19 +88,21 @@
|
|
|
83
88
|
"@types/ejs": "^3.1.5",
|
|
84
89
|
"@types/express": "^5.0.6",
|
|
85
90
|
"@types/node": "^24.10.1",
|
|
91
|
+
"@types/proper-lockfile": "^4.1.4",
|
|
86
92
|
"@types/react": "^19.2.6",
|
|
87
93
|
"@types/react-dom": "^19.2.3",
|
|
88
94
|
"@types/semver": "^7.7.0",
|
|
89
|
-
"ejs": "^
|
|
95
|
+
"ejs": "^6.0.0",
|
|
90
96
|
"express": "^5.2.1",
|
|
91
97
|
"msw": "^2.13.6",
|
|
92
98
|
"react": "^19.2.6",
|
|
93
99
|
"react-dom": "^19.2.6",
|
|
94
100
|
"tsup": "^8.4.0",
|
|
95
101
|
"typescript": "^5.0.0",
|
|
96
|
-
"vitest": "4.1.
|
|
102
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
103
|
+
"vitest": "4.1.10"
|
|
97
104
|
},
|
|
98
105
|
"engines": {
|
|
99
|
-
"node": ">=20"
|
|
106
|
+
"node": ">=20 <22.23.0 || >=22.23.1 <24.17.0 || >=24.18.0 <26.3.1 || >=26.4.0"
|
|
100
107
|
}
|
|
101
108
|
}
|
package/dist/chunk-74X2P7OO.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
var we=Object.defineProperty;var ee=n=>{throw TypeError(n)};var o=(n,e)=>we(n,"name",{value:e,configurable:!0});var te=(n,e,t)=>e.has(n)||ee("Cannot "+t);var ne=(n,e,t)=>(te(n,e,"read from private field"),t?t.call(n):e.get(n)),re=(n,e,t)=>e.has(n)?ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),ie=(n,e,t,r)=>(te(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{mkdir as nt,readFile as rt}from"fs/promises";import{basename as it,dirname as ot}from"path";var F=class F extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:xe(e.cause)}}};o(F,"HintedError");var d=F;var oe="https://docs.cognite.com/cdf/access/",ve="https://status.cognite.com";function ke(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:oe};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:oe};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:ve};default:return{}}}o(ke,"defaultHintForStatus");var _=class _ extends d{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ke(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};o(_,"HintedHttpError");var v=_;function Ce(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(Ce,"hintForErrno");function xe(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=Ce(r.code,r);if(i!==void 0)return i;e=r.cause}}o(xe,"hintForCause");import{inspect as Ie}from"util";var L="[REDACTED]",x,R=class R{constructor(e){re(this,x);ie(this,x,e)}toString(){return L}toJSON(){return L}[Ie.custom](){return L}expose(){return ne(this,x)}static from(e){return new R(e)}};x=new WeakMap,o(R,"SensitiveString");var S=R;var se="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}o(g,"isRecord");function I(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}o(I,"isHttpError");function Pe(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
-
See: ${se}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
-
See: ${se}`;default:return}}o(Pe,"httpStatusHint");function m(n){let e=n instanceof Error?n:new Error(String(n));if(!I(e))return null;let t=Pe(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
-
${t}`),{cause:e}):null}o(m,"enrichedHttpError");function Te(n){if(!g(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(g(t)){let r=t.error;if(g(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}o(Te,"findMissingArray");function be(n,e){if(!I(n)||n.status!==400)return!1;let t=Te(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}o(be,"isMissingExternalIdError");function D(n,e){return I(n)&&n.status===404||be(n,e)}o(D,"isNotFoundError");var pe=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ce=["ACTIVE","PREVIEW"],H=class H extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};o(H,"AppVersionNotFoundError");var $=H,B=class B extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};o(B,"AppNotFoundError");var U=B;function N(n,e){return n.includes(e)}o(N,"includesValue");function Re(n){return N(pe,n)}o(Re,"isAppVersionLifecycleState");function De(n){return N(ce,n)}o(De,"isAppVersionAlias");function $e(n){return typeof n.version=="string"&&Re(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||De(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}o($e,"isAppVersion");function ae(n){if(!g(n)){let e=JSON.stringify(n)?.slice(0,200)??String(n);throw new Error(`Invalid version response: expected object, got ${e}`)}if(!$e(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}o(ae,"parseAppVersion");function Ue(n){if(!g(n))throw new Error("Invalid app response: not an object");let{externalId:e,name:t,description:r}=n;if(typeof e!="string")throw new Error("Invalid app response: missing externalId");if(typeof t!="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:e,name:t,description:typeof r=="string"?r:void 0}}o(Ue,"parseAppMetadata");var M=class M{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(i){throw m(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw m(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Ue(r.data)}catch(r){throw D(r,[e])?new U(e):m(r)??r}}async uploadVersion(e,t,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),i),a.append("version",t),a.append("entryPath",s);let c=encodeURIComponent(e),p=`${this.appsBasePath}/${c}/versions`,u=await this.client.authenticate();if(!u)throw new d("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let E=S.from(u),f=`${this.client.getBaseUrl()}${p}`,X=new AbortController,Ee=setTimeout(()=>X.abort(),300*1e3),A;try{A=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${E.expose()}`},body:a,signal:X.signal})}catch(h){throw h instanceof Error&&h.name==="AbortError"?new d("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 d(`Failed to upload version to ${f}`,{cause:h,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Ee)}if(!A.ok){let h=await A.text(),w;try{w=JSON.parse(h)}catch{}let b=h;if(g(w)){let k=w.error;if(typeof k=="string")b=k;else if(g(k)){let C=k.message,Q=k.code;b=typeof C=="string"?C:Q!=null?`Unknown error (code: ${Q})`:h}else{let C=w.message;b=typeof C=="string"?C:h}}let Z=A.headers.get("x-request-id"),Se=Z?` | X-Request-ID: ${Z}`:"",Ae=g(w)?w:h;throw new v(`Upload failed: ${A.status} \u2014 ${b}${Se}`,{httpStatusCode:A.status,requestUrl:f,responseBody:Ae})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(s);return ae(a.data)}catch(a){throw D(a,[e,t])?new $(e,t):m(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/versions/list`;try{let i=await this.client.post(r,{data:{filter:{aliases:["ACTIVE"]}}});if(!g(i.data)||!Array.isArray(i.data.items))throw new Error("Invalid versions/list response: expected an object with an items array");let{items:s}=i.data;if(s.length===0)return null;if(s.length>1)throw new Error(`Unexpected response: ${s.length} versions have the ACTIVE alias, expected at most 1`);return ae(s[0])}catch(i){if(D(i,[e]))return null;throw m(i)??i}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(s){throw m(s)??s}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw m(c)??c}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Oe(a.data)}catch(a){throw m(a)??a}}};o(M,"AppHostingApi");var V=M,Ne=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ve=["developer","certifier"];function Oe(n){if(!g(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=Fe(t);return r?[r]:[]})}o(Oe,"parseStoredSignatures");function Fe(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!N(Ve,t)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!N(Ne,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:s,status:a}}o(Fe,"parseStoredSignature");function _e(n,e){let t=[];n.name!==e.name&&t.push({field:"name",remote:n.name,local:e.name});let r=n.description??"";return r!==e.description&&t.push({field:"description",remote:r,local:e.description}),t}o(_e,"diffAppMetadata");function Le(n){let e=["Cannot deploy: metadata in app.json differs from what's deployed:"];for(let{field:t,remote:r,local:i}of n){let s=`${t}:`.padEnd(14);e.push(` ${s}"${r}" \u2192 "${i}"`)}return e.join(`
|
|
5
|
-
`)}o(Le,"formatMetadataDriftError");var j=class j{constructor(e){this.api=new V(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,s){return this.api.uploadVersion(e,t,r,i,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(i){if(I(i)&&i.status===409){console.log(`\u2705 App '${e}' already exists`),await this.checkMetadataDrift(e,t,r);return}throw i}}async checkMetadataDrift(e,t,r){let i;try{i=await this.getApp(e)}catch{return}let s=_e(i,{name:t,description:r});if(s.length!==0)throw new d(Le(s),{hint:"Run npx @cognite/cli apps metadata update to sync before deploying",shouldReport:!1})}getApp(e){return this.api.getApp(e)}async updateAppMetadata(e,t,r){await this.api.updateApps([{externalId:e,update:{name:{set:t},description:r?{set:r}:{setNull:!0}}}])}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let i=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(e,t,r,i,s,a,c=!1){console.log(`
|
|
6
|
-
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
-
`),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,s,a),c&&await this.publishAndActivate(e,i),console.log(`
|
|
8
|
-
\u2705 Deployment successful!`)}};o(j,"AppHostingClient");var P=j;import{execFileSync as O}from"child_process";import y from"fs";import l from"path";import{parseAndValidateManifestConfig as He}from"@cognite/app-sdk/vite";import{BlobReader as Be,Uint8ArrayWriter as Me,ZipWriter as je}from"@zip.js/zip.js";var q="package.json",J="package-lock.json",ue="manifest.json",G=".cognite",qe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],Y=class Y{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,q);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,J);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new je(new Me,{level:9}),i=o(async(p,u)=>{await r.add(u,new Be(await y.openAsBlob(p))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=o(async p=>{let u=await y.promises.readdir(p,{withFileTypes:!0});for(let E of u){let f=l.join(p,E.name);E.isDirectory()?await s(f):await i(f,l.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let p=l.join(this.appRoot,q);await i(p,l.posix.join(G,q));let u=l.join(this.appRoot,ue);if(y.existsSync(u)){let f=y.readFileSync(u,"utf-8");He(f,u),await i(u,l.posix.join(G,ue))}let E=l.join(this.appRoot,J);await i(E,l.posix.join(G,J)),a=await r.close()}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${u}`)}try{await y.promises.writeFile(e,a)}catch(p){throw new d(`Failed to write bundle to ${e}`,{cause:p})}let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${c} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=O("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(p){throw p instanceof Error&&"code"in p&&p.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=O("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,s);try{O("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(p){let u=p instanceof Error?p.message:String(p);throw new Error(`Failed to create source archive: ${u}`)}let c=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${c} MB)`),e}validateNoSensitiveFiles(e,t){let r=O("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
9
|
-
`).filter(Boolean),i=o(a=>a.split("/").some(c=>qe.some(p=>p.test(c))),"isSensitive"),s=r.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
10
|
-
`+s.map(a=>` ${a}`).join(`
|
|
11
|
-
`)+`
|
|
12
|
-
Hint: git rm --cached <file>`)}};o(Y,"ApplicationPackager");var T=Y;import Je from"path";var de=".cognite-bundles";function le(n,e){return`${n}-${e}.zip`}o(le,"bundleFileName");function z(n,e,t){return Je.join(n,de,le(e,t))}o(z,"bundlePath");import{CogniteClient as tt}from"@cognite/sdk";function Ge(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}o(Ge,"exponentialBackoffWithJitter");function Ye(n){return new Promise(e=>setTimeout(e,n))}o(Ye,"sleep");async function ge(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Ge;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let c=i(s);e.onAttemptFail?.(a,s,c),await Ye(c),s++}}o(ge,"retryAsync");var ze="https://auth.cognite.com/oauth2/token",Ke=o(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function fe({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await ge(()=>fetch(e,t),{maxAttempts:3})}catch(c){throw new d(`Failed to fetch access token from ${e}`,{cause:c})}if(!i.ok){let c=await i.text();throw new v(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:c})}let s=await i.text(),a;try{a=JSON.parse(s)}catch{throw new d(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!Ke(a))throw new d(`No access token in ${n} authentication response`,{hint:r});return S.from(a.access_token)}o(fe,"fetchOAuthToken");var We=o(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,i]of Object.entries(e))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Xe=o(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=We()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return S.from(e)},"getSecretFromEnv"),Ze=o((n,e)=>{let t=e.expose();return fe({idp:"CDF",tokenUrl:ze,init:{method:"POST",headers:{Authorization:`Basic ${btoa(`${n}:${t}`)}`,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})},missingTokenHint:"Check the client ID in app.json and the deployment secret in your environment."})},"getTokenCdf"),he=o(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:s})=>fe({idp:n,tokenUrl:e,init:{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:t,client_secret:r,grant_type:"client_credentials",...i!==void 0?{scope:i.join(" ")}:{}})},missingTokenHint:s}),"getTokenWithClientCredentials"),Qe=o((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");try{return`${new URL(n).origin}/.default`}catch{throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`)}},"resolveEntraScope"),et=o((n,e,t,r,i)=>he({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[Qe(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),K=o(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return S.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:c,tokenUrl:p}=n,u=Xe(r);if(i==="oauth"){if(!p)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return he({idp:"OAuth",tokenUrl:p,clientId:t,clientSecret:u.expose(),scopes:c,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return et(t,u,s,a,c)}return Ze(t,u)},"getToken");async function W(n,e,t=process.env,r){let i=await K(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new tt(c)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:o(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}o(W,"getSdk");async function me(n,e,t,r){let{externalId:i,name:s,description:a,versionTag:c}=e,p=z(t,i,c);await nt(ot(p),{recursive:!0}),await new T(`${t}/dist`).createZip(p,!0);let u;try{u=await rt(p)}catch(E){throw new d(`Failed to read bundle file: ${p}`,{cause:E})}await new P(n).deploy(i,s,a,c,u,it(p),r)}o(me,"packageAndUpload");var st=o(async(n,e,t)=>{let r=await W(n,t);await me(r,e,t,n.published)},"deploy");import{existsSync as at,readFileSync as pt}from"fs";var ye=[".dev.sig",".cert.sig"];function ct(n,e={}){let t=e.existsSync??at,r=e.readFileSync??((s,a)=>pt(s,a)),i=[];for(let s of ye){let a=`${n}${s}`;if(!t(a))continue;let c=r(a,"utf8").trim();c.length>0&&i.push(c)}return i}o(ct,"discoverSignatures");export{P as a,T as b,de as c,le as d,z as e,K as f,W as g,me as h,st as i,ye as j,ct as k};
|