@cognite/cli 1.7.0 → 1.8.0-alpha.sdk-gen
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_templates/agents/create/README_TEMPLATE.md +66 -0
- package/_templates/app/new/config/vitest.config.ts.ejs.t +3 -2
- package/_templates/app/new/root/.npmrc.ejs.t +1 -1
- package/_templates/app/new/root/AGENTS.md.ejs.t +62 -12
- package/_templates/app/new/root/SPEC.md.ejs.t +17 -15
- package/_templates/app/new/root/app.json.ejs.t +1 -0
- package/_templates/app/new/root/manifest.json.ejs.t +6 -1
- package/_templates/app/new/root/package.json.ejs.t +4 -1
- package/_templates/app/new/src/App.test.tsx.ejs.t +32 -2
- package/_templates/app/new/src/App.tsx.ejs.t +54 -5
- package/_templates/app/new/src/main.tsx.ejs.t +0 -70
- package/dist/chunk-ATR2SGLU.js +1 -0
- package/dist/chunk-M3FWAJ4N.js +12 -0
- package/dist/chunk-PZ2YS5FR.js +1 -0
- package/dist/cli/cli.js +241 -101
- package/dist/deploy/index.d.ts +37 -10
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/sdk-runtime/index.d.ts +371 -0
- package/dist/sdk-runtime/index.js +1 -0
- package/package.json +18 -4
- package/dist/chunk-74X2P7OO.js +0 -12
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# {{displayName}}
|
|
2
|
+
|
|
3
|
+
> Edit `agent.yaml` to configure your agent — tools, model, instructions.
|
|
4
|
+
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# Push agent config to CDF (draft)
|
|
9
|
+
cognite agents push
|
|
10
|
+
|
|
11
|
+
# Open agent in Fusion for testing
|
|
12
|
+
cognite agents open
|
|
13
|
+
|
|
14
|
+
# Publish agent (makes it visible to users)
|
|
15
|
+
cognite agents publish
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Project layout
|
|
19
|
+
|
|
20
|
+
| Path | Purpose |
|
|
21
|
+
|------|---------|
|
|
22
|
+
| `agent.yaml` | Agent definition (externalId, tools, model, instructions) |
|
|
23
|
+
| `README.md` | This file |
|
|
24
|
+
|
|
25
|
+
## Adding tools
|
|
26
|
+
|
|
27
|
+
Edit the `tools` array in `agent.yaml`. Available tool types:
|
|
28
|
+
|
|
29
|
+
- `analyzeData` — analyze tabular or structured data
|
|
30
|
+
- `analyzeImage` — analyze images and P&ID diagrams
|
|
31
|
+
- `analyzeTimeSeries` — analyze time series data
|
|
32
|
+
- `askDocument` — ask questions about documents
|
|
33
|
+
- `callFunction` — call a Cognite Function
|
|
34
|
+
- `callRestApi` — call an external REST API
|
|
35
|
+
- `callWebhook` — POST a payload to an external webhook
|
|
36
|
+
- `examineDataSemantically` — semantic data examination
|
|
37
|
+
- `query` — structured queries against CDF data models
|
|
38
|
+
- `queryKnowledgeGraph` — query CDF data models with natural language
|
|
39
|
+
- `queryTimeSeriesDatapoints` — fetch raw or aggregated time series data
|
|
40
|
+
- `runPythonCode` — execute custom Python code
|
|
41
|
+
- `summarizeDocument` — summarize documents
|
|
42
|
+
- `timeSeriesAnalysis` — advanced time series analysis and anomaly detection
|
|
43
|
+
|
|
44
|
+
Example tool:
|
|
45
|
+
|
|
46
|
+
```yaml
|
|
47
|
+
tools:
|
|
48
|
+
- name: find_assets
|
|
49
|
+
type: queryKnowledgeGraph
|
|
50
|
+
description: Find assets and related instances in the knowledge graph.
|
|
51
|
+
configuration:
|
|
52
|
+
version: v2
|
|
53
|
+
dataModels:
|
|
54
|
+
- space: cdf_cdm
|
|
55
|
+
externalId: CogniteCore
|
|
56
|
+
version: v1
|
|
57
|
+
viewExternalIds:
|
|
58
|
+
- CogniteAsset
|
|
59
|
+
instanceSpaces:
|
|
60
|
+
type: all
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Deployment with Toolkit
|
|
64
|
+
|
|
65
|
+
The generated `agent.yaml` is compatible with [Cognite Toolkit](https://docs.cognite.com/cdf/deploy/toolkit/).
|
|
66
|
+
Place it in your Toolkit module under `agents/` and deploy with `cdf deploy`.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>vitest.config.ts'
|
|
3
3
|
---
|
|
4
4
|
import react from '@vitejs/plugin-react';
|
|
5
|
-
import { defineConfig } from 'vitest/config';
|
|
5
|
+
import { configDefaults, defineConfig } from 'vitest/config';
|
|
6
6
|
|
|
7
7
|
export default defineConfig({
|
|
8
8
|
plugins: [react()],
|
|
@@ -10,10 +10,11 @@ export default defineConfig({
|
|
|
10
10
|
globals: true,
|
|
11
11
|
environment: 'happy-dom',
|
|
12
12
|
setupFiles: ['vitest.setup.ts'],
|
|
13
|
+
exclude: [...configDefaults.exclude, '.claude/**', '.agents/**'],
|
|
13
14
|
coverage: {
|
|
14
15
|
provider: 'v8',
|
|
15
16
|
reporter: ['text', 'json', 'html', 'lcov'],
|
|
16
|
-
exclude: ['node_modules/', 'dist/', 'vitest.setup.ts', '**/*.config.ts', '**/*.d.ts'],
|
|
17
|
+
exclude: ['node_modules/', 'dist/', '.claude/', '.agents/', 'vitest.setup.ts', '**/*.config.ts', '**/*.d.ts'],
|
|
17
18
|
},
|
|
18
19
|
},
|
|
19
20
|
});
|
|
@@ -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,13 +21,64 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
|
|
|
22
21
|
|
|
23
22
|
---
|
|
24
23
|
|
|
25
|
-
## 1.
|
|
24
|
+
## 1. CDF Data & Generated SDK
|
|
25
|
+
|
|
26
|
+
Before writing any feature code that reads CDF data model instances, check whether a generated SDK exists:
|
|
27
|
+
|
|
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>/types.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 **resource-namespaced and read-only**: `sdk.<resource>.<query | getById | count | search | aggregate>(...)`, where `<resource>` is the camelCase view name (e.g. view `MyView` → `sdk.myView`). No write operations.
|
|
53
|
+
- Relation fields appear only where the type exposes them: list/search results include direct relations as references; `getById` additionally includes reverse relations and edges as connection objects (`{ items: [...], pageInfo: {...} }`)
|
|
54
|
+
- `getById` takes flat `{ space, externalId }`; `count` returns a number; `query` sort uses `direction: 'ascending' | 'descending'`; `select` narrows the fetched fields (identity is always returned and is not selectable)
|
|
55
|
+
- For writes, use `client.instances.upsert` / `client.instances.delete` directly
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { createSdk } from '../generated_sdks/<name>';
|
|
59
|
+
|
|
60
|
+
const sdk = createSdk(client); // no network call — instantiation is synchronous
|
|
61
|
+
|
|
62
|
+
const result = await sdk.myView.query({
|
|
63
|
+
filter: { status: { eq: 'active' } },
|
|
64
|
+
select: ['name', 'status'], // optional: fetch only these fields (identity always returned)
|
|
65
|
+
limit: 25,
|
|
66
|
+
});
|
|
67
|
+
// result.items[0].relatedView ← direct relation fields resolve in the same call
|
|
68
|
+
|
|
69
|
+
const detail = await sdk.myView.getById({ space: '...', externalId: '...' });
|
|
70
|
+
// detail.reverseRelationField.items ← reverse/edge relations only available here
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## 2. UI Components
|
|
26
76
|
|
|
27
77
|
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
78
|
|
|
29
79
|
---
|
|
30
80
|
|
|
31
|
-
##
|
|
81
|
+
## 3. Host integration (`@cognite/app-sdk`)
|
|
32
82
|
|
|
33
83
|
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
84
|
|
|
@@ -75,7 +125,7 @@ async function updateState(next: AppState, api: HostAppAPI) {
|
|
|
75
125
|
|
|
76
126
|
---
|
|
77
127
|
|
|
78
|
-
##
|
|
128
|
+
## 4. Dependency Injection
|
|
79
129
|
|
|
80
130
|
**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
131
|
|
|
@@ -109,7 +159,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
|
|
|
109
159
|
|
|
110
160
|
---
|
|
111
161
|
|
|
112
|
-
##
|
|
162
|
+
## 5. Interface-Based Services
|
|
113
163
|
|
|
114
164
|
Define an interface; implement with a class. Never reference the concrete class outside its own file.
|
|
115
165
|
|
|
@@ -126,7 +176,7 @@ export class ApiDataService implements DataService {
|
|
|
126
176
|
|
|
127
177
|
---
|
|
128
178
|
|
|
129
|
-
##
|
|
179
|
+
## 6. ViewModel Pattern
|
|
130
180
|
|
|
131
181
|
Business logic lives in `use<Name>ViewModel`. Components only render.
|
|
132
182
|
|
|
@@ -162,11 +212,11 @@ This matters because each call to a `useState`-backed hook creates an **independ
|
|
|
162
212
|
|
|
163
213
|
### Host-synced state inside a ViewModel
|
|
164
214
|
|
|
165
|
-
When a ViewModel exposes state that falls under §
|
|
215
|
+
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.
|
|
166
216
|
|
|
167
217
|
---
|
|
168
218
|
|
|
169
|
-
##
|
|
219
|
+
## 7. Test-First Development
|
|
170
220
|
|
|
171
221
|
Write tests before implementation for all non-trivial behavior changes.
|
|
172
222
|
|
|
@@ -262,7 +312,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
|
|
|
262
312
|
|
|
263
313
|
---
|
|
264
314
|
|
|
265
|
-
##
|
|
315
|
+
## 8. TypeScript Rules
|
|
266
316
|
|
|
267
317
|
- Never use `any`; prefer `unknown` or explicit strong types
|
|
268
318
|
- Never use `as` casts — they silence the compiler without providing safety. Use type guards instead.
|
|
@@ -289,14 +339,14 @@ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
|
|
|
289
339
|
|
|
290
340
|
---
|
|
291
341
|
|
|
292
|
-
##
|
|
342
|
+
## 9. CogniteClient / authentication
|
|
293
343
|
|
|
294
344
|
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
345
|
|
|
296
346
|
---
|
|
297
347
|
|
|
298
348
|
|
|
299
|
-
##
|
|
349
|
+
## 10. Commits and pull requests
|
|
300
350
|
|
|
301
351
|
Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
|
|
302
352
|
|
|
@@ -307,4 +357,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
|
|
|
307
357
|
- **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
|
|
308
358
|
- Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
|
|
309
359
|
|
|
310
|
-
---
|
|
360
|
+
---
|
|
@@ -51,27 +51,29 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
|
|
|
51
51
|
|
|
52
52
|
---
|
|
53
53
|
|
|
54
|
-
##
|
|
54
|
+
## CDF Data *(mandatory)*
|
|
55
55
|
|
|
56
56
|
<!--
|
|
57
|
-
|
|
58
|
-
|
|
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
|
-
|
|
60
|
+
npx @cognite/cli@<%= cliVersion %> apps sdk --interactive
|
|
62
61
|
|
|
63
|
-
|
|
64
|
-
|
|
62
|
+
Once generated, src/generated_sdks/<name>/types.generated.ts 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
|
-
###
|
|
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
|
-
###
|
|
73
|
+
### What this app reads
|
|
74
74
|
|
|
75
|
-
<!--
|
|
76
|
-
|
|
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. -->
|
|
@@ -26,12 +26,15 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
26
26
|
"setup-https": "npx @cognite/cli@latest apps setup-https"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@cognite/aura": "^0.1
|
|
29
|
+
"@cognite/aura": "^0.3.1",
|
|
30
30
|
"@cognite/sdk": "^10.10.0",
|
|
31
|
+
"@cognite/cli": "<%= cliVersion %>",
|
|
31
32
|
"@cognite/app-sdk": "^0.8.0",
|
|
32
33
|
"@tabler/icons-react": "^3.35.0",
|
|
33
34
|
"@tanstack/react-query": "^5.90.10",
|
|
34
35
|
"clsx": "^2.1.1",
|
|
36
|
+
"graphql": "^16.14.0",
|
|
37
|
+
"graphql-tag": "^2.12.6",
|
|
35
38
|
"react": "^18.3.1",
|
|
36
39
|
"react-dom": "^18.3.1",
|
|
37
40
|
"tailwind-merge": "^3.4.0"
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.test.tsx'
|
|
3
3
|
---
|
|
4
4
|
import { render, screen, waitFor } from '@testing-library/react';
|
|
5
|
+
import userEvent from '@testing-library/user-event';
|
|
5
6
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
6
7
|
import type { HostAppAPI, ConnectToHostAppResult } from '@cognite/app-sdk';
|
|
7
8
|
import { CogniteClient } from '@cognite/sdk';
|
|
@@ -35,9 +36,9 @@ function makeLoadingDeps(): AppDeps {
|
|
|
35
36
|
};
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
function makeConnectedDeps(): AppDeps {
|
|
39
|
+
function makeConnectedDeps(api = makeApi()): AppDeps {
|
|
39
40
|
return {
|
|
40
|
-
connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api
|
|
41
|
+
connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api })),
|
|
41
42
|
createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
|
|
42
43
|
};
|
|
43
44
|
}
|
|
@@ -69,4 +70,33 @@ describe('App', () => {
|
|
|
69
70
|
expect(screen.getAllByText(/SPEC\.md/).length).toBeGreaterThan(0);
|
|
70
71
|
expect(screen.getByText(/apps deploy --interactive/)).toBeInTheDocument();
|
|
71
72
|
});
|
|
73
|
+
|
|
74
|
+
it('syncs internal state when the open step changes', async () => {
|
|
75
|
+
const api = makeApi();
|
|
76
|
+
render(<App deps={makeConnectedDeps(api)} />);
|
|
77
|
+
await waitFor(() => expect(screen.getByText('App deployment checklist')).toBeInTheDocument());
|
|
78
|
+
|
|
79
|
+
await userEvent.click(screen.getByText('Explore'));
|
|
80
|
+
|
|
81
|
+
expect(api.syncInternalState).toHaveBeenCalledWith(
|
|
82
|
+
JSON.stringify({ openStep: 'Explore' })
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('restores the open step from initial state', async () => {
|
|
87
|
+
const api = makeApi();
|
|
88
|
+
const deps: AppDeps = {
|
|
89
|
+
connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() =>
|
|
90
|
+
Promise.resolve({ api, initialState: JSON.stringify({ openStep: 'Deploy' }) })
|
|
91
|
+
),
|
|
92
|
+
createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
|
|
93
|
+
};
|
|
94
|
+
render(<App deps={deps} />);
|
|
95
|
+
await waitFor(() => expect(screen.getByText('App deployment checklist')).toBeInTheDocument());
|
|
96
|
+
|
|
97
|
+
await waitFor(() =>
|
|
98
|
+
expect(screen.getByRole('button', { name: /deploy/i })).toHaveAttribute('aria-expanded', 'true')
|
|
99
|
+
);
|
|
100
|
+
expect(screen.getByRole('button', { name: /plan/i })).toHaveAttribute('aria-expanded', 'false');
|
|
101
|
+
});
|
|
72
102
|
});
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/App.tsx'
|
|
3
3
|
---
|
|
4
4
|
import type { ComponentProps } from 'react';
|
|
5
|
+
import { useEffect, useState } from 'react';
|
|
6
|
+
import { connectToHostApp as connectToHostAppImpl } from '@cognite/app-sdk';
|
|
7
|
+
import type { HostAppAPI } from '@cognite/app-sdk';
|
|
5
8
|
import { CogniteSdkProvider, useCogniteSdk } from '@cognite/app-sdk/react';
|
|
6
9
|
import {
|
|
7
10
|
Alert,
|
|
@@ -62,6 +65,8 @@ const CHECKLIST_STEPS = [
|
|
|
62
65
|
},
|
|
63
66
|
] as const;
|
|
64
67
|
|
|
68
|
+
type AppInternalState = { openStep: string | null };
|
|
69
|
+
|
|
65
70
|
const loadingFallback = (
|
|
66
71
|
<main className="min-h-screen bg-muted/50 text-foreground">
|
|
67
72
|
<section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
|
|
@@ -91,13 +96,37 @@ const errorFallback = (
|
|
|
91
96
|
</main>
|
|
92
97
|
);
|
|
93
98
|
|
|
94
|
-
|
|
99
|
+
type AppContentProps = { api: HostAppAPI | null; initialState?: string };
|
|
100
|
+
|
|
101
|
+
function AppContent({ api, initialState }: AppContentProps) {
|
|
95
102
|
const client = useCogniteSdk();
|
|
96
103
|
|
|
97
104
|
const deployment = appConfig.deployments?.[0];
|
|
98
105
|
const orgLabel = deployment?.org ?? '';
|
|
99
106
|
const projectLabel = deployment?.project ?? client.project ?? '';
|
|
100
107
|
|
|
108
|
+
const [openStep, setOpenStep] = useState<string | null>(CHECKLIST_STEPS[0].label);
|
|
109
|
+
|
|
110
|
+
// initialState is restored from the ?customAppInternalState search param by the host.
|
|
111
|
+
useEffect(() => {
|
|
112
|
+
if (!initialState) return;
|
|
113
|
+
try {
|
|
114
|
+
const saved = JSON.parse(initialState) as AppInternalState;
|
|
115
|
+
if (typeof saved.openStep === 'string' || saved.openStep === null) {
|
|
116
|
+
setOpenStep(saved.openStep);
|
|
117
|
+
}
|
|
118
|
+
} catch {
|
|
119
|
+
// ignore malformed saved state
|
|
120
|
+
}
|
|
121
|
+
}, [initialState]);
|
|
122
|
+
|
|
123
|
+
function handleStepToggle(label: string, isOpen: boolean) {
|
|
124
|
+
const next = isOpen ? label : null;
|
|
125
|
+
setOpenStep(next);
|
|
126
|
+
// Writes to the ?customAppInternalState search param so the URL is bookmarkable/shareable.
|
|
127
|
+
void api?.syncInternalState(JSON.stringify({ openStep: next } satisfies AppInternalState));
|
|
128
|
+
}
|
|
129
|
+
|
|
101
130
|
return (
|
|
102
131
|
<main className="min-h-screen bg-muted/50 text-foreground">
|
|
103
132
|
<section className="mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center p-4 sm:p-8">
|
|
@@ -118,8 +147,12 @@ function AppContent() {
|
|
|
118
147
|
</div>
|
|
119
148
|
|
|
120
149
|
<div className="flex flex-col gap-4 px-4">
|
|
121
|
-
{CHECKLIST_STEPS.map((step
|
|
122
|
-
<Collapsible
|
|
150
|
+
{CHECKLIST_STEPS.map((step) => (
|
|
151
|
+
<Collapsible
|
|
152
|
+
key={step.label}
|
|
153
|
+
open={openStep === step.label}
|
|
154
|
+
onOpenChange={(isOpen) => handleStepToggle(step.label, isOpen)}
|
|
155
|
+
>
|
|
123
156
|
<CollapsibleTrigger className="w-full">
|
|
124
157
|
<div className="flex w-full min-w-0 items-center justify-between gap-3 text-left">
|
|
125
158
|
<span className="text-lg">{step.label}</span>
|
|
@@ -202,12 +235,28 @@ function AppContent() {
|
|
|
202
235
|
|
|
203
236
|
type AppProps = {
|
|
204
237
|
deps?: ComponentProps<typeof CogniteSdkProvider>['deps'];
|
|
238
|
+
connectToHostApp?: typeof connectToHostAppImpl;
|
|
205
239
|
};
|
|
206
240
|
|
|
207
|
-
function App({
|
|
241
|
+
function App({
|
|
242
|
+
deps,
|
|
243
|
+
connectToHostApp = deps?.connectToHostApp ?? connectToHostAppImpl,
|
|
244
|
+
}: AppProps) {
|
|
245
|
+
const [connection, setConnection] = useState<{ api: HostAppAPI; initialState?: string } | null>(null);
|
|
246
|
+
|
|
247
|
+
useEffect(() => {
|
|
248
|
+
let cancelled = false;
|
|
249
|
+
void connectToHostApp().then((result) => {
|
|
250
|
+
if (!cancelled) setConnection(result);
|
|
251
|
+
});
|
|
252
|
+
return () => {
|
|
253
|
+
cancelled = true;
|
|
254
|
+
};
|
|
255
|
+
}, [connectToHostApp]);
|
|
256
|
+
|
|
208
257
|
return (
|
|
209
258
|
<CogniteSdkProvider loadingFallback={loadingFallback} errorFallback={errorFallback} deps={deps}>
|
|
210
|
-
<AppContent />
|
|
259
|
+
<AppContent api={connection?.api ?? null} initialState={connection?.initialState} />
|
|
211
260
|
</CogniteSdkProvider>
|
|
212
261
|
);
|
|
213
262
|
}
|
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>src/main.tsx'
|
|
3
3
|
---
|
|
4
|
-
import {
|
|
5
|
-
dispatchSessionExpired,
|
|
6
|
-
MESSAGE_TYPES,
|
|
7
|
-
reloadPreservingRoute,
|
|
8
|
-
restoreRouteOnBoot,
|
|
9
|
-
} from '@cognite/app-sdk';
|
|
10
4
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
11
5
|
import React from 'react';
|
|
12
6
|
import ReactDOM from 'react-dom/client';
|
|
@@ -15,70 +9,6 @@ import App from './App.tsx';
|
|
|
15
9
|
|
|
16
10
|
import './styles.css';
|
|
17
11
|
|
|
18
|
-
// Session-recovery helpers (opt-in; safe to remove).
|
|
19
|
-
restoreRouteOnBoot();
|
|
20
|
-
|
|
21
|
-
// Host refreshed the session: reload, keeping the current route.
|
|
22
|
-
window.addEventListener('message', (event) => {
|
|
23
|
-
if (event.source !== window.parent) return; // ignore non-host senders
|
|
24
|
-
if (event.data?.type === MESSAGE_TYPES.FUSION_HOST.SESSION_REFRESHED) {
|
|
25
|
-
reloadPreservingRoute();
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
|
|
29
|
-
// A failed dynamic import (chunk load) usually means the session expired; messages vary by browser, so match case-insensitively.
|
|
30
|
-
const isDynamicImportFailure = (message: string): boolean => {
|
|
31
|
-
const lower = message.toLowerCase();
|
|
32
|
-
return (
|
|
33
|
-
lower.includes('failed to fetch dynamically imported module') || // Chromium
|
|
34
|
-
lower.includes('error loading dynamically imported module') || // Firefox
|
|
35
|
-
lower.includes('importing a module script failed') // Safari
|
|
36
|
-
);
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
const RECOVERY_GUARD_KEY = '__cogniteSessionRecovery';
|
|
40
|
-
const RECOVERY_MAX_ATTEMPTS = 3;
|
|
41
|
-
const RECOVERY_WINDOW_MS = 30_000;
|
|
42
|
-
|
|
43
|
-
// Cap recovery reloads per window so a non-session chunk failure can't loop forever.
|
|
44
|
-
const requestSessionRecovery = (now: number = Date.now()): void => {
|
|
45
|
-
let attempts = 0;
|
|
46
|
-
let since = now;
|
|
47
|
-
try {
|
|
48
|
-
const saved = JSON.parse(sessionStorage.getItem(RECOVERY_GUARD_KEY) ?? '{}') as {
|
|
49
|
-
attempts?: number;
|
|
50
|
-
since?: number;
|
|
51
|
-
};
|
|
52
|
-
if (now - (saved.since ?? 0) <= RECOVERY_WINDOW_MS) {
|
|
53
|
-
attempts = saved.attempts ?? 0;
|
|
54
|
-
since = saved.since ?? now;
|
|
55
|
-
}
|
|
56
|
-
} catch {
|
|
57
|
-
// sessionStorage unavailable (sandboxed doc): dispatch uncapped.
|
|
58
|
-
}
|
|
59
|
-
if (attempts >= RECOVERY_MAX_ATTEMPTS) return;
|
|
60
|
-
try {
|
|
61
|
-
sessionStorage.setItem(RECOVERY_GUARD_KEY, JSON.stringify({ attempts: attempts + 1, since }));
|
|
62
|
-
} catch {
|
|
63
|
-
// Can't persist the count; recovering once still beats not recovering.
|
|
64
|
-
}
|
|
65
|
-
dispatchSessionExpired();
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
window.addEventListener('unhandledrejection', (event) => {
|
|
69
|
-
if (isDynamicImportFailure(event.reason?.message ?? '')) requestSessionRecovery();
|
|
70
|
-
});
|
|
71
|
-
window.addEventListener(
|
|
72
|
-
'error',
|
|
73
|
-
(event) => {
|
|
74
|
-
// ErrorEvent.message is the reliable string; event.error can be null (e.g. cross-origin).
|
|
75
|
-
if (isDynamicImportFailure(event.message || event.error?.message || '')) {
|
|
76
|
-
requestSessionRecovery();
|
|
77
|
-
}
|
|
78
|
-
},
|
|
79
|
-
true, // capture phase: chunk/resource load errors do not bubble to window
|
|
80
|
-
);
|
|
81
|
-
|
|
82
12
|
const queryClient = new QueryClient({
|
|
83
13
|
defaultOptions: {
|
|
84
14
|
queries: {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.defineProperty;var e=a=>{throw TypeError(a)};var h=(a,b)=>g(a,"name",{value:b,configurable:!0});var f=(a,b,c)=>b.has(a)||e("Cannot "+c);var i=(a,b,c)=>(f(a,b,"read from private field"),c?c.call(a):b.get(a)),j=(a,b,c)=>b.has(a)?e("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),k=(a,b,c,d)=>(f(a,b,"write to private field"),d?d.call(a,c):b.set(a,c),c);export{h as a,i as b,j as c,k as d};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{a as s,b as ne,c as re,d as ie}from"./chunk-ATR2SGLU.js";import{existsSync as ot}from"fs";import{mkdir as at,readFile as pt}from"fs/promises";import{basename as ct,dirname as dt}from"path";var H=class H 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)}}};s(H,"HintedError");var l=H;var se="https://docs.cognite.com/cdf/access/",Ae="https://status.cognite.com";function ve(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:se};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:se};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:Ae};default:return{}}}s(ve,"defaultHintForStatus");var L=class L extends l{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=ve(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};s(L,"HintedHttpError");var v=L;function ke(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}}s(ke,"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=ke(r.code,r);if(i!==void 0)return i;e=r.cause}}s(xe,"hintForCause");import{inspect as Ie}from"util";var M="[REDACTED]",I,R=class R{constructor(e){re(this,I);ie(this,I,e)}toString(){return M}toJSON(){return M}[Ie.custom](){return M}expose(){return ne(this,I)}static from(e){return new R(e)}};I=new WeakMap,s(R,"SensitiveString");var w=R;var oe="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}s(g,"isRecord");function P(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(P,"isHttpError");function Pe(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${oe}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${oe}`;default:return}}s(Pe,"httpStatusHint");function h(n){let e=n instanceof Error?n:new Error(String(n));if(!P(e))return null;let t=Pe(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
+
${t}`),{cause:e}):null}s(h,"enrichedHttpError");function Ce(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}s(Ce,"findMissingArray");function Te(n,e){if(!P(n)||n.status!==400)return!1;let t=Ce(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}s(Te,"isMissingExternalIdError");function D(n,e){return P(n)&&n.status===404||Te(n,e)}s(D,"isNotFoundError");var pe=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],ce=["ACTIVE","PREVIEW"],j=class j extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};s(j,"AppVersionNotFoundError");var $=j,G=class G extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};s(G,"AppNotFoundError");var U=G;function V(n,e){return n.includes(e)}s(V,"includesValue");function be(n){return V(pe,n)}s(be,"isAppVersionLifecycleState");function Re(n){return V(ce,n)}s(Re,"isAppVersionAlias");function De(n){return typeof n.version=="string"&&be(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Re(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(De,"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(!De(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}s(ae,"parseAppVersion");function $e(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}}s($e,"parseAppMetadata");var q=class q{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 h(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw h(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return $e(r.data)}catch(r){throw D(r,[e])?new U(e):h(r)??r}}async uploadVersion(e,t,r,i,o="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",o);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,d=await this.client.authenticate();if(!d)throw new l("Failed to authenticate for upload",{hint:"Check your credentials and try again."});let S=w.from(d),f=`${this.client.getBaseUrl()}${c}`,Q=new AbortController,Se=setTimeout(()=>Q.abort(),300*1e3),E;try{E=await fetch(f,{method:"POST",headers:{Authorization:`Bearer ${S.expose()}`},body:a,signal:Q.signal})}catch(m){throw m instanceof Error&&m.name==="AbortError"?new l("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 l(`Failed to upload version to ${f}`,{cause:m,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Se)}if(!E.ok){let m=await E.text(),A;try{A=JSON.parse(m)}catch{}let b=m;if(g(A)){let k=A.error;if(typeof k=="string")b=k;else if(g(k)){let x=k.message,te=k.code;b=typeof x=="string"?x:te!=null?`Unknown error (code: ${te})`:m}else{let x=A.message;b=typeof x=="string"?x:m}}let ee=E.headers.get("x-request-id"),we=ee?` | X-Request-ID: ${ee}`:"",Ee=g(A)?A:m;throw new v(`Upload failed: ${E.status} \u2014 ${b}${we}`,{httpStatusCode:E.status,requestUrl:f,responseBody:Ee})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}`;try{let a=await this.client.get(o);return ae(a.data)}catch(a){throw D(a,[e,t])?new $(e,t):h(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:o}=i.data;if(o.length===0)return null;if(o.length>1)throw new Error(`Unexpected response: ${o.length} versions have the ACTIVE alias, expected at most 1`);return ae(o[0])}catch(i){if(D(i,[e]))return null;throw h(i)??i}}async deleteVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/delete`;try{await this.client.post(i,{data:{items:t.map(o=>({version:o}))}})}catch(o){throw h(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(i,{data:{items:t}})}catch(o){throw h(o)??o}}async submitSignatures(e,t,r){let i=encodeURIComponent(e),o=encodeURIComponent(t),a=`${this.appsBasePath}/${i}/versions/${o}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw h(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),i=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/${i}/signatures/list`;try{let a=await this.client.post(o,{data:{}});return Ne(a.data)}catch(a){throw h(a)??a}}};s(q,"AppHostingApi");var N=q,Ue=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ve=["developer","certifier"];function Ne(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]:[]})}s(Ne,"parseStoredSignatures");function Fe(n){if(!g(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}=n;return typeof e!="string"||e===""||!V(Ve,t)||typeof r!="number"||typeof i!="number"||typeof o!="number"||!V(Ue,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}}s(Fe,"parseStoredSignature");function Oe(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}s(Oe,"diffAppMetadata");function _e(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 o=`${t}:`.padEnd(14);e.push(` ${o}"${r}" \u2192 "${i}"`)}return e.join(`
|
|
5
|
+
`)}s(_e,"formatMetadataDriftError");var J=class J{constructor(e){this.api=new N(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,i,o){return this.api.uploadVersion(e,t,r,i,o)}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(P(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 o=Oe(i,{name:t,description:r});if(o.length!==0)throw new l(_e(o),{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 deleteVersion(e,t){await this.api.deleteVersions(e,[t])}async deprecateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"DEPRECATED"}}}])}async archiveVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"ARCHIVED"}}}])}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,o,a,p=!1){console.log(`
|
|
6
|
+
\u{1F680} Deploying application via App Hosting API...
|
|
7
|
+
`),await this.ensureApp(e,t,r),await this.uploadVersion(e,i,o,a),p&&await this.publishAndActivate(e,i),console.log(`
|
|
8
|
+
\u2705 Deployment successful!`)}};s(J,"AppHostingClient");var C=J;import{execFileSync as F}from"child_process";import y from"fs";import u from"path";import{parseAndValidateManifestConfig as Le}from"@cognite/app-sdk/vite";import{BlobReader as Me,Uint8ArrayWriter as je,ZipWriter as Ge}from"@zip.js/zip.js";import{execFileSync as Be}from"child_process";function He(n={}){let{execFileSync:e=Be}=n;try{return e("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}s(He,"isGitInstalled");function de(n={}){if(!He(n))throw new l("Git is not installed or not found on PATH.",{hint:"Install Git (https://git-scm.com) and ensure it is on your PATH, then try again.",shouldReport:!1})}s(de,"throwIfGitMissing");var z="package.json",Y="package-lock.json",le="manifest.json",K=".cognite",qe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],W=class W{constructor(e="dist"){this.distPath=u.isAbsolute(e)?e:u.join(process.cwd(),e),this.appRoot=u.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=u.join(this.appRoot,z);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=u.join(this.appRoot,Y);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 Ge(new je,{level:9}),i=s(async(c,d)=>{await r.add(d,new Me(await y.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${d}`)},"addFile"),o=s(async c=>{let d=await y.promises.readdir(c,{withFileTypes:!0});for(let S of d){let f=u.join(c,S.name);S.isDirectory()?await o(f):await i(f,u.relative(this.distPath,f).replace(/\\/g,"/"))}},"addDir"),a;try{await o(this.distPath);let c=u.join(this.appRoot,z);await i(c,u.posix.join(K,z));let d=u.join(this.appRoot,le);if(y.existsSync(d)){let f=y.readFileSync(d,"utf-8");Le(f,d),await i(d,u.posix.join(K,le))}let S=u.join(this.appRoot,Y);await i(S,u.posix.join(K,Y)),a=await r.close()}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${d}`)}try{await y.promises.writeFile(e,a)}catch(c){throw new l(`Failed to write bundle to ${e}`,{cause:c})}let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=F("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw de(),new l("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=F("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=r?r.replace(/\/$/,""):".",o=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(t,o);try{F("git",["-C",t,"archive","--format=zip",`--output=${e}`,o])}catch(c){let d=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${d}`)}let p=(y.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${u.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=F("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
9
|
+
`).filter(Boolean),i=s(a=>a.split("/").some(p=>qe.some(c=>c.test(p))),"isSensitive"),o=r.filter(i);if(o.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
|
|
10
|
+
`+o.map(a=>` ${a}`).join(`
|
|
11
|
+
`)+`
|
|
12
|
+
Hint: git rm --cached <file>`)}};s(W,"ApplicationPackager");var T=W;import Je from"path";var ue=".cognite-bundles";function ge(n,e){return`${n}-${e}.zip`}s(ge,"bundleFileName");function O(n,e,t){return Je.join(n,ue,ge(e,t))}s(O,"bundlePath");import{CogniteClient as nt}from"@cognite/sdk";function ze(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}s(ze,"exponentialBackoffWithJitter");function Ye(n){return new Promise(e=>setTimeout(e,n))}s(Ye,"sleep");async function he(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??ze;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 o=1;for(;;)try{return await n()}catch(a){if(o>=t||!r(a))throw a;let p=i(o);e.onAttemptFail?.(a,o,p),await Ye(p),o++}}s(he,"retryAsync");var Ke="https://auth.cognite.com/oauth2/token",We=s(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 he(()=>fetch(e,t),{maxAttempts:3})}catch(p){throw new l(`Failed to fetch access token from ${e}`,{cause:p})}if(!i.ok){let p=await i.text();throw new v(`Failed to get token from ${n}: ${i.status} ${i.statusText}`,{httpStatusCode:i.status,requestUrl:e,responseBody:p})}let o=await i.text(),a;try{a=JSON.parse(o)}catch{throw new l(`Unexpected response from ${n} authentication (invalid JSON)`,{hint:r})}if(!We(a))throw new l(`No access token in ${n} authentication response`,{hint:r});return w.from(a.access_token)}s(fe,"fetchOAuthToken");var Xe=s(()=>{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 o=r.toLowerCase().replace(/_/g,"-");t[o]=i}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Ze=s(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Xe()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return w.from(e)},"getSecretFromEnv"),Qe=s((n,e)=>{let t=e.expose();return fe({idp:"CDF",tokenUrl:Ke,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"),me=s(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:o})=>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:o}),"getTokenWithClientCredentials"),et=s((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"),tt=s((n,e,t,r,i)=>me({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[et(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),X=s(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return w.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:o,baseUrl:a,scopes:p,tokenUrl:c}=n,d=Ze(r);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return me({idp:"OAuth",tokenUrl:c,clientId:t,clientSecret:d.expose(),scopes:p,missingTokenHint:"Check the tokenUrl, client ID, scopes, and deployment secret in app.json and your environment."})}if(i==="entra_id"){if(!o)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return tt(t,d,o,a,p)}return Qe(t,d)},"getToken");async function _(n,e,t=process.env,r){let i=await X(n,t),o=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new nt(p)))({appId:e,project:n.project,baseUrl:o,oidcTokenProvider:s(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}s(_,"getSdk");import{existsSync as rt,readFileSync as it}from"fs";var B=[".dev.sig",".cert.sig"];function st(n,e={}){let t=e.existsSync??rt,r=e.readFileSync??((o,a)=>it(o,a)),i=[];for(let o of B){let a=`${n}${o}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}s(st,"discoverSignatures");async function ye(n,e,{existsSync:t=ot,mkdir:r=at,createZip:i=s((o,a)=>new T(o).createZip(a,!0),"createZipFn")}={}){let{externalId:o,versionTag:a}=n,p=O(e,o,a);if(t(p)){let d=B.some(S=>t(`${p}${S}`))?"A signed bundle already exists here. Re-deploying will invalidate the signing process. Bump versionTag in app.json to deploy as a new version, or delete the bundle and its .sig files then re-sign after deploying.":"Bump versionTag in app.json to deploy as a new version, or delete the existing bundle from .cognite-bundles/ to redeploy the same version.";throw new l(`Bundle already exists: ${p}`,{hint:d,shouldReport:!1})}await r(dt(p),{recursive:!0}),await i(`${e}/dist`,p)}s(ye,"packageBundle");async function Z(n,e,t,r,{readFile:i=pt,upload:o=s(async(a,p)=>new C(n).deploy(e.externalId,e.name,e.description,e.versionTag,a,p,r),"uploadFn")}={}){let a=O(t,e.externalId,e.versionTag),p;try{p=await i(a)}catch(c){throw new l(`Failed to read bundle file: ${a}`,{cause:c})}await o(p,ct(a))}s(Z,"uploadBundle");var lt=s(async(n,e,t)=>{let r=await _(n,t);await ye(e,t),await Z(r,e,t,n.published)},"deploy"),ut=s(async(n,e,t)=>{let r=await _(n,t);await Z(r,e,t,n.published)},"deployBundle");export{C as a,T as b,ue as c,ge as d,O as e,X as f,_ as g,B as h,st as i,ye as j,Z as k,lt as l,ut as m};
|