@cognite/cli 1.3.1 → 1.3.2-alpha.52

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.
@@ -2,4 +2,3 @@
2
2
  to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>.npmrc'
3
3
  ---
4
4
  engine-strict=true
5
- min-release-age=2
@@ -10,7 +10,6 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
10
10
 
11
11
  - To start a new feature, run `/speckit.specify <description>` in Claude Code or Cursor. It generates a properly numbered feature directory and a spec to fill in. Then run `/speckit.clarify` → `/speckit.plan` → `/speckit.tasks` → `/speckit.implement`.
12
12
  - When user-visible behavior changes in an existing feature, update its `specs/<NNN>-<feature>/spec.md` before or alongside the code change.
13
- - When a feature touches Cognite Data Fusion data, the spec must document existing CDF views read from, new views needed, and spaces used.
14
13
  <% } else { -%>
15
14
  ## 0. Product Spec (SPEC.md)
16
15
 
@@ -22,13 +21,59 @@ This app uses [github/spec-kit](https://github.com/github/spec-kit) for spec-dri
22
21
 
23
22
  ---
24
23
 
25
- ## 1. UI Components
24
+ ## 1. CDF Data & Generated SDK
25
+
26
+ Before writing any feature code that reads CDF data model instances, check whether a generated SDK exists:
27
+
28
+ ```bash
29
+ ls src/generated_sdks/
30
+ ```
31
+
32
+ ### If the SDK does not exist
33
+
34
+ Stop. Do not write placeholder code or stub SDK calls. Tell the user:
35
+
36
+ > To read data from your CDF data model, you'll need to generate a typed SDK first. Run this from the app root (where `app.json` lives):
37
+ >
38
+ > ```bash
39
+ > npx @cognite/cli apps sdk --interactive
40
+ > ```
41
+ >
42
+ > The wizard will log you in via the browser, let you pick a data model, and write the generated files into `src/generated_sdks/`. Come back when it's done.
43
+
44
+ Wait for the user to confirm generation is complete before continuing.
45
+
46
+ ### If the SDK exists
47
+
48
+ Use `createSdk(client)` from `src/generated_sdks/<name>/index.ts` for all reads. Rules:
49
+
50
+ - **Read `schema.graphql` first** to understand what views, fields, and relations are available — it is the source of truth for the data model
51
+ - **Do not call `client.instances.list`, `client.instances.query`, or `client.instances.search` directly** — always go through the generated SDK for reads
52
+ - The SDK is **read-only**: `queryX`, `getByIdX`, `searchX`, `countX`, `aggregateX` — no write operations
53
+ - Relation fields (direct relations, edges, reverse relations) resolve automatically in a single SDK call — never write separate fetches to follow relations
54
+ - For writes, use `client.instances.upsert` / `client.instances.delete` directly
55
+
56
+ ```ts
57
+ import { createSdk } from '../generated_sdks/<name>';
58
+
59
+ const sdk = createSdk(client); // no network call — instantiation is synchronous
60
+
61
+ const result = await sdk.queryMyView({
62
+ filter: { status: { eq: 'active' } },
63
+ limit: 25,
64
+ });
65
+ // result.items[0].relatedView ← relation fields resolve in the same call
66
+ ```
67
+
68
+ ---
69
+
70
+ ## 2. UI Components
26
71
 
27
72
  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
73
 
29
74
  ---
30
75
 
31
- ## 2. Host integration (`@cognite/app-sdk`)
76
+ ## 3. Host integration (`@cognite/app-sdk`)
32
77
 
33
78
  The Fusion host exposes a `HostAppAPI` (imported as `HostAppAPI` from `@cognite/app-sdk`) via `connectToHostApp(...)`. Reach for it whenever the situation calls for it — don't hand-roll an equivalent or read browser globals directly.
34
79
 
@@ -75,7 +120,7 @@ async function updateState(next: AppState, api: HostAppAPI) {
75
120
 
76
121
  ---
77
122
 
78
- ## 3. Dependency Injection
123
+ ## 4. Dependency Injection
79
124
 
80
125
  **All non-stateless dependencies must be injected.** Never import and call a service, SDK client, or stateful module directly inside a component or hook — it makes the code untestable and tightly coupled.
81
126
 
@@ -109,7 +154,7 @@ export const doWork = async (props: Props, overrides?: Partial<Deps>) => {
109
154
 
110
155
  ---
111
156
 
112
- ## 4. Interface-Based Services
157
+ ## 5. Interface-Based Services
113
158
 
114
159
  Define an interface; implement with a class. Never reference the concrete class outside its own file.
115
160
 
@@ -126,7 +171,7 @@ export class ApiDataService implements DataService {
126
171
 
127
172
  ---
128
173
 
129
- ## 5. ViewModel Pattern
174
+ ## 6. ViewModel Pattern
130
175
 
131
176
  Business logic lives in `use<Name>ViewModel`. Components only render.
132
177
 
@@ -162,11 +207,11 @@ This matters because each call to a `useState`-backed hook creates an **independ
162
207
 
163
208
  ### Host-synced state inside a ViewModel
164
209
 
165
- When a ViewModel exposes state that falls under §2's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
210
+ When a ViewModel exposes state that falls under §3's "host-synced" category, the **ViewModel** — not the view component — is responsible for seeding from `initialState` and pushing changes via `syncInternalState`. The state itself still lives in the shared storage layer described above; the ViewModel just owns the read/write contract with the host.
166
211
 
167
212
  ---
168
213
 
169
- ## 6. Test-First Development
214
+ ## 7. Test-First Development
170
215
 
171
216
  Write tests before implementation for all non-trivial behavior changes.
172
217
 
@@ -262,7 +307,7 @@ Place reusable factories in `src/__mocks__/`. Use `.test` TLD for fake URLs (RFC
262
307
 
263
308
  ---
264
309
 
265
- ## 7. TypeScript Rules
310
+ ## 8. TypeScript Rules
266
311
 
267
312
  - Never use `any`; prefer `unknown` or explicit strong types
268
313
  - Never use `as` casts — they silence the compiler without providing safety. Use type guards instead.
@@ -289,14 +334,14 @@ const mock = { postMessage: vi.fn() } as Partial<Window> as Window;
289
334
 
290
335
  ---
291
336
 
292
- ## 8. CogniteClient / authentication
337
+ ## 9. CogniteClient / authentication
293
338
 
294
339
  Auth is handled by `CogniteSdkProvider` from `@cognite/app-sdk/react` (see `App.tsx`). Nested components get the client via `useCogniteSdk()`. To wire up or migrate auth, run the `/setup-flows-auth` skill.
295
340
 
296
341
  ---
297
342
 
298
343
 
299
- ## 9. Commits and pull requests
344
+ ## 10. Commits and pull requests
300
345
 
301
346
  Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/).
302
347
 
@@ -307,4 +352,4 @@ Use [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/
307
352
  - **Pull requests:** title and **Summary** should match the same vocabulary; do not replace conventional commits with only a PR headline.
308
353
  - Before committing: review **`git status`** and **`git diff`** (including staged); unstage and commit separately if the index mixes unrelated concerns.
309
354
 
310
- ---
355
+ ---
@@ -51,27 +51,29 @@ to: '<%= useSpecKit ? null : (useCurrentDir ? "" : ((directoryName || name) + "/
51
51
 
52
52
  ---
53
53
 
54
- ## Data Models & CDF Integration *(mandatory)*
54
+ ## CDF Data *(mandatory)*
55
55
 
56
56
  <!--
57
- Capture how this app integrates with Cognite Data Fusion data models.
58
- Every Flows app should fill this in.
59
- -->
57
+ Which data model does this app connect to? If you haven't already, generate a
58
+ typed SDK by running from the app root:
60
59
 
61
- ### Existing views
60
+ npx @cognite/cli apps sdk --interactive
62
61
 
63
- <!--
64
- CDF views this app reads from. Format: `<space>.<view>:<version>`.
62
+ Once generated, src/generated_sdks/<name>/schema.graphql is the source of truth
63
+ for what views, fields, and relations are available.
64
+
65
+ Describe below what data this feature reads and why — in plain terms, not view IDs.
66
+ Example: "Reads active work orders and their assigned assets."
65
67
  -->
66
68
 
67
- ### New views
69
+ ### Data model
68
70
 
69
- <!--
70
- Views this app needs that don't yet exist. Describe properties and relationships.
71
- -->
71
+ <!-- Which data model: name, space, version. -->
72
72
 
73
- ### Spaces
73
+ ### What this app reads
74
74
 
75
- <!--
76
- CDF spaces this app uses, and what each contains.
77
- -->
75
+ <!-- Plain-language description of the data this feature needs and any key filters. -->
76
+
77
+ ### Writes
78
+
79
+ <!-- Does this feature write back to CDF? If so, what and under what conditions? If read-only, note that here. -->
@@ -27,10 +27,13 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
27
27
  "dependencies": {
28
28
  "@cognite/aura": "^0.1.7",
29
29
  "@cognite/sdk": "^10.3.0",
30
+ "@cognite/cli": "1.1.0-alpha.51",
30
31
  "@cognite/app-sdk": "^0.5.1",
31
32
  "@tabler/icons-react": "^3.35.0",
32
33
  "@tanstack/react-query": "^5.90.10",
33
34
  "clsx": "^2.1.1",
35
+ "graphql": "^16.14.0",
36
+ "graphql-tag": "^2.12.6",
34
37
  "react": "^18.3.1",
35
38
  "react-dom": "^18.3.1",
36
39
  "tailwind-merge": "^3.4.0"
@@ -0,0 +1,9 @@
1
+ import{a as s}from"./chunk-EI7MMDWY.js";import Y from"fs";import gt from"path";var B="https://docs.cognite.com/cdf/access/";function m(n){return n!==null&&typeof n=="object"}s(m,"isRecord");function S(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}s(S,"isHttpError");function X(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ See: ${B}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
+ See: ${B}`;default:return}}s(X,"httpStatusHint");function h(n){let t=n instanceof Error?n:new Error(String(n));if(!S(t))return null;let e=X(t.status);return e?Object.assign(new Error(`${t.message}
4
+ ${e}`),{cause:t}):null}s(h,"enrichedHttpError");function Z(n){if(!m(n))return null;let t=n.missing;if(Array.isArray(t))return t;let e=n.data;if(m(e)){let r=e.error;if(m(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(e.missing))return e.missing}return null}s(Z,"findMissingArray");function Q(n,t){if(!S(n)||n.status!==400)return!1;let e=Z(n);return e?e.some(r=>m(r)&&typeof r.externalId=="string"&&t.includes(r.externalId)):!1}s(Q,"isMissingExternalIdError");function $(n,t){return S(n)&&n.status===404||Q(n,t)}s($,"isNotFoundError");var M=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],J=["ACTIVE","PREVIEW"],I=class I extends Error{constructor(t,e){super(`Version ${e} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=e}};s(I,"AppVersionNotFoundError");var C=I;function q(n,t){return n.includes(t)}s(q,"includesValue");function tt(n){return q(M,n)}s(tt,"isAppVersionLifecycleState");function et(n){return q(J,n)}s(et,"isAppVersionAlias");function nt(n){return typeof n.version=="string"&&tt(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||et(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}s(nt,"isAppVersion");function H(n){if(!m(n))throw new Error("Invalid version response: not an object");if(!nt(n))throw new Error("Invalid version response: missing or malformed fields");return n}s(H,"parseAppVersion");var b=class b{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,e,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:e,description:r}]}})}catch(o){throw h(o)??o}}async uploadVersion(t,e,r,o,i="index.html"){console.log(`\u{1F4E4} Uploading version ${e}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",e),a.append("entryPath",i);let c=encodeURIComponent(t),p=`${this.appsBasePath}/${c}/versions`,l=await this.client.authenticate(),g=`${this.client.getBaseUrl()}${p}`,u=new AbortController,K=setTimeout(()=>u.abort(),300*1e3),A;try{A=await fetch(g,{method:"POST",headers:{Authorization:`Bearer ${l}`},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(K)}if(!A.ok){let f=await A.text(),x=f;try{let k=JSON.parse(f);if(m(k)){let w=k.error;if(typeof w=="string")x=w;else if(m(w)){let E=w.message,j=w.code;x=typeof E=="string"?E:j!=null?`Unknown error (code: ${j})`:f}else{let E=k.message;x=typeof E=="string"?E:f}}}catch{}let O=A.headers.get("x-request-id"),W=O?` | X-Request-ID: ${O}`:"",N=Object.assign(new Error(`Upload failed: ${A.status} \u2014 ${x}${W}`),{status:A.status});throw h(N)??N}console.log(`\u2705 Version ${e} uploaded`)}async getVersion(t,e){let r=encodeURIComponent(t),o=encodeURIComponent(e),i=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(i);return H(a.data)}catch(a){throw $(a,[t,e])?new C(t,e):h(a)??a}}async getActiveVersion(t){let e=encodeURIComponent(t),r=`${this.appsBasePath}/${e}/active`;try{let o=await this.client.get(r);return H(o.data)}catch(o){if($(o,[t]))return null;throw h(o)??o}}async updateVersions(t,e){let r=encodeURIComponent(t),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:e}})}catch(i){throw h(i)??i}}async submitSignatures(t,e,r){let o=encodeURIComponent(t),i=encodeURIComponent(e),a=`${this.appsBasePath}/${o}/versions/${i}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(c){throw h(c)??c}}};s(b,"AppHostingApi");var V=b;var T=class T{constructor(t){this.api=new V(t)}getVersion(t,e){return this.api.getVersion(t,e)}uploadVersion(t,e,r,o,i){return this.api.uploadVersion(t,e,r,o,i)}async ensureApp(t,e,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,e,r),console.log(`\u2705 App '${t}' created`)}catch(o){if(S(o)&&o.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw o}}async submitSignatures(t,e,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${e}...`),await this.api.submitSignatures(t,e,r),console.log("\u2705 Signatures stored"))}async publishVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,e){console.log(`\u{1F680} Publishing and activating version ${e}...`),await this.api.updateVersions(t,[{version:e,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${e} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,e){await this.api.updateVersions(t,[{version:e,update:{alias:{setNull:!0}}}])}async activateVersion(t,e){let r=null;try{r=await this.api.getActiveVersion(t)}catch{r=null}let o=r&&r.version!==e?r.version:void 0;return await this.api.updateVersions(t,[{version:e,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(t,e,r,o,i,a,c=!1){console.log(`
5
+ \u{1F680} Deploying application via App Hosting API...
6
+ `);try{await this.ensureApp(t,e,r),await this.uploadVersion(t,o,i,a),c&&await this.publishAndActivate(t,o),console.log(`
7
+ \u2705 Deployment successful!`)}catch(p){let l=p instanceof Error?p.message:String(p);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:p})}}};s(T,"AppHostingClient");var P=T;import y from"fs";import d from"path";import{parseAndValidateManifestConfig as rt}from"@cognite/app-sdk/vite";import{BlobReader as ot,Uint8ArrayWriter as st,ZipWriter as it}from"@zip.js/zip.js";var R="package.json",D="package-lock.json",z="manifest.json",_=".cognite",U=class U{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 e=d.join(this.appRoot,D);if(!y.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`)}async createZip(t="app.zip",e=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new it(new st,{level:9}),o=s(async(p,l)=>{await r.add(l,new ot(await y.openAsBlob(p))),e&&console.log(` \u{1F4C4} ${l}`)},"addFile"),i=s(async p=>{let l=await y.promises.readdir(p,{withFileTypes:!0});for(let g of l){let u=d.join(p,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 p=d.join(this.appRoot,R);await o(p,d.posix.join(_,R));let l=d.join(this.appRoot,z);if(y.existsSync(l)){let u=y.readFileSync(l,"utf-8");rt(u,l),await o(l,d.posix.join(_,z))}let g=d.join(this.appRoot,D);await o(g,d.posix.join(_,D)),a=await r.close()}catch(p){let l=p instanceof Error?p.message:String(p);throw new Error(`Failed to create zip: ${l}`)}await y.promises.writeFile(t,a);let c=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${c} MB)`),t}};s(U,"ApplicationPackager");var v=U;import{CogniteClient as ut}from"@cognite/sdk";var at=s(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let t=JSON.parse(n),e={};for(let[r,o]of Object.entries(t))if(typeof o=="string"){let i=r.toLowerCase().replace(/_/g,"-");e[i]=o}return e}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),ct=s(n=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=at()[n]),t||(t=process.env[n]),!t)throw new Error(`Secret not found in environment: ${n}`);return t},"getSecretFromEnv"),pt=s(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let t=n.replace(/^https?:\/\//,"");return t=t.split("/")[0],t=t.split(":")[0],t=t.replace(/\.cognitedata\.com$/,""),t}},"extractClusterFromUrl"),lt=s(async(n,t)=>{let e=`Basic ${btoa(`${n}:${t}`)}`,r=await fetch("https://auth.cognite.com/oauth2/token",{method:"POST",headers:{Authorization:e,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})});if(!r.ok){let 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"),dt=s(async(n,t,e,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=pt(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/${e}/oauth2/v2.0/token`,a=`https://${o}.cognitedata.com/.default`,c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:t,scope:a,grant_type:"client_credentials"})});if(!c.ok){let l=await c.text();throw new Error(`Failed to get token from Entra ID: ${c.status} ${c.statusText}
9
+ ${l}`)}let p=await c.json();if(!p.access_token)throw new Error("No access token returned from Entra ID authentication");return p.access_token},"getTokenEntra"),F=s(async(n,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:e,deploySecretName:r,idpType:o="cdf",tenantId:i,baseUrl:a}=n,c=ct(r);if(o==="entra_id"){if(!i)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return dt(e,c,i,a)}return lt(e,c)},"getToken");async function L(n,t,e=process.env,r){let o=await F(n,e),i=e.COGNITE_BASE_URL??n.baseUrl,a=(r??(c=>new ut(c)))({appId:t,project:n.project,baseUrl:i,oidcTokenProvider:s(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}s(L,"getSdk");var ft=s(async(n,t,e)=>{let r=await new v(`${e}/dist`).createZip("app.zip",!0);try{let{externalId:o,name:i,description:a,versionTag:c}=t,p=await L(n,e),l=new P(p),g=Y.readFileSync(r),u=gt.basename(r);await l.deploy(o,i,a,c,g,u,n.published)}finally{try{Y.unlinkSync(r)}catch{}}},"deploy");import{existsSync as mt,readFileSync as yt}from"fs";var G=[".dev.sig",".cert.sig"];function ht(n,t={}){let e=t.existsSync??mt,r=t.readFileSync??((i,a)=>yt(i,a)),o=[];for(let i of G){let a=`${n}${i}`;if(!e(a))continue;let c=r(a,"utf8").trim();c.length>0&&o.push(c)}return o}s(ht,"discoverSignatures");export{P as a,v as b,F as c,L as d,ft as e,G as f,ht as g};
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var d=(a,b)=>c(a,"name",{value:b,configurable:!0});export{d as a};
@@ -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,8 @@
1
+ var c=Object.defineProperty;var s=(l,i)=>c(l,"name",{value:i,configurable:!0});import{execFileSync as a}from"child_process";import{createRequire as p}from"module";import{InvalidArgumentError as u}from"commander";var t="https://github.com/cognitedata/builder-skills/tree/data-modeling-runtime-sdk-alpha",e=["claude-code","cursor"],o=e.flatMap(l=>["-a",l]),d=p(import.meta.url).resolve("skills/bin/cli.mjs");function n(l,i={}){a(process.execPath,[d,...l],{stdio:"inherit",cwd:process.cwd(),...i})}s(n,"execSkillsCli");function y(){return["add",t,...o,"--skill","*","-y"]}s(y,"pullAllArgs");function m(l){let i=/^[\w.-]+\/[\w.-]+$/.test(l),r=/^https:\/\/github\.com\/[\w.-]+\/[\w.-]+(\/tree\/[^\s]+)?$/.test(l);if(!i&&!r)throw new u("Expected owner/repo or GitHub URL with optional branch (e.g., cognitedata/builder-skills or https://github.com/cognitedata/builder-skills/tree/alpha)");return l}s(m,"validateSource");function g(l){let i=["add",l.source,...o];return l.skill?i.push("--skill",l.skill):l.interactive||i.push("--skill","*","-y"),l.global&&i.push("--global"),i}s(g,"buildPullArgs");function k(l){console.log(`\u{1F504} Pulling skills from ${l.source}...`),n(g(l)),console.log(`
2
+ \u2705 Skills pulled successfully`)}s(k,"handlePull");function S(l){let i=l.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
3
+ Supports: ${e.join(", ")}`).addHelpText("after",`
4
+ Examples:
5
+ npx @cognite/cli apps skills pull Pull all skills
6
+ npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
7
+ npx @cognite/cli apps skills pull --source https://github.com/cognitedata/builder-skills/tree/alpha Pull from a specific branch
8
+ npx @cognite/cli apps skills list List installed skills`);return i.command("pull").description("Pull all skills into your project").option("--source <owner/repo|url>","Skills repository \u2014 owner/repo shorthand or full GitHub URL (supports /tree/<branch>)",m,t).option("--skill <name>","Pull a specific skill by name").option("-i, --interactive","Interactively select which skills to install",!1).option("--global","Install skills globally",!1).action(k),i.command("list").description("List installed skills").action(()=>{n(["list"])}),i}s(S,"registerSkillsCommand");export{s as a,n as b,y as c,g as d,S as e};