@cognite/cli 1.3.4-alpha.selfsigned → 1.4.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/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
@@ -10,7 +10,6 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
10
10
 
11
11
  - To start a new feature, run `/speckit.specify <description>` in Claude Code or Cursor. It generates a properly numbered feature directory and a spec to fill in. Then run `/speckit.clarify` → `/speckit.plan` → `/speckit.tasks` → `/speckit.implement`.
12
12
  - When user-visible behavior changes in an existing feature, update its `specs/<NNN>-<feature>/spec.md` before or alongside the code change.
13
- - When a feature touches Cognite Data Fusion data, the spec must document existing CDF views read from, new views needed, and spaces used.
14
13
  <% } else { -%>
15
14
  ## 0. Product Spec (SPEC.md)
16
15
 
@@ -22,11 +21,118 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
22
21
 
23
22
  ---
24
23
 
25
- ## 1. Dependency Injection
24
+ ## 1. CDF Data & Generated SDK
26
25
 
27
- Inject dependencies via React context (hooks/components) or factory-override pattern (plain functions). Never hard-code dependencies.
26
+ Before writing any feature code that reads CDF data model instances, check whether a generated SDK exists:
28
27
 
29
- ### React context
28
+ ```bash
29
+ ls src/generated_sdks/
30
+ ```
31
+
32
+ ### If the SDK does not exist
33
+
34
+ Stop. Do not write placeholder code or stub SDK calls. Tell the user:
35
+
36
+ > To read data from your CDF data model, you'll need to generate a typed SDK first. Run this from the app root (where `app.json` lives):
37
+ >
38
+ > ```bash
39
+ > npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
40
+ > ```
41
+ >
42
+ > The wizard will log you in via the browser, let you pick a data model, and write the generated files into `src/generated_sdks/`. Come back when it's done.
43
+
44
+ Wait for the user to confirm generation is complete before continuing.
45
+
46
+ ### If the SDK exists
47
+
48
+ Use `createSdk(client)` from `src/generated_sdks/<name>/index.ts` for all reads. Rules:
49
+
50
+ - **Read the generated TypeScript types first** (`src/generated_sdks/<name>/*.generated.ts`) to understand what views, fields, and relations are available — the return types show exactly which fields exist on list vs detail queries, including relation fields
51
+ - **Do not call `client.instances.list`, `client.instances.query`, or `client.instances.search` directly** — always go through the generated SDK for reads
52
+ - The SDK is **read-only**: `queryX`, `getByIdX`, `searchX`, `countX`, `aggregateX` — no write operations
53
+ - Relation fields appear only where the type exposes them: list/search results include direct relations as references; `getByIdX` additionally includes reverse relations and edges as connection objects (`{ items: [...], pageInfo: {...} }`)
54
+ - For writes, use `client.instances.upsert` / `client.instances.delete` directly
55
+
56
+ ```ts
57
+ import { createSdk } from '../generated_sdks/<name>';
58
+
59
+ const sdk = createSdk(client); // no network call — instantiation is synchronous
60
+
61
+ const result = await sdk.queryMyView({
62
+ filter: { status: { eq: 'active' } },
63
+ limit: 25,
64
+ });
65
+ // result.items[0].relatedView ← direct relation fields resolve in the same call
66
+
67
+ const detail = await sdk.getByIdMyView({ space: '...', externalId: '...' });
68
+ // detail.reverseRelationField.items ← reverse/edge relations only available here
69
+ ```
70
+
71
+ ---
72
+
73
+ ## 2. UI Components
74
+
75
+ 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.
76
+
77
+ ---
78
+
79
+ ## 3. Host integration (`@cognite/app-sdk`)
80
+
81
+ 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.
82
+
83
+ ### Decision rule for any new piece of state
84
+
85
+ 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.
86
+
87
+ - **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.
88
+ - **No, local-only:** in-flight form input before submit, hover/focus, transient toasts, animation state, optimistic UI mid-flight.
89
+
90
+ When in doubt, host-synced is the safer default — over-syncing is cheap, under-syncing breaks reload and share.
91
+
92
+ ### API surface
93
+
94
+ - **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.
95
+ - **Navigating elsewhere in Fusion** (another app, a Fusion route) → `api.navigateInternal({ path, queryParams, hash })`. Never set `window.location` directly.
96
+ - **Navigating to an external URL** → `api.navigateExternal({ url, openInNewTab })`. Only `https:` is allowed.
97
+ - **Needing a CDF base URL or access token** for API requests → `api.getBaseUrl()` / `api.getAccessToken()`. Never hardcode the cluster URL.
98
+ - **Needing the current CDF project name** → `api.getProject()`. Don't read it from config or URL params.
99
+ - **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)`.
100
+
101
+ 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.
102
+
103
+ ### Round-trip example: host-synced state
104
+
105
+ ```typescript
106
+ import { connectToHostApp, type HostAppAPI } from '@cognite/app-sdk';
107
+
108
+ type AppState = { page: 'a' | 'b'; filters: string[] };
109
+ const DEFAULT_STATE: AppState = { page: 'a', filters: [] };
110
+
111
+ // On startup — seed from initialState, not from a hardcoded default.
112
+ const { api, initialState } = await connectToHostApp({ applicationName: '<%= name %>' });
113
+ const seeded: AppState = initialState ? (JSON.parse(initialState) as AppState) : DEFAULT_STATE;
114
+
115
+ // On every change — push the new state to the host so the URL stays in sync.
116
+ async function updateState(next: AppState, api: HostAppAPI) {
117
+ setState(next); // your local React/store setter
118
+ await api.syncInternalState(JSON.stringify(next));
119
+ }
120
+ ```
121
+
122
+ `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.
123
+
124
+ ---
125
+
126
+ ## 4. Dependency Injection
127
+
128
+ **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.
129
+
130
+ What to inject: SDK clients, API services, analytics, timers (`Date.now`, `setTimeout`), random generators, external stores.
131
+ What not to inject: pure functions, constants, type utilities.
132
+
133
+ Use **narrow interfaces** — depend only on the subset of a service you actually need.
134
+
135
+ ### React context (hooks and components)
30
136
 
31
137
  ```typescript
32
138
  const defaultDeps = { useDataSource, useAnalytics };
@@ -38,7 +144,7 @@ export function useMyHook() {
38
144
  }
39
145
  ```
40
146
 
41
- ### Factory overrides
147
+ ### Factory overrides (plain functions)
42
148
 
43
149
  ```typescript
44
150
  type Deps = { serviceFactory: () => SomeService };
@@ -51,7 +157,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
51
157
 
52
158
  ---
53
159
 
54
- ## 2. Interface-Based Services
160
+ ## 5. Interface-Based Services
55
161
 
56
162
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
57
163
 
@@ -68,7 +174,7 @@ export class ApiDataService implements DataService {
68
174
 
69
175
  ---
70
176
 
71
- ## 3. ViewModel Pattern
177
+ ## 6. ViewModel Pattern
72
178
 
73
179
  Business logic lives in `use<Name>ViewModel`. Components only render.
74
180
 
@@ -89,9 +195,26 @@ export const TodoView = () => {
89
195
  };
90
196
  ```
91
197
 
198
+ ### Where state lives
199
+
200
+ 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.
201
+
202
+ 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.
203
+
204
+ > ⚠️ Anti-pattern: `useState` inside `useFooViewModel`, then two sibling components each call `useFooViewModel()`. Clicks update one copy; the other renders stale data.
205
+
206
+ ### How many times to call a ViewModel hook
207
+
208
+ - **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.
209
+ - **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.
210
+
211
+ ### Host-synced state inside a ViewModel
212
+
213
+ When a ViewModel exposes state that falls under §3'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.
214
+
92
215
  ---
93
216
 
94
- ## 4. Test-First Development
217
+ ## 7. Test-First Development
95
218
 
96
219
  Write tests before implementation for all non-trivial behavior changes.
97
220
 
@@ -187,21 +310,41 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
187
310
 
188
311
  ---
189
312
 
190
- ## 5. TypeScript Rules
313
+ ## 8. TypeScript Rules
191
314
 
192
315
  - 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`
316
+ - Never use `as` casts they silence the compiler without providing safety. Use type guards instead.
317
+ - Exception: `Partial<T> as T` is acceptable for test mocks only.
318
+ - All function parameters must have type annotations.
194
319
  - Use direct React type imports: `import type { ComponentType, ReactNode } from 'react'`
195
320
 
196
321
  ```typescript
197
- function createMockWindow(overrides: Partial<Window> = {}): Window {
198
- return { postMessage: vi.fn(), ...overrides } as Window;
322
+ // Never
323
+ const x: any = data;
324
+ const y = data as SomeType;
325
+ const z = {} as unknown as Window;
326
+ function process(data) { ... } // missing parameter type
327
+
328
+ // ✅ Type guard
329
+ function isSomeType(value: unknown): value is SomeType {
330
+ return typeof value === 'object' && value !== null && 'id' in value;
199
331
  }
332
+ if (isSomeType(data)) { /* TypeScript now knows */ }
333
+
334
+ // ✅ Test mock only
335
+ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
200
336
  ```
201
337
 
202
338
  ---
203
339
 
204
- ## 6. Commits and pull requests
340
+ ## 9. CogniteClient / authentication
341
+
342
+ 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.
343
+
344
+ ---
345
+
346
+
347
+ ## 10. Commits and pull requests
205
348
 
206
349
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
207
350
 
@@ -212,4 +355,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
212
355
  - **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
213
356
  - Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
214
357
 
215
- ---
358
+ ---
@@ -51,27 +51,29 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
51
51
 
52
52
  ---
53
53
 
54
- ## Data Models & CDF Integration *(mandatory)*
54
+ ## CDF Data *(mandatory)*
55
55
 
56
56
  <!--
57
- Capture how this app integrates with Cognite Data Fusion data models.
58
- Every Flows app should fill this in.
59
- -->
57
+ Which data model does this app connect to? If you haven't already, generate a
58
+ typed SDK by running from the app root:
60
59
 
61
- ### Existing views
60
+ npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
62
61
 
63
- <!--
64
- CDF views this app reads from. Format: `<space>.<view>:<version>`.
62
+ Once generated, src/generated_sdks/<name>/schema.graphql is the source of truth
63
+ for what views, fields, and relations are available.
64
+
65
+ Describe below what data this feature reads and why — in plain terms, not view IDs.
66
+ Example: "Reads active work orders and their assigned assets."
65
67
  -->
66
68
 
67
- ### New views
69
+ ### Data model
68
70
 
69
- <!--
70
- Views this app needs that don't yet exist. Describe properties and relationships.
71
- -->
71
+ <!-- Which data model: name, space, version. -->
72
72
 
73
- ### Spaces
73
+ ### What this app reads
74
74
 
75
- <!--
76
- CDF spaces this app uses, and what each contains.
77
- -->
75
+ <!-- Plain-language description of the data this feature needs and any key filters. -->
76
+
77
+ ### Writes
78
+
79
+ <!-- Does this feature write back to CDF? If so, what and under what conditions? If read-only, note that here. -->
@@ -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,18 +18,23 @@ 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/cli": "<%= cliVersion %>",
32
+ "@cognite/app-sdk": "^0.5.1",
30
33
  "@tabler/icons-react": "^3.35.0",
31
34
  "@tanstack/react-query": "^5.90.10",
32
35
  "clsx": "^2.1.1",
36
+ "graphql": "^16.14.0",
37
+ "graphql-tag": "^2.12.6",
33
38
  "react": "^18.3.1",
34
39
  "react-dom": "^18.3.1",
35
40
  "tailwind-merge": "^3.4.0"
@@ -44,6 +49,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
44
49
  "@types/react": "^18.3.1",
45
50
  "@types/react-dom": "^18.3.1",
46
51
  "@vitejs/plugin-react": "^5.1.1",
52
+ "@vitest/coverage-v8": "^2.1.8",
47
53
  "@vitest/ui": "^2.1.8",
48
54
  "autoprefixer": "^10.4.22",
49
55
  "eslint": "9.39.4",
@@ -58,7 +64,6 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
58
64
  "typescript": "^5.0.0",
59
65
  "typescript-eslint": "^8.46.4",
60
66
  "vite": "7.3.2",
61
- "vite-plugin-mkcert": "^1.17.9",
62
67
  "vitest": "^2.1.8"
63
68
  }
64
69
  }
@@ -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 @@
1
+ var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};