@cognite/cli 1.7.1-alpha.1 → 1.8.0-alpha.263
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/_templates/agents/create/EVAL_CASES_TEMPLATE.yaml +77 -0
- package/_templates/agents/create/README_TEMPLATE.md +78 -0
- package/_templates/app/new/config/vitest.config.ts.ejs.t +3 -2
- package/_templates/app/new/root/AGENTS.md.ejs.t +3 -1
- package/_templates/app/new/root/package.json.ejs.t +10 -10
- package/_templates/app/new/src/App.test.tsx.ejs.t +33 -2
- package/_templates/app/new/src/App.tsx.ejs.t +64 -11
- package/dist/chunk-IYQSEWZ2.js +12 -0
- package/dist/cli/cli.js +120 -92
- package/dist/deploy/index.d.ts +43 -11
- package/dist/deploy/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +15 -8
- package/dist/chunk-74X2P7OO.js +0 -12
package/README.md
CHANGED
|
@@ -12,6 +12,10 @@ npx @cognite/cli apps create
|
|
|
12
12
|
|
|
13
13
|
This prompts for your app name, org, project, and cluster, then generates a fully configured React + TypeScript project.
|
|
14
14
|
|
|
15
|
+
## Feature Flags
|
|
16
|
+
|
|
17
|
+
Set environment variable `COGNITE_ALPHA_ENABLE_SESSION_AUTH` to true in order to enable session authentication enabling auth login and logout commands which will let you skip browser login by securely persisting access tokens on your machine.
|
|
18
|
+
|
|
15
19
|
## Authentication
|
|
16
20
|
|
|
17
21
|
New apps created with `npx @cognite/cli apps create` depend on [`@cognite/app-sdk`](https://www.npmjs.com/package/@cognite/app-sdk) — **not `@cognite/cli`** — for auth and host integration. `@cognite/cli` is the CLI used to scaffold, develop, and deploy the app; the generated app itself talks to the Fusion app host via `@cognite/app-sdk`'s Comlink handshake. The template wires this up for you.
|
|
@@ -140,6 +144,7 @@ MOCK_SCENARIO=403 pnpm mock:server
|
|
|
140
144
|
| `republish` | `ensureApp` recovers (409), then `uploadVersion` fails (409 — version already published) |
|
|
141
145
|
|
|
142
146
|
The mock server and MSW handlers live in `cli/testing/msw/`. The same handlers are used by the Vitest integration tests in `src/deploy/apphosting-deployer.msw.test.ts`.
|
|
147
|
+
|
|
143
148
|
## Maintenance
|
|
144
149
|
|
|
145
150
|
### Updating the spec-kit vendor snapshot
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Eval cases for {{displayName}}
|
|
2
|
+
#
|
|
3
|
+
# Each case is a conversation with the agent plus one or more "scorers" that
|
|
4
|
+
# judge the responses. An LLM judge grades every scored turn. Run the suite with:
|
|
5
|
+
#
|
|
6
|
+
# cognite agents eval
|
|
7
|
+
#
|
|
8
|
+
# Supported scorer types:
|
|
9
|
+
# - correctness: compares the answer to a reference description you provide
|
|
10
|
+
# (`reference`). Use it when you can describe a good answer.
|
|
11
|
+
# - faithfulness: checks the answer is grounded in the supplied `context` and
|
|
12
|
+
# does not hallucinate. Use it for retrieval / grounded answers.
|
|
13
|
+
# - toolSelection: checks whether the agent picked an appropriate tool (or
|
|
14
|
+
# correctly used none) for the question, based on the tools
|
|
15
|
+
# configured in agent.yaml. Requires no extra fields, but only
|
|
16
|
+
# makes sense once you've added tools (see README.md's
|
|
17
|
+
# "Adding tools" section).
|
|
18
|
+
# - toolInvocation: checks whether the agent invoked tools with correct
|
|
19
|
+
# arguments and formatting. Complements toolSelection — use
|
|
20
|
+
# both when you need full tool-calling coverage. Requires no
|
|
21
|
+
# extra fields.
|
|
22
|
+
#
|
|
23
|
+
# These are placeholders — edit the inputs, references, and context to match what
|
|
24
|
+
# your agent actually does, then add more cases over time.
|
|
25
|
+
|
|
26
|
+
# To split cases across multiple files as your suite grows, add:
|
|
27
|
+
# include:
|
|
28
|
+
# - cases/maintenance.yaml
|
|
29
|
+
|
|
30
|
+
cases:
|
|
31
|
+
# Single-turn case scored for correctness.
|
|
32
|
+
- id: greeting
|
|
33
|
+
turns:
|
|
34
|
+
- input: "Hi, what can you help me with?"
|
|
35
|
+
scorers:
|
|
36
|
+
- type: correctness
|
|
37
|
+
# Describe what a good answer looks like; the judge compares against this.
|
|
38
|
+
reference: >-
|
|
39
|
+
A friendly greeting that briefly explains what this agent can help
|
|
40
|
+
the user with.
|
|
41
|
+
|
|
42
|
+
# Single-turn case scored for faithfulness against supplied context.
|
|
43
|
+
- id: grounded-answer
|
|
44
|
+
turns:
|
|
45
|
+
- input: "Where is the main compressor located?"
|
|
46
|
+
scorers:
|
|
47
|
+
- type: faithfulness
|
|
48
|
+
# The answer must be grounded in this context and not invent facts.
|
|
49
|
+
context: >-
|
|
50
|
+
The main compressor (unit C-101) is installed on Deck 2 of the
|
|
51
|
+
North platform, next to the gas separation train.
|
|
52
|
+
|
|
53
|
+
# Single-turn case scored for tool selection. Assumes you've added the
|
|
54
|
+
# `find_assets` tool from README.md's "Adding tools" example — the judge
|
|
55
|
+
# checks whether the agent picked an appropriate tool (or none) based on
|
|
56
|
+
# the tools listed in agent.yaml.
|
|
57
|
+
- id: find-assets-tool
|
|
58
|
+
turns:
|
|
59
|
+
- input: "Find assets related to compressors in the knowledge graph."
|
|
60
|
+
scorers:
|
|
61
|
+
- type: toolSelection
|
|
62
|
+
- type: toolInvocation
|
|
63
|
+
|
|
64
|
+
# Multi-turn case: the agent should carry context across turns.
|
|
65
|
+
- id: assets-followup
|
|
66
|
+
turns:
|
|
67
|
+
- input: "List the assets in the cooling system."
|
|
68
|
+
scorers:
|
|
69
|
+
- type: correctness
|
|
70
|
+
reference: "Lists the assets that belong to the cooling system."
|
|
71
|
+
- input: "Now show only the ones that are currently active."
|
|
72
|
+
scorers:
|
|
73
|
+
- type: correctness
|
|
74
|
+
# Relies on the previous turn — the judge sees the earlier turns as context.
|
|
75
|
+
reference: >-
|
|
76
|
+
Narrows the previously listed cooling-system assets down to only
|
|
77
|
+
the active ones.
|
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
| `eval/eval.yaml` | Example eval cases — run with `cognite agents eval` |
|
|
24
|
+
| `README.md` | This file |
|
|
25
|
+
|
|
26
|
+
## Evaluating the agent
|
|
27
|
+
|
|
28
|
+
`eval/eval.yaml` contains starter test cases (single-turn and multi-turn) that
|
|
29
|
+
grade the agent's responses with an LLM judge. After pushing the agent, run:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
cognite agents eval
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Edit the cases to match what your agent does, and add more over time.
|
|
36
|
+
|
|
37
|
+
## Adding tools
|
|
38
|
+
|
|
39
|
+
Edit the `tools` array in `agent.yaml`. Available tool types:
|
|
40
|
+
|
|
41
|
+
- `analyzeData` — analyze tabular or structured data
|
|
42
|
+
- `analyzeImage` — analyze images and P&ID diagrams
|
|
43
|
+
- `analyzeTimeSeries` — analyze time series data
|
|
44
|
+
- `askDocument` — ask questions about documents
|
|
45
|
+
- `callFunction` — call a Cognite Function
|
|
46
|
+
- `callRestApi` — call an external REST API
|
|
47
|
+
- `callWebhook` — POST a payload to an external webhook
|
|
48
|
+
- `examineDataSemantically` — semantic data examination
|
|
49
|
+
- `query` — structured queries against CDF data models
|
|
50
|
+
- `queryKnowledgeGraph` — query CDF data models with natural language
|
|
51
|
+
- `queryTimeSeriesDatapoints` — fetch raw or aggregated time series data
|
|
52
|
+
- `runPythonCode` — execute custom Python code
|
|
53
|
+
- `summarizeDocument` — summarize documents
|
|
54
|
+
- `timeSeriesAnalysis` — advanced time series analysis and anomaly detection
|
|
55
|
+
|
|
56
|
+
Example tool:
|
|
57
|
+
|
|
58
|
+
```yaml
|
|
59
|
+
tools:
|
|
60
|
+
- name: find_assets
|
|
61
|
+
type: queryKnowledgeGraph
|
|
62
|
+
description: Find assets and related instances in the knowledge graph.
|
|
63
|
+
configuration:
|
|
64
|
+
version: v2
|
|
65
|
+
dataModels:
|
|
66
|
+
- space: cdf_cdm
|
|
67
|
+
externalId: CogniteCore
|
|
68
|
+
version: v1
|
|
69
|
+
viewExternalIds:
|
|
70
|
+
- CogniteAsset
|
|
71
|
+
instanceSpaces:
|
|
72
|
+
type: all
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Deployment with Toolkit
|
|
76
|
+
|
|
77
|
+
The generated `agent.yaml` is compatible with [Cognite Toolkit](https://docs.cognite.com/cdf/deploy/toolkit/).
|
|
78
|
+
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
|
});
|
|
@@ -24,7 +24,9 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
|
|
|
24
24
|
|
|
25
25
|
## 1. UI Components
|
|
26
26
|
|
|
27
|
-
Always check
|
|
27
|
+
Always check Aura 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
|
+
|
|
29
|
+
Import each component from its own subpath — `@cognite/aura/components/button`, `@cognite/aura/components/card`, etc. — rather than from the `@cognite/aura/components` barrel. The barrel pulls in Aura's entire dependency graph (including large libraries like mermaid and shiki), which slows the build and can exhaust memory in constrained environments.
|
|
28
30
|
|
|
29
31
|
---
|
|
30
32
|
|
|
@@ -7,7 +7,7 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
7
7
|
"private": true,
|
|
8
8
|
"type": "module",
|
|
9
9
|
"engines": {
|
|
10
|
-
"node": ">=20",
|
|
10
|
+
"node": ">=20 <22.23.0 || >=22.23.1 <24.17.0 || >=24.18.0 <26.3.1 || >=26.4.0",
|
|
11
11
|
"npm": ">=11.10.0"
|
|
12
12
|
},
|
|
13
13
|
"scripts": {
|
|
@@ -26,9 +26,9 @@ 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/app-sdk": "^0.
|
|
31
|
+
"@cognite/app-sdk": "^0.8.0",
|
|
32
32
|
"@tabler/icons-react": "^3.35.0",
|
|
33
33
|
"@tanstack/react-query": "^5.90.10",
|
|
34
34
|
"clsx": "^2.1.1",
|
|
@@ -42,25 +42,25 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
42
42
|
"@testing-library/jest-dom": "^6.6.3",
|
|
43
43
|
"@testing-library/react": "^16.1.0",
|
|
44
44
|
"@testing-library/user-event": "^14.5.2",
|
|
45
|
-
"@types/node": "^
|
|
45
|
+
"@types/node": "^26.0.0",
|
|
46
46
|
"@types/react": "^18.3.1",
|
|
47
47
|
"@types/react-dom": "^18.3.1",
|
|
48
|
-
"@vitejs/plugin-react": "
|
|
49
|
-
"@vitest/coverage-v8": "4.1.
|
|
50
|
-
"@vitest/ui": "4.1.
|
|
48
|
+
"@vitejs/plugin-react": ">=5.1.1 <6.0.0",
|
|
49
|
+
"@vitest/coverage-v8": "4.1.10",
|
|
50
|
+
"@vitest/ui": "4.1.10",
|
|
51
51
|
"autoprefixer": "^10.4.22",
|
|
52
52
|
"eslint": "9.39.4",
|
|
53
53
|
"eslint-plugin-import": "^2.32.0",
|
|
54
54
|
"eslint-plugin-no-only-tests": "^3.3.0",
|
|
55
55
|
"eslint-plugin-react-hooks": "^7.1.1",
|
|
56
56
|
"eslint-plugin-react-refresh": "^0.5.2",
|
|
57
|
-
"globals": "^
|
|
57
|
+
"globals": "^17.0.0",
|
|
58
58
|
"happy-dom": "^20.9.0",
|
|
59
59
|
"postcss": "^8.5.6",
|
|
60
60
|
"tailwindcss": "^4.1.17",
|
|
61
61
|
"typescript": "^5.0.0",
|
|
62
62
|
"typescript-eslint": "^8.46.4",
|
|
63
|
-
"vite": "7.3.5",
|
|
64
|
-
"vitest": "4.1.
|
|
63
|
+
"vite": ">=7.3.5 <8.0.0",
|
|
64
|
+
"vitest": "4.1.10"
|
|
65
65
|
}
|
|
66
66
|
}
|
|
@@ -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';
|
|
@@ -24,6 +25,7 @@ function makeApi(): HostAppAPI {
|
|
|
24
25
|
unregisterAgentServer: vi.fn<HostAppAPI['unregisterAgentServer']>(() => Promise.resolve()),
|
|
25
26
|
sendAgentLayoutMode: vi.fn<HostAppAPI['sendAgentLayoutMode']>(() => Promise.resolve()),
|
|
26
27
|
sendAgentMessage: vi.fn<HostAppAPI['sendAgentMessage']>(() => Promise.resolve()),
|
|
28
|
+
sendAgentTheme: vi.fn<HostAppAPI['sendAgentTheme']>(() => Promise.resolve()),
|
|
27
29
|
};
|
|
28
30
|
}
|
|
29
31
|
|
|
@@ -34,9 +36,9 @@ function makeLoadingDeps(): AppDeps {
|
|
|
34
36
|
};
|
|
35
37
|
}
|
|
36
38
|
|
|
37
|
-
function makeConnectedDeps(): AppDeps {
|
|
39
|
+
function makeConnectedDeps(api = makeApi()): AppDeps {
|
|
38
40
|
return {
|
|
39
|
-
connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api
|
|
41
|
+
connectToHostApp: vi.fn<AppDeps['connectToHostApp']>(() => Promise.resolve({ api })),
|
|
40
42
|
createClient: vi.fn<AppDeps['createClient']>((config) => new CogniteClient(config)),
|
|
41
43
|
};
|
|
42
44
|
}
|
|
@@ -68,4 +70,33 @@ describe('App', () => {
|
|
|
68
70
|
expect(screen.getAllByText(/SPEC\.md/).length).toBeGreaterThan(0);
|
|
69
71
|
expect(screen.getByText(/apps deploy --interactive/)).toBeInTheDocument();
|
|
70
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
|
+
});
|
|
71
102
|
});
|
|
@@ -2,22 +2,29 @@
|
|
|
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';
|
|
9
|
+
// Import per-component, not from the `@cognite/aura/components` barrel: the
|
|
10
|
+
// barrel pulls in Aura's whole dependency graph (including large libraries like
|
|
11
|
+
// mermaid and shiki), which slows the build and can exhaust memory in CI.
|
|
12
|
+
import { Alert, AlertDescription } from '@cognite/aura/components/alert';
|
|
13
|
+
import { Badge } from '@cognite/aura/components/badge';
|
|
6
14
|
import {
|
|
7
|
-
Alert,
|
|
8
|
-
AlertDescription,
|
|
9
|
-
Badge,
|
|
10
15
|
Card,
|
|
11
16
|
CardContent,
|
|
12
17
|
CardDescription,
|
|
13
18
|
CardHeader,
|
|
14
19
|
CardTitle,
|
|
20
|
+
} from '@cognite/aura/components/card';
|
|
21
|
+
import {
|
|
15
22
|
Collapsible,
|
|
16
23
|
CollapsibleContent,
|
|
17
24
|
CollapsibleTrigger,
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
} from '@cognite/aura/components';
|
|
25
|
+
} from '@cognite/aura/components/collapsible';
|
|
26
|
+
import { Loader } from '@cognite/aura/components/loader';
|
|
27
|
+
import { Separator } from '@cognite/aura/components/separator';
|
|
21
28
|
import { IconCaretUpDown, IconRocket } from '@tabler/icons-react';
|
|
22
29
|
|
|
23
30
|
import appConfig from '../app.json';
|
|
@@ -62,6 +69,8 @@ const CHECKLIST_STEPS = [
|
|
|
62
69
|
},
|
|
63
70
|
] as const;
|
|
64
71
|
|
|
72
|
+
type AppInternalState = { openStep: string | null };
|
|
73
|
+
|
|
65
74
|
const loadingFallback = (
|
|
66
75
|
<main className="min-h-screen bg-muted/50 text-foreground">
|
|
67
76
|
<section className="mx-auto flex min-h-screen w-full max-w-lg flex-col justify-center p-4 sm:p-8">
|
|
@@ -91,13 +100,37 @@ const errorFallback = (
|
|
|
91
100
|
</main>
|
|
92
101
|
);
|
|
93
102
|
|
|
94
|
-
|
|
103
|
+
type AppContentProps = { api: HostAppAPI | null; initialState?: string };
|
|
104
|
+
|
|
105
|
+
function AppContent({ api, initialState }: AppContentProps) {
|
|
95
106
|
const client = useCogniteSdk();
|
|
96
107
|
|
|
97
108
|
const deployment = appConfig.deployments?.[0];
|
|
98
109
|
const orgLabel = deployment?.org ?? '';
|
|
99
110
|
const projectLabel = deployment?.project ?? client.project ?? '';
|
|
100
111
|
|
|
112
|
+
const [openStep, setOpenStep] = useState<string | null>(CHECKLIST_STEPS[0].label);
|
|
113
|
+
|
|
114
|
+
// initialState is restored from the ?customAppInternalState search param by the host.
|
|
115
|
+
useEffect(() => {
|
|
116
|
+
if (!initialState) return;
|
|
117
|
+
try {
|
|
118
|
+
const saved = JSON.parse(initialState) as AppInternalState;
|
|
119
|
+
if (typeof saved.openStep === 'string' || saved.openStep === null) {
|
|
120
|
+
setOpenStep(saved.openStep);
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
// ignore malformed saved state
|
|
124
|
+
}
|
|
125
|
+
}, [initialState]);
|
|
126
|
+
|
|
127
|
+
function handleStepToggle(label: string, isOpen: boolean) {
|
|
128
|
+
const next = isOpen ? label : null;
|
|
129
|
+
setOpenStep(next);
|
|
130
|
+
// Writes to the ?customAppInternalState search param so the URL is bookmarkable/shareable.
|
|
131
|
+
void api?.syncInternalState(JSON.stringify({ openStep: next } satisfies AppInternalState));
|
|
132
|
+
}
|
|
133
|
+
|
|
101
134
|
return (
|
|
102
135
|
<main className="min-h-screen bg-muted/50 text-foreground">
|
|
103
136
|
<section className="mx-auto flex min-h-screen w-full max-w-3xl flex-col justify-center p-4 sm:p-8">
|
|
@@ -118,8 +151,12 @@ function AppContent() {
|
|
|
118
151
|
</div>
|
|
119
152
|
|
|
120
153
|
<div className="flex flex-col gap-4 px-4">
|
|
121
|
-
{CHECKLIST_STEPS.map((step
|
|
122
|
-
<Collapsible
|
|
154
|
+
{CHECKLIST_STEPS.map((step) => (
|
|
155
|
+
<Collapsible
|
|
156
|
+
key={step.label}
|
|
157
|
+
open={openStep === step.label}
|
|
158
|
+
onOpenChange={(isOpen) => handleStepToggle(step.label, isOpen)}
|
|
159
|
+
>
|
|
123
160
|
<CollapsibleTrigger className="w-full">
|
|
124
161
|
<div className="flex w-full min-w-0 items-center justify-between gap-3 text-left">
|
|
125
162
|
<span className="text-lg">{step.label}</span>
|
|
@@ -202,12 +239,28 @@ function AppContent() {
|
|
|
202
239
|
|
|
203
240
|
type AppProps = {
|
|
204
241
|
deps?: ComponentProps<typeof CogniteSdkProvider>['deps'];
|
|
242
|
+
connectToHostApp?: typeof connectToHostAppImpl;
|
|
205
243
|
};
|
|
206
244
|
|
|
207
|
-
function App({
|
|
245
|
+
function App({
|
|
246
|
+
deps,
|
|
247
|
+
connectToHostApp = deps?.connectToHostApp ?? connectToHostAppImpl,
|
|
248
|
+
}: AppProps) {
|
|
249
|
+
const [connection, setConnection] = useState<{ api: HostAppAPI; initialState?: string } | null>(null);
|
|
250
|
+
|
|
251
|
+
useEffect(() => {
|
|
252
|
+
let cancelled = false;
|
|
253
|
+
void connectToHostApp().then((result) => {
|
|
254
|
+
if (!cancelled) setConnection(result);
|
|
255
|
+
});
|
|
256
|
+
return () => {
|
|
257
|
+
cancelled = true;
|
|
258
|
+
};
|
|
259
|
+
}, [connectToHostApp]);
|
|
260
|
+
|
|
208
261
|
return (
|
|
209
262
|
<CogniteSdkProvider loadingFallback={loadingFallback} errorFallback={errorFallback} deps={deps}>
|
|
210
|
-
<AppContent />
|
|
263
|
+
<AppContent api={connection?.api ?? null} initialState={connection?.initialState} />
|
|
211
264
|
</CogniteSdkProvider>
|
|
212
265
|
);
|
|
213
266
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var xe=Object.defineProperty;var re=n=>{throw TypeError(n)};var s=(n,e)=>xe(n,"name",{value:e,configurable:!0});var ie=(n,e,t)=>e.has(n)||re("Cannot "+t);var R=(n,e,t)=>(ie(n,e,"read from private field"),t?t.call(n):e.get(n)),se=(n,e,t)=>e.has(n)?re("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),oe=(n,e,t,r)=>(ie(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{existsSync as dt}from"fs";import{mkdir as lt,readFile as ut}from"fs/promises";import{basename as gt,dirname as ft}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:be(e.cause)}}};s(H,"HintedError");var l=H;var ae="https://docs.cognite.com/cdf/access/",Ie="https://status.cognite.com";function Ce(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:ae};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:ae};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:Ie};default:return{}}}s(Ce,"defaultHintForStatus");var M=class M 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=Ce(t),i=super.deriveDefaults(e);return{hint:r.hint??i.hint,helpUrl:r.helpUrl}}};s(M,"HintedHttpError");var k=M;function Pe(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(Pe,"hintForErrno");function be(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,i=Pe(r.code,r);if(i!==void 0)return i;e=r.cause}}s(be,"hintForCause");import{inspect as Te}from"util";var j="[REDACTED]",w,D=class D{constructor(e){se(this,w);oe(this,w,e)}toString(){return j}toJSON(){return j}[Te.custom](){return j}expose(){return R(this,w)}equals(e){return R(this,w)===R(e,w)}static from(e){return new D(e)}};w=new WeakMap,s(D,"SensitiveString");var E=D;var pe="https://docs.cognite.com/cdf/access/";function g(n){return n!==null&&typeof n=="object"}s(g,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(C,"isHttpError");function Re(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${pe}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${pe}`;default:return}}s(Re,"httpStatusHint");function f(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=Re(e.status);return t?Object.assign(new Error(`${e.message}
|
|
4
|
+
${t}`),{cause:e}):null}s(f,"enrichedHttpError");function De(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(De,"findMissingArray");function $e(n,e){if(!C(n)||n.status!==400)return!1;let t=De(n);return t?t.some(r=>g(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}s($e,"isMissingExternalIdError");function $(n,e){return C(n)&&n.status===404||$e(n,e)}s($,"isNotFoundError");var de=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],le=["ACTIVE","PREVIEW"],G=class G extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};s(G,"AppVersionNotFoundError");var U=G,q=class q extends Error{constructor(e){super(`App ${e} not found`),this.name="AppNotFoundError",this.appExternalId=e}};s(q,"AppNotFoundError");var N=q;function V(n,e){return n.includes(e)}s(V,"includesValue");function Ue(n){return V(de,n)}s(Ue,"isAppVersionLifecycleState");function Ne(n){return V(le,n)}s(Ne,"isAppVersionAlias");function Ve(n){return typeof n.version=="string"&&Ue(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||Ne(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(Ve,"isAppVersion");function ce(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(!Ve(n)){let e=JSON.stringify(n).slice(0,300);throw new Error(`Invalid version response: missing or malformed fields. Got: ${e}`)}return n}s(ce,"parseAppVersion");function Fe(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(Fe,"parseAppMetadata");var J=class J{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 f(i)??i}}async updateApps(e){try{await this.client.post(`${this.appsBasePath}/update`,{data:{items:e}})}catch(t){throw f(t)??t}}async getApp(e){let t=`${this.appsBasePath}/${encodeURIComponent(e)}`;try{let r=await this.client.get(t);return Fe(r.data)}catch(r){throw $(r,[e])?new N(e):f(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=E.from(d),h=`${this.client.getBaseUrl()}${c}`,ee=new AbortController,Ae=setTimeout(()=>ee.abort(),300*1e3),A;try{A=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${S.expose()}`},body:a,signal:ee.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 ${h}`,{cause:m,hint:"Check your network connection. Uploads can also fail behind a proxy that blocks multipart POST requests."})}finally{clearTimeout(Ae)}if(!A.ok){let m=await A.text(),v;try{v=JSON.parse(m)}catch{}let T=m;if(g(v)){let x=v.error;if(typeof x=="string")T=x;else if(g(x)){let I=x.message,ne=x.code;T=typeof I=="string"?I:ne!=null?`Unknown error (code: ${ne})`:m}else{let I=v.message;T=typeof I=="string"?I:m}}let te=A.headers.get("x-request-id"),ve=te?` | X-Request-ID: ${te}`:"",ke=g(v)?v:m;throw new k(`Upload failed: ${A.status} \u2014 ${T}${ve}`,{httpStatusCode:A.status,requestUrl:h,responseBody:ke})}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 ce(a.data)}catch(a){throw $(a,[e,t])?new U(e,t):f(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 ce(o[0])}catch(i){if($(i,[e]))return null;throw f(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 f(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 f(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 f(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 Be(a.data)}catch(a){throw f(a)??a}}};s(J,"AppHostingApi");var F=J,Oe=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY","SCOPE_MISMATCH","VERIFICATION_FAILED"],_e=["developer","certifier"];function Be(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=Le(t);return r?[r]:[]})}s(Be,"parseStoredSignatures");function Le(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(_e,t)||typeof r!="number"||typeof i!="number"||typeof o!="number"||!V(Oe,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:i,createdTime:o,status:a}}s(Le,"parseStoredSignature");function He(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(He,"diffAppMetadata");function Me(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(Me,"formatMetadataDriftError");var z=class z{constructor(e){this.api=new F(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(C(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=He(i,{name:t,description:r});if(o.length!==0)throw new l(Me(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(z,"AppHostingClient");var P=z;import{execFileSync as O}from"child_process";import y from"fs";import u from"path";import{parseAndValidateManifestConfig as qe}from"@cognite/app-sdk/vite";import{BlobReader as Je,Uint8ArrayWriter as ze,ZipWriter as Ye}from"@zip.js/zip.js";import{execFileSync as je}from"child_process";function Ge(n={}){let{execFileSync:e=je}=n;try{return e("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}s(Ge,"isGitInstalled");function ue(n={}){if(!Ge(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(ue,"throwIfGitMissing");var Y="package.json",K="package-lock.json",ge="manifest.json",W=".cognite",Ke=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],X=class X{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,Y);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=u.join(this.appRoot,K);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 Ye(new ze,{level:9}),i=s(async(c,d)=>{await r.add(d,new Je(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 h=u.join(c,S.name);S.isDirectory()?await o(h):await i(h,u.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),a;try{await o(this.distPath);let c=u.join(this.appRoot,Y);await i(c,u.posix.join(W,Y));let d=u.join(this.appRoot,ge);if(y.existsSync(d)){let h=y.readFileSync(d,"utf-8");qe(h,d),await i(d,u.posix.join(W,ge))}let S=u.join(this.appRoot,K);await i(S,u.posix.join(W,K)),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=O("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw ue(),new l("Source packaging requires a git repository.",{hint:"Run `git init` first.",shouldReport:!1,cause:c})}let r=O("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{O("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=O("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=>Ke.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(X,"ApplicationPackager");var b=X;import We from"path";var fe=".cognite-bundles";function he(n,e){return`${n}-${e}.zip`}s(he,"bundleFileName");function _(n,e,t){return We.join(n,fe,he(e,t))}s(_,"bundlePath");import{CogniteClient as ot}from"@cognite/sdk";function me(n=process.env){return n.COGNITE_ALPHA_ENABLE_SESSION_AUTH?.trim().toLowerCase()==="true"}s(me,"isSessionAuthEnabled");function Xe(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}s(Xe,"exponentialBackoffWithJitter");function Ze(n){return new Promise(e=>setTimeout(e,n))}s(Ze,"sleep");async function ye(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),i=e.delayInMsCalculator??Xe;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 Ze(p),o++}}s(ye,"retryAsync");var Qe="https://auth.cognite.com/oauth2/token",et=s(n=>typeof n=="object"&&n!==null&&"access_token"in n&&typeof n.access_token=="string","hasAccessToken");async function Se({idp:n,tokenUrl:e,init:t,missingTokenHint:r}){let i;try{i=await ye(()=>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 k(`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(!et(a))throw new l(`No access token in ${n} authentication response`,{hint:r});return E.from(a.access_token)}s(Se,"fetchOAuthToken");var tt=s(n=>{let e=n.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),r={};for(let[i,o]of Object.entries(t))if(typeof o=="string"){let a=i.toLowerCase().replace(/_/g,"-");r[a]=o}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),nt=s((n,e)=>{let t;if(e.DEPLOYMENT_SECRET&&(t=e.DEPLOYMENT_SECRET),t||(t=tt(e)[n]),t||(t=e[n]),!t)throw new l(`Set the ${n} environment variable (named by deploySecretName in app.json) to your deploy client secret, e.g. in a .env file.`,{shouldReport:!1,hint:me(e)?"Alternatively, run `cognite auth login` to use your session, or pass --interactive for a one-off browser login.":"Alternatively, pass --interactive for a one-off browser login."});return E.from(t)},"getSecretFromEnv"),rt=s((n,e)=>{let t=e.expose();return Se({idp:"CDF",tokenUrl:Qe,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"),Ee=s(({idp:n,tokenUrl:e,clientId:t,clientSecret:r,scopes:i,missingTokenHint:o})=>Se({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"),it=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"),st=s((n,e,t,r,i)=>Ee({idp:"Entra ID",tokenUrl:`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,clientId:n,clientSecret:e.expose(),scopes:i!==void 0?i:[it(r)],missingTokenHint:"Check the client ID and tenant ID in app.json and the deployment secret in your environment."}),"getTokenEntra"),Z=s(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return E.from(e.COGNITE_TOKEN);let{deployClientId:t,deploySecretName:r,idpType:i="cdf",tenantId:o,baseUrl:a,scopes:p,tokenUrl:c}=n,d=nt(r,e);if(i==="oauth"){if(!c)throw new Error("OAuth authentication requires 'tokenUrl' in deployment configuration");return Ee({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 st(t,d,o,a,p)}return rt(t,d)},"getToken");async function B(n,e,t=process.env,r){let i=await Z(n,t),o=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new ot(p)))({appId:e,project:n.project,baseUrl:o,oidcTokenProvider:s(async()=>i.expose(),"oidcTokenProvider")});return await a.authenticate(),a}s(B,"getSdk");import{existsSync as at,readFileSync as pt}from"fs";var L=[".dev.sig",".cert.sig"];function ct(n,e={}){let t=e.existsSync??at,r=e.readFileSync??((o,a)=>pt(o,a)),i=[];for(let o of L){let a=`${n}${o}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&i.push(p)}return i}s(ct,"discoverSignatures");async function we(n,e,{existsSync:t=dt,mkdir:r=lt,createZip:i=s((o,a)=>new b(o).createZip(a,!0),"createZipFn")}={}){let{externalId:o,versionTag:a}=n,p=_(e,o,a);if(t(p)){let d=L.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(ft(p),{recursive:!0}),await i(`${e}/dist`,p)}s(we,"packageBundle");async function Q(n,e,t,r,{readFile:i=ut,upload:o=s(async(a,p)=>new P(n).deploy(e.externalId,e.name,e.description,e.versionTag,a,p,r),"uploadFn")}={}){let a=_(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,gt(a))}s(Q,"uploadBundle");var ht=s(async(n,e,t)=>{let r=await B(n,t);await we(e,t),await Q(r,e,t,n.published)},"deploy"),mt=s(async(n,e,t)=>{let r=await B(n,t);await Q(r,e,t,n.published)},"deployBundle");export{P as a,b,fe as c,he as d,_ as e,Z as f,B as g,L as h,ct as i,we as j,Q as k,ht as l,mt as m};
|