@cognite/cli 1.3.4-alpha.selfsigned → 1.4.0

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/LICENSE.md ADDED
@@ -0,0 +1,6 @@
1
+ Commercial Software Licence Agreement
2
+
3
+ Copyright (c) Cognite AS 2026
4
+
5
+ See Master Subscription and Professional Services Agreement for details:
6
+ https://www.cognite.com/en/company/legal/master-subscription-services-agreement-2025
package/README.md CHANGED
@@ -47,6 +47,18 @@ Browse available skills at [cognitedata/builder-skills](https://github.com/cogni
47
47
  - Node.js ≥ 20
48
48
  - React ≥ 18 (optional peer dependency — only needed for auth components)
49
49
 
50
+ ## Telemetry
51
+
52
+ `@cognite/cli` collects anonymous usage data (commands run, success/failure, CLI and Node.js versions) to help improve the tool.
53
+
54
+ To opt out:
55
+
56
+ ```bash
57
+ export COGNITE_TELEMETRY_DISABLED=1
58
+ ```
59
+
60
+ `DO_NOT_TRACK=1` is also honoured.
61
+
50
62
  ## Development
51
63
 
52
64
  ### Running tests
@@ -0,0 +1,11 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.mcp.json'
3
+ ---
4
+ {
5
+ "mcpServers": {
6
+ "cognite-docs": {
7
+ "type": "http",
8
+ "url": "https://docs.cognite.com/mcp"
9
+ }
10
+ }
11
+ }
@@ -3,17 +3,20 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>vite.config.ts'
3
3
  ---
4
4
  import path from 'node:path';
5
5
 
6
- import { fusionOpenPlugin, manifestCspPlugin } from '@cognite/app-sdk/vite';
6
+ import {
7
+ fusionOpenPlugin,
8
+ manifestCspPlugin,
9
+ mkcertPlugin,
10
+ } from '@cognite/app-sdk/vite';
7
11
  import tailwindcss from '@tailwindcss/vite';
8
12
  import react from '@vitejs/plugin-react';
9
13
  import { defineConfig } from 'vite';
10
- import mkcert from 'vite-plugin-mkcert';
11
14
 
12
15
  export default defineConfig({
13
16
  base: './',
14
17
  // manifestCspPlugin() must stay first — its middleware sets the
15
18
  // Content-Security-Policy header before any HTML response is sent.
16
- plugins: [manifestCspPlugin(), react(), mkcert(), fusionOpenPlugin(), tailwindcss()],
19
+ plugins: [manifestCspPlugin(), react(), mkcertPlugin(), fusionOpenPlugin(), tailwindcss()],
17
20
  resolve: {
18
21
  alias: {
19
22
  '@': path.resolve(__dirname, './src'),
@@ -10,5 +10,10 @@ export default defineConfig({
10
10
  globals: true,
11
11
  environment: 'happy-dom',
12
12
  setupFiles: ['vitest.setup.ts'],
13
+ coverage: {
14
+ provider: 'v8',
15
+ reporter: ['text', 'json', 'html', 'lcov'],
16
+ exclude: ['node_modules/', 'dist/', 'vitest.setup.ts', '**/*.config.ts', '**/*.d.ts'],
17
+ },
13
18
  },
14
19
  });
@@ -0,0 +1,10 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.cursor/mcp.json'
3
+ ---
4
+ {
5
+ "mcpServers": {
6
+ "cognite-docs": {
7
+ "url": "https://docs.cognite.com/mcp"
8
+ }
9
+ }
10
+ }
@@ -2,4 +2,4 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.npmrc'
3
3
  ---
4
4
  engine-strict=true
5
- min-release-age=2
5
+ min-release-age=1
@@ -22,11 +22,69 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
22
22
 
23
23
  ---
24
24
 
25
- ## 1. Dependency Injection
25
+ ## 1. UI Components
26
26
 
27
- Inject dependencies via React context (hooks/components) or factory-override pattern (plain functions). Never hard-code dependencies.
27
+ Always check `@cognite/aura/components` before reaching for a raw HTML element or custom CSS/Tailwind solution. If Aura has a component that covers the need, use it. Only fall back to custom solutions when Aura genuinely doesn't cover the use case.
28
28
 
29
- ### React context
29
+ ---
30
+
31
+ ## 2. Host integration (`@cognite/app-sdk`)
32
+
33
+ The Fusion host exposes a `HostAppAPI` (imported as `HostAppAPI` from `@cognite/app-sdk`) via `connectToHostApp(...)`. Reach for it whenever the situation calls for it — don't hand-roll an equivalent or read browser globals directly.
34
+
35
+ ### Decision rule for any new piece of state
36
+
37
+ Before adding `useState`, `useReducer`, or a store entry, ask: **"would a user expect this to survive a page reload, or to be restored when someone opens a shared link?"** If yes, it belongs in `syncInternalState` + `initialState`, **not** in plain React state.
38
+
39
+ - **Yes, host-synced:** current page / active view / route, selected tab, active filters, selected resource id, search query, sort order, expanded rows, focused row, side-panel open/closed — anything that drives what the user sees.
40
+ - **No, local-only:** in-flight form input before submit, hover/focus, transient toasts, animation state, optimistic UI mid-flight.
41
+
42
+ When in doubt, host-synced is the safer default — over-syncing is cheap, under-syncing breaks reload and share.
43
+
44
+ ### API surface
45
+
46
+ - **Host-synced UI state** → on startup, seed your state from the `initialState` string returned by `connectToHostApp`. On every change, call `api.syncInternalState(JSON.stringify(state))`. The host serializes this into the URL so reloads and shared links restore the same state. **Do not** hold state from the "host-synced" category above in plain `useState` / `useRef` / a local store.
47
+ - **Navigating elsewhere in Fusion** (another app, a Fusion route) → `api.navigateInternal({ path, queryParams, hash })`. Never set `window.location` directly.
48
+ - **Navigating to an external URL** → `api.navigateExternal({ url, openInNewTab })`. Only `https:` is allowed.
49
+ - **Needing a CDF base URL or access token** for API requests → `api.getBaseUrl()` / `api.getAccessToken()`. Never hardcode the cluster URL.
50
+ - **Needing the current CDF project name** → `api.getProject()`. Don't read it from config or URL params.
51
+ - **Exposing the app's capabilities to a Fusion agent** → register a custom agent server with `api.registerAgentServer(handle)` and clean up on unmount with `api.unregisterAgentServer(uri)`.
52
+
53
+ Get `api` once at app startup and surface it to the rest of the app via React context so view models can depend on it through the patterns below.
54
+
55
+ ### Round-trip example: host-synced state
56
+
57
+ ```typescript
58
+ import { connectToHostApp, type HostAppAPI } from '@cognite/app-sdk';
59
+
60
+ type AppState = { page: 'a' | 'b'; filters: string[] };
61
+ const DEFAULT_STATE: AppState = { page: 'a', filters: [] };
62
+
63
+ // On startup — seed from initialState, not from a hardcoded default.
64
+ const { api, initialState } = await connectToHostApp({ applicationName: '<%= name %>' });
65
+ const seeded: AppState = initialState ? (JSON.parse(initialState) as AppState) : DEFAULT_STATE;
66
+
67
+ // On every change — push the new state to the host so the URL stays in sync.
68
+ async function updateState(next: AppState, api: HostAppAPI) {
69
+ setState(next); // your local React/store setter
70
+ await api.syncInternalState(JSON.stringify(next));
71
+ }
72
+ ```
73
+
74
+ `initialState` is the JSON string the host extracted from the URL on this load — the host owns the URL plumbing, the app just reads/writes the string.
75
+
76
+ ---
77
+
78
+ ## 3. Dependency Injection
79
+
80
+ **All non-stateless dependencies must be injected.** Never import and call a service, SDK client, or stateful module directly inside a component or hook — it makes the code untestable and tightly coupled.
81
+
82
+ What to inject: SDK clients, API services, analytics, timers (`Date.now`, `setTimeout`), random generators, external stores.
83
+ What not to inject: pure functions, constants, type utilities.
84
+
85
+ Use **narrow interfaces** — depend only on the subset of a service you actually need.
86
+
87
+ ### React context (hooks and components)
30
88
 
31
89
  ```typescript
32
90
  const defaultDeps = { useDataSource, useAnalytics };
@@ -38,7 +96,7 @@ export function useMyHook() {
38
96
  }
39
97
  ```
40
98
 
41
- ### Factory overrides
99
+ ### Factory overrides (plain functions)
42
100
 
43
101
  ```typescript
44
102
  type Deps = { serviceFactory: () => SomeService };
@@ -51,7 +109,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
51
109
 
52
110
  ---
53
111
 
54
- ## 2. Interface-Based Services
112
+ ## 4. Interface-Based Services
55
113
 
56
114
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
57
115
 
@@ -68,7 +126,7 @@ export class ApiDataService implements DataService {
68
126
 
69
127
  ---
70
128
 
71
- ## 3. ViewModel Pattern
129
+ ## 5. ViewModel Pattern
72
130
 
73
131
  Business logic lives in `use<Name>ViewModel`. Components only render.
74
132
 
@@ -89,9 +147,26 @@ export const TodoView = () => {
89
147
  };
90
148
  ```
91
149
 
150
+ ### Where state lives
151
+
152
+ A ViewModel hook must **not** hold state with `useState` / `useReducer` directly. State lives in a shared storage layer — a context-backed hook (like `useTodoStorage` above), a store, or a `*StateProvider` rendered once near the root of the view tree. The ViewModel composes that storage with commands and derivations; it is itself stateless.
153
+
154
+ This matters because each call to a `useState`-backed hook creates an **independent** piece of React state. Two components calling the same ViewModel hook would each get their own copy and never sync.
155
+
156
+ > ⚠️ Anti-pattern: `useState` inside `useFooViewModel`, then two sibling components each call `useFooViewModel()`. Clicks update one copy; the other renders stale data.
157
+
158
+ ### How many times to call a ViewModel hook
159
+
160
+ - **Backed by shared context / store** → multiple components may call the hook; they all observe the same value. This is the default for non-trivial views.
161
+ - **Not backed by shared state** → call the hook **once** at the top of the view tree and pass values down as props. Never call it twice and expect them to stay in sync.
162
+
163
+ ### Host-synced state inside a ViewModel
164
+
165
+ When a ViewModel exposes state that falls under §2's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
166
+
92
167
  ---
93
168
 
94
- ## 4. Test-First Development
169
+ ## 6. Test-First Development
95
170
 
96
171
  Write tests before implementation for all non-trivial behavior changes.
97
172
 
@@ -187,21 +262,41 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
187
262
 
188
263
  ---
189
264
 
190
- ## 5. TypeScript Rules
265
+ ## 7. TypeScript Rules
191
266
 
192
267
  - Never use `any`; prefer `unknown` or explicit strong types
193
- - Never use `as unknown as T`; for partial test doubles use `{ ...defaults, ...overrides } as T`
268
+ - Never use `as` casts they silence the compiler without providing safety. Use type guards instead.
269
+ - Exception: `Partial<T> as T` is acceptable for test mocks only.
270
+ - All function parameters must have type annotations.
194
271
  - Use direct React type imports: `import type { ComponentType, ReactNode } from 'react'`
195
272
 
196
273
  ```typescript
197
- function createMockWindow(overrides: Partial<Window> = {}): Window {
198
- return { postMessage: vi.fn(), ...overrides } as Window;
274
+ // Never
275
+ const x: any = data;
276
+ const y = data as SomeType;
277
+ const z = {} as unknown as Window;
278
+ function process(data) { ... } // missing parameter type
279
+
280
+ // ✅ Type guard
281
+ function isSomeType(value: unknown): value is SomeType {
282
+ return typeof value === 'object' && value !== null && 'id' in value;
199
283
  }
284
+ if (isSomeType(data)) { /* TypeScript now knows */ }
285
+
286
+ // ✅ Test mock only
287
+ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
200
288
  ```
201
289
 
202
290
  ---
203
291
 
204
- ## 6. Commits and pull requests
292
+ ## 8. CogniteClient / authentication
293
+
294
+ Auth is handled by `CogniteSdkProvider` from `@cognite/app-sdk/react` (see `App.tsx`). Nested components get the client via `useCogniteSdk()`. To wire up or migrate auth, run the `/setup-flows-auth` skill.
295
+
296
+ ---
297
+
298
+
299
+ ## 9. Commits and pull requests
205
300
 
206
301
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
207
302
 
@@ -6,6 +6,13 @@ node_modules
6
6
 
7
7
  # Build output
8
8
  dist
9
+ coverage
10
+
11
+ # Retained app bundles from `cognite apps deploy` (signed before publish)
12
+ .cognite-bundles
13
+
14
+ # Local HTTPS certificates from `cognite apps setup-https`
15
+ certificates
9
16
 
10
17
  # Environment variables
11
18
  .env
@@ -18,15 +18,17 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
18
18
  "test": "vitest run",
19
19
  "test:watch": "vitest",
20
20
  "test:ui": "vitest --ui",
21
+ "test:coverage": "vitest run --coverage",
21
22
  "lint": "eslint . --ext .js,.mjs,.cjs,.ts,.tsx",
22
23
  "lint:fix": "eslint . --fix --ext .js,.mjs,.cjs,.ts,.tsx",
23
24
  "deploy": "npx @cognite/cli@latest apps deploy --interactive",
24
- "activate": "npx @cognite/cli@latest apps activate --interactive"
25
+ "activate": "npx @cognite/cli@latest apps activate --interactive",
26
+ "setup-https": "npx @cognite/cli@latest apps setup-https"
25
27
  },
26
28
  "dependencies": {
27
29
  "@cognite/aura": "^0.1.7",
28
30
  "@cognite/sdk": "^10.3.0",
29
- "@cognite/app-sdk": "^0.4.0",
31
+ "@cognite/app-sdk": "^0.5.1",
30
32
  "@tabler/icons-react": "^3.35.0",
31
33
  "@tanstack/react-query": "^5.90.10",
32
34
  "clsx": "^2.1.1",
@@ -44,6 +46,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
44
46
  "@types/react": "^18.3.1",
45
47
  "@types/react-dom": "^18.3.1",
46
48
  "@vitejs/plugin-react": "^5.1.1",
49
+ "@vitest/coverage-v8": "^2.1.8",
47
50
  "@vitest/ui": "^2.1.8",
48
51
  "autoprefixer": "^10.4.22",
49
52
  "eslint": "9.39.4",
@@ -58,7 +61,6 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
58
61
  "typescript": "^5.0.0",
59
62
  "typescript-eslint": "^8.46.4",
60
63
  "vite": "7.3.2",
61
- "vite-plugin-mkcert": "^1.17.9",
62
64
  "vitest": "^2.1.8"
63
65
  }
64
66
  }
@@ -1,13 +1,45 @@
1
1
  ---
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.test.tsx'
3
3
  ---
4
- import * as appSdk from '@cognite/app-sdk';
5
4
  import { render, screen, waitFor } from '@testing-library/react';
6
5
  import { beforeEach, describe, expect, it, vi } from 'vitest';
6
+ import type { HostAppAPI, ConnectToHostAppResult } from '@cognite/app-sdk';
7
+ import { CogniteClient } from '@cognite/sdk';
8
+ import type { ComponentProps } from 'react';
7
9
 
8
10
  import App from './App';
9
11
 
10
- vi.mock(import('@cognite/app-sdk'));
12
+ type AppDeps = NonNullable<ComponentProps<typeof App>['deps']>;
13
+
14
+ function makeApi(): HostAppAPI {
15
+ return {
16
+ getProject: vi.fn<HostAppAPI['getProject']>(() => Promise.resolve('<%= project %>')),
17
+ getBaseUrl: vi.fn<HostAppAPI['getBaseUrl']>(() => Promise.resolve('https://cognite.test')),
18
+ getAccessToken: vi.fn<HostAppAPI['getAccessToken']>(() => Promise.resolve('test-token')),
19
+ getAppId: vi.fn<HostAppAPI['getAppId']>(() => Promise.resolve('test-app-id')),
20
+ syncInternalState: vi.fn<HostAppAPI['syncInternalState']>(() => Promise.resolve(true)),
21
+ navigateInternal: vi.fn<HostAppAPI['navigateInternal']>(() => Promise.resolve(true)),
22
+ navigateExternal: vi.fn<HostAppAPI['navigateExternal']>(() => Promise.resolve(true)),
23
+ registerAgentServer: vi.fn<HostAppAPI['registerAgentServer']>(() => Promise.resolve()),
24
+ unregisterAgentServer: vi.fn<HostAppAPI['unregisterAgentServer']>(() => Promise.resolve()),
25
+ sendAgentLayoutMode: vi.fn<HostAppAPI['sendAgentLayoutMode']>(() => Promise.resolve()),
26
+ sendAgentMessage: vi.fn<HostAppAPI['sendAgentMessage']>(() => Promise.resolve()),
27
+ };
28
+ }
29
+
30
+ function makeLoadingDeps(): AppDeps {
31
+ return {
32
+ connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => new Promise<ConnectToHostAppResult>(() => undefined)),
33
+ createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
34
+ };
35
+ }
36
+
37
+ function makeConnectedDeps(): AppDeps {
38
+ return {
39
+ connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api: makeApi() })),
40
+ createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
41
+ };
42
+ }
11
43
 
12
44
  describe('App', () => {
13
45
  beforeEach(() => {
@@ -15,19 +47,13 @@ describe('App', () => {
15
47
  });
16
48
 
17
49
  it('renders loading state', () => {
18
- vi.mocked(appSdk.connectToHostApp).mockReturnValue(new Promise(() => {}));
19
-
20
- render(<App />);
50
+ render(<App deps={makeLoadingDeps()} />);
21
51
  expect(screen.getByText('Loading project...')).toBeInTheDocument();
22
52
  });
23
53
 
24
54
  it('renders splash with deployment targets and checklist copy', async () => {
25
- vi.mocked(appSdk.connectToHostApp).mockResolvedValue({
26
- api: { getProject: vi.fn().mockResolvedValue('my-test-project') } as Partial<appSdk.HostAppAPI> as appSdk.HostAppAPI,
27
- });
28
-
29
- render(<App />);
30
- await waitFor(() => expect(screen.getByText('Welcome to Flows')).toBeInTheDocument());
55
+ render(<App deps={makeConnectedDeps()} />);
56
+ await waitFor(() => expect(screen.getByText('Welcome to Flows custom apps')).toBeInTheDocument());
31
57
  expect(screen.getByText('App deployment checklist')).toBeInTheDocument();
32
58
  expect(screen.getByText('Plan')).toBeInTheDocument();
33
59
  expect(screen.getByText('Explore')).toBeInTheDocument();
@@ -1,7 +1,8 @@
1
1
  ---
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.tsx'
3
3
  ---
4
- import { connectToHostApp } from '@cognite/app-sdk';
4
+ import type { ComponentProps } from 'react';
5
+ import { CogniteSdkProvider, useCogniteSdk } from '@cognite/app-sdk/react';
5
6
  import {
6
7
  Alert,
7
8
  AlertDescription,
@@ -18,7 +19,6 @@ import {
18
19
  Separator,
19
20
  } from '@cognite/aura/components';
20
21
  import { IconCaretUpDown, IconRocket } from '@tabler/icons-react';
21
- import { useEffect, useState } from 'react';
22
22
 
23
23
  import appConfig from '../app.json';
24
24
 
@@ -62,71 +62,41 @@ const CHECKLIST_STEPS = [
62
62
  },
63
63
  ] as const;
64
64
 
65
- function App() {
66
- // Connect to the Fusion host via @cognite/app-sdk. The handshake is
67
- // asynchronous `project` is only populated after Comlink finishes
68
- // exposing the host API, so we render a loader until then.
69
- const [project, setProject] = useState<string | null>(null);
70
- const [isLoading, setIsLoading] = useState(true);
71
- const [error, setError] = useState<string | undefined>();
72
-
73
- useEffect(() => {
74
- let cancelled = false;
75
- connectToHostApp({ applicationName: '<%= name %>' })
76
- .then(async ({ api }) => {
77
- if (cancelled) return;
78
- const proj = await api.getProject();
79
- if (cancelled) return;
80
- setProject(proj);
81
- })
82
- .catch((err: unknown) => {
83
- if (cancelled) return;
84
- setError(err instanceof Error ? err.message : String(err));
85
- })
86
- .finally(() => {
87
- if (!cancelled) setIsLoading(false);
88
- });
89
- return () => {
90
- cancelled = true;
91
- };
92
- }, []);
93
-
94
- if (isLoading) {
95
- return (
96
- <main className="min-h-screen bg-muted/50 text-foreground">
97
- <section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
98
- <div className="mx-auto w-full max-w-sm">
99
- <Card aria-label="Loading project" aria-live="polite">
100
- <CardContent>
101
- <div className="inline-flex items-center gap-3 text-muted-foreground">
102
- <Loader size={20} />
103
- <span>Loading project...</span>
104
- </div>
105
- </CardContent>
106
- </Card>
107
- </div>
108
- </section>
109
- </main>
110
- );
111
- }
112
-
113
- if (error) {
114
- return (
115
- <main className="min-h-screen bg-muted/50 text-foreground">
116
- <section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
117
- <div className="mx-auto w-full max-w-sm">
118
- <Alert>
119
- <AlertDescription>Failed to connect to Fusion host: {error}</AlertDescription>
120
- </Alert>
121
- </div>
122
- </section>
123
- </main>
124
- );
125
- }
65
+ const loadingFallback = (
66
+ <main className="min-h-screen bg-muted/50 text-foreground">
67
+ <section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
68
+ <div className="mx-auto w-full max-w-sm">
69
+ <Card aria-label="Loading project" aria-live="polite">
70
+ <CardContent>
71
+ <div className="inline-flex items-center gap-3 text-muted-foreground">
72
+ <Loader size={20} />
73
+ <span>Loading project...</span>
74
+ </div>
75
+ </CardContent>
76
+ </Card>
77
+ </div>
78
+ </section>
79
+ </main>
80
+ );
81
+
82
+ const errorFallback = (
83
+ <main className="min-h-screen bg-muted/50 text-foreground">
84
+ <section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
85
+ <div className="mx-auto w-full max-w-sm">
86
+ <Alert>
87
+ <AlertDescription>Failed to connect to Fusion host</AlertDescription>
88
+ </Alert>
89
+ </div>
90
+ </section>
91
+ </main>
92
+ );
93
+
94
+ function AppContent() {
95
+ const client = useCogniteSdk();
126
96
 
127
97
  const deployment = appConfig.deployments?.[0];
128
98
  const orgLabel = deployment?.org ?? '';
129
- const projectLabel = deployment?.project ?? project ?? '';
99
+ const projectLabel = deployment?.project ?? client.project ?? '';
130
100
 
131
101
  return (
132
102
  <main className="min-h-screen bg-muted/50 text-foreground">
@@ -230,4 +200,16 @@ function App() {
230
200
  );
231
201
  }
232
202
 
203
+ type AppProps = {
204
+ deps?: ComponentProps<typeof CogniteSdkProvider>['deps'];
205
+ };
206
+
207
+ function App({ deps }: AppProps) {
208
+ return (
209
+ <CogniteSdkProvider loadingFallback={loadingFallback} errorFallback={errorFallback} deps={deps}>
210
+ <AppContent />
211
+ </CogniteSdkProvider>
212
+ );
213
+ }
214
+
233
215
  export default App;
@@ -0,0 +1,11 @@
1
+ ---
2
+ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.vscode/mcp.json'
3
+ ---
4
+ {
5
+ "servers": {
6
+ "cognite-docs": {
7
+ "type": "http",
8
+ "url": "https://docs.cognite.com/mcp"
9
+ }
10
+ }
11
+ }
@@ -0,0 +1,13 @@
1
+ var et=Object.defineProperty;var a=(n,t)=>et(n,"name",{value:t,configurable:!0});import{mkdir as xt,readFile as It}from"fs/promises";import{basename as kt,dirname as Ct}from"path";var z="https://docs.cognite.com/cdf/access/";function d(n){return n!==null&&typeof n=="object"}a(d,"isRecord");function w(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}a(w,"isHttpError");function nt(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${z}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${z}`;default:return}}a(nt,"httpStatusHint");function h(n){let t=n instanceof Error?n:new Error(String(n));if(!w(t))return null;let e=nt(t.status);return e?Object.assign(new Error(`${t.message}
4
+ ${e}`),{cause:t}):null}a(h,"enrichedHttpError");function rt(n){if(!d(n))return null;let t=n.missing;if(Array.isArray(t))return t;let e=n.data;if(d(e)){let r=e.error;if(d(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(e.missing))return e.missing}return null}a(rt,"findMissingArray");function it(n,t){if(!w(n)||n.status!==400)return!1;let e=rt(n);return e?e.some(r=>d(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}a(it,"isMissingExternalIdError");function b(n,t){return w(n)&&n.status===404||it(n,t)}a(b,"isNotFoundError");var J=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Y=["ACTIVE","PREVIEW"],T=class T extends Error{constructor(t,e){super(`Version ${e} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=e}};a(T,"AppVersionNotFoundError");var I=T;function k(n,t){return n.includes(t)}a(k,"includesValue");function ot(n){return k(J,n)}a(ot,"isAppVersionLifecycleState");function st(n){return k(Y,n)}a(st,"isAppVersionAlias");function at(n){return typeof n.version=="string"&&ot(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||st(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}a(at,"isAppVersion");function G(n){if(!d(n))throw new Error("Invalid version response: not an object");if(!at(n))throw new Error("Invalid version response: missing or malformed fields");return n}a(G,"parseAppVersion");var V=class V{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,e,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:e,description:r}]}})}catch(i){throw h(i)??i}}async uploadVersion(t,e,r,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${e}...`);let o=new FormData;o.append("file",new Blob([new Uint8Array(r)]),i),o.append("version",e),o.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),y=`${this.client.getBaseUrl()}${c}`,f=new AbortController,Q=setTimeout(()=>f.abort(),300*1e3),S;try{S=await fetch(y,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:o,signal:f.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?new Error("Upload timed out after 5 minutes"):m}finally{clearTimeout(Q)}if(!S.ok){let m=await S.text(),x=m;try{let R=JSON.parse(m);if(d(R)){let E=R.error;if(typeof E=="string")x=E;else if(d(E)){let A=E.message,M=E.code;x=typeof A=="string"?A:M!=null?`Unknown error (code: ${M})`:m}else{let A=R.message;x=typeof A=="string"?A:m}}}catch{}let j=S.headers.get("x-request-id"),tt=j?` | X-Request-ID: ${j}`:"",H=Object.assign(new Error(`Upload failed: ${S.status} \u2014 ${x}${tt}`),{status:S.status});throw h(H)??H}console.log(`\u2705 Version ${e} uploaded`)}async getVersion(t,e){let r=encodeURIComponent(t),i=encodeURIComponent(e),s=`${this.appsBasePath}/${r}/versions/${i}`;try{let o=await this.client.get(s);return G(o.data)}catch(o){throw b(o,[t,e])?new I(t,e):h(o)??o}}async getActiveVersion(t){let e=encodeURIComponent(t),r=`${this.appsBasePath}/${e}/active`;try{let i=await this.client.get(r);return G(i.data)}catch(i){if(b(i,[t]))return null;throw h(i)??i}}async updateVersions(t,e){let r=encodeURIComponent(t),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:e}})}catch(s){throw h(s)??s}}async submitSignatures(t,e,r){let i=encodeURIComponent(t),s=encodeURIComponent(e),o=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(o,{data:{items:r}})}catch(p){throw h(p)??p}}async listSignatures(t,e){let r=encodeURIComponent(t),i=encodeURIComponent(e),s=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let o=await this.client.post(s,{data:{}});return lt(o.data)}catch(o){throw h(o)??o}}};a(V,"AppHostingApi");var C=V,ct=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],pt=["developer","certifier"];function lt(n){if(!d(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=n;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(e=>{let r=ut(e);return r?[r]:[]})}a(lt,"parseStoredSignatures");function ut(n){if(!d(n))return null;let{signerKid:t,signerRole:e,signatureIat:r,receivedAt:i,createdTime:s,status:o}=n;return typeof t!="string"||t===""||!k(pt,e)||typeof r!="number"||typeof i!="number"||typeof s!="number"||!k(ct,o)?null:{signerKid:t,signerRole:e,signatureIat:r,receivedAt:i,createdTime:s,status:o}}a(ut,"parseStoredSignature");var D=class D{constructor(t){this.api=new C(t)}getVersion(t,e){return this.api.getVersion(t,e)}uploadVersion(t,e,r,i,s){return this.api.uploadVersion(t,e,r,i,s)}async ensureApp(t,e,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,e,r),console.log(`\u2705 App '${t}' created`)}catch(i){if(w(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async submitSignatures(t,e,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${e}...`),await this.api.submitSignatures(t,e,r),console.log("\u2705 Signatures stored"))}listSignatures(t,e){return this.api.listSignatures(t,e)}async publishVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,e){console.log(`\u{1F680} Publishing and activating version ${e}...`),await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${e} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{alias:{setNull:!0}}}])}async activateVersion(t,e){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let i=r&&r.version!==e?r.version:void 0;return await this.api.updateVersions(t,[{version:e,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,e,r,i,s,o,p=!1){console.log(`
5
+ \u{1F680} Deploying application via App Hosting API...
6
+ `);try{await this.ensureApp(t,e,r),await this.uploadVersion(t,i,s,o),p&&await this.publishAndActivate(t,i),console.log(`
7
+ \u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};a(D,"AppHostingClient");var v=D;import{execFileSync as $}from"child_process";import g from"fs";import u from"path";import{parseAndValidateManifestConfig as dt}from"@cognite/app-sdk/vite";import{BlobReader as gt,Uint8ArrayWriter as ft,ZipWriter as mt}from"@zip.js/zip.js";var _="package.json",U="package-lock.json",q="manifest.json",N=".cognite",ht=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],F=class F{constructor(t="dist"){this.distPath=u.isAbsolute(t)?t:u.join(process.cwd(),t),this.appRoot=u.dirname(this.distPath)}validateBuildDirectory(){if(!g.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=u.join(this.appRoot,_);if(!g.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let e=u.join(this.appRoot,U);if(!g.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`)}async createZip(t="app.zip",e=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new mt(new ft,{level:9}),i=a(async(c,l)=>{await r.add(l,new gt(await g.openAsBlob(c))),e&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=a(async c=>{let l=await g.promises.readdir(c,{withFileTypes:!0});for(let y of l){let f=u.join(c,y.name);y.isDirectory()?await s(f):await i(f,u.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),o;try{await s(this.distPath);let c=u.join(this.appRoot,_);await i(c,u.posix.join(N,_));let l=u.join(this.appRoot,q);if(g.existsSync(l)){let f=g.readFileSync(l,"utf-8");dt(f,l),await i(l,u.posix.join(N,q))}let y=u.join(this.appRoot,U);await i(y,u.posix.join(N,U)),o=await r.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await g.promises.writeFile(t,o);let p=(o.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 e;try{e=$("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=$("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(e,s);try{$("git",["-C",e,"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=(g.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${u.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,e){let r=$("git",["-C",t,"ls-tree","-r","--name-only",e],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
8
+ `).filter(Boolean),i=a(o=>o.split("/").some(p=>ht.some(c=>c.test(p))),"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:
9
+ `+s.map(o=>` ${o}`).join(`
10
+ `)+`
11
+ Hint: git rm --cached <file>`)}};a(F,"ApplicationPackager");var P=F;import yt from"path";var K=".cognite-bundles";function W(n,t){return`${n}-${t}.zip`}a(W,"bundleFileName");function O(n,t,e){return yt.join(n,K,W(t,e))}a(O,"bundlePath");import{CogniteClient as Pt}from"@cognite/sdk";var St=a(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let t=JSON.parse(n),e={};for(let[r,i]of Object.entries(t))if(typeof i=="string"){let s=r.toLowerCase().replace(/_/g,"-");e[s]=i}return e}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Et=a(n=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=St()[n]),t||(t=process.env[n]),!t)throw new Error(`Secret not found in environment: ${n}`);return t},"getSecretFromEnv"),At=a(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=n.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),wt=a(async(n,t)=>{let e=`Basic ${btoa(`${n}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:e,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let s=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
12
+ ${s}`)}let i=await r.json();if(!i.access_token)throw new Error("No access token returned from CDF authentication");return i.access_token},"getTokenCdf"),vt=a(async(n,t,e,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=At(r);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let s=`https://login.microsoftonline.com/${e}/oauth2/v2.0/token`,o=`https://${i}.cognitedata.com/.default`,p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:t,scope:o,grant_type:"client_credentials"})});if(!p.ok){let l=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
13
+ ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),L=a(async(n,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:e,deploySecretName:r,idpType:i="cdf",tenantId:s,baseUrl:o}=n,p=Et(r);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return vt(e,p,s,o)}return wt(e,p)},"getToken");async function B(n,t,e=process.env,r){let i=await L(n,e),s=e.COGNITE_BASE_URL??n.baseUrl,o=(r??(p=>new Pt(p)))({appId:t,project:n.project,baseUrl:s,oidcTokenProvider:a(async()=>i,"oidcTokenProvider")});return await o.authenticate(),o}a(B,"getSdk");async function X(n,t,e,r){let{externalId:i,name:s,description:o,versionTag:p}=t,c=O(e,i,p);await xt(Ct(c),{recursive:!0}),await new P(`${e}/dist`).createZip(c,!0);let l=await It(c);await new v(n).deploy(i,s,o,p,l,kt(c),r)}a(X,"packageAndUpload");var $t=a(async(n,t,e)=>{let r=await B(n,e);await X(r,t,e,n.published)},"deploy");import{existsSync as Rt,readFileSync as bt}from"fs";var Z=[".dev.sig",".cert.sig"];function Tt(n,t={}){let e=t.existsSync??Rt,r=t.readFileSync??((s,o)=>bt(s,o)),i=[];for(let s of Z){let o=`${n}${s}`;if(!e(o))continue;let p=r(o,"utf8").trim();p.length>0&&i.push(p)}return i}a(Tt,"discoverSignatures");export{v as a,P as b,K as c,W as d,O as e,L as f,B as g,X as h,$t as i,Z as j,Tt as k};