@cognite/cli 1.0.0 → 1.1.0-alpha.49
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 +1 -1
- package/_templates/app/new/claude/mcp.json.ejs.t +11 -0
- package/_templates/app/new/cursor/mcp.json.ejs.t +10 -0
- package/_templates/app/new/prompt.js +3 -3
- package/_templates/app/new/root/AGENTS.md.ejs.t +12 -6
- package/_templates/app/new/root/package.json.ejs.t +5 -2
- package/_templates/app/new/vscode/mcp.json.ejs.t +11 -0
- package/_vendor/spec-kit/README.md +8 -8
- package/dist/chunk-EILVJ2ZW.js +1 -0
- package/dist/chunk-HE6P4LDC.js +9 -0
- package/dist/cli/cli.js +155 -37
- package/dist/deploy/index.d.ts +5 -7
- package/dist/deploy/index.js +1 -9
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/sdk-runtime/index.d.ts +199 -0
- package/dist/sdk-runtime/index.js +1 -0
- package/package.json +13 -14
- package/dist/auth/index.d.ts +0 -51
- package/dist/auth/index.js +0 -1
- package/dist/chunk-QGJ3VKXY.js +0 -1
- package/dist/vite/index.d.ts +0 -1
- package/dist/vite/index.js +0 -1
package/README.md
CHANGED
|
@@ -83,7 +83,7 @@ To test against your own app instead of the fixture:
|
|
|
83
83
|
|
|
84
84
|
```bash
|
|
85
85
|
cd apps/my-app
|
|
86
|
-
COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 pnpm exec
|
|
86
|
+
COGNITE_TOKEN=test-token COGNITE_BASE_URL=http://localhost:9090 pnpm exec cognite apps deploy --skip-build
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
#### Simulating error scenarios
|
|
@@ -3,7 +3,7 @@ export default [
|
|
|
3
3
|
type: 'input',
|
|
4
4
|
name: 'name',
|
|
5
5
|
message: 'What is the app name? (use kebab-case, e.g., my-awesome-app)',
|
|
6
|
-
initial: 'my-
|
|
6
|
+
initial: 'my-flows-app',
|
|
7
7
|
validate: (input) =>
|
|
8
8
|
/^[a-z][a-z0-9-]*$/.test(input)
|
|
9
9
|
? true
|
|
@@ -13,13 +13,13 @@ export default [
|
|
|
13
13
|
type: 'input',
|
|
14
14
|
name: 'displayName',
|
|
15
15
|
message: 'What is the display name? (e.g., My Awesome App)',
|
|
16
|
-
initial: 'My
|
|
16
|
+
initial: 'My Flows app',
|
|
17
17
|
},
|
|
18
18
|
{
|
|
19
19
|
type: 'input',
|
|
20
20
|
name: 'description',
|
|
21
21
|
message: 'What is the app description?',
|
|
22
|
-
initial: 'A
|
|
22
|
+
initial: 'A Flows application',
|
|
23
23
|
},
|
|
24
24
|
{
|
|
25
25
|
type: 'input',
|
|
@@ -22,7 +22,13 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
|
|
|
22
22
|
|
|
23
23
|
---
|
|
24
24
|
|
|
25
|
-
## 1.
|
|
25
|
+
## 1. UI Components
|
|
26
|
+
|
|
27
|
+
Always check `@cognite/aura/components` before reaching for a raw HTML element or custom CSS/Tailwind solution. If Aura has a component that covers the need, use it. Only fall back to custom solutions when Aura genuinely doesn't cover the use case.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 2. Dependency Injection
|
|
26
32
|
|
|
27
33
|
Inject dependencies via React context (hooks/components) or factory-override pattern (plain functions). Never hard-code dependencies.
|
|
28
34
|
|
|
@@ -51,7 +57,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
|
|
|
51
57
|
|
|
52
58
|
---
|
|
53
59
|
|
|
54
|
-
##
|
|
60
|
+
## 3. Interface-Based Services
|
|
55
61
|
|
|
56
62
|
Define an interface; implement with a class. Never reference the concrete class outside its own file.
|
|
57
63
|
|
|
@@ -68,7 +74,7 @@ export class ApiDataService implements DataService {
|
|
|
68
74
|
|
|
69
75
|
---
|
|
70
76
|
|
|
71
|
-
##
|
|
77
|
+
## 4. ViewModel Pattern
|
|
72
78
|
|
|
73
79
|
Business logic lives in `use<Name>ViewModel`. Components only render.
|
|
74
80
|
|
|
@@ -91,7 +97,7 @@ export const TodoView = () => {
|
|
|
91
97
|
|
|
92
98
|
---
|
|
93
99
|
|
|
94
|
-
##
|
|
100
|
+
## 5. Test-First Development
|
|
95
101
|
|
|
96
102
|
Write tests before implementation for all non-trivial behavior changes.
|
|
97
103
|
|
|
@@ -187,7 +193,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
|
|
|
187
193
|
|
|
188
194
|
---
|
|
189
195
|
|
|
190
|
-
##
|
|
196
|
+
## 6. TypeScript Rules
|
|
191
197
|
|
|
192
198
|
- Never use `any`; prefer `unknown` or explicit strong types
|
|
193
199
|
- Never use `as unknown as T`; for partial test doubles use `{ ...defaults, ...overrides } as T`
|
|
@@ -201,7 +207,7 @@ function createMockWindow(overrides: Partial<Window> = {}): Window {
|
|
|
201
207
|
|
|
202
208
|
---
|
|
203
209
|
|
|
204
|
-
##
|
|
210
|
+
## 7. Commits and pull requests
|
|
205
211
|
|
|
206
212
|
Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
|
|
207
213
|
|
|
@@ -20,16 +20,19 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
|
|
|
20
20
|
"test:ui": "vitest --ui",
|
|
21
21
|
"lint": "eslint . --ext .js,.mjs,.cjs,.ts,.tsx",
|
|
22
22
|
"lint:fix": "eslint . --fix --ext .js,.mjs,.cjs,.ts,.tsx",
|
|
23
|
-
"deploy": "npx @cognite/cli@latest apps deploy --interactive
|
|
24
|
-
"
|
|
23
|
+
"deploy": "npx @cognite/cli@latest apps deploy --interactive",
|
|
24
|
+
"activate": "npx @cognite/cli@latest apps activate --interactive"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@cognite/aura": "^0.1.7",
|
|
28
28
|
"@cognite/sdk": "^10.3.0",
|
|
29
|
+
"@cognite/cli": "1.1.0-alpha.49",
|
|
29
30
|
"@cognite/app-sdk": "^0.4.0",
|
|
30
31
|
"@tabler/icons-react": "^3.35.0",
|
|
31
32
|
"@tanstack/react-query": "^5.90.10",
|
|
32
33
|
"clsx": "^2.1.1",
|
|
34
|
+
"graphql": "^16.14.0",
|
|
35
|
+
"graphql-tag": "^2.12.6",
|
|
33
36
|
"react": "^18.3.1",
|
|
34
37
|
"react-dom": "^18.3.1",
|
|
35
38
|
"tailwind-merge": "^3.4.0"
|
|
@@ -4,25 +4,25 @@ Selected, generated files from [github/spec-kit](https://github.com/github/spec-
|
|
|
4
4
|
|
|
5
5
|
## Why this exists
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Flows app authors should not need Python, `uv`, or network access just because they pass `cognite create --spec-kit`.
|
|
8
8
|
|
|
9
|
-
Instead,
|
|
9
|
+
Instead, Flows builder app maintainers refresh spec-kit inside this monorepo, commit the selected generated files here, and let `cognite create` copy them into new apps. That keeps end-user scaffolding fast and JS/TS-only while still letting us track upstream spec-kit intentionally.
|
|
10
10
|
|
|
11
11
|
## Maintainer-only refresh
|
|
12
12
|
|
|
13
|
-
The refresh script is for
|
|
13
|
+
The refresh script is for Flows app maintainers only:
|
|
14
14
|
|
|
15
15
|
```sh
|
|
16
16
|
pnpm --filter @cognite/cli refresh-spec-kit <tag>
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
It requires `uv` locally, which provides `uvx`. That is acceptable for maintainers; it must not become a requirement for generated
|
|
19
|
+
It requires `uv` locally, which provides `uvx`. That is acceptable for maintainers; it must not become a requirement for generated Flows apps.
|
|
20
20
|
|
|
21
21
|
The script runs spec-kit's own `specify init` for the requested tag, stages the selected output in a temporary directory, and swaps it into `_vendor/spec-kit` only after all copies succeed.
|
|
22
22
|
|
|
23
23
|
## What we vendor
|
|
24
24
|
|
|
25
|
-
We vendor the parts
|
|
25
|
+
We vendor the parts Flows apps uses:
|
|
26
26
|
|
|
27
27
|
- generated `commands/speckit.{specify,clarify,plan,tasks,implement,analyze,checklist}.md`
|
|
28
28
|
- `templates/{spec,plan,tasks,checklist}-template.md`
|
|
@@ -30,10 +30,10 @@ We vendor the parts Dune uses:
|
|
|
30
30
|
|
|
31
31
|
Deliberately excluded:
|
|
32
32
|
|
|
33
|
-
- spec-kit's `AGENTS.md`, constitution command, and constitution template, because
|
|
33
|
+
- spec-kit's `AGENTS.md`, constitution command, and constitution template, because Flows apps uses the app's `AGENTS.md` as the constitution
|
|
34
34
|
- integration metadata/workflows generated by `specify init`
|
|
35
35
|
- optional commands such as taskstoissues
|
|
36
|
-
- PowerShell scripts, until
|
|
36
|
+
- PowerShell scripts, until Flows apps chooses to support a PowerShell command set
|
|
37
37
|
- spec-kit's Python CLI, tests, and docs
|
|
38
38
|
|
|
39
|
-
**Cadence:** refresh at least once per
|
|
39
|
+
**Cadence:** refresh at least once per cognite CLI minor release, sooner if upstream ships a fix we depend on.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-EI7MMDWY.js";import{GraphQLSchema as Zt,GraphQLObjectType as er,GraphQLNonNull as x,GraphQLList as Q,GraphQLString as b,GraphQLInt as tr,GraphQLInputObjectType as Ye,printSchema as rr}from"graphql";function ie(e){return{space:e.space,externalId:e.externalId,version:e.version}}a(ie,"toSharedViewId");function St(e){switch(e){case"text":return"String";case"boolean":return"Boolean";case"int32":case"int64":return"Int";case"float32":case"float64":return"Float";case"timestamp":return"DateTime";case"date":return"Date";case"json":return"JSON";case"timeseries":return"CogniteTimeSeriesReference";case"file":return"CogniteFileReference";case"sequence":return"CogniteSequenceReference";case"enum":return"String";default:return"String"}}a(St,"dmsTypeToGraphQL");function Ne(e){if(!("source"in e)){if(e.type?.type==="direct")return e.type.list?{kind:"scalar",isList:!1,graphqlType:"JSON"}:e.type.source?{kind:"directRelation",targetView:ie(e.type.source)}:{kind:"scalar",isList:!1,graphqlType:"JSON"};if(e.type?.type==="enum"){let t=e.type,n={};if(typeof t=="object"&&t!==null&&"values"in t){let i=t.values;if(typeof i=="object"&&i!==null)for(let[r,s]of Object.entries(i))n[r]={name:typeof s=="object"&&s!==null&&"name"in s?String(s.name):void 0}}return{kind:"enum",values:Object.keys(n),valueNames:Object.fromEntries(Object.entries(n).map(([i,r])=>[i,r.name??i]))}}return{kind:"scalar",isList:e.type!==void 0&&"list"in e.type&&e.type.list===!0,graphqlType:e.type?.type?St(e.type.type):"String"}}if("through"in e)return{kind:e.connectionType==="single_reverse_direct_relation"?"reverseDirect":"reverseList",sourceView:ie(e.source),throughProperty:e.through.identifier};if(e.connectionType==="single_edge_connection"||e.connectionType==="multi_edge_connection"){let t=e.direction==="inwards"?"inwards":"outwards";return{kind:"edge",targetView:ie(e.source),direction:t}}return{kind:"scalar"}}a(Ne,"parsePropertyDescriptor");var Ee=new Set(["String","Boolean","Int","Float","DateTime","Date"]);var xt=new Set(["String","Int","Float","DateTime","Date"]);function Qe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:Ee.has(e.graphqlType??"String")}a(Qe,"isFilterableDescriptor");function Ve(e){return e.kind==="enum"?!0:e.kind!=="scalar"||e.isList===!0?!1:Ee.has(e.graphqlType??"String")}a(Ve,"isSortableDescriptor");function Fe(e){return e.kind==="directRelation"||e.kind==="enum"?!0:e.kind==="scalar"&&e.isList!==!0&&xt.has(e.graphqlType??"")}a(Fe,"hasInOpDescriptor");function Ae(e){return e.kind==="scalar"&&e.isList===!0}a(Ae,"hasListOpsDescriptor");function O(e){return e.usedFor!=="edge"}a(O,"isNodeOrAll");function T(e){return Object.entries(e.properties).map(([t,n])=>[t,Ne(n),n.description])}a(T,"parsedProperties");import{GraphQLObjectType as Pe,GraphQLNonNull as F,GraphQLString as ae,GraphQLFloat as j,GraphQLList as vt,GraphQLEnumType as kt}from"graphql";import{GraphQLScalarType as L,Kind as h}from"graphql";function oe(e){switch(e.kind){case h.STRING:case h.BOOLEAN:return e.value;case h.INT:return parseInt(e.value,10);case h.FLOAT:return parseFloat(e.value);case h.OBJECT:{let t={};for(let n of e.fields)t[n.name.value]=oe(n.value);return t}case h.LIST:return e.values.map(oe);case h.NULL:return null;default:return null}}a(oe,"parseLiteralJSON");var Rt=new L({name:"DateTime",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),It=new L({name:"Date",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),se=new L({name:"JSON",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:oe}),Tt=new L({name:"CogniteTimeSeriesReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),Dt=new L({name:"CogniteFileReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),Lt=new L({name:"CogniteSequenceReference",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.STRING?e.value:null,"parseLiteral")}),$=new L({name:"ListLimit",description:"Limit for list/search queries (1\u20131000).",serialize:a(e=>e,"serialize"),parseValue:a(e=>e,"parseValue"),parseLiteral:a(e=>e.kind===h.INT?parseInt(e.value,10):null,"parseLiteral")}),v={DateTime:Rt,Date:It,JSON:se,CogniteTimeSeriesReference:Tt,CogniteFileReference:Dt,CogniteSequenceReference:Lt,ListLimit:$};var bt=new kt({name:"AggregateFunction",values:{count:{value:"count"},avg:{value:"avg"},sum:{value:"sum"},min:{value:"min"},max:{value:"max"},histogram:{value:"histogram"}}}),qe={function:{type:new F(bt)},property:{type:ae},interval:{type:j}},Ct=new Pe({name:"HistogramBucket",fields:{start:{type:new F(j)},count:{type:new F(j)}}}),_e=new Pe({name:"AggregateResult",fields:{aggregate:{type:new F(ae)},property:{type:ae},value:{type:j},buckets:{type:new vt(new F(Ct))},group:{type:se}}});import{GraphQLObjectType as pe,GraphQLNonNull as C,GraphQLList as Nt,GraphQLString as ce,GraphQLBoolean as Et}from"graphql";var Qt=new pe({name:"PageInfo",fields:{endCursor:{type:ce},hasNextPage:{type:new C(Et)}}}),B=new pe({name:"NodeReference",fields:{space:{type:new C(ce)},externalId:{type:new C(ce)}}});function K(e,t){return new pe({name:`${e}Connection`,fields:{items:{type:new C(new Nt(new C(t)))},pageInfo:{type:new C(Qt)}}})}a(K,"makeConnectionType");import{GraphQLInputObjectType as N,GraphQLList as S,GraphQLNonNull as je,GraphQLString as k,GraphQLBoolean as w,GraphQLFloat as Mt,GraphQLInt as Ot}from"graphql";import{GraphQLObjectType as Vt,GraphQLNonNull as Ge,GraphQLList as Ft,GraphQLString as U,GraphQLBoolean as At,GraphQLInt as Pt,GraphQLFloat as qt,GraphQLEnumType as _t}from"graphql";function Me(e){return e==="String"?U:e==="Boolean"?At:e==="Int"?Pt:e==="Float"?qt:v[e]??U}a(Me,"scalarForName");function Oe(e){return{typeRegistry:new Map,connectionRegistry:new Map,viewsByExtId:new Map(e.map(t=>[t.externalId,t])),enumRegistry:new Map,enumFilterRegistry:new Map}}a(Oe,"createTypeContext");function Gt(e){let t=e.replace(/[^_A-Za-z0-9]/g,"_");return/^[0-9]/.test(t)&&(t=`_${t}`),t||"_UNKNOWN"}a(Gt,"sanitizeEnumValue");function le(e,t,n,i){let r=n.enumRegistry.get(e);if(r)return r;let s=new _t({name:e,values:Object.fromEntries(t.map(o=>[Gt(o),{value:o,description:i?.[o]}]))});return n.enumRegistry.set(e,s),s}a(le,"getOrCreateEnumType");function $e(e,t){return new Vt({name:e.externalId,description:e.description??e.name,fields:a(()=>{let n={space:{type:new Ge(U)},externalId:{type:new Ge(U)}};for(let[i,r,s]of T(e))if(r.kind==="scalar")r.isList?n[i]={type:new Ft(Me(r.graphqlType??"String")),description:s}:n[i]={type:Me(r.graphqlType??"String"),description:s};else if(r.kind==="enum"){let o=`${e.externalId}${i.charAt(0).toUpperCase()}${i.slice(1)}`;n[i]={type:le(o,r.values,t,r.valueNames),description:s}}else if(r.kind==="directRelation"){let o=t.typeRegistry.get(r.targetView.externalId)??B;n[i]={type:o,description:s}}else if(r.kind==="reverseList"||r.kind==="edge"){let o=r.kind==="reverseList"?r.sourceView.externalId:r.targetView.externalId,u=t.typeRegistry.get(o)??B,d=t.connectionRegistry.get(o);d||(d=K(o,u),t.connectionRegistry.set(o,d)),n[i]={type:d,description:s}}else if(r.kind==="reverseDirect"){let o=t.typeRegistry.get(r.sourceView.externalId)??B;n[i]={type:o,description:s}}return n},"fields")})}a($e,"generateViewObjectType");function E(e,t,n){let i={isNull:{type:w},exists:{type:w},eq:{type:t}};return n.hasIn&&(i.in={type:new S(t)}),n.hasPrefix&&(i.prefix={type:k}),n.hasRange&&(i.gte={type:t},i.gt={type:t},i.lte={type:t},i.lt={type:t}),n.hasListOps&&(i.containsAny={type:new S(t)},i.containsAll={type:new S(t)},i.overlaps={type:new S(t)}),new N({name:e,fields:i})}a(E,"makeScalarFilter");var H=E("StringFilter",k,{hasIn:!0,hasPrefix:!0}),$t=E("BooleanFilter",w,{}),jt=E("IntFilter",Ot,{hasIn:!0,hasRange:!0}),Bt=E("FloatFilter",Mt,{hasIn:!0,hasRange:!0}),Kt=E("DateTimeFilter",v.DateTime,{hasIn:!0,hasRange:!0}),Ut=E("DateFilter",v.Date,{hasIn:!0,hasRange:!0}),Ht=new N({name:"StringListFilter",fields:{isNull:{type:w},exists:{type:w},containsAny:{type:new S(k)},containsAll:{type:new S(k)},overlaps:{type:new S(k)}}}),A=new N({name:"DirectRelationRef",fields:{space:{type:new je(k)},externalId:{type:new je(k)}}}),zt=new N({name:"DirectRelationFilter",fields:{isNull:{type:w},exists:{type:w},eq:{type:A},in:{type:new S(A)}}});function Xt(e){switch(e){case"String":return H;case"Boolean":return $t;case"Int":return jt;case"Float":return Bt;case"DateTime":return Kt;case"Date":return Ut;default:return H}}a(Xt,"scalarFilterForName");var Be=["space","externalId"];function Ke(e,t,n){let i=t.get(e.externalId),r={};for(let o of Be)r[o]={type:H};let s=new Set(Be);for(let[o,u]of T(e)){if(s.has(o))continue;let d=Qe(u),p=Ae(u);if(!(!d&&!p))if(u.kind==="directRelation"){let c={isNull:{type:w},exists:{type:w},eq:{type:A},in:{type:new S(A)}};Fe(u)&&(c.in={type:new S(A)});let l=t.get(u.targetView.externalId);l&&(c.nested={type:l}),r[o]=l?{type:new N({name:`_${e.externalId}_${o}_Filter`,fields:c})}:{type:zt}}else if(u.kind==="enum"){let c=`${e.externalId}${o.charAt(0).toUpperCase()}${o.slice(1)}`,l=le(c,u.values,n),m=n.enumFilterRegistry.get(c);m||(m=new N({name:`${c}Filter`,fields:{isNull:{type:w},exists:{type:w},eq:{type:l},in:{type:new S(l)}}}),n.enumFilterRegistry.set(c,m)),r[o]={type:m}}else if(p)r[o]={type:Ht};else{let c=u.kind==="scalar"?u.graphqlType??"String":"String",l=Xt(c);l&&(r[o]={type:l})}}return{...r,hasData:{type:w},matchAll:{type:w},_and:{type:new S(i)},_or:{type:new S(i)},_not:{type:i}}}a(Ke,"generateFilterFields");import{GraphQLEnumType as Ue,GraphQLInputObjectType as He,GraphQLList as Yt,GraphQLNonNull as z,GraphQLString as Jt,GraphQLBoolean as Wt}from"graphql";var X=new Ue({name:"SortDirection",values:{ASC:{value:"ascending"},DESC:{value:"descending"}}});function ze(e){let t=[];for(let[i,r]of T(e))Ve(r)&&t.push(i);if(t.length===0)return null;let n=new Ue({name:`${e.externalId}SortField`,values:Object.fromEntries(t.map(i=>[i,{value:i}]))});return new He({name:`${e.externalId}Sort`,fields:{field:{type:new z(n)},direction:{type:new z(X)},nullsFirst:{type:Wt}}})}a(ze,"generateSortInput");var Xe=new He({name:"SearchSort",fields:{property:{type:new z(new Yt(new z(Jt)))},direction:{type:X}}});function Je(e){let t=e.filter(O),n=Oe(t);for(let c of t){let l=$e(c,n);n.typeRegistry.set(c.externalId,l)}let i=new Map;for(let c of t){let l=new Ye({name:`${c.externalId}Filter`,fields:a(()=>Ke(c,i,n),"fields")});i.set(c.externalId,l)}let r={};for(let c of t){let l=c.externalId,m=n.typeRegistry.get(l),f=n.connectionRegistry.get(l);f||(f=K(l,m),n.connectionRegistry.set(l,f));let g=i.get(l),y=ze(c),D={limit:{type:$},cursor:{type:b},filter:{type:g}};y&&(D.sort={type:new Q(y)}),r[`query${l}`]={type:new x(f),args:D},r[`get${l}ById`]={type:m,args:{space:{type:new x(b)},externalId:{type:new x(b)}}},r[`count${l}`]={type:new x(tr),args:{filter:{type:g}}},r[`search${l}`]={type:new x(f),args:{query:{type:b},limit:{type:$},filter:{type:g},sort:{type:new Q(new x(Xe))},properties:{type:new Q(new x(b))}}},r[`aggregate${l}`]={type:new x(new Q(new x(_e))),args:{filter:{type:g},aggregates:{type:new Q(new x(new Ye({name:`${l}AggregateRequest`,fields:qe})))},groupBy:{type:new Q(new x(b))},query:{type:b}}}}let s=[];for(let[c,l]of n.typeRegistry)s.push({name:l.name,source:`typeRegistry[${c}]`});for(let[c,l]of n.connectionRegistry)s.push({name:l.name,source:`connectionRegistry[${c}]`});let o=new Map;for(let{name:c,source:l}of s)o.has(c)||o.set(c,[]),o.get(c).push(l);for(let[c,l]of o)l.length>1&&console.error(`[dune] duplicate type "${c}" from: ${l.join(", ")}`);let u=new Zt({query:new er({name:"Query",fields:r}),types:[X,...Object.values(v),...n.enumRegistry.values()]}),d=new Map;for(let c of t){let l=new Map;for(let[m,f]of T(c))l.set(m,f);d.set(c.externalId,{view:{space:c.space,externalId:c.externalId,version:c.version},properties:l})}let p={view(c){let l=d.get(c.externalId);if(!l)throw new Error(`SchemaKnowledge: no view for externalId "${c.externalId}"`);return l},property(c,l){return d.get(c.externalId)?.properties.get(l)}};return{schema:u,sdl:rr(u),schemaKnowledge:p}}a(Je,"buildSchema");async function We(e,t){let i=(await t.dataModels.retrieve([{space:e.space,externalId:e.dataModelExternalId,version:e.dataModelVersion}],{inlineViews:!1})).items[0];if(!i)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} not found`);if(!i.views?.length)throw new Error(`Data model ${e.space}/${e.dataModelExternalId}/${e.dataModelVersion} has no views`);let r=i.views.map(o=>({space:o.space,externalId:o.externalId,version:o.version}));return(await t.views.retrieve(r,{includeInheritedProperties:!0})).items}a(We,"fetchViews");import{execute as nr,parse as Dn}from"graphql";function Ze(e,t){return async(n,i)=>{let r=await nr({schema:e,document:n,variableValues:i,rootValue:t,fieldResolver:a((s,o,u,d)=>{let p=s[d.fieldName];return typeof p=="function"?p(s,o,u,d):p},"fieldResolver")});if(r.errors?.length)throw r.errors[0];return r.data}}a(Ze,"createDuneRequester");import{CogniteError as gr}from"@cognite/sdk";function et(){return{initialBatchLimit:1e3,maxBatchLimit:5e3,searchLimit:1e3,inFilterChunkSize:100,previewLimit:3,nestedDetailLimit:5,enableRemoveNotConnected:!1,max408Retries:3,max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4,maxNestingDepth:2,maxTotalItems:1e4}}a(et,"defaultPlannerConfig");var fe=class fe extends Error{constructor(t){super(t),this.name="PlannerValidationError"}};a(fe,"PlannerValidationError");var I=fe;function J(e){return e.connections.size===0?0:1+Math.max(...[...e.connections.values()].map(t=>J(t.select)))}a(J,"selectionDepth");function mr(e,t,n){for(let i of t.scalars)if(i!=="*"&&!n.property(e,i))throw new I(`Property "${i}" does not exist on view ${e.externalId}/${e.version}`);for(let[i]of t.connections)if(!n.property(e,i))throw new I(`Connection "${i}" does not exist on view ${e.externalId}/${e.version}`)}a(mr,"validateSelection");function V(e){return{hasData:[e]}}a(V,"hasDataFilter");function rt(e,t){let n=V(t);return e?{and:[e,n]}:n}a(rt,"scopedFilter");function nt(e,t,n,i,r){return{name:"0",kind:"root",view:e,filter:rt(t,e),sort:n&&n.length>0?n:void 0,select:i.length>0?i:["*"],limit:r,queryable:!0}}a(nt,"makeRootStep");function it(e,t,n,i,r,s){return{name:e,from:t.name,kind:"directRelation",view:i,through:{view:t.view,property:n},direction:"outwards",filter:V(i),select:r.length>0?r:["*"],limit:s,queryable:!0,fieldName:n}}a(it,"makeDirectRelationStep");function ot(e,t,n,i,r,s,o){return{name:e,from:t.name,kind:"reverseDirect",view:i,through:{view:i,property:r},direction:"inwards",filter:V(i),select:s.length>0?s:["*"],limit:o,queryable:!0,fieldName:n}}a(ot,"makeReverseDirectStep");function st(e,t,n,i,r,s,o){return{name:e,from:t.name,kind:"reverseList",view:i,through:{view:i,property:r},direction:"inwards",filter:V(i),select:s.length>0?s:["*"],limit:o,queryable:!1,fieldName:n}}a(st,"makeReverseListStep");function at(e,t,n,i,r,s,o,u){let d={name:e,from:n.name,kind:"edgeIntermediate",view:r,direction:s,filter:void 0,select:[],limit:u,limitEach:u,queryable:!0},p={name:t,from:e,kind:"edge",view:r,filter:V(r),select:o.length>0?o:["*"],limit:u,queryable:!0,fieldName:i,chainTo:s==="outwards"?"destination":"source"};return[d,p]}a(at,"makeEdgeSteps");function Y(e){return{type:"view",space:e.space,externalId:e.externalId,version:e.version}}a(Y,"toRef");function P(e,t,n,i,r,s){let o=0;for(let[u,d]of n.connections){let p=r.property(t,u);if(!p)continue;o++;let c=d.limit??i,l=d.select.scalars,m=d.select,f=`${e.name}_${o}`;if(p.kind==="directRelation"){let g=Y(p.targetView),y=it(f,e,u,g,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="reverseDirect"){let g=Y(p.sourceView),y=ot(f,e,u,g,p.throughProperty,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="reverseList"){let g=Y(p.sourceView),y=st(f,e,u,g,p.throughProperty,l,c);s.push(y),P(y,g,m,i,r,s)}else if(p.kind==="edge"){let g=Y(p.targetView),y=`${e.name}_${o}_e`,[D,M]=at(y,f,e,u,g,p.direction,l,c);s.push(D,M),P(M,g,m,i,r,s)}}}a(P,"addConnectionSteps");function W(e,t,n,i,r,s,o){s&&mr(e,t,s);let u=nt(e,n,i,t.scalars,r),d=[u];return s&&P(u,e,t,o??r,s,d),d}a(W,"buildSteps");function ge(e,t){let n=new Set,i=new Map(e.map(r=>[r.name,r]));for(let r of e){if(r.queryable)continue;let s=r.from;if(!s||s in t)continue;let o=i.get(s);o?.view&&(t[s]={sources:[{source:o.view,properties:["*"]}]},n.add(s))}return n}a(ge,"injectPhantomSelects");function fr(e){let t=e.property.view;return{property:[t.space,`${t.externalId}/${t.version}`,e.property.property],direction:e.direction,nullsFirst:e.nullsFirst??!1}}a(fr,"compileSortClause");function ye(e,t,n){let i={},r={};for(let p of e){if(!p.queryable)continue;if(p.kind==="edgeIntermediate"){let m={edges:{from:p.from,direction:p.direction,maxDistance:1},limit:Math.min(p.limit,n)};p.filter&&(m.edges.filter=p.filter),p.limitEach!=null&&(m.edges.limitEach=p.limitEach),i[p.name]=m,r[p.name]={sources:[]};continue}let c={filter:p.filter};p.from&&(c.from=p.from),p.chainTo?c.chainTo=p.chainTo:p.through?(c.through={view:p.through.view,identifier:p.through.property},c.direction=p.direction):p.direction&&(c.direction=p.direction);let l={limit:Math.min(p.limit,n),nodes:c};p.sort&&p.sort.length>0&&(l.sort=p.sort.map(fr)),i[p.name]=l,r[p.name]={sources:[{source:p.view,properties:p.select}]}}let s=ge(e,r),o={with:i,select:r},u={},d=!1;for(let p of e){if(!p.queryable||p.kind==="edgeIntermediate")continue;let c=t.get(p.name);c!=null&&(u[p.name]=c,d=!0)}return d&&(o.cursors=u),{query:o,tempSelectSteps:s}}a(ye,"compileQuery");function he(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}a(he,"chunkArray");var we=class we{constructor(t,n){this.dms=t;this.config=n}async run(t,n,i){let{response:r,tempSelectSteps:s,batchLimit:o}=await this.queryWithRetry(t,n,i),u={},d=new Map;for(let[p,c]of Object.entries(r.items))u[p]=c,d.set(p,r.nextCursor[p]??null);return await this.fetchReverseLists(t,u),{batch:u,nextCursors:d,tempSelectSteps:s,batchLimit:o}}async queryWithRetry(t,n,i){let r=i,s=0;for(;;){let{query:o,tempSelectSteps:u}=ye(t,n,r);try{return{response:await this.dms.query({with:o.with,select:o.select,cursors:o.cursors}),tempSelectSteps:u,batchLimit:r}}catch(d){if(d instanceof gr&&d.status===408){if(s>=this.config.max408Retries)throw d;s++,r=Math.max(1,Math.floor(r/2))}else throw d}}}async fetchReverseLists(t,n){let i=t.filter(r=>!r.queryable&&r.from);for(let r of i){let s=n[r.from]??[];if(s.length===0){n[r.name]=[];continue}let o=s.map(l=>({space:l.space,externalId:l.externalId})),u=r.through,d=[u.view.space,`${u.view.externalId}/${u.view.version}`,u.property],p=he(o,this.config.inFilterChunkSize),c=[];for(let l of p){let m=r.limit-c.length;if(m<=0)break;let f=await this.dms.search({view:r.view,filter:{in:{property:d,values:l}},limit:m});c.push(...f.items)}n[r.name]=c}}async fetchQueryableConnections(t,n){let i=t.filter(r=>r.queryable&&r.from&&(r.kind==="directRelation"||r.kind==="reverseDirect"));for(let r of i){let s=n[r.from]??[];if(s.length===0){n[r.name]=[];continue}if(r.kind==="directRelation"){let o=r.through,u=`${o.view.externalId}/${o.view.version}`,d=[],p=new Set;for(let m of s){let f=m.properties?.[o.view.space]?.[u]?.[o.property];if(f&&typeof f=="object"&&"space"in f&&"externalId"in f){let g=f,y=`${g.space}:${g.externalId}`;p.has(y)||(p.add(y),d.push({space:g.space,externalId:g.externalId}))}}if(d.length===0){n[r.name]=[];continue}let c=he(d,this.config.inFilterChunkSize),l=[];for(let m of c){let f=await this.dms.retrieve({items:m.map(g=>({instanceType:"node",...g})),sources:[{source:r.view}]});l.push(...f.items)}n[r.name]=l}else{let o=s.map(l=>({space:l.space,externalId:l.externalId})),u=r.through,d=[u.view.space,`${u.view.externalId}/${u.view.version}`,u.property],p=he(o,this.config.inFilterChunkSize),c=[];for(let l of p){let m=r.limit-c.length;if(m<=0)break;let f=await this.dms.search({view:r.view,filter:{in:{property:d,values:l}},limit:m});c.push(...f.items)}n[r.name]=c}}}async fetchEdgeConnections(t,n){let i=t.filter(r=>r.kind==="edgeIntermediate"&&r.from);for(let r of i){let s=n[r.from]??[],o=t.find(f=>f.kind==="edge"&&f.from===r.name);if(!o)continue;if(s.length===0){n[r.name]=[],n[o.name]=[];continue}let u=`${r.from}__edge_root`,d=s.map(f=>f.externalId),p={nodes:{filter:{in:{property:["node","externalId"],values:d}}},limit:s.length},c={edges:{from:u,direction:r.direction,maxDistance:1},limit:r.limit};r.filter&&(c.edges.filter=r.filter),r.limitEach!=null&&(c.edges.limitEach=r.limitEach);let l={nodes:{from:r.name,chainTo:o.chainTo},limit:o.limit};o.filter&&(l.nodes.filter=o.filter);let m=await this.dms.query({with:{[u]:p,[r.name]:c,[o.name]:l},select:{[u]:{sources:[]},[r.name]:{sources:[]},[o.name]:{sources:[{source:o.view,properties:o.select}]}}});n[r.name]=m.items[r.name]??[],n[o.name]=m.items[o.name]??[]}}};a(we,"QueryExecutor");var q=we;var yr={endCursor:null,hasNextPage:!1};function ct(e){return{items:e,pageInfo:yr}}a(ct,"wrapConnection");function pt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.space=="string"&&typeof t.externalId=="string"}a(pt,"isDmsRef");function lt(e,t){let n=`${t.externalId}/${t.version}`;return{...e.properties?.[t.space]?.[n]??{},space:e.space,externalId:e.externalId}}a(lt,"extractViewProperties");function Z(e,t,n,i){if(t.length===0)return;let r=[...n.values()].filter(o=>o.from===e.name&&o.fieldName),s=[...n.values()].filter(o=>o.kind==="edge"&&o.fieldName&&o.from!=null&&n.get(o.from)?.from===e.name);for(let o of[...r,...s]){let u=(i[o.name]??[]).map(d=>lt(d,o.view));if(o.kind==="directRelation"){let d=new Map;for(let p of u)d.set(`${p.space}:${p.externalId}`,p);for(let p of t){let c=p[o.fieldName];p[o.fieldName]=pt(c)?d.get(`${c.space}:${c.externalId}`)??null:null}Z(o,u,n,i)}else if(o.kind==="reverseDirect"||o.kind==="reverseList"){let d=o.through.property,p=new Map;for(let c of t)p.set(`${c.space}:${c.externalId}`,[]);for(let c of u){let l=c[d];pt(l)&&p.get(`${l.space}:${l.externalId}`)?.push(c)}for(let c of t){let l=p.get(`${c.space}:${c.externalId}`)??[];c[o.fieldName]=o.kind==="reverseList"?ct(l):l}Z(o,u,n,i)}else if(o.kind==="edge"){let d=i[o.from]??[],p=new Map;for(let l of d){if(l.instanceType!=="edge")continue;let{startNode:m,endNode:f}=l;if(!m||!f)continue;let g=o.chainTo==="destination"?m:f,y=o.chainTo==="destination"?f:m,D=`${g.space}:${g.externalId}`,M=`${y.space}:${y.externalId}`,Ce=p.get(D)??[];Ce.push(M),p.set(D,Ce)}let c=new Map;for(let l of u)c.set(`${l.space}:${l.externalId}`,l);for(let l of t){let m=`${l.space}:${l.externalId}`,g=(p.get(m)??[]).map(y=>c.get(y)).filter(y=>y!==void 0);l[o.fieldName]=ct(g)}Z(o,u,n,i)}}}a(Z,"nestChildrenForStep");function hr(e,t,n){let i=e.find(s=>!s.from);if(!i)return n;let r=new Map(e.map(s=>[s.name,s]));return Z(i,n,r,t),n}a(hr,"nestChildren");function ee(e,t){let n=e.find(r=>!r.from);if(!n)return[];let i=(t[n.name]??[]).map(r=>lt(r,n.view));return hr(e,t,i)}a(ee,"unpack");function Se(e,t){for(let n of e)delete t[n]}a(Se,"stripTempSelects");function xe(e){let t={};for(let[n,i]of e)i!=null&&(t[n]=i);return Object.keys(t).length===0?null:btoa(JSON.stringify(t))}a(xe,"encodeCursors");function Re(e){if(!e)return new Map;try{let t=JSON.parse(atob(e));return new Map(Object.entries(t))}catch{throw new I("Invalid pagination cursor \u2014 the value is malformed or has been modified by the client.")}}a(Re,"decodeCursors");import{CogniteError as wr}from"@cognite/sdk";function ut(){return{max429Retries:5,retryBaseDelayMs:500,maxConcurrentRequests:4}}a(ut,"defaultRetryConfig");function Sr(e){return new Promise(t=>setTimeout(t,e))}a(Sr,"sleep");var Te=class Te{constructor(t){this.queue=[];this.count=t}acquire(){return this.count>0?(this.count--,Promise.resolve()):new Promise(t=>this.queue.push(t))}release(){let t=this.queue.shift();t?t():this.count++}};a(Te,"Semaphore");var Ie=Te,De=class De{constructor(t,n=ut()){this.inner=t;this.config=n;this.semaphore=new Ie(n.maxConcurrentRequests)}query(t){return this.withRetry(()=>this.inner.query(t))}search(t){return this.withRetry(()=>this.inner.search(t))}aggregate(t){return this.withRetry(()=>this.inner.aggregate(t))}retrieve(t){return this.withRetry(()=>this.inner.retrieve(t))}sync(t){return this.withRetry(()=>this.inner.sync(t))}upsert(t){return this.inner.upsert(t)}delete(t){return this.inner.delete(t)}inspect(t){return this.inner.inspect(t)}async withRetry(t){let n=0;for(;;){await this.semaphore.acquire();try{return await t()}catch(i){if(i instanceof wr&&i.status===429){if(n>=this.config.max429Retries)throw i;n++,await Sr(this.config.retryBaseDelayMs*2**(n-1))}else throw i}finally{this.semaphore.release()}}}};a(De,"RetryingDmsClient");var _=De;var Le=class Le{get schemaKnowledge(){return this.schema}constructor(t,n,i){this.schema=n,this.config={...et(),...i},this.dms=new _(t,{max429Retries:this.config.max429Retries,retryBaseDelayMs:this.config.retryBaseDelayMs,maxConcurrentRequests:this.config.maxConcurrentRequests}),this.executor=new q(this.dms,{max408Retries:this.config.max408Retries,inFilterChunkSize:this.config.inFilterChunkSize})}async query(t){let n=J(t.select);if(n>this.config.maxNestingDepth)throw new I(`Query nesting depth ${n} exceeds maximum ${this.config.maxNestingDepth}. Reduce connection depth or raise maxNestingDepth in config.`);let i=t.limit??this.config.initialBatchLimit,r=W(t.view,t.select,t.filter,t.sort,i,this.schema,this.config.previewLimit),s=Re(t.cursor),o={steps:r,tempSelectSteps:new Set,cursors:new Map(s),batchLimit:Math.min(this.config.initialBatchLimit,this.config.maxBatchLimit)},{batch:u,nextCursors:d,tempSelectSteps:p}=await this.executor.run(r,o.cursors,o.batchLimit);Se(p,u);let c=ee(r,u),l=r[0],m=d.get(l.name)??null,f=xe(d),g=m!=null;return{items:c,pageInfo:{endCursor:f,hasNextPage:g}}}async queryAll(t,n){let i=n??this.config.maxTotalItems,r=[],s,o=!0;for(;o;){let u=await this.query({...t,cursor:s});if(r.push(...u.items),o=u.pageInfo.hasNextPage,s=u.pageInfo.endCursor??void 0,r.length>=i){if(n===void 0&&o)throw new I(`listAll reached the hard ceiling of ${i} items. Pass an explicit maxTotal to acknowledge this or raise maxTotalItems in config.`);break}}return r}async search(t){let n=t.limit??this.config.searchLimit,i=await this.dms.search({view:t.view,query:t.query,filter:t.filter,sort:t.sort,limit:n,properties:t.properties}),r=W(t.view,t.select,void 0,void 0,n,this.schema,this.config.previewLimit),s={0:i.items};return await this.executor.fetchReverseLists(r,s),await this.executor.fetchQueryableConnections(r,s),await this.executor.fetchEdgeConnections(r,s),{items:ee(r,s),pageInfo:{endCursor:null,hasNextPage:!1}}}async getByIds(t,n){if(t.length===0)return[];let i=await this.dms.retrieve({items:t.map(s=>({instanceType:"node",space:s.space,externalId:s.externalId})),sources:[{source:n}]}),r=`${n.externalId}/${n.version}`;return i.items.map(s=>({...s.properties?.[n.space]?.[r]??{},space:s.space,externalId:s.externalId}))}async count(t){let i=(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:[{count:{property:"externalId"}}]})).items[0]?.aggregates[0];return(i?.aggregate!=="histogram"?i?.value:void 0)??0}async aggregate(t){return{items:(await this.dms.aggregate({view:t.view,filter:t.filter,aggregates:t.aggregates,groupBy:t.groupBy,query:t.query})).items}}async*queryPages(t){let n,i=!0;for(;i;){let r=await this.query({...t,cursor:n});yield r,i=r.pageInfo.hasNextPage,n=r.pageInfo.endCursor??void 0}}};a(Le,"QueryRunner");var G=Le;function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(ve,"isRecord");function te(e){return typeof e=="string"||typeof e=="number"}a(te,"isScalar");var xr={space:["node","space"],externalId:["node","externalId"]};function Rr(e,t){return xr[t]??[e.space,`${e.externalId}/${e.version}`,t]}a(Rr,"propRef");var Ir={exists:a((e,t)=>typeof t!="boolean"?void 0:t?{exists:{property:e}}:{not:{exists:{property:e}}},"exists"),eq:a((e,t)=>({equals:{property:e,value:t}}),"eq"),in:a((e,t)=>Array.isArray(t)?{in:{property:e,values:t}}:void 0,"in"),isNull:a((e,t)=>typeof t!="boolean"?void 0:t?{not:{exists:{property:e}}}:{exists:{property:e}},"isNull"),prefix:a((e,t)=>typeof t=="string"?{prefix:{property:e,value:t}}:void 0,"prefix"),gte:a((e,t)=>te(t)?{range:{property:e,gte:t}}:void 0,"gte"),gt:a((e,t)=>te(t)?{range:{property:e,gt:t}}:void 0,"gt"),lte:a((e,t)=>te(t)?{range:{property:e,lte:t}}:void 0,"lte"),lt:a((e,t)=>te(t)?{range:{property:e,lt:t}}:void 0,"lt"),containsAny:a((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"containsAny"),containsAll:a((e,t)=>Array.isArray(t)?{containsAll:{property:e,values:t}}:void 0,"containsAll"),overlaps:a((e,t)=>Array.isArray(t)?{containsAny:{property:e,values:t}}:void 0,"overlaps")};function Tr(e,t,n,i){let r=Rr(n,e),s=Object.entries(t).flatMap(([o,u])=>{if(u==null)return[];if(o==="nested"&&i&&ve(u)){let p=i.property(n,e);if(p?.kind==="directRelation"){let c={type:"view",...p.targetView},l=R(u,c,i);if(l)return[{nested:{scope:[n.space,`${n.externalId}/${n.version}`,e],filter:l}}]}return[]}let d=Ir[o]?.(r,u);return d?[d]:[]});if(s.length!==0)return s.length===1?s[0]:{and:s}}a(Tr,"translatePropertyFilter");function Dr(e){if(e.length!==0)return e.length===1?e[0]:{and:e}}a(Dr,"collapse");function R(e,t,n){if(!ve(e))return;let i=Object.entries(e).flatMap(([r,s])=>{if(s==null)return[];if(r==="_not"){let o=R(s,t,n);return o?[{not:o}]:[]}if(r==="hasData"&&typeof s=="boolean"&&s)return[{hasData:[{type:"view",space:t.space,externalId:t.externalId,version:t.version}]}];if(r==="matchAll"&&typeof s=="boolean"&&s)return[{matchAll:{}}];if((r==="_and"||r==="_or")&&Array.isArray(s)){let o=s.flatMap(u=>{let d=R(u,t,n);return d?[d]:[]});return o.length>0?[r==="_and"?{and:o}:{or:o}]:[]}if(ve(s)){let o=Tr(r,s,t,n);return o?[o]:[]}return[]});return Dr(i)}a(R,"buildFilter");function Lr(e){switch(e.function){case"avg":return{avg:{property:e.property}};case"sum":return{sum:{property:e.property}};case"min":return{min:{property:e.property}};case"max":return{max:{property:e.property}};case"histogram":return{histogram:{property:e.property,interval:e.interval}};default:return{count:{property:e.property??"externalId"}}}}a(Lr,"toAggregationDefinition");function dt(e,t){return a(async function(i,r){let{items:s}=await t.aggregate({view:e,filter:R(r.filter,e,t.schemaKnowledge),aggregates:(r.aggregates??[{function:"count"}]).map(Lr),groupBy:r.groupBy,query:r.query});return s.flatMap(o=>o.aggregates.map(u=>{if(u.aggregate==="histogram"){let{aggregate:l,property:m,buckets:f}=u;return{aggregate:l,property:m,value:null,buckets:f,group:o.group??null}}let{aggregate:d,property:p,value:c}=u;return{aggregate:d,property:p,value:c,buckets:null,group:o.group??null}}))},"aggregateResolver")}a(dt,"makeAggregateResolver");function mt(e,t){return a(async function(i,r){let s=R(r.filter,e,t.schemaKnowledge);return t.count({view:e,filter:s})},"countResolver")}a(mt,"makeCountResolver");import{Kind as ke,isObjectType as vr,getNamedType as kr}from"graphql";function re(e,t){let n=[];for(let i of e.selections)if(i.kind===ke.FIELD)n.push(i);else if(i.kind===ke.INLINE_FRAGMENT&&i.selectionSet)n.push(...re(i.selectionSet,t));else if(i.kind===ke.FRAGMENT_SPREAD){let r=t[i.name.value];r&&n.push(...re(r.selectionSet,t))}return n}a(re,"collectFields");var br=new Set(["space","externalId"]);function ft(e,t,n){let i=[],r=new Map;for(let s of re(e,n.fragments)){let o=s.name.value;if(o==="__typename"||br.has(o))continue;if(!s.selectionSet){i.push(o);continue}let u=n.schema.getType(t);if(vr(u)){let d=u.getFields()[o];if(d){let p=kr(d.type).name,c=ft(s.selectionSet,p,n);r.set(o,{select:c});continue}}i.push(o)}return{scalars:i,connections:r}}a(ft,"buildTree");function be(e,t,n){return e?ft(e,t,n):{scalars:[],connections:new Map}}a(be,"buildSelectionTree");function ne(e,t){let n=e.fieldNodes[0]?.selectionSet;if(!n)return{scalars:[],connections:new Map};let i=re(n,e.fragments).find(r=>r.name.value==="items");return be(i?.selectionSet,t,e)}a(ne,"buildSelectionTreeFromListInfo");function gt(e,t,n){return a(async function(r,s,o,u){let{space:d,externalId:p}=s,c=be(u.fieldNodes[0]?.selectionSet,t,u),l={and:[{equals:{property:["node","space"],value:d}},{equals:{property:["node","externalId"],value:p}}]},{items:m}=await n.query({view:e,select:c,filter:l,limit:1});return m[0]??null},"getByIdResolver")}a(gt,"makeGetByIdResolver");function yt(e,t,n){return a(async function(r,s,o,u){let d=ne(u,t),p=R(s.filter,e,n.schemaKnowledge),c=Cr(s.sort,e);return n.query({view:e,select:d,filter:p,sort:c,cursor:s.cursor,limit:s.limit})},"queryResolver")}a(yt,"makeQueryResolver");function Cr(e,t){if(!(!e||e.length===0))return e.map(n=>({property:{view:t,property:n.field},direction:n.direction??"ascending",nullsFirst:n.nullsFirst}))}a(Cr,"parseSortArg");function ht(e,t,n){return a(async function(r,s,o,u){let d=ne(u,t),p={view:e,query:s.query,limit:s.limit,filter:R(s.filter,e,n.schemaKnowledge),sort:s.sort,select:d,properties:s.properties},{items:c,pageInfo:l}=await n.search(p);return{items:c,pageInfo:l}},"searchResolver")}a(ht,"makeSearchResolver");function Nr(e,t){let n={};for(let i of e.filter(O)){let r={type:"view",space:i.space,externalId:i.externalId,version:i.version},s=i.externalId;n[`query${s}`]=yt(r,s,t),n[`get${s}ById`]=gt(r,s,t),n[`count${s}`]=mt(r,t),n[`search${s}`]=ht(r,s,t),n[`aggregate${s}`]=dt(r,t)}return n}a(Nr,"buildRootValue");async function Er(e,t){let n=await We(e,t);return wt(n,t)}a(Er,"createDuneRuntime");function wt(e,t){let{schema:n,schemaKnowledge:i}=Je(e),r=new G(t.instances,i),s=Nr(e,r),o=Ze(n,s);return{schema:n,rootValue:s,runner:r,requester:o}}a(wt,"createDuneRuntimeFromViews");export{Er as a,wt as b};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{a as s}from"./chunk-EI7MMDWY.js";import Y from"fs";import ut from"path";var N="https://docs.cognite.com/cdf/access/";function m(e){return e!==null&&typeof e=="object"}s(m,"isRecord");function S(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}s(S,"isHttpError");function W(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
|
|
2
|
+
See: ${N}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
|
|
3
|
+
See: ${N}`;default:return}}s(W,"httpStatusHint");function A(e){let t=e instanceof Error?e:new Error(String(e));if(!S(t))return null;let n=W(t.status);return n?Object.assign(new Error(`${t.message}
|
|
4
|
+
${n}`),{cause:t}):null}s(A,"enrichedHttpError");function Z(e){if(!m(e))return null;let t=e.missing;if(Array.isArray(t))return t;let n=e.data;if(m(n)){let r=n.error;if(m(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(n.missing))return n.missing}return null}s(Z,"findMissingArray");function X(e,t){if(!S(e)||e.status!==400)return!1;let n=Z(e);return n?n.some(r=>m(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(X,"isMissingExternalIdError");function $(e,t){return S(e)&&e.status===404||X(e,t)}s($,"isNotFoundError");var M=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],J=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,n){super(`Version ${n} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=n}};s(I,"AppVersionNotFoundError");var V=I;function q(e,t){return e.includes(t)}s(q,"includesValue");function Q(e){return q(M,e)}s(Q,"isAppVersionLifecycleState");function tt(e){return q(J,e)}s(tt,"isAppVersionAlias");function et(e){return typeof e.version=="string"&&Q(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||tt(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}s(et,"isAppVersion");function H(e){if(!m(e))throw new Error("Invalid version response: not an object");if(!et(e))throw new Error("Invalid version response: missing or malformed fields");return e}s(H,"parseAppVersion");var T=class T{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,n,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:n,description:r}]}})}catch(o){throw A(o)??o}}async uploadVersion(t,n,r,o,i="index.html"){console.log(`\u{1F4E4} Uploading version ${n}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",n),a.append("entryPath",i);let l=encodeURIComponent(t),c=`${this.appsBasePath}/${l}/versions`,p=await this.client.authenticate(),g=`${this.client.getBaseUrl()}${c}`,u=new AbortController,G=setTimeout(()=>u.abort(),300*1e3),h;try{h=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${p}`},body:a,signal:u.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error("Upload timed out after 5 minutes"):f}finally{clearTimeout(G)}if(!h.ok){let f=await h.text(),k=f;try{let x=JSON.parse(f);if(m(x)){let w=x.error;if(typeof w=="string")k=w;else if(m(w)){let E=w.message,F=w.code;k=typeof E=="string"?E:F!=null?`Unknown error (code: ${F})`:f}else{let E=x.message;k=typeof E=="string"?E:f}}}catch{}let j=h.headers.get("x-request-id"),K=j?` | X-Request-ID: ${j}`:"",B=Object.assign(new Error(`Upload failed: ${h.status} \u2014 ${k}${K}`),{status:h.status});throw A(B)??B}console.log(`\u2705 Version ${n} uploaded`)}async getVersion(t,n){let r=encodeURIComponent(t),o=encodeURIComponent(n),i=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(i);return H(a.data)}catch(a){throw $(a,[t,n])?new V(t,n):A(a)??a}}async getActiveVersion(t){let n=encodeURIComponent(t),r=`${this.appsBasePath}/${n}/active`;try{let o=await this.client.get(r);return H(o.data)}catch(o){if($(o,[t]))return null;throw A(o)??o}}async updateVersions(t,n){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:n}})}catch(i){throw A(i)??i}}};s(T,"AppHostingApi");var v=T;var b=class b{constructor(t){this.api=new v(t)}getVersion(t,n){return this.api.getVersion(t,n)}uploadVersion(t,n,r,o,i){return this.api.uploadVersion(t,n,r,o,i)}async ensureApp(t,n,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,n,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(S(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async publishVersion(t,n){await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,n){console.log(`\u{1F680} Publishing and activating version ${n}...`),await this.api.updateVersions(t,[{version:n,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${n} is now PUBLISHED and ACTIVE`)}async activateVersion(t,n){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==n?r.version:void 0;return await this.api.updateVersions(t,[{version:n,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,n,r,o,i,a,l=!1){console.log(`
|
|
5
|
+
\u{1F680} Deploying application via App Hosting API...
|
|
6
|
+
`);try{await this.ensureApp(t,n,r),await this.uploadVersion(t,o,i,a),l&&await this.publishAndActivate(t,o),console.log(`
|
|
7
|
+
\u2705 Deployment successful!`)}catch(c){let p=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${p}`),{cause:c})}}};s(b,"AppHostingClient");var P=b;import y from"fs";import d from"path";import{parseAndValidateManifestConfig as nt}from"@cognite/app-sdk/vite";import{BlobReader as rt,Uint8ArrayWriter as ot,ZipWriter as st}from"@zip.js/zip.js";var R="package.json",D="package-lock.json",z="manifest.json",_=".cognite",L=class L{constructor(t="dist"){this.distPath=d.isAbsolute(t)?t:d.join(process.cwd(),t),this.appRoot=d.dirname(this.distPath)}validateBuildDirectory(){if(!y.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=d.join(this.appRoot,R);if(!y.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let n=d.join(this.appRoot,D);if(!y.existsSync(n))throw new Error(`"${n}" not found. It is required for deployment.`)}async createZip(t="app.zip",n=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new st(new ot,{level:9}),o=s(async(c,p)=>{await r.add(p,new rt(await y.openAsBlob(c))),n&&console.log(` \u{1F4C4} ${p}`)},"addFile"),i=s(async c=>{let p=await y.promises.readdir(c,{withFileTypes:!0});for(let g of p){let u=d.join(c,g.name);g.isDirectory()?await i(u):await o(u,d.relative(this.distPath,u).replace(/\\/g,"/"))}},"addDir"),a;try{await i(this.distPath);let c=d.join(this.appRoot,R);await o(c,d.posix.join(_,R));let p=d.join(this.appRoot,z);if(y.existsSync(p)){let u=y.readFileSync(p,"utf-8");nt(u,p),await o(p,d.posix.join(_,z))}let g=d.join(this.appRoot,D);await o(g,d.posix.join(_,D)),a=await r.close()}catch(c){let p=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${p}`)}await y.promises.writeFile(t,a);let l=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${l} MB)`),t}};s(L,"ApplicationPackager");var C=L;import{CogniteClient as dt}from"@cognite/sdk";var it=s(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),n={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=r.toLowerCase().replace(/_/g,"-");n[i]=o}return n}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),at=s(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=it()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),ct=s(e=>{if(!e)return"";try{return new URL(e).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=e.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),pt=s(async(e,t)=>{let n=`Basic ${btoa(`${e}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:n,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let i=await r.text();throw new Error(`Failed to get token from CDF: ${r.status} ${r.statusText}
|
|
8
|
+
${i}`)}let o=await r.json();if(!o.access_token)throw new Error("No access token returned from CDF authentication");return o.access_token},"getTokenCdf"),lt=s(async(e,t,n,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=ct(r);if(!o)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${r}`);let i=`https://login.microsoftonline.com/${n}/oauth2/v2.0/token`,a=`https://${o}.cognitedata.com/.default`,l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!l.ok){let p=await l.text();throw new Error(`Failed to get token from Entra ID: ${l.status} ${l.statusText}
|
|
9
|
+
${p}`)}let c=await l.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),O=s(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:n,deploySecretName:r,idpType:o="cdf",tenantId:i,baseUrl:a}=e,l=at(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return lt(n,l,i,a)}return pt(n,l)},"getToken");async function U(e,t,n=process.env,r){let o=await O(e,n),i=n.COGNITE_BASE_URL??e.baseUrl,a=(r??(l=>new dt(l)))({appId:t,project:e.project,baseUrl:i,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}s(U,"getSdk");var gt=s(async(e,t,n)=>{let r=await new C(`${n}/dist`).createZip("app.zip",!0);try{let{externalId:o,name:i,description:a,versionTag:l}=t,c=await U(e,n),p=new P(c),g=Y.readFileSync(r),u=ut.basename(r);await p.deploy(o,i,a,l,g,u,e.published)}finally{try{Y.unlinkSync(r)}catch{}}},"deploy");export{P as a,C as b,O as c,U as d,gt as e};
|