@cognite/cli 1.4.1 → 1.5.0

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.
@@ -0,0 +1,78 @@
1
+ ---
2
+ description: Generate or refresh the CDF data model documentation (data-model.md) for the current feature. Documents CDF spaces, views, properties, and optionally ingestion/transformations/data quality for Solution Support handoff.
3
+ ---
4
+
5
+ ## User Input
6
+
7
+ ```text
8
+ $ARGUMENTS
9
+ ```
10
+
11
+ Consider any user input before proceeding (e.g. explicit space names or view IDs to include).
12
+
13
+ ## Outline
14
+
15
+ 1. **Load feature context**:
16
+ - Read `.specify/feature.json` to get `feature_directory`
17
+ - Read `{feature_directory}/spec.md`
18
+ - If `{feature_directory}/plan.md` exists, read it too
19
+
20
+ 2. **Decide whether to run** (early exit):
21
+ - Inspect the loaded spec (and plan, if present) for any of the following CDF concepts:
22
+ - **Data Modeling**: spaces, data models, views, containers, node types, edge types, properties on a view
23
+ - **Ingestion / Transformations**: extractors, connectors, CDF Transformations, raw tables that feed CDF
24
+ - If **none** of the above are referenced (directly or by clear implication), skip this command entirely:
25
+ - Do NOT write `data-model.md`
26
+ - Report a single line to the user: `Skipped /speckit.cdf-datamodel: feature does not interact with CDF data.`
27
+ - Stop here.
28
+ - Otherwise, continue with step 3.
29
+
30
+ 3. **Load template**:
31
+ - Read `.specify/templates/data-model-template.md`
32
+
33
+ 4. **Determine CDF scope**:
34
+ - Extract any CDF spaces, view names, data model names, container names, or property names mentioned in the spec and plan.
35
+
36
+ 5. **Ask the user to provide missing data model details** (interactive elicitation):
37
+ - For every required field still unknown after step 4 — spaces, data model external IDs and versions, view definitions — ask the user in a single batched message. Example:
38
+ ```
39
+ I need a bit more CDF detail to write data-model.md. Could you share:
40
+ 1. The space external ID(s) this feature reads from / writes to?
41
+ 2. The data model(s) used (external ID + version)?
42
+ 3. The view definitions you care about — feel free to paste the JSON/YAML straight from Fusion → Data Models, or from your generated SDK types.
43
+ If anything is still TBD, just say "unknown" and I'll mark it as an open question.
44
+ ```
45
+ - Parse anything the user pastes (view JSON, SDK type definitions, screenshots described in text) and use it verbatim as the source of truth — do not paraphrase property names, types, or external IDs.
46
+ - For anything the user explicitly marks as unknown or doesn't answer, set the field to `[NEEDS CLARIFICATION]` and add a corresponding entry to the Open Questions section.
47
+ - Skip this step entirely if the spec/plan already contains all required information.
48
+
49
+ 6. **Fill required sections** (always include):
50
+ - **Spaces**: list every CDF space the feature reads from or writes to
51
+ - **Data Models Used**: list each data model by name, space, version, and whether the feature reads or writes
52
+ - **Views**: for each view, one subsection with external ID, space, container, role, and only the properties this feature actually accesses — not every property on the view
53
+
54
+ 7. **Fill optional sections** (include only if there is concrete information; omit the entire section if not applicable):
55
+ - **Containers**: include if the feature writes directly to containers or creates new containers
56
+ - **Ingestion & Transformations**: include if data enters CDF from an external source (connectors, extractors, CDF Transforms, SDK writes from a pipeline)
57
+ - **Data Processing & Transformations**: include if non-trivial transforms occur before data lands in the views (unit conversion, aggregation, joins, enrichment)
58
+ - **Data Quality**: include if there are known validation rules, quality monitoring, or documented data issues
59
+ - **Relationships / Edges**: include if the feature traverses or creates edges between node types
60
+ - **Access Control**: include if the feature requires non-standard permissions, specific capability groups, or write access to any space or container; omit for simple read-only features using standard CDF access
61
+ - **Open Questions**: include only if there are actual unknowns that need resolution before Solution Support can take over; omit if the data model is fully understood
62
+
63
+ 8. **Write output**:
64
+ - Write the filled document to `{feature_directory}/data-model.md`
65
+ - If `/speckit.plan` has already run and produced a generic `data-model.md`, this replaces it.
66
+
67
+ 9. **Report**:
68
+ - Path written
69
+ - Which optional sections were included and why
70
+ - If Open Questions were included, prompt user to resolve them before Solution Support handoff
71
+
72
+ ## Key rules
73
+
74
+ - Only run the body of this command if the feature interacts with CDF data (see step 2). When in doubt, prefer skipping over writing a near-empty file.
75
+ - Document only what is known or can be reasonably inferred from the spec and plan. Do not invent spaces, views, or properties.
76
+ - Keep the Views section focused: list only properties this feature uses, not all properties available on the view.
77
+ - Use CDF external IDs (not display names) for spaces, views, containers, and data models where known.
78
+ - The document audience is Solution Support — write for someone who knows CDF but does not know this codebase.
@@ -0,0 +1,13 @@
1
+ # Cognite CDF extensions for spec-kit.
2
+ # This file is installed by @cognite/cli into .specify/extensions.yml.
3
+ # Do NOT modify _vendor/spec-kit/ to extend spec-kit — add extensions here instead.
4
+ #
5
+ # TODO(DUNE-866): speckit.cdf-datamodel currently infers the data model from the spec/plan.
6
+ # Once the CDF SDK Generator is stable, switch the command to consume its output
7
+ # as the source of truth for spaces, views, containers, and properties.
8
+ hooks:
9
+ after_specify:
10
+ - extension: "cognite-cdf"
11
+ command: "speckit.cdf-datamodel"
12
+ optional: false
13
+ description: "Generate CDF data model documentation if the feature touches CDF data (Solution Support handoff)"
@@ -0,0 +1,132 @@
1
+ # CDF Data Model: [FEATURE NAME]
2
+
3
+ **Feature**: [link to spec.md]
4
+ **Created**: [DATE]
5
+ **Status**: Draft
6
+
7
+ <!--
8
+ PURPOSE: This document gives Solution Support enough context about CDF data models
9
+ to take over or support this feature. Focus on WHAT exists in CDF and WHERE it lives,
10
+ not on application code.
11
+
12
+ REQUIRED SECTIONS: Spaces, Data Models Used, Views — always fill these.
13
+ OPTIONAL SECTIONS: marked with OPTIONAL below — include only if applicable,
14
+ omit the section entirely if the feature does not involve it.
15
+ -->
16
+
17
+ ## Spaces
18
+
19
+ | Space | Purpose | Owner |
20
+ |-------|---------|-------|
21
+ | [space-external-id] | [why this space is used] | [team or service that owns it] |
22
+
23
+ ## Data Models Used
24
+
25
+ | Data Model | Space | Version | Role |
26
+ |------------|-------|---------|------|
27
+ | [model-external-id] | [space] | [version] | read / write / both |
28
+
29
+ ## Views
30
+
31
+ <!--
32
+ One subsection per view. List only the properties this feature actually reads or writes
33
+ — not every property on the view.
34
+ -->
35
+
36
+ ### [ViewExternalId] (Space: [space], Version: [version])
37
+
38
+ - **Container**: [container-external-id]
39
+ - **Role**: read / write / both
40
+
41
+ **Properties used**:
42
+
43
+ | Property | Type | Description | Required by feature |
44
+ |----------|------|-------------|---------------------|
45
+ | [externalId] | [direct / text / int32 / float64 / boolean / timestamp / json / ...] | [what this property represents] | yes / no |
46
+
47
+ **Filters applied when querying**: [describe any view filters, e.g. "filter by status = 'active'" — or "none"]
48
+
49
+ ---
50
+
51
+ <!-- OPTIONAL: include Containers section only if the feature writes to new or existing containers directly -->
52
+
53
+ ## Containers
54
+
55
+ | Container | Space | Description |
56
+ |-----------|-------|-------------|
57
+ | [container-external-id] | [space] | [what data it stores] |
58
+
59
+ <!-- END OPTIONAL: Containers -->
60
+
61
+ ---
62
+
63
+ <!-- OPTIONAL: include Ingestion & Transformations only if data enters CDF from an external source for this feature -->
64
+
65
+ ## Ingestion & Transformations
66
+
67
+ | Source | Mechanism | Target View | Frequency | Notes |
68
+ |--------|-----------|-------------|-----------|-------|
69
+ | [data source, e.g. SAP, OSIsoft PI, CSV upload] | [connector / CDF Transform / Extractor / SDK write] | [view external ID] | [real-time / hourly / daily / on-demand] | [caveats, e.g. "staging space first"] |
70
+
71
+ <!-- END OPTIONAL: Ingestion & Transformations -->
72
+
73
+ ---
74
+
75
+ <!-- OPTIONAL: include Data Processing & Transformations only if non-trivial transforms happen before data lands in the views above -->
76
+
77
+ ## Data Processing & Transformations
78
+
79
+ - [Describe each transformation step: e.g. "unit conversion from psi to bar before writing to pressure property"]
80
+ - [Any aggregations, joins, or enrichment applied]
81
+ - [Reference to CDF Transformations job name if applicable]
82
+
83
+ <!-- END OPTIONAL: Data Processing & Transformations -->
84
+
85
+ ---
86
+
87
+ <!-- OPTIONAL: include Data Quality only if there are known quality rules, monitoring, or data issues -->
88
+
89
+ ## Data Quality
90
+
91
+ - **Validation rules**: [e.g. "externalId must be non-empty; startTime must be before endTime"]
92
+ - **Monitoring**: [e.g. "CDF Transform job health checked in Grafana dashboard X" — or "none in place"]
93
+ - **Known data issues**: [e.g. "legacy records before 2022 have null unit property; treat as 'unknown'"]
94
+
95
+ <!-- END OPTIONAL: Data Quality -->
96
+
97
+ ---
98
+
99
+ <!-- OPTIONAL: include Relationships / Edges only if the feature traverses or creates edges between node types -->
100
+
101
+ ## Relationships / Edges
102
+
103
+ | From Type | Edge Type | To Type | Description |
104
+ |-----------|-----------|---------|-------------|
105
+ | [node type / view] | [relation external ID] | [node type / view] | [what the edge represents] |
106
+
107
+ <!-- END OPTIONAL: Relationships / Edges -->
108
+
109
+ <!-- OPTIONAL: include Access Control only if the feature requires non-standard permissions,
110
+ specific capability groups, or write access to any space or container -->
111
+
112
+ ## Access Control
113
+
114
+ - **Read**: [spaces and/or data sets this feature reads; CDF capability groups required]
115
+ - **Write**: [spaces and/or containers this feature writes to]
116
+
117
+ <!-- END OPTIONAL: Access Control -->
118
+
119
+ ---
120
+
121
+ <!-- OPTIONAL: include Open Questions only if there are actual unknowns to resolve -->
122
+
123
+ ## Open Questions
124
+
125
+ <!--
126
+ List anything that could not be determined from the spec or plan.
127
+ Each item should be a concrete question with a named owner if possible.
128
+ -->
129
+
130
+ - [ ] [Question] — owner: [name or team]
131
+
132
+ <!-- END OPTIONAL: Open Questions -->
@@ -27,8 +27,8 @@ to: '<%= useCurrentDir ? "" : ((directoryName || name) + "/") %>package.json'
27
27
  },
28
28
  "dependencies": {
29
29
  "@cognite/aura": "^0.1.7",
30
- "@cognite/sdk": "^10.3.0",
31
- "@cognite/app-sdk": "^0.5.1",
30
+ "@cognite/sdk": "^10.10.0",
31
+ "@cognite/app-sdk": "^0.6.0",
32
32
  "@tabler/icons-react": "^3.35.0",
33
33
  "@tanstack/react-query": "^5.90.10",
34
34
  "clsx": "^2.1.1",
@@ -1,13 +1,13 @@
1
- var ie=Object.defineProperty;var i=(n,e)=>ie(n,"name",{value:e,configurable:!0});import{mkdir as Ve,readFile as _e}from"fs/promises";import{basename as Fe,dirname as Oe}from"path";var D=class D extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:ue(e.cause)}}};i(D,"HintedError");var w=D;var J="https://docs.cognite.com/cdf/access/",ae="https://status.cognite.com";function ce(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:J};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:J};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ae};default:return{}}}i(ce,"defaultHintForStatus");var U=class U extends w{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ce(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var x=U;function pe(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}i(pe,"hintForErrno");function ue(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=pe(r.code,r);if(o!==void 0)return o;e=r.cause}}i(ue,"hintForCause");var K="https://docs.cognite.com/cdf/access/";function d(n){return n!==null&&typeof n=="object"}i(d,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(C,"isHttpError");function le(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
1
+ var ie=Object.defineProperty;var i=(n,e)=>ie(n,"name",{value:e,configurable:!0});import{mkdir as _e,readFile as Fe}from"fs/promises";import{basename as Oe,dirname as Le}from"path";var D=class D extends Error{constructor(e,t={}){super(e),this.name="HintedError",t.cause!==void 0&&(this.cause=t.cause);let r=this.deriveDefaults(t);this.hint=t.hint??r.hint,this.helpUrl=t.helpUrl??r.helpUrl,this.shouldReport=t.shouldReport??!0}deriveDefaults(e){return{hint:ue(e.cause)}}};i(D,"HintedError");var w=D;var J="https://docs.cognite.com/cdf/access/",ae="https://status.cognite.com";function ce(n){switch(n){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:J};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:J};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:ae};default:return{}}}i(ce,"defaultHintForStatus");var U=class U extends w{constructor(e,t){super(e,t),this.name="HintedHttpError",this.httpStatusCode=t.httpStatusCode,this.requestUrl=t.requestUrl,this.responseBody=t.responseBody}deriveDefaults(e){let{httpStatusCode:t}=e,r=ce(t),o=super.deriveDefaults(e);return{hint:r.hint??o.hint,helpUrl:r.helpUrl}}};i(U,"HintedHttpError");var x=U;function pe(n,e){if(n)switch(n){case"ENOTFOUND":return e.hostname?`DNS lookup failed for ${e.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return e.hostname&&e.port?`Connection refused by ${e.hostname}:${e.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return e.path?`Permission denied: ${e.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return e.path?`File or directory not found: ${e.path}.`:"File or directory not found.";case"EISDIR":return e.path?`Expected a file but found a directory: ${e.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return e.port?`Port ${e.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}i(pe,"hintForErrno");function ue(n){let e=n,t=new Set;for(;e!=null&&!t.has(e)&&(t.add(e),typeof e=="object");){let r=e,o=pe(r.code,r);if(o!==void 0)return o;e=r.cause}}i(ue,"hintForCause");var K="https://docs.cognite.com/cdf/access/";function d(n){return n!==null&&typeof n=="object"}i(d,"isRecord");function C(n){return n instanceof Error&&"status"in n&&typeof n.status=="number"}i(C,"isHttpError");function le(n){switch(n){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
2
  See: ${K}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
3
3
  See: ${K}`;default:return}}i(le,"httpStatusHint");function y(n){let e=n instanceof Error?n:new Error(String(n));if(!C(e))return null;let t=le(e.status);return t?Object.assign(new Error(`${e.message}
4
- ${t}`),{cause:e}):null}i(y,"enrichedHttpError");function de(n){if(!d(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(d(t)){let r=t.error;if(d(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}i(de,"findMissingArray");function ge(n,e){if(!C(n)||n.status!==400)return!1;let t=de(n);return t?t.some(r=>d(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(ge,"isMissingExternalIdError");function N(n,e){return C(n)&&n.status===404||ge(n,e)}i(N,"isNotFoundError");var X=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Z=["ACTIVE","PREVIEW"],V=class V extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};i(V,"AppVersionNotFoundError");var b=V;function R(n,e){return n.includes(e)}i(R,"includesValue");function fe(n){return R(X,n)}i(fe,"isAppVersionLifecycleState");function he(n){return R(Z,n)}i(he,"isAppVersionAlias");function me(n){return typeof n.version=="string"&&fe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||he(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(me,"isAppVersion");function W(n){if(!d(n))throw new Error("Invalid version response: not an object");if(!me(n))throw new Error("Invalid version response: missing or malformed fields");return n}i(W,"parseAppVersion");var _=class _{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(o){throw y(o)??o}}async uploadVersion(e,t,r,o,a="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let s=new FormData;s.append("file",new Blob([new Uint8Array(r)]),o),s.append("version",t),s.append("entryPath",a);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,u=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${c}`,h=new AbortController,oe=setTimeout(()=>h.abort(),300*1e3),E;try{E=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:s,signal:h.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(oe)}if(!E.ok){let g=await E.text(),S;try{S=JSON.parse(g)}catch{}let I=g;if(d(S)){let A=S.error;if(typeof A=="string")I=A;else if(d(A)){let k=A.message,z=A.code;I=typeof k=="string"?k:z!=null?`Unknown error (code: ${z})`:g}else{let k=S.message;I=typeof k=="string"?k:g}}let Y=E.headers.get("x-request-id"),se=Y?` | X-Request-ID: ${Y}`:"";throw new x(`Upload failed: ${E.status} \u2014 ${I}${se}`,{httpStatusCode:E.status,requestUrl:m,responseBody:d(S)?S:g})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),a=`${this.appsBasePath}/${r}/versions/${o}`;try{let s=await this.client.get(a);return W(s.data)}catch(s){throw N(s,[e,t])?new b(e,t):y(s)??s}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/active`;try{let o=await this.client.get(r);return W(o.data)}catch(o){if(N(o,[e]))return null;throw y(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:t}})}catch(a){throw y(a)??a}}async submitSignatures(e,t,r){let o=encodeURIComponent(e),a=encodeURIComponent(t),s=`${this.appsBasePath}/${o}/versions/${a}/signatures`;try{await this.client.post(s,{data:{items:r}})}catch(p){throw y(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),a=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let s=await this.client.post(a,{data:{}});return Se(s.data)}catch(s){throw y(s)??s}}};i(_,"AppHostingApi");var T=_,ye=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ee=["developer","certifier"];function Se(n){if(!d(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=we(t);return r?[r]:[]})}i(Se,"parseStoredSignatures");function we(n){if(!d(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:a,status:s}=n;return typeof e!="string"||e===""||!R(Ee,t)||typeof r!="number"||typeof o!="number"||typeof a!="number"||!R(ye,s)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:a,status:s}}i(we,"parseStoredSignature");var F=class F{constructor(e){this.api=new T(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,o,a){return this.api.uploadVersion(e,t,r,o,a)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(o){if(C(o)&&o.status===409){console.log(`\u2705 App '${e}' already exists`);return}throw o}}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let o=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(e,t,r,o,a,s,p=!1){console.log(`
4
+ ${t}`),{cause:e}):null}i(y,"enrichedHttpError");function de(n){if(!d(n))return null;let e=n.missing;if(Array.isArray(e))return e;let t=n.data;if(d(t)){let r=t.error;if(d(r)&&Array.isArray(r.missing))return r.missing;if(Array.isArray(t.missing))return t.missing}return null}i(de,"findMissingArray");function ge(n,e){if(!C(n)||n.status!==400)return!1;let t=de(n);return t?t.some(r=>d(r)&&typeof r.externalId=="string"&&e.includes(r.externalId)):!1}i(ge,"isMissingExternalIdError");function N(n,e){return C(n)&&n.status===404||ge(n,e)}i(N,"isNotFoundError");var X=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Z=["ACTIVE","PREVIEW"],V=class V extends Error{constructor(e,t){super(`Version ${t} of app ${e} not found`),this.name="AppVersionNotFoundError",this.appExternalId=e,this.version=t}};i(V,"AppVersionNotFoundError");var b=V;function R(n,e){return n.includes(e)}i(R,"includesValue");function fe(n){return R(X,n)}i(fe,"isAppVersionLifecycleState");function he(n){return R(Z,n)}i(he,"isAppVersionAlias");function me(n){return typeof n.version=="string"&&fe(n.lifecycleState)&&typeof n.entrypoint=="string"&&typeof n.createdTime=="number"&&typeof n.createdBy=="string"&&typeof n.appExternalId=="string"&&(n.alias===void 0||he(n.alias))&&(n.comment===void 0||typeof n.comment=="string")}i(me,"isAppVersion");function W(n){if(!d(n))throw new Error("Invalid version response: not an object");if(!me(n))throw new Error("Invalid version response: missing or malformed fields");return n}i(W,"parseAppVersion");var _=class _{constructor(e){this.client=e}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(e,t,r){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:e,name:t,description:r}]}})}catch(o){throw y(o)??o}}async uploadVersion(e,t,r,o,s="index.html"){console.log(`\u{1F4E4} Uploading version ${t}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(r)]),o),a.append("version",t),a.append("entryPath",s);let p=encodeURIComponent(e),c=`${this.appsBasePath}/${p}/versions`,u=await this.client.authenticate(),m=`${this.client.getBaseUrl()}${c}`,h=new AbortController,oe=setTimeout(()=>h.abort(),300*1e3),E;try{E=await fetch(m,{method:"POST",headers:{Authorization:`Bearer ${u}`},body:a,signal:h.signal})}catch(g){throw g instanceof Error&&g.name==="AbortError"?new Error("Upload timed out after 5 minutes"):g}finally{clearTimeout(oe)}if(!E.ok){let g=await E.text(),S;try{S=JSON.parse(g)}catch{}let I=g;if(d(S)){let A=S.error;if(typeof A=="string")I=A;else if(d(A)){let k=A.message,z=A.code;I=typeof k=="string"?k:z!=null?`Unknown error (code: ${z})`:g}else{let k=S.message;I=typeof k=="string"?k:g}}let Y=E.headers.get("x-request-id"),se=Y?` | X-Request-ID: ${Y}`:"";throw new x(`Upload failed: ${E.status} \u2014 ${I}${se}`,{httpStatusCode:E.status,requestUrl:m,responseBody:d(S)?S:g})}console.log(`\u2705 Version ${t} uploaded`)}async getVersion(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}`;try{let a=await this.client.get(s);return W(a.data)}catch(a){throw N(a,[e,t])?new b(e,t):y(a)??a}}async getActiveVersion(e){let t=encodeURIComponent(e),r=`${this.appsBasePath}/${t}/active`;try{let o=await this.client.get(r);return W(o.data)}catch(o){if(N(o,[e]))return null;throw y(o)??o}}async updateVersions(e,t){let r=encodeURIComponent(e),o=`${this.appsBasePath}/${r}/versions/update`;try{await this.client.post(o,{data:{items:t}})}catch(s){throw y(s)??s}}async submitSignatures(e,t,r){let o=encodeURIComponent(e),s=encodeURIComponent(t),a=`${this.appsBasePath}/${o}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:r}})}catch(p){throw y(p)??p}}async listSignatures(e,t){let r=encodeURIComponent(e),o=encodeURIComponent(t),s=`${this.appsBasePath}/${r}/versions/${o}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return Se(a.data)}catch(a){throw y(a)??a}}};i(_,"AppHostingApi");var T=_,ye=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],Ee=["developer","certifier"];function Se(n){if(!d(n))throw new Error("Invalid signatures response: expected an object with an items array");let{items:e}=n;if(!Array.isArray(e))throw new Error("Invalid signatures response: items property is missing or not an array");return e.flatMap(t=>{let r=we(t);return r?[r]:[]})}i(Se,"parseStoredSignatures");function we(n){if(!d(n))return null;let{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}=n;return typeof e!="string"||e===""||!R(Ee,t)||typeof r!="number"||typeof o!="number"||typeof s!="number"||!R(ye,a)?null:{signerKid:e,signerRole:t,signatureIat:r,receivedAt:o,createdTime:s,status:a}}i(we,"parseStoredSignature");var F=class F{constructor(e){this.api=new T(e)}getVersion(e,t){return this.api.getVersion(e,t)}uploadVersion(e,t,r,o,s){return this.api.uploadVersion(e,t,r,o,s)}async ensureApp(e,t,r){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(e,t,r),console.log(`\u2705 App '${e}' created`)}catch(o){if(C(o)&&o.status===409){console.log(`\u2705 App '${e}' already exists`);return}throw o}}async submitSignatures(e,t,r){r.length!==0&&(console.log(`\u{1F50F} Submitting ${r.length} signature${r.length===1?"":"s"} for version ${t}...`),await this.api.submitSignatures(e,t,r),console.log("\u2705 Signatures stored"))}listSignatures(e,t){return this.api.listSignatures(e,t)}async publishVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(e,t){console.log(`\u{1F680} Publishing and activating version ${t}...`),await this.api.updateVersions(e,[{version:t,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${t} is now PUBLISHED and ACTIVE`)}getActiveVersion(e){return this.api.getActiveVersion(e)}async deactivateVersion(e,t){await this.api.updateVersions(e,[{version:t,update:{alias:{setNull:!0}}}])}async activateVersion(e,t){let r=null;try{r=await this.api.getActiveVersion(e)}catch{r=null}let o=r&&r.version!==t?r.version:void 0;return await this.api.updateVersions(e,[{version:t,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:o}}async deploy(e,t,r,o,s,a,p=!1){console.log(`
5
5
  \u{1F680} Deploying application via App Hosting API...
6
- `);try{await this.ensureApp(e,t,r),await this.uploadVersion(e,o,a,s),p&&await this.publishAndActivate(e,o),console.log(`
7
- \u2705 Deployment successful!`)}catch(c){let u=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${u}`),{cause:c})}}};i(F,"AppHostingClient");var v=F;import{execFileSync as $}from"child_process";import f from"fs";import l from"path";import{parseAndValidateManifestConfig as Ae}from"@cognite/app-sdk/vite";import{BlobReader as ke,Uint8ArrayWriter as Ce,ZipWriter as ve}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Q="manifest.json",B=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],H=class H{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!f.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,O);if(!f.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,L);if(!f.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new ve(new Ce,{level:9}),o=i(async(c,u)=>{await r.add(u,new ke(await f.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),a=i(async c=>{let u=await f.promises.readdir(c,{withFileTypes:!0});for(let m of u){let h=l.join(c,m.name);m.isDirectory()?await a(h):await o(h,l.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),s;try{await a(this.distPath);let c=l.join(this.appRoot,O);await o(c,l.posix.join(B,O));let u=l.join(this.appRoot,Q);if(f.existsSync(u)){let h=f.readFileSync(u,"utf-8");Ae(h,u),await o(u,l.posix.join(B,Q))}let m=l.join(this.appRoot,L);await o(m,l.posix.join(B,L)),s=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}await f.promises.writeFile(e,s);let p=(s.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=$("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=$("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",a=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(t,a);try{$("git",["-C",t,"archive","--format=zip",`--output=${e}`,a])}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${u}`)}let p=(f.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=$("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
8
- `).filter(Boolean),o=i(s=>s.split("/").some(p=>Pe.some(c=>c.test(p))),"isSensitive"),a=r.filter(o);if(a.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
9
- `+a.map(s=>` ${s}`).join(`
6
+ `);try{await this.ensureApp(e,t,r),await this.uploadVersion(e,o,s,a),p&&await this.publishAndActivate(e,o),console.log(`
7
+ \u2705 Deployment successful!`)}catch(c){let u=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${u}`),{cause:c})}}};i(F,"AppHostingClient");var v=F;import{execFileSync as $}from"child_process";import f from"fs";import l from"path";import{parseAndValidateManifestConfig as Ae}from"@cognite/app-sdk/vite";import{BlobReader as ke,Uint8ArrayWriter as Ce,ZipWriter as ve}from"@zip.js/zip.js";var O="package.json",L="package-lock.json",Q="manifest.json",B=".cognite",Pe=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],H=class H{constructor(e="dist"){this.distPath=l.isAbsolute(e)?e:l.join(process.cwd(),e),this.appRoot=l.dirname(this.distPath)}validateBuildDirectory(){if(!f.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let e=l.join(this.appRoot,O);if(!f.existsSync(e))throw new Error(`"${e}" not found. It is required for deployment.`);let t=l.join(this.appRoot,L);if(!f.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`)}async createZip(e="app.zip",t=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let r=new ve(new Ce,{level:9}),o=i(async(c,u)=>{await r.add(u,new ke(await f.openAsBlob(c))),t&&console.log(` \u{1F4C4} ${u}`)},"addFile"),s=i(async c=>{let u=await f.promises.readdir(c,{withFileTypes:!0});for(let m of u){let h=l.join(c,m.name);m.isDirectory()?await s(h):await o(h,l.relative(this.distPath,h).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=l.join(this.appRoot,O);await o(c,l.posix.join(B,O));let u=l.join(this.appRoot,Q);if(f.existsSync(u)){let h=f.readFileSync(u,"utf-8");Ae(h,u),await o(u,l.posix.join(B,Q))}let m=l.join(this.appRoot,L);await o(m,l.posix.join(B,L)),a=await r.close()}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${u}`)}await f.promises.writeFile(e,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${e} (${p} MB)`),e}async createSourceArchive(e){console.log("\u{1F4E6} Packaging source for review...");let t;try{t=$("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let r=$("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),o=r?r.replace(/\/$/,""):".",s=o==="."?"HEAD":`HEAD:${o}`;this.validateNoSensitiveFiles(t,s);try{$("git",["-C",t,"archive","--format=zip",`--output=${e}`,s])}catch(c){let u=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${u}`)}let p=(f.statSync(e).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${l.basename(e)} (${p} MB)`),e}validateNoSensitiveFiles(e,t){let r=$("git",["-C",e,"ls-tree","-r","--name-only",t],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
8
+ `).filter(Boolean),o=i(a=>a.split("/").some(p=>Pe.some(c=>c.test(p))),"isSensitive"),s=r.filter(o);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
9
+ `+s.map(a=>` ${a}`).join(`
10
10
  `)+`
11
- Hint: git rm --cached <file>`)}};i(H,"ApplicationPackager");var P=H;import Ie from"path";var ee=".cognite-bundles";function te(n,e){return`${n}-${e}.zip`}i(te,"bundleFileName");function j(n,e,t){return Ie.join(n,ee,te(e,t))}i(j,"bundlePath");import{CogniteClient as Ne}from"@cognite/sdk";function xe(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(xe,"exponentialBackoffWithJitter");function be(n){return new Promise(e=>setTimeout(e,n))}i(be,"sleep");async function M(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??xe;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let a=1;for(;;)try{return await n()}catch(s){if(a>=t||!r(s))throw s;let p=o(a);e.onAttemptFail?.(s,a,p),await be(p),a++}}i(M,"retryAsync");var Re=i(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let a=r.toLowerCase().replace(/_/g,"-");t[a]=o}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Te=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Re()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),$e=i(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let e=n.replace(/^https?:\/\//,"");return e=e.split("/")[0],e=e.split(":")[0],e=e.replace(/\.cognitedata\.com$/,""),e}},"extractClusterFromUrl"),De=i(async(n,e)=>{let t=`Basic ${btoa(`${n}:${e}`)}`,r="https://auth.cognite.com/oauth2/token",o;try{o=await M(()=>fetch(r,{method:"POST",headers:{Authorization:t,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})}),{maxAttempts:3})}catch(s){throw new w(`Failed to fetch access token from ${r}`,{cause:s})}if(!o.ok){let s=await o.text();throw new Error(`Failed to get token from CDF: ${o.status} ${o.statusText}
12
- ${s}`)}let a=await o.json();if(!a.access_token)throw new Error("No access token returned from CDF authentication");return a.access_token},"getTokenCdf"),Ue=i(async(n,e,t,r)=>{if(!r)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let o=$e(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 a=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,s=`https://${o}.cognitedata.com/.default`,p;try{p=await M(()=>fetch(a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,scope:s,grant_type:"client_credentials"})}),{maxAttempts:3})}catch(u){throw new w(`Failed to fetch access token from ${a}`,{cause:u})}if(!p.ok){let u=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
13
- ${u}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),q=i(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:o="cdf",tenantId:a,baseUrl:s}=n,p=Te(r);if(o==="entra_id"){if(!a)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Ue(t,p,a,s)}return De(t,p)},"getToken");async function G(n,e,t=process.env,r){let o=await q(n,t),a=t.COGNITE_BASE_URL??n.baseUrl,s=(r??(p=>new Ne(p)))({appId:e,project:n.project,baseUrl:a,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await s.authenticate(),s}i(G,"getSdk");async function ne(n,e,t,r){let{externalId:o,name:a,description:s,versionTag:p}=e,c=j(t,o,p);await Ve(Oe(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u=await _e(c);await new v(n).deploy(o,a,s,p,u,Fe(c),r)}i(ne,"packageAndUpload");var Le=i(async(n,e,t)=>{let r=await G(n,t);await ne(r,e,t,n.published)},"deploy");import{existsSync as Be,readFileSync as He}from"fs";var re=[".dev.sig",".cert.sig"];function je(n,e={}){let t=e.existsSync??Be,r=e.readFileSync??((a,s)=>He(a,s)),o=[];for(let a of re){let s=`${n}${a}`;if(!t(s))continue;let p=r(s,"utf8").trim();p.length>0&&o.push(p)}return o}i(je,"discoverSignatures");export{v as a,P as b,ee as c,te as d,j as e,q as f,G as g,ne as h,Le as i,re as j,je as k};
11
+ Hint: git rm --cached <file>`)}};i(H,"ApplicationPackager");var P=H;import Ie from"path";var ee=".cognite-bundles";function te(n,e){return`${n}-${e}.zip`}i(te,"bundleFileName");function j(n,e,t){return Ie.join(n,ee,te(e,t))}i(j,"bundlePath");import{CogniteClient as Ve}from"@cognite/sdk";function xe(n){return Math.floor(Math.random()*Math.min(2**n*250,15e3))}i(xe,"exponentialBackoffWithJitter");function be(n){return new Promise(e=>setTimeout(e,n))}i(be,"sleep");async function M(n,e={}){let t=e.maxAttempts??5,r=e.shouldRetry??(()=>!0),o=e.delayInMsCalculator??xe;if(t<1)throw new Error("`maxAttempts` must be 1 or greater");if(t>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await n()}catch(a){if(s>=t||!r(a))throw a;let p=o(s);e.onAttemptFail?.(a,s,p),await be(p),s++}}i(M,"retryAsync");var Re=i(()=>{let n=process.env.DEPLOYMENT_SECRETS;if(!n)return{};try{let e=JSON.parse(n),t={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=r.toLowerCase().replace(/_/g,"-");t[s]=o}return t}catch(e){return console.error("Error parsing DEPLOYMENT_SECRETS:",e),{}}},"loadSecretsFromEnv"),Te=i(n=>{let e;if(process.env.DEPLOYMENT_SECRET&&(e=process.env.DEPLOYMENT_SECRET),e||(e=Re()[n]),e||(e=process.env[n]),!e)throw new Error(`Secret not found in environment: ${n}`);return e},"getSecretFromEnv"),$e=i(n=>{if(!n)return"";try{return new URL(n).hostname.replace(/\.cognitedata\.com$/,"")}catch{let e=n.replace(/^https?:\/\//,"");return e=e.split("/")[0],e=e.split(":")[0],e=e.replace(/\.cognitedata\.com$/,""),e}},"extractClusterFromUrl"),De=i(async(n,e)=>{let t=`Basic ${btoa(`${n}:${e}`)}`,r="https://auth.cognite.com/oauth2/token",o={grant_type:"client_credentials"},s;try{s=await M(()=>fetch(r,{method:"POST",headers:{Authorization:t,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(o)}),{maxAttempts:3})}catch(p){throw new w(`Failed to fetch access token from ${r}`,{cause:p})}if(!s.ok){let p=await s.text();throw new Error(`Failed to get token from CDF: ${s.status} ${s.statusText}
12
+ ${p}`)}let a=await s.json();if(!a.access_token)throw new Error("No access token returned from CDF authentication");return a.access_token},"getTokenCdf"),Ue=i((n,e)=>{if(e!==void 0)return e.join(" ");if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let t=$e(n);if(!t)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);return`https://${t}.cognitedata.com/.default`},"resolveEntraScope"),Ne=i(async(n,e,t,r,o)=>{let s=`https://login.microsoftonline.com/${t}/oauth2/v2.0/token`,a=Ue(r,o),p;try{p=await M(()=>fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n,client_secret:e,grant_type:"client_credentials",...a?{scope:a}:{}})}),{maxAttempts:3})}catch(u){throw new w(`Failed to fetch access token from ${s}`,{cause:u})}if(!p.ok){let u=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
13
+ ${u}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),q=i(async(n,e=process.env)=>{if(e.COGNITE_TOKEN)return e.COGNITE_TOKEN;let{deployClientId:t,deploySecretName:r,idpType:o="cdf",tenantId:s,baseUrl:a,scopes:p}=n,c=Te(r);if(o==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Ne(t,c,s,a,p)}return De(t,c)},"getToken");async function G(n,e,t=process.env,r){let o=await q(n,t),s=t.COGNITE_BASE_URL??n.baseUrl,a=(r??(p=>new Ve(p)))({appId:e,project:n.project,baseUrl:s,oidcTokenProvider:i(async()=>o,"oidcTokenProvider")});return await a.authenticate(),a}i(G,"getSdk");async function ne(n,e,t,r){let{externalId:o,name:s,description:a,versionTag:p}=e,c=j(t,o,p);await _e(Le(c),{recursive:!0}),await new P(`${t}/dist`).createZip(c,!0);let u=await Fe(c);await new v(n).deploy(o,s,a,p,u,Oe(c),r)}i(ne,"packageAndUpload");var Be=i(async(n,e,t)=>{let r=await G(n,t);await ne(r,e,t,n.published)},"deploy");import{existsSync as He,readFileSync as je}from"fs";var re=[".dev.sig",".cert.sig"];function Me(n,e={}){let t=e.existsSync??He,r=e.readFileSync??((s,a)=>je(s,a)),o=[];for(let s of re){let a=`${n}${s}`;if(!t(a))continue;let p=r(a,"utf8").trim();p.length>0&&o.push(p)}return o}i(Me,"discoverSignatures");export{v as a,P as b,ee as c,te as d,j as e,q as f,G as g,ne as h,Be as i,re as j,Me as k};
package/dist/cli/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- var ro=Object.defineProperty;var o=(e,t)=>ro(e,"name",{value:t,configurable:!0});import{writeSync as Vp}from"fs";import{Command as Bp}from"commander";var Ke=class Ke extends Error{constructor(t,r={}){super(t),this.name="HintedError",r.cause!==void 0&&(this.cause=r.cause);let n=this.deriveDefaults(r);this.hint=r.hint??n.hint,this.helpUrl=r.helpUrl??n.helpUrl,this.shouldReport=r.shouldReport??!0}deriveDefaults(t){return{hint:so(t.cause)}}};o(Ke,"HintedError");var D=Ke;function Nt(e){return e instanceof D}o(Nt,"isHintedError");var Lt="https://docs.cognite.com/cdf/access/",no="https://status.cognite.com";function oo(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Lt};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Lt};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:no};default:return{}}}o(oo,"defaultHintForStatus");var je=class je extends D{constructor(t,r){super(t,r),this.name="HintedHttpError",this.httpStatusCode=r.httpStatusCode,this.requestUrl=r.requestUrl,this.responseBody=r.responseBody}deriveDefaults(t){let{httpStatusCode:r}=t,n=oo(r),i=super.deriveDefaults(t);return{hint:n.hint??i.hint,helpUrl:n.helpUrl}}};o(je,"HintedHttpError");var pe=je;function Kt(e){return e instanceof pe}o(Kt,"isHintedHttpError");function io(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(io,"hintForErrno");function so(e){let t=e,r=new Set;for(;t!=null&&!r.has(t)&&(r.add(t),typeof t=="object");){let n=t,i=io(n.code,n);if(i!==void 0)return i;t=n.cause}}o(so,"hintForCause");var jt="https://docs.cognite.com/cdf/access/";function L(e){return e!==null&&typeof e=="object"}o(L,"isRecord");function J(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(J,"isHttpError");function ao(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
2
+ var no=Object.defineProperty;var o=(e,t)=>no(e,"name",{value:t,configurable:!0});import{writeSync as Bp}from"fs";import{Command as Gp}from"commander";var Ke=class Ke extends Error{constructor(t,r={}){super(t),this.name="HintedError",r.cause!==void 0&&(this.cause=r.cause);let n=this.deriveDefaults(r);this.hint=r.hint??n.hint,this.helpUrl=r.helpUrl??n.helpUrl,this.shouldReport=r.shouldReport??!0}deriveDefaults(t){return{hint:ao(t.cause)}}};o(Ke,"HintedError");var D=Ke;function Nt(e){return e instanceof D}o(Nt,"isHintedError");var Lt="https://docs.cognite.com/cdf/access/",oo="https://status.cognite.com";function io(e){switch(e){case 401:return{hint:"Your credentials are invalid or expired. Check your client ID and secret.",helpUrl:Lt};case 403:return{hint:"You don't have the required CDF capabilities. Please contact your CDF admin.",helpUrl:Lt};case 413:return{hint:"The deployment exceeds the App Hosting size limit. Reduce the build output \u2014 remove unused assets, code-split bundles, or strip source maps."};case 429:return{hint:"You are being rate limited. Wait a few moments and retry. If this persists, contact CDF support."};case 500:case 502:case 503:case 504:return{hint:"CDF service error. The issue is on the server side. Check the status page and retry shortly.",helpUrl:oo};default:return{}}}o(io,"defaultHintForStatus");var je=class je extends D{constructor(t,r){super(t,r),this.name="HintedHttpError",this.httpStatusCode=r.httpStatusCode,this.requestUrl=r.requestUrl,this.responseBody=r.responseBody}deriveDefaults(t){let{httpStatusCode:r}=t,n=io(r),i=super.deriveDefaults(t);return{hint:n.hint??i.hint,helpUrl:n.helpUrl}}};o(je,"HintedHttpError");var pe=je;function Kt(e){return e instanceof pe}o(Kt,"isHintedHttpError");function so(e,t){if(e)switch(e){case"ENOTFOUND":return t.hostname?`DNS lookup failed for ${t.hostname}. Check your network, VPN, or proxy settings.`:"DNS lookup failed. Check your network, VPN, or proxy settings.";case"ECONNREFUSED":return t.hostname&&t.port?`Connection refused by ${t.hostname}:${t.port}. The service may be down or the port may be wrong.`:"Connection refused. The service may be down or the port may be wrong.";case"ECONNRESET":return"Connection was reset. The server closed the connection unexpectedly; check for proxy/firewall interference and retry.";case"ETIMEDOUT":return"Connection timed out. Check your network, VPN, or proxy settings, and retry.";case"EAI_AGAIN":return"Temporary DNS failure. Retry shortly; if it persists, check your DNS configuration.";case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"SELF_SIGNED_CERT_IN_CHAIN":return"TLS certificate validation failed. Check system clock and CA trust store; if you use a corporate proxy, ensure its root cert is trusted.";case"EACCES":return t.path?`Permission denied: ${t.path}. Check file ownership and permissions.`:"Permission denied. Check file ownership and permissions.";case"ENOENT":return t.path?`File or directory not found: ${t.path}.`:"File or directory not found.";case"EISDIR":return t.path?`Expected a file but found a directory: ${t.path}.`:"Expected a file but found a directory.";case"ENOSPC":return"No space left on device. Free up disk space and retry.";case"EADDRINUSE":return t.port?`Port ${t.port} is already in use. Stop the process using it or pick a different port.`:"Address is already in use. Stop the conflicting process or change the port.";case"EMFILE":case"ENFILE":return"Too many open files. Close other programs or raise the file descriptor limit.";default:return}}o(so,"hintForErrno");function ao(e){let t=e,r=new Set;for(;t!=null&&!r.has(t)&&(r.add(t),typeof t=="object");){let n=t,i=so(n.code,n);if(i!==void 0)return i;t=n.cause}}o(ao,"hintForCause");var jt="https://docs.cognite.com/cdf/access/";function L(e){return e!==null&&typeof e=="object"}o(L,"isRecord");function z(e){return e instanceof Error&&"status"in e&&typeof e.status=="number"}o(z,"isHttpError");function po(e){switch(e){case 401:return`Your credentials are invalid or expired. Check your client ID and secret.
3
3
  See: ${jt}`;case 403:return`You don't have the required CDF capabilities. Please contact your CDF admin.
4
- See: ${jt}`;default:return}}o(ao,"httpStatusHint");function z(e){let t=e instanceof Error?e:new Error(String(e));if(!J(t))return null;let r=ao(t.status);return r?Object.assign(new Error(`${t.message}
5
- ${r}`),{cause:t}):null}o(z,"enrichedHttpError");function po(e){if(!L(e))return null;let t=e.missing;if(Array.isArray(t))return t;let r=e.data;if(L(r)){let n=r.error;if(L(n)&&Array.isArray(n.missing))return n.missing;if(Array.isArray(r.missing))return r.missing}return null}o(po,"findMissingArray");function co(e,t){if(!J(e)||e.status!==400)return!1;let r=po(e);return r?r.some(n=>L(n)&&typeof n.externalId=="string"&&t.includes(n.externalId)):!1}o(co,"isMissingExternalIdError");function Me(e,t){return J(e)&&e.status===404||co(e,t)}o(Me,"isNotFoundError");var Ht=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Vt=["ACTIVE","PREVIEW"],He=class He extends Error{constructor(t,r){super(`Version ${r} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=r}};o(He,"AppVersionNotFoundError");var K=He;function Se(e,t){return e.includes(t)}o(Se,"includesValue");function lo(e){return Se(Ht,e)}o(lo,"isAppVersionLifecycleState");function mo(e){return Se(Vt,e)}o(mo,"isAppVersionAlias");function uo(e){return typeof e.version=="string"&&lo(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||mo(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(uo,"isAppVersion");function Mt(e){if(!L(e))throw new Error("Invalid version response: not an object");if(!uo(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Mt,"parseAppVersion");var Ve=class Ve{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,r,n){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:r,description:n}]}})}catch(i){throw z(i)??i}}async uploadVersion(t,r,n,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${r}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(n)]),i),a.append("version",r),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),d=`${this.client.getBaseUrl()}${c}`,m=new AbortController,y=setTimeout(()=>m.abort(),300*1e3),g;try{g=await fetch(d,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:m.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?new Error("Upload timed out after 5 minutes"):u}finally{clearTimeout(y)}if(!g.ok){let u=await g.text(),S;try{S=JSON.parse(u)}catch{}let h=u;if(L(S)){let U=S.error;if(typeof U=="string")h=U;else if(L(U)){let x=U.message,M=U.code;h=typeof x=="string"?x:M!=null?`Unknown error (code: ${M})`:u}else{let x=S.message;h=typeof x=="string"?x:u}}let k=g.headers.get("x-request-id"),f=k?` | X-Request-ID: ${k}`:"";throw new pe(`Upload failed: ${g.status} \u2014 ${h}${f}`,{httpStatusCode:g.status,requestUrl:d,responseBody:L(S)?S:u})}console.log(`\u2705 Version ${r} uploaded`)}async getVersion(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}`;try{let a=await this.client.get(s);return Mt(a.data)}catch(a){throw Me(a,[t,r])?new K(t,r):z(a)??a}}async getActiveVersion(t){let r=encodeURIComponent(t),n=`${this.appsBasePath}/${r}/active`;try{let i=await this.client.get(n);return Mt(i.data)}catch(i){if(Me(i,[t]))return null;throw z(i)??i}}async updateVersions(t,r){let n=encodeURIComponent(t),i=`${this.appsBasePath}/${n}/versions/update`;try{await this.client.post(i,{data:{items:r}})}catch(s){throw z(s)??s}}async submitSignatures(t,r,n){let i=encodeURIComponent(t),s=encodeURIComponent(r),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:n}})}catch(p){throw z(p)??p}}async listSignatures(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return yo(a.data)}catch(a){throw z(a)??a}}};o(Ve,"AppHostingApi");var we=Ve,go=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],fo=["developer","certifier"];function yo(e){if(!L(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(r=>{let n=ho(r);return n?[n]:[]})}o(yo,"parseStoredSignatures");function ho(e){if(!L(e))return null;let{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Se(fo,r)||typeof n!="number"||typeof i!="number"||typeof s!="number"||!Se(go,a)?null:{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}}o(ho,"parseStoredSignature");var Be=class Be{constructor(t){this.api=new we(t)}getVersion(t,r){return this.api.getVersion(t,r)}uploadVersion(t,r,n,i,s){return this.api.uploadVersion(t,r,n,i,s)}async ensureApp(t,r,n){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,r,n),console.log(`\u2705 App '${t}' created`)}catch(i){if(J(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async submitSignatures(t,r,n){n.length!==0&&(console.log(`\u{1F50F} Submitting ${n.length} signature${n.length===1?"":"s"} for version ${r}...`),await this.api.submitSignatures(t,r,n),console.log("\u2705 Signatures stored"))}listSignatures(t,r){return this.api.listSignatures(t,r)}async publishVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,r){console.log(`\u{1F680} Publishing and activating version ${r}...`),await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${r} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{alias:{setNull:!0}}}])}async activateVersion(t,r){let n=null;try{n=await this.api.getActiveVersion(t)}catch{n=null}let i=n&&n.version!==r?n.version:void 0;return await this.api.updateVersions(t,[{version:r,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,r,n,i,s,a,p=!1){console.log(`
4
+ See: ${jt}`;default:return}}o(po,"httpStatusHint");function W(e){let t=e instanceof Error?e:new Error(String(e));if(!z(t))return null;let r=po(t.status);return r?Object.assign(new Error(`${t.message}
5
+ ${r}`),{cause:t}):null}o(W,"enrichedHttpError");function co(e){if(!L(e))return null;let t=e.missing;if(Array.isArray(t))return t;let r=e.data;if(L(r)){let n=r.error;if(L(n)&&Array.isArray(n.missing))return n.missing;if(Array.isArray(r.missing))return r.missing}return null}o(co,"findMissingArray");function lo(e,t){if(!z(e)||e.status!==400)return!1;let r=co(e);return r?r.some(n=>L(n)&&typeof n.externalId=="string"&&t.includes(n.externalId)):!1}o(lo,"isMissingExternalIdError");function Me(e,t){return z(e)&&e.status===404||lo(e,t)}o(Me,"isNotFoundError");var Ht=["DRAFT","PUBLISHED","DEPRECATED","ARCHIVED"],Vt=["ACTIVE","PREVIEW"],He=class He extends Error{constructor(t,r){super(`Version ${r} of app ${t} not found`),this.name="AppVersionNotFoundError",this.appExternalId=t,this.version=r}};o(He,"AppVersionNotFoundError");var j=He;function Se(e,t){return e.includes(t)}o(Se,"includesValue");function mo(e){return Se(Ht,e)}o(mo,"isAppVersionLifecycleState");function uo(e){return Se(Vt,e)}o(uo,"isAppVersionAlias");function go(e){return typeof e.version=="string"&&mo(e.lifecycleState)&&typeof e.entrypoint=="string"&&typeof e.createdTime=="number"&&typeof e.createdBy=="string"&&typeof e.appExternalId=="string"&&(e.alias===void 0||uo(e.alias))&&(e.comment===void 0||typeof e.comment=="string")}o(go,"isAppVersion");function Mt(e){if(!L(e))throw new Error("Invalid version response: not an object");if(!go(e))throw new Error("Invalid version response: missing or malformed fields");return e}o(Mt,"parseAppVersion");var Ve=class Ve{constructor(t){this.client=t}get appsBasePath(){return`/api/v1/projects/${encodeURIComponent(this.client.project)}/apphosting/apps`}async createApp(t,r,n){try{await this.client.post(this.appsBasePath,{data:{items:[{externalId:t,name:r,description:n}]}})}catch(i){throw W(i)??i}}async uploadVersion(t,r,n,i,s="index.html"){console.log(`\u{1F4E4} Uploading version ${r}...`);let a=new FormData;a.append("file",new Blob([new Uint8Array(n)]),i),a.append("version",r),a.append("entryPath",s);let p=encodeURIComponent(t),c=`${this.appsBasePath}/${p}/versions`,l=await this.client.authenticate(),d=`${this.client.getBaseUrl()}${c}`,m=new AbortController,y=setTimeout(()=>m.abort(),300*1e3),g;try{g=await fetch(d,{method:"POST",headers:{Authorization:`Bearer ${l}`},body:a,signal:m.signal})}catch(u){throw u instanceof Error&&u.name==="AbortError"?new Error("Upload timed out after 5 minutes"):u}finally{clearTimeout(y)}if(!g.ok){let u=await g.text(),S;try{S=JSON.parse(u)}catch{}let h=u;if(L(S)){let U=S.error;if(typeof U=="string")h=U;else if(L(U)){let x=U.message,M=U.code;h=typeof x=="string"?x:M!=null?`Unknown error (code: ${M})`:u}else{let x=S.message;h=typeof x=="string"?x:u}}let k=g.headers.get("x-request-id"),f=k?` | X-Request-ID: ${k}`:"";throw new pe(`Upload failed: ${g.status} \u2014 ${h}${f}`,{httpStatusCode:g.status,requestUrl:d,responseBody:L(S)?S:u})}console.log(`\u2705 Version ${r} uploaded`)}async getVersion(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}`;try{let a=await this.client.get(s);return Mt(a.data)}catch(a){throw Me(a,[t,r])?new j(t,r):W(a)??a}}async getActiveVersion(t){let r=encodeURIComponent(t),n=`${this.appsBasePath}/${r}/active`;try{let i=await this.client.get(n);return Mt(i.data)}catch(i){if(Me(i,[t]))return null;throw W(i)??i}}async updateVersions(t,r){let n=encodeURIComponent(t),i=`${this.appsBasePath}/${n}/versions/update`;try{await this.client.post(i,{data:{items:r}})}catch(s){throw W(s)??s}}async submitSignatures(t,r,n){let i=encodeURIComponent(t),s=encodeURIComponent(r),a=`${this.appsBasePath}/${i}/versions/${s}/signatures`;try{await this.client.post(a,{data:{items:n}})}catch(p){throw W(p)??p}}async listSignatures(t,r){let n=encodeURIComponent(t),i=encodeURIComponent(r),s=`${this.appsBasePath}/${n}/versions/${i}/signatures/list`;try{let a=await this.client.post(s,{data:{}});return ho(a.data)}catch(a){throw W(a)??a}}};o(Ve,"AppHostingApi");var we=Ve,fo=["VALID","REVOKED","EXPIRED","SIGNED_BEFORE_KEY_ISSUED","IAT_IN_FUTURE","BUNDLE_TOO_OLD","KEY_NOT_IN_REGISTRY"],yo=["developer","certifier"];function ho(e){if(!L(e))throw new Error("Invalid signatures response: expected an object with an items array");let{items:t}=e;if(!Array.isArray(t))throw new Error("Invalid signatures response: items property is missing or not an array");return t.flatMap(r=>{let n=So(r);return n?[n]:[]})}o(ho,"parseStoredSignatures");function So(e){if(!L(e))return null;let{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}=e;return typeof t!="string"||t===""||!Se(yo,r)||typeof n!="number"||typeof i!="number"||typeof s!="number"||!Se(fo,a)?null:{signerKid:t,signerRole:r,signatureIat:n,receivedAt:i,createdTime:s,status:a}}o(So,"parseStoredSignature");var Be=class Be{constructor(t){this.api=new we(t)}getVersion(t,r){return this.api.getVersion(t,r)}uploadVersion(t,r,n,i,s){return this.api.uploadVersion(t,r,n,i,s)}async ensureApp(t,r,n){console.log("\u{1F50D} Ensuring app exists...");try{await this.api.createApp(t,r,n),console.log(`\u2705 App '${t}' created`)}catch(i){if(z(i)&&i.status===409){console.log(`\u2705 App '${t}' already exists`);return}throw i}}async submitSignatures(t,r,n){n.length!==0&&(console.log(`\u{1F50F} Submitting ${n.length} signature${n.length===1?"":"s"} for version ${r}...`),await this.api.submitSignatures(t,r,n),console.log("\u2705 Signatures stored"))}listSignatures(t,r){return this.api.listSignatures(t,r)}async publishVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"}}}])}async publishAndActivate(t,r){console.log(`\u{1F680} Publishing and activating version ${r}...`),await this.api.updateVersions(t,[{version:r,update:{lifecycleState:{set:"PUBLISHED"},alias:{set:"ACTIVE"}}}]),console.log(`\u2705 Version ${r} is now PUBLISHED and ACTIVE`)}getActiveVersion(t){return this.api.getActiveVersion(t)}async deactivateVersion(t,r){await this.api.updateVersions(t,[{version:r,update:{alias:{setNull:!0}}}])}async activateVersion(t,r){let n=null;try{n=await this.api.getActiveVersion(t)}catch{n=null}let i=n&&n.version!==r?n.version:void 0;return await this.api.updateVersions(t,[{version:r,update:{alias:{set:"ACTIVE"}}}]),{supersededVersion:i}}async deploy(t,r,n,i,s,a,p=!1){console.log(`
6
6
  \u{1F680} Deploying application via App Hosting API...
7
7
  `);try{await this.ensureApp(t,r,n),await this.uploadVersion(t,i,s,a),p&&await this.publishAndActivate(t,i),console.log(`
8
- \u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};o(Be,"AppHostingClient");var E=Be;import{existsSync as Do,readFileSync as Io}from"fs";import{resolve as $o}from"path";import{array as So,boolean as wo,check as Bt,forward as Gt,literal as vo,maxLength as Co,minLength as Eo,nonEmpty as te,object as Yt,optional as W,picklist as ko,pipe as B,safeParse as Po,string as j,url as bo}from"valibot";var Ge=B(j(),te("must not be empty")),Ye=B(j(),te("must not be empty"),Co(256,"must be 256 characters or fewer")),qe=B(j(),te("must not be empty"),bo("must be a valid URL")),Je=B(j(),te("must not be empty")),ze=B(j(),te("must not be empty")),xo=B(Yt({org:Je,project:ze,baseUrl:qe,deployClientId:W(j(),""),deploySecretName:W(j(),""),published:W(wo(),!1),idpType:W(ko(["cdf","entra_id"]),"cdf"),tenantId:W(j())}),Gt(Bt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Gt(Bt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Ao=Yt({name:Ge,externalId:Ye,versionTag:B(j(),te("must not be empty")),description:W(j(),""),deployments:B(So(xo),Eo(1,"must contain at least one deployment")),infra:W(vo("appsApi"))});function We(e){let t=Po(Ao,e);if(t.success)return t.output;let r=t.issues[0],n=r.path?.map(s=>s.key).join(".")??"",i=n?`"${n}" `:"";throw new Error(`app.json: ${i}${r.message}`)}o(We,"validateAppConfig");function v(e,t={}){let{validator:r=We,existsSync:n=Do,readFileSync:i=Io}=t,s=$o(e,"app.json");if(!n(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return r(p)}o(v,"loadAppConfig");import{CogniteClient as oi}from"@cognite/sdk";import{CogniteClient as No}from"@cognite/sdk";function Ro(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Ro,"exponentialBackoffWithJitter");function To(e){return new Promise(t=>setTimeout(t,e))}o(To,"sleep");async function Xe(e,t={}){let r=t.maxAttempts??5,n=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Ro;if(r<1)throw new Error("`maxAttempts` must be 1 or greater");if(r>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=r||!n(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await To(p),s++}}o(Xe,"retryAsync");var Fo=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),r={};for(let[n,i]of Object.entries(t))if(typeof i=="string"){let s=n.toLowerCase().replace(/_/g,"-");r[s]=i}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Oo=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Fo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),_o=o(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"),Uo=o(async(e,t)=>{let r=`Basic ${btoa(`${e}:${t}`)}`,n="https://auth.cognite.com/oauth2/token",i;try{i=await Xe(()=>fetch(n,{method:"POST",headers:{Authorization:r,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials"})}),{maxAttempts:3})}catch(a){throw new D(`Failed to fetch access token from ${n}`,{cause:a})}if(!i.ok){let a=await i.text();throw new Error(`Failed to get token from CDF: ${i.status} ${i.statusText}
9
- ${a}`)}let s=await i.json();if(!s.access_token)throw new Error("No access token returned from CDF authentication");return s.access_token},"getTokenCdf"),Lo=o(async(e,t,r,n)=>{if(!n)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let i=_o(n);if(!i)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${n}`);let s=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`,a=`https://${i}.cognitedata.com/.default`,p;try{p=await Xe(()=>fetch(s,{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"})}),{maxAttempts:3})}catch(l){throw new D(`Failed to fetch access token from ${s}`,{cause:l})}if(!p.ok){let l=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
10
- ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),Ze=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:r,deploySecretName:n,idpType:i="cdf",tenantId:s,baseUrl:a}=e,p=Oo(n);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return Lo(r,p,s,a)}return Uo(r,p)},"getToken");async function ce(e,t,r=process.env,n){let i=await Ze(e,r),s=r.COGNITE_BASE_URL??e.baseUrl,a=(n??(p=>new No(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(ce,"getSdk");import Yo from"os";import qo from"path";import Jo from"open";import{buildAuthorizationUrl as zo,calculatePKCECodeChallenge as Wo,discovery as Xo,None as Zo,randomPKCECodeVerifier as Qo,randomState as ei}from"openid-client";import Ko from"https";import{authorizationCodeGrant as jo}from"openid-client";function qt(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(qt,"escapeHtml");function Qe(e,t,r){let n=qt(t),i=qt(r);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
8
+ \u2705 Deployment successful!`)}catch(c){let l=c instanceof Error?c.message:String(c);throw Object.assign(new Error(`Deployment failed: ${l}`),{cause:c})}}};o(Be,"AppHostingClient");var E=Be;import{existsSync as Do,readFileSync as Io}from"fs";import{resolve as $o}from"path";import{array as Yt,boolean as wo,check as Bt,forward as Gt,literal as vo,maxLength as Co,minLength as Eo,nonEmpty as X,object as qt,optional as G,picklist as ko,pipe as V,safeParse as Po,string as N,url as bo}from"valibot";var Ge=V(N(),X("must not be empty")),Ye=V(N(),X("must not be empty"),Co(256,"must be 256 characters or fewer")),qe=V(N(),X("must not be empty"),bo("must be a valid URL")),Je=V(N(),X("must not be empty")),ze=V(N(),X("must not be empty")),xo=V(qt({org:Je,project:ze,baseUrl:qe,deployClientId:G(N(),""),deploySecretName:G(N(),""),published:G(wo(),!1),idpType:G(ko(["cdf","entra_id"]),"cdf"),tenantId:G(N()),scopes:G(Yt(V(N(),X("must not be empty"))))}),Gt(Bt(e=>e.idpType!=="entra_id"||!!e.tenantId,'must be set when idpType is "entra_id"'),["tenantId"]),Gt(Bt(e=>!e.deployClientId||!!e.deploySecretName,"must be set when deployClientId is set"),["deploySecretName"])),Ao=qt({name:Ge,externalId:Ye,versionTag:V(N(),X("must not be empty")),description:G(N(),""),deployments:V(Yt(xo),Eo(1,"must contain at least one deployment")),infra:G(vo("appsApi"))});function We(e){let t=Po(Ao,e);if(t.success)return t.output;let r=t.issues[0],n=r.path?.map(s=>s.key).join(".")??"",i=n?`"${n}" `:"";throw new Error(`app.json: ${i}${r.message}`)}o(We,"validateAppConfig");function v(e,t={}){let{validator:r=We,existsSync:n=Do,readFileSync:i=Io}=t,s=$o(e,"app.json");if(!n(s))throw new Error(`No app.json found at ${s}. Make sure you're running this command from your app's root directory.`);let a=i(s,"utf-8"),p;try{p=JSON.parse(a)}catch{throw new Error("Failed to parse app.json \u2014 check that it contains valid JSON.")}return r(p)}o(v,"loadAppConfig");import{CogniteClient as ii}from"@cognite/sdk";import{CogniteClient as Ko}from"@cognite/sdk";function Ro(e){return Math.floor(Math.random()*Math.min(2**e*250,15e3))}o(Ro,"exponentialBackoffWithJitter");function To(e){return new Promise(t=>setTimeout(t,e))}o(To,"sleep");async function Xe(e,t={}){let r=t.maxAttempts??5,n=t.shouldRetry??(()=>!0),i=t.delayInMsCalculator??Ro;if(r<1)throw new Error("`maxAttempts` must be 1 or greater");if(r>100)throw new Error("`maxAttempts` must be 100 or less");let s=1;for(;;)try{return await e()}catch(a){if(s>=r||!n(a))throw a;let p=i(s);t.onAttemptFail?.(a,s,p),await To(p),s++}}o(Xe,"retryAsync");var Fo=o(()=>{let e=process.env.DEPLOYMENT_SECRETS;if(!e)return{};try{let t=JSON.parse(e),r={};for(let[n,i]of Object.entries(t))if(typeof i=="string"){let s=n.toLowerCase().replace(/_/g,"-");r[s]=i}return r}catch(t){return console.error("Error parsing DEPLOYMENT_SECRETS:",t),{}}},"loadSecretsFromEnv"),Oo=o(e=>{let t;if(process.env.DEPLOYMENT_SECRET&&(t=process.env.DEPLOYMENT_SECRET),t||(t=Fo()[e]),t||(t=process.env[e]),!t)throw new Error(`Secret not found in environment: ${e}`);return t},"getSecretFromEnv"),_o=o(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"),Uo=o(async(e,t)=>{let r=`Basic ${btoa(`${e}:${t}`)}`,n="https://auth.cognite.com/oauth2/token",i={grant_type:"client_credentials"},s;try{s=await Xe(()=>fetch(n,{method:"POST",headers:{Authorization:r,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(i)}),{maxAttempts:3})}catch(p){throw new D(`Failed to fetch access token from ${n}`,{cause:p})}if(!s.ok){let p=await s.text();throw new Error(`Failed to get token from CDF: ${s.status} ${s.statusText}
9
+ ${p}`)}let a=await s.json();if(!a.access_token)throw new Error("No access token returned from CDF authentication");return a.access_token},"getTokenCdf"),Lo=o((e,t)=>{if(t!==void 0)return t.join(" ");if(!e)throw new Error("Entra ID authentication requires 'baseUrl' to be set in deployment configuration");let r=_o(e);if(!r)throw new Error(`Entra ID authentication requires 'baseUrl' to be a valid CDF URL (e.g., https://cluster.cognitedata.com), got: ${e}`);return`https://${r}.cognitedata.com/.default`},"resolveEntraScope"),No=o(async(e,t,r,n,i)=>{let s=`https://login.microsoftonline.com/${r}/oauth2/v2.0/token`,a=Lo(n,i),p;try{p=await Xe(()=>fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e,client_secret:t,grant_type:"client_credentials",...a?{scope:a}:{}})}),{maxAttempts:3})}catch(l){throw new D(`Failed to fetch access token from ${s}`,{cause:l})}if(!p.ok){let l=await p.text();throw new Error(`Failed to get token from Entra ID: ${p.status} ${p.statusText}
10
+ ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token returned from Entra ID authentication");return c.access_token},"getTokenEntra"),Ze=o(async(e,t=process.env)=>{if(t.COGNITE_TOKEN)return t.COGNITE_TOKEN;let{deployClientId:r,deploySecretName:n,idpType:i="cdf",tenantId:s,baseUrl:a,scopes:p}=e,c=Oo(n);if(i==="entra_id"){if(!s)throw new Error("Entra ID authentication requires 'tenantId' in deployment configuration");return No(r,c,s,a,p)}return Uo(r,c)},"getToken");async function ce(e,t,r=process.env,n){let i=await Ze(e,r),s=r.COGNITE_BASE_URL??e.baseUrl,a=(n??(p=>new Ko(p)))({appId:t,project:e.project,baseUrl:s,oidcTokenProvider:o(async()=>i,"oidcTokenProvider")});return await a.authenticate(),a}o(ce,"getSdk");import qo from"os";import Jo from"path";import zo from"open";import{buildAuthorizationUrl as Wo,calculatePKCECodeChallenge as Xo,discovery as Zo,None as Qo,randomPKCECodeVerifier as ei,randomState as ti}from"openid-client";import jo from"https";import{authorizationCodeGrant as Mo}from"openid-client";function Jt(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t]??t)}o(Jt,"escapeHtml");function Qe(e,t,r){let n=Jt(t),i=Jt(r);return`<html><body style="font-family: system-ui; padding: 40px; text-align: center;">
11
11
  <h1>${n}</h1><p>${i}</p><p>You can close this window.</p>${e==="success"?`<style>
12
12
  @keyframes checkmark {
13
13
  0% { transform: scale(0); }
@@ -16,31 +16,31 @@ ${l}`)}let c=await p.json();if(!c.access_token)throw new Error("No access token
16
16
  }
17
17
  h1 { animation: checkmark 0.5s ease-out; }
18
18
  </style>`:""}
19
- </body></html>`}o(Qe,"generateHtml");async function Mo(e,t,r,n,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(r,a,{pkceCodeVerifier:n,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Qe("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(Qe("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Mo,"handleCallback");function Ho(e){let t=e/6e4,r=Math.round(t*10)/10;return`${r} ${r===1?"minute":"minutes"}`}o(Ho,"formatTimeoutMinutes");function Jt(e,t,r,n,i,s={createServer:Ko.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:jo}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,y)=>{try{let g=await Mo(m,y,r,n,i,s);g.shouldClose&&(d(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){d(),p(g instanceof Error?g:new Error(String(g)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Ho(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}o(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${m.message}`),p(m)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(Jt,"startCallbackServer");import{mkdirSync as Vo}from"fs";import{loadLocalCertificates as Bo}from"@cognite/app-sdk/https";var Go={loadLocalCertificates:Bo,mkdirSync:Vo,logger:console};async function zt(e,t=Go){t.mkdirSync(e,{recursive:!0});let{cert:r,key:n,source:i}=await t.loadLocalCertificates({certDir:e});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:r,key:n}}o(zt,"getOrCreateCertificates");var ti={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:qo.join(Yo.homedir(),".cdf-login")},ri={open:Jo,getOrCreateCertificates:zt,startCallbackServer:Jt,discovery:Xo,buildAuthorizationUrl:zo,randomPKCECodeVerifier:Qo,calculatePKCECodeChallenge:Wo,randomState:ei,logger:console};async function Xt(e,t=ti,r){return r===void 0?Wt(e,t,ri):Wt(e,t,r)}o(Xt,"login");async function ni(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,Zo())}catch(r){throw new D(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}o(ni,"fetchOpenIdConfig");async function Wt(e,t,r){r.logger.log(`\u{1F510} Starting CDF login flow...
20
- `),r.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let n=await ni(r,t),i=r.randomPKCECodeVerifier(),s=await r.calculatePKCECodeChallenge(i),a=r.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(p.organization_hint=e);let c=r.buildAuthorizationUrl(n,p).toString(),l=await r.getOrCreateCertificates(t.certDir);e&&r.logger.log(`\u{1F3E2} Organization: ${e}`),r.logger.log(`\u{1F680} Opening browser for authentication...
19
+ </body></html>`}o(Qe,"generateHtml");async function Ho(e,t,r,n,i,s){let a=new URL(e.url??"/",`https://${e.headers.host??"localhost"}`);if(a.pathname!=="/")return t.writeHead(404),t.end("Not found"),{shouldClose:!1};try{console.log("\u{1F504} Exchanging authorization code for tokens...");let p=await s.authorizationCodeGrant(r,a,{pkceCodeVerifier:n,expectedState:i});return t.writeHead(200,{"Content-Type":"text/html"}),t.end(Qe("success","Login Successful!","You can close this window and return to the terminal.")),{shouldClose:!0,tokens:p}}catch(p){let c=p instanceof Error?p:new Error(String(p));return t.writeHead(400,{"Content-Type":"text/html"}),t.end(Qe("error","Authentication Error",c.message)),{shouldClose:!0,error:c}}}o(Ho,"handleCallback");function Vo(e){let t=e/6e4,r=Math.round(t*10)/10;return`${r} ${r===1?"minute":"minutes"}`}o(Vo,"formatTimeoutMinutes");function zt(e,t,r,n,i,s={createServer:jo.createServer,setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,authorizationCodeGrant:Mo}){return new Promise((a,p)=>{let c=s.createServer(t,async(m,y)=>{try{let g=await Ho(m,y,r,n,i,s);g.shouldClose&&(d(),g.error?p(g.error):g.tokens?a(g.tokens):p(new Error("No tokens received")))}catch(g){d(),p(g instanceof Error?g:new Error(String(g)))}}),l=s.setTimeout(()=>{d(),p(new Error(`Login timeout - no response received within ${Vo(e.loginTimeout)}`))},e.loginTimeout);function d(){s.clearTimeout(l),c.close()}o(d,"cleanup"),c.on("error",m=>{d(),m.code==="EADDRINUSE"?console.error(`\u274C Port ${e.port} is already in use.`):console.error(`\u274C Server error: ${m.message}`),p(m)}),c.listen(e.port,"127.0.0.1",()=>{console.log(`\u{1F310} Local HTTPS server started on https://localhost:${e.port}`)})})}o(zt,"startCallbackServer");import{mkdirSync as Bo}from"fs";import{loadLocalCertificates as Go}from"@cognite/app-sdk/https";var Yo={loadLocalCertificates:Go,mkdirSync:Bo,logger:console};async function Wt(e,t=Yo){t.mkdirSync(e,{recursive:!0});let{cert:r,key:n,source:i}=await t.loadLocalCertificates({certDir:e});return i==="mkcert"?t.logger.log("\u{1F510} Using mkcert certificates for HTTPS"):(t.logger.log("\u{1F510} Using in-memory self-signed certificate for HTTPS \u2014 your browser will give you a warning."),t.logger.log(" Run `npx @cognite/cli@latest apps setup-https` to install trusted local https certificates.")),{cert:r,key:n}}o(Wt,"getOrCreateCertificates");var ri={authority:"https://auth.cognite.com",clientId:"0404baaa-0a90-43a2-aba7-a110b53fb41c",redirectUri:"https://localhost:3000/",port:3e3,loginTimeout:300*1e3,certDir:Jo.join(qo.homedir(),".cdf-login")},ni={open:zo,getOrCreateCertificates:Wt,startCallbackServer:zt,discovery:Zo,buildAuthorizationUrl:Wo,randomPKCECodeVerifier:ei,calculatePKCECodeChallenge:Xo,randomState:ti,logger:console};async function Zt(e,t=ri,r){return r===void 0?Xt(e,t,ni):Xt(e,t,r)}o(Zt,"login");async function oi(e,t){try{return await e.discovery(new URL(t.authority),t.clientId,void 0,Qo())}catch(r){throw new D(`Failed to fetch OpenID configuration from ${t.authority}`,{cause:r})}}o(oi,"fetchOpenIdConfig");async function Xt(e,t,r){r.logger.log(`\u{1F510} Starting CDF login flow...
20
+ `),r.logger.log(`\u{1F4E1} Fetching OpenID configuration from ${t.authority}...`);let n=await oi(r,t),i=r.randomPKCECodeVerifier(),s=await r.calculatePKCECodeChallenge(i),a=r.randomState(),p={redirect_uri:t.redirectUri,scope:"openid profile email",code_challenge:s,code_challenge_method:"S256",state:a};e&&(p.organization_hint=e);let c=r.buildAuthorizationUrl(n,p).toString(),l=await r.getOrCreateCertificates(t.certDir);e&&r.logger.log(`\u{1F3E2} Organization: ${e}`),r.logger.log(`\u{1F680} Opening browser for authentication...
21
21
  `);try{await r.open(c)}catch(d){let m=d instanceof Error?d.message:String(d);r.logger.error("\u274C Failed to open browser automatically."),r.logger.error(` Reason: ${m}`),r.logger.error(`Please open this URL manually:
22
- `),r.logger.error(c),r.logger.error("")}return r.startCallbackServer(t,l,n,i,a)}o(Wt,"loginImpl");async function I(e,t,r={}){let{login:n=Xt,getSdk:i=ce,createClient:s=o(a=>new oi(a),"createClient")}=r;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await n(a),c=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>p.access_token,"getToken")});return await c.authenticate(),c}return i(e,t.appId)}o(I,"getClientForDeployment");import Zt from"enquirer";var Qt="Enter custom target...";function er(e,t){let r=t.map((n,i)=>` ${i}: ${n.org}/${n.project}`).join(`
22
+ `),r.logger.error(c),r.logger.error("")}return r.startCallbackServer(t,l,n,i,a)}o(Xt,"loginImpl");async function I(e,t,r={}){let{login:n=Zt,getSdk:i=ce,createClient:s=o(a=>new ii(a),"createClient")}=r;if(t.interactive){let a=t.orgHint||e.org||void 0,p=await n(a),c=s({appId:t.appId,project:e.project,baseUrl:e.baseUrl,getToken:o(async()=>p.access_token,"getToken")});return await c.authenticate(),c}return i(e,t.appId)}o(I,"getClientForDeployment");import Qt from"enquirer";var er="Enter custom target...";function tr(e,t){let r=t.map((n,i)=>` ${i}: ${n.org}/${n.project}`).join(`
23
23
  `);throw new Error(`Deployment "${e}" not found. Available deployments:
24
- ${r}`)}o(er,"deploymentNotFoundError");function b(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let n=e[Number.parseInt(t)];if(n)return n;er(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;er(t,e)}o(b,"findDeployment");function $(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o($,"getMissingCredentials");async function R(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return b(e.deployments,t.deployment);let r=[...e.deployments.map(s=>`${s.org}/${s.project}`),Qt],{selected:n}=await Zt.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==Qt){let s=e.deployments.find(a=>`${a.org}/${a.project}`===n);if(s)return s;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await Zt.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(R,"resolveDeployment");import{existsSync as ii}from"fs";import{resolve as si}from"path";import{config as ai}from"dotenv";function T(e,t={existsSync:ii,config:ai}){let r=si(e,".env");t.existsSync(r)&&(console.log(`Loading environment variables from ${r}`),t.config({path:r}))}o(T,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
24
+ ${r}`)}o(tr,"deploymentNotFoundError");function b(e,t){if(e.length===0)throw new Error("No deployments configured in app.json");if(t===void 0)return e[0];if(/^\d+$/.test(t)){let n=e[Number.parseInt(t)];if(n)return n;tr(t,e)}let r=e.find(n=>n.project===t||`${n.org}/${n.project}`===t);if(r)return r;tr(t,e)}o(b,"findDeployment");function $(e){let t=[];return e.deployClientId||t.push("deployClientId"),e.deploySecretName||t.push("deploySecretName"),t}o($,"getMissingCredentials");async function R(e,t){if(t.baseUrl&&t.project)return{org:t.org??"",project:t.project,baseUrl:t.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"};if(t.deployment!==void 0)return b(e.deployments,t.deployment);let r=[...e.deployments.map(s=>`${s.org}/${s.project}`),er],{selected:n}=await Qt.prompt({type:"select",name:"selected",message:"Select deployment target",choices:r});if(n!==er){let s=e.deployments.find(a=>`${a.org}/${a.project}`===n);if(s)return s;throw new Error(`Deployment "${n}" could not be resolved from app.json.`)}let i=await Qt.prompt([{type:"input",name:"baseUrl",message:"CDF Base URL",initial:"https://api.cognitedata.com"},{type:"input",name:"project",message:"CDF Project",validate:o(s=>s?!0:"Project is required","validate")},{type:"input",name:"org",message:"Organization (for login hint)",initial:""}]);return{org:i.org||"",project:i.project,baseUrl:i.baseUrl,deployClientId:"",deploySecretName:"",published:!1,idpType:"cdf"}}o(R,"resolveDeployment");import{existsSync as si}from"fs";import{resolve as ai}from"path";import{config as pi}from"dotenv";function T(e,t={existsSync:si,config:pi}){let r=ai(e,".env");t.existsSync(r)&&(console.log(`Loading environment variables from ${r}`),t.config({path:r}))}o(T,"loadEnvFile");function F(e){e.infra!=="appsApi"&&(console.error(`
25
25
  \u26A0\uFE0F Legacy infrastructure is no longer supported.
26
26
 
27
27
  Your app.json is missing \`"infra": "appsApi"\`, which means it was created for
28
28
  the old CDF Application Registry. This deploy path has been removed.
29
29
 
30
30
  To migrate: add \`"infra": "appsApi"\` to your app.json, wire up the correct authentication and re-deploy.
31
- `),process.exit(1))}o(F,"assertAppHostingInfra");async function pi(e){let t=process.cwd();T(t);let r=v(t);F(r);let n=e.interactive?await R(r,e):b(r.deployments,e.deployment);if(!e.interactive){let d=$(n);if(d.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new E(i),{externalId:a,versionTag:p}=r,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof K?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(pi,"handleActivate");function tr(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
31
+ `),process.exit(1))}o(F,"assertAppHostingInfra");async function ci(e){let t=process.cwd();T(t);let r=v(t);F(r);let n=e.interactive?await R(r,e):b(r.deployments,e.deployment);if(!e.interactive){let d=$(n);if(d.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${d.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps activate --interactive\` for browser-based authentication instead.`)}let i=await I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new E(i),{externalId:a,versionTag:p}=r,c;try{c=await s.getVersion(a,p)}catch(d){throw d instanceof j?new Error(`Version ${p} of ${a} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):d}if(c.alias==="ACTIVE"){console.log(` ${a} @ ${p} is already ACTIVE \u2014 nothing to do.`);return}if(c.lifecycleState==="DEPRECATED"||c.lifecycleState==="ARCHIVED")throw new Error(`Cannot activate ${a} @ ${p}: version is ${c.lifecycleState} (terminal).`);c.lifecycleState==="DRAFT"&&(await s.publishVersion(a,p),console.log(`\u2713 Published ${a} @ ${p} is now PUBLISHED`));let{supersededVersion:l}=await s.activateVersion(a,p);console.log(`\u2713 Activated ${a} @ ${p} is now ACTIVE`),l&&console.log(` Superseded ${l} \u2192 PUBLISHED`)}o(ci,"handleActivate");function rr(e){return e.command("activate").description("Activate the current app version (publish if needed, then set ACTIVE alias)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
32
32
  Examples:
33
33
  npx @cognite/cli apps activate . Activate using env-var auth
34
- npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>pi(r))}o(tr,"registerActivateCommand");import{basename as Sr,dirname as Vi,normalize as Bi,resolve as xe}from"path";import{fileURLToPath as Gi,pathToFileURL as Yi}from"url";import{Logger as qi,runner as Ji}from"hygen";import{execFileSync as le}from"child_process";function ve(e={}){let{execFileSync:t=le}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(ve,"isGitInstalled");function Ce(e,t={}){let{execFileSync:r=le}=t;try{return r("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ce,"isInsideGitRepo");function rr(e,t={}){let{execFileSync:r=le}=t;r("git",["-C",e,"init"],{stdio:"pipe"}),r("git",["-C",e,"add","."],{stdio:"pipe"}),r("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(rr,"gitInitAndCommit");function nr(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(nr,"gitUserName");function or(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(or,"gitUserEmail");import{safeParse as ci}from"valibot";function de(e,t){return r=>{let n=ci(t,r);return n.success?!0:`${e} ${n.issues[0].message}`}}o(de,"toPromptValidator");var ir={name:de("App name",Ye),displayName:de("Display name",Ge),baseUrl:de("Base URL",qe),org:de("Org",Je),project:de("Project",ze)};function li(e,t){return e?async r=>{let n=t(r);return n===!0?e(r):n}:t}o(li,"composeValidators");function Ee(e){return e.map(t=>{if(!(t.name in ir))return t;let r=ir[t.name];return{...t,validate:li(t.validate,r)}})}o(Ee,"applySchemaValidators");import{basename as sr}from"path";import ar from"enquirer";function et(e){return e.replace(/[A-Z]/g,(t,r)=>r===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(et,"kebabCase");var di={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
35
- `),initial:!1};async function mi(e,t,r){return e!==void 0?e:t?!!(await r([di])).useSpecKit:!1}o(mi,"resolveSpecKit");function ui(e){return typeof e=="function"}o(ui,"isFunctionInitial");function pr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(pr,"normalizeCluster");function cr({isCurrentDir:e,dirName:t,onAppName:r,onUseSpecKit:n,presets:i={},specKit:s,prompt:a=ar.prompt.bind(ar)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(w=>w[1]!==void 0)),l=Object.keys(c).length>0,d=e?sr(process.cwd()):t?sr(t):null,m=l&&d!==null,y=!m&&d?p.map(w=>w.name==="name"?{...w,initial:d}:w):p,g=Ee(y),u=m&&d?{...c,name:d}:c,S=new Set(Object.keys(u)),h=g.filter(w=>!S.has(w.name)),k=h.findIndex(w=>w.name==="baseUrl"),f;if(m){let w=pr(u.cluster),H=o(C=>ui(C.initial)?C.initial():C.initial,"resolveInitial"),ee=o(C=>{if(C.name==="baseUrl")return`https://${w}.cognitedata.com`;let G=H(C);if(G===void 0)throw new Error(`Non-interactive mode: --${et(C.name)} has no default. Pass it as a flag.`);return G},"deriveValue");f=Object.fromEntries(h.map(C=>[C.name,ee(C)]))}else if(k!==-1){let w=h.filter(A=>A.name!=="baseUrl"),H=w.length>0?await a(w):{},ee=typeof H.cluster=="string"?H.cluster:"",G=`https://${pr(ee||u.cluster)}.cognitedata.com`,Y=h[k],q=await a([{...Y,initial:G}]);f={...H,...q}}else f=h.length>0?await a(h):{};let U={...u,...f},x=typeof U.name=="string"?U.name:"";x&&r(x);let ae=await mi(s,!m&&h.length>0,a);return n?.(ae),{...U,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:ae}},"prompt")})}o(cr,"createAppPrompter");async function lr(e,t,r){let n=[];Object.values(t).some(s=>s!==void 0)&&r!==null&&n.push({key:"name",value:r,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&n.push({key:s,value:a,label:`--${et(s)}`});for(let{key:s,value:a,label:p}of n){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(lr,"validatePresets");import{cpSync as tt,existsSync as wi,mkdirSync as rt,writeFileSync as vi}from"fs";import{dirname as Pe,posix as Ci,resolve as O}from"path";import{fileURLToPath as mr}from"url";import{copyFileSync as gi,symlinkSync as fi}from"fs";import{dirname as yi,join as hi}from"path";function Si(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(Si,"errno");function dr(e){return e instanceof Error?e.message:String(e)}o(dr,"messageOf");function ke({target:e,linkPath:t,label:r,symlink:n=fi,copyFile:i=gi}){try{return n(e,t),!0}catch(s){let a=Si(s);if(a==="EEXIST")return!0;let p=dr(s);if(a==="EPERM"||a==="EACCES")try{let c=hi(yi(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${r} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${r} symlink: ${p} (copy fallback also failed: ${dr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${r} symlink:`,p),!1}}o(ke,"linkOrCopyOrWarn");var Ei=O(Pe(mr(import.meta.url)),"..","..","_vendor","spec-kit"),ki=O(Pe(mr(import.meta.url)),"..","..","_cognite-spec-extensions"),Pi={branch_numbering:"sequential"},bi=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],xi=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function ur({appDir:e,vendorDir:t=Ei,cogniteExtensionsDir:r=ki}){let n=O(e,".specify"),i=O(n,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of bi){let l=O(e,c);s=`copy ${p} to ${c}`,rt(Pe(l),{recursive:!0}),tt(O(t,p),l,{recursive:!0})}for(let{from:p,to:c}of xi){let l=O(e,c);s=`copy cognite extension ${p} to ${c}`,rt(Pe(l),{recursive:!0}),tt(O(r,p),l,{recursive:!0})}let a=O(n,"extensions.yml");wi(a)||(s="write .specify/extensions.yml",tt(O(r,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${n}`,vi(O(n,"init-options.json"),`${JSON.stringify(Pi,null,2)}
36
- `),s=`link .specify/memory/constitution.md in specifyDir=${n}`,rt(i,{recursive:!0}),ke({target:Ci.join("..","..","AGENTS.md"),linkPath:O(i,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}o(ur,"installSpecKit");import{execFileSync as be}from"child_process";import{mkdtempSync as Ai,readdirSync as Di,rmSync as Ii}from"fs";import{createRequire as $i}from"module";import{tmpdir as Ri}from"os";import{join as Ti,resolve as gr}from"path";import{InvalidArgumentError as Fi}from"commander";import Oi from"enquirer";var fr="cognitedata/builder-skills",nt=["claude-code","cursor","github-copilot","opencode","codex"],_i=$i(import.meta.url).resolve("skills/bin/cli.mjs");function ot(e,t={}){be(process.execPath,[_i,...e],{stdio:"inherit",cwd:process.cwd(),...t})}o(ot,"execSkillsCli");function Ui(){return nt.map(e=>["add",fr,"-a",e,"--skill","*","-y"])}o(Ui,"pullAllArgsPerAgent");var Li=1e4;async function yr(e,t={}){let r=t.exec??ot,n=t.timeout??Li,i=t.readdir??(p=>Di(p));for(let p of Ui())try{r(p,{cwd:e,timeout:n,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[gr(e,".claude","skills"),gr(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(yr,"pullAllSkillsInto");function Ni(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Fi("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Ni,"validateSource");function Ki(e){let t=Ai(Ti(Ri(),"skills-"));try{try{be("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let r;try{r=be("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{r=be("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return r.toString().trim().split(/\r?\n/).filter(n=>!!n&&!n.startsWith("."))}finally{Ii(t,{recursive:!0,force:!0})}}o(Ki,"listRemoteSkills");async function ji(e,t={}){let r=o(p=>Oi.prompt(p),"defaultPrompt"),{listSkills:n=Ki,prompt:i=r}=t,s=n(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(ji,"pickSkillsInteractive");function Mi(e,t,r){let n=["add",e.source,"-a",t];return e.skill?n.push("--skill",e.skill):r&&r.length>0?n.push("--skill",...r,"-y"):n.push("--skill","*","-y"),e.global&&n.push("--global"),n}o(Mi,"buildPullArgs");async function Hi(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await ji(e.source)}catch(n){let i=n instanceof Error?n.message:String(n);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let r=!1;for(let n of nt)try{ot(Mi(e,n,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${n}: ${s}`),r=!0}r?(console.log(`
34
+ npx @cognite/cli apps activate . --interactive Activate using browser auth (no secrets needed)`).action((t,r)=>ci(r))}o(rr,"registerActivateCommand");import{basename as wr,dirname as Bi,normalize as Gi,resolve as xe}from"path";import{fileURLToPath as Yi,pathToFileURL as qi}from"url";import{Logger as Ji,runner as zi}from"hygen";import{execFileSync as le}from"child_process";function ve(e={}){let{execFileSync:t=le}=e;try{return t("git",["--version"],{stdio:"ignore"}),!0}catch{return!1}}o(ve,"isGitInstalled");function Ce(e,t={}){let{execFileSync:r=le}=t;try{return r("git",["-C",e,"status"],{stdio:"ignore"}),!0}catch{return!1}}o(Ce,"isInsideGitRepo");function nr(e,t={}){let{execFileSync:r=le}=t;r("git",["-C",e,"init"],{stdio:"pipe"}),r("git",["-C",e,"add","."],{stdio:"pipe"}),r("git",["-C",e,"commit","-m","Initial commit","--no-gpg-sign","--no-verify"],{stdio:"pipe"})}o(nr,"gitInitAndCommit");function or(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.name"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(or,"gitUserName");function ir(e={}){let{execFileSync:t=le}=e;try{return String(t("git",["config","--get","user.email"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]})).trim()||void 0}catch{return}}o(ir,"gitUserEmail");import{safeParse as li}from"valibot";function de(e,t){return r=>{let n=li(t,r);return n.success?!0:`${e} ${n.issues[0].message}`}}o(de,"toPromptValidator");var sr={name:de("App name",Ye),displayName:de("Display name",Ge),baseUrl:de("Base URL",qe),org:de("Org",Je),project:de("Project",ze)};function di(e,t){return e?async r=>{let n=t(r);return n===!0?e(r):n}:t}o(di,"composeValidators");function Ee(e){return e.map(t=>{if(!(t.name in sr))return t;let r=sr[t.name];return{...t,validate:di(t.validate,r)}})}o(Ee,"applySchemaValidators");import{basename as ar}from"path";import pr from"enquirer";function et(e){return e.replace(/[A-Z]/g,(t,r)=>r===0?t.toLowerCase():`-${t.toLowerCase()}`)}o(et,"kebabCase");var mi={type:"confirm",name:"useSpecKit",message:["Enable spec-driven development?"," Adds the github/spec-kit slash commands (/speckit.specify, .clarify, .plan, .tasks, .implement)"," to your app for use in Claude Code or Cursor. They walk you through writing SPEC.md and"," generating a plan, tasks, and implementation."].join(`
35
+ `),initial:!1};async function ui(e,t,r){return e!==void 0?e:t?!!(await r([mi])).useSpecKit:!1}o(ui,"resolveSpecKit");function gi(e){return typeof e=="function"}o(gi,"isFunctionInitial");function cr(e){return(e??"").trim().replace(/\/+$/,"")||"api"}o(cr,"normalizeCluster");function lr({isCurrentDir:e,dirName:t,onAppName:r,onUseSpecKit:n,presets:i={},specKit:s,prompt:a=pr.prompt.bind(pr)}){return()=>({prompt:o(async p=>{if(!Array.isArray(p))return a([p]);let c=Object.fromEntries(Object.entries(i).filter(w=>w[1]!==void 0)),l=Object.keys(c).length>0,d=e?ar(process.cwd()):t?ar(t):null,m=l&&d!==null,y=!m&&d?p.map(w=>w.name==="name"?{...w,initial:d}:w):p,g=Ee(y),u=m&&d?{...c,name:d}:c,S=new Set(Object.keys(u)),h=g.filter(w=>!S.has(w.name)),k=h.findIndex(w=>w.name==="baseUrl"),f;if(m){let w=cr(u.cluster),H=o(C=>gi(C.initial)?C.initial():C.initial,"resolveInitial"),te=o(C=>{if(C.name==="baseUrl")return`https://${w}.cognitedata.com`;let Y=H(C);if(Y===void 0)throw new Error(`Non-interactive mode: --${et(C.name)} has no default. Pass it as a flag.`);return Y},"deriveValue");f=Object.fromEntries(h.map(C=>[C.name,te(C)]))}else if(k!==-1){let w=h.filter(A=>A.name!=="baseUrl"),H=w.length>0?await a(w):{},te=typeof H.cluster=="string"?H.cluster:"",Y=`https://${cr(te||u.cluster)}.cognitedata.com`,q=h[k],J=await a([{...q,initial:Y}]);f={...H,...J}}else f=h.length>0?await a(h):{};let U={...u,...f},x=typeof U.name=="string"?U.name:"";x&&r(x);let ae=await ui(s,!m&&h.length>0,a);return n?.(ae),{...U,name:x,useCurrentDir:e,directoryName:e?void 0:t??void 0,useSpecKit:ae}},"prompt")})}o(lr,"createAppPrompter");async function dr(e,t,r){let n=[];Object.values(t).some(s=>s!==void 0)&&r!==null&&n.push({key:"name",value:r,label:"directory"});for(let[s,a]of Object.entries(t))a!==void 0&&n.push({key:s,value:a,label:`--${et(s)}`});for(let{key:s,value:a,label:p}of n){let c=e.find(d=>d.name===s)?.validate;if(!c)continue;let l=await c(a);if(l!==!0)throw new Error(`Invalid ${p}: ${l}`)}}o(dr,"validatePresets");import{cpSync as tt,existsSync as vi,mkdirSync as rt,writeFileSync as Ci}from"fs";import{dirname as Pe,posix as Ei,resolve as O}from"path";import{fileURLToPath as ur}from"url";import{copyFileSync as fi,symlinkSync as yi}from"fs";import{dirname as hi,join as Si}from"path";function wi(e){if(e&&typeof e=="object"&&"code"in e&&typeof e.code=="string")return e.code}o(wi,"errno");function mr(e){return e instanceof Error?e.message:String(e)}o(mr,"messageOf");function ke({target:e,linkPath:t,label:r,symlink:n=yi,copyFile:i=fi}){try{return n(e,t),!0}catch(s){let a=wi(s);if(a==="EEXIST")return!0;let p=mr(s);if(a==="EPERM"||a==="EACCES")try{let c=Si(hi(t),e);return i(c,t),console.log(`\u2139\uFE0F Wrote ${r} as a copy of ${e} (symlinks need Developer Mode or an elevated shell on Windows).`),!0}catch(c){return console.warn(`\u26A0\uFE0F Could not create ${r} symlink: ${p} (copy fallback also failed: ${mr(c)})`),!1}return console.warn(`\u26A0\uFE0F Could not create ${r} symlink:`,p),!1}}o(ke,"linkOrCopyOrWarn");var ki=O(Pe(ur(import.meta.url)),"..","..","_vendor","spec-kit"),Pi=O(Pe(ur(import.meta.url)),"..","..","_cognite-spec-extensions"),bi={branch_numbering:"sequential"},xi=[{from:"templates",to:".specify/templates"},{from:"scripts/bash",to:".specify/scripts/bash"},{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"}],Ai=[{from:"commands",to:".claude/commands"},{from:"commands",to:".cursor/commands"},{from:"templates",to:".specify/templates"}];function gr({appDir:e,vendorDir:t=ki,cogniteExtensionsDir:r=Pi}){let n=O(e,".specify"),i=O(n,"memory"),s=`prepare spec-kit install for appDir=${e}`;try{for(let{from:p,to:c}of xi){let l=O(e,c);s=`copy ${p} to ${c}`,rt(Pe(l),{recursive:!0}),tt(O(t,p),l,{recursive:!0})}for(let{from:p,to:c}of Ai){let l=O(e,c);s=`copy cognite extension ${p} to ${c}`,rt(Pe(l),{recursive:!0}),tt(O(r,p),l,{recursive:!0})}let a=O(n,"extensions.yml");vi(a)||(s="write .specify/extensions.yml",tt(O(r,"extensions.yml"),a)),s=`write init-options.json under specifyDir=${n}`,Ci(O(n,"init-options.json"),`${JSON.stringify(bi,null,2)}
36
+ `),s=`link .specify/memory/constitution.md in specifyDir=${n}`,rt(i,{recursive:!0}),ke({target:Ei.join("..","..","AGENTS.md"),linkPath:O(i,"constitution.md"),label:".specify/memory/constitution.md"})}catch(a){let p=a instanceof Error?a.message:String(a);throw new Error(`installSpecKit failed while ${s} (appDir=${e}, vendorDir=${t}): ${p}`,{cause:a})}}o(gr,"installSpecKit");import{execFileSync as be}from"child_process";import{mkdtempSync as Di,readdirSync as Ii,rmSync as $i}from"fs";import{createRequire as Ri}from"module";import{tmpdir as Ti}from"os";import{join as Fi,resolve as fr}from"path";import{InvalidArgumentError as Oi}from"commander";import _i from"enquirer";var yr="cognitedata/builder-skills",nt=["claude-code","cursor","github-copilot","opencode","codex"],Ui=Ri(import.meta.url).resolve("skills/bin/cli.mjs");function ot(e,t={}){be(process.execPath,[Ui,...e],{stdio:"inherit",cwd:process.cwd(),...t})}o(ot,"execSkillsCli");function Li(){return nt.map(e=>["add",yr,"-a",e,"--skill","*","-y"])}o(Li,"pullAllArgsPerAgent");var Ni=1e4;async function hr(e,t={}){let r=t.exec??ot,n=t.timeout??Ni,i=t.readdir??(p=>Ii(p));for(let p of Li())try{r(p,{cwd:e,timeout:n,stdio:["pipe","pipe","inherit"]})}catch(c){let l=c instanceof Error?c.message:String(c);console.warn("\u26A0\uFE0F Could not pull skills for args ["+p.join(" ")+"]:",l)}let s=new Set;for(let p of[fr(e,".claude","skills"),fr(e,".agents","skills")])try{i(p).forEach(c=>s.add(c))}catch{}let a=s.size;a>0?console.log(`Installed ${a} skills successfully.`):console.log("No skills were installed.")}o(hr,"pullAllSkillsInto");function Ki(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Oi("Expected owner/repo format (e.g., cognitedata/builder-skills)");return e}o(Ki,"validateSource");function ji(e){let t=Di(Fi(Ti(),"skills-"));try{try{be("git",["clone","--depth","1","--filter=blob:none","--no-checkout","-q",`https://github.com/${e}.git`,t],{stdio:"ignore"})}catch{throw new Error(`Failed to clone skills repository "${e}". Please check your internet connection and ensure git is installed.`)}let r;try{r=be("git",["ls-tree","-d","--name-only","HEAD:skills"],{cwd:t})}catch{r=be("git",["ls-tree","-d","--name-only","HEAD"],{cwd:t})}return r.toString().trim().split(/\r?\n/).filter(n=>!!n&&!n.startsWith("."))}finally{$i(t,{recursive:!0,force:!0})}}o(ji,"listRemoteSkills");async function Mi(e,t={}){let r=o(p=>_i.prompt(p),"defaultPrompt"),{listSkills:n=ji,prompt:i=r}=t,s=n(e),{selected:a}=await i({type:"multiselect",name:"selected",message:"Select skills to install (space to toggle, a to toggle all, enter to confirm)",choices:s});return a}o(Mi,"pickSkillsInteractive");function Hi(e,t,r){let n=["add",e.source,"-a",t];return e.skill?n.push("--skill",e.skill):r&&r.length>0?n.push("--skill",...r,"-y"):n.push("--skill","*","-y"),e.global&&n.push("--global"),n}o(Hi,"buildPullArgs");async function Vi(e){console.log(`Pulling skills from ${e.source}...`);let t;if(e.interactive&&!e.skill){try{t=await Mi(e.source)}catch(n){let i=n instanceof Error?n.message:String(n);console.error(`Failed to resolve skills interactively: ${i}`),process.exitCode=1;return}if(t.length===0){console.log("No skills selected.");return}}let r=!1;for(let n of nt)try{ot(Hi(e,n,t))}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`\u26A0\uFE0F Could not pull skills for ${n}: ${s}`),r=!0}r?(console.log(`
37
37
  Skills pulled with some errors (see warnings above)`),process.exitCode=1):console.log(`
38
- Skills pulled successfully`)}o(Hi,"handlePull");function hr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
38
+ Skills pulled successfully`)}o(Vi,"handlePull");function Sr(e){let t=e.command("skills").summary("Manage AI agent skills for your app").description(`Manage AI agent skills for your app.
39
39
  Supports: ${nt.join(", ")}`).addHelpText("after",`
40
40
  Examples:
41
41
  npx @cognite/cli apps skills pull Pull all skills
42
42
  npx @cognite/cli apps skills pull --skill create-client-tool Pull a specific skill
43
- npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",Ni,fr).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(Hi),t.command("list").description("List installed skills").action(()=>{ot(["list"])}),t}o(hr,"registerSkillsCommand");var wr=xe(Vi(Gi(import.meta.url)),"..","..","_templates");async function zi(){let e=xe(wr,"app","new","prompt.js");return(await import(Yi(e).href)).default}o(zi,"loadPromptDefs");function Wi(e,t){return!e||t?null:Bi(e)}o(Wi,"resolveDirName");function Xi(e,t,r){if(e)return{cwd:process.cwd(),display:"."};let n=t??r;if(!n)throw new Error("App creation completed without a target directory or name.");return{cwd:xe(process.cwd(),n),display:n}}o(Xi,"resolveAppLocation");function Zi(e,t,r){let n=` npm install
43
+ npx @cognite/cli apps skills list List installed skills`);return t.command("pull").description("Pull all skills into your project").option("--source <owner/repo>","Skills repository",Ki,yr).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(Vi),t.command("list").description("List installed skills").action(()=>{ot(["list"])}),t}o(Sr,"registerSkillsCommand");var vr=xe(Bi(Yi(import.meta.url)),"..","..","_templates");async function Wi(){let e=xe(vr,"app","new","prompt.js");return(await import(qi(e).href)).default}o(Wi,"loadPromptDefs");function Xi(e,t){return!e||t?null:Gi(e)}o(Xi,"resolveDirName");function Zi(e,t,r){if(e)return{cwd:process.cwd(),display:"."};let n=t??r;if(!n)throw new Error("App creation completed without a target directory or name.");return{cwd:xe(process.cwd(),n),display:n}}o(Zi,"resolveAppLocation");function Qi(e,t,r){let n=` npm install
44
44
  npm run dev`,i="To deploy your app:",s="npx @cognite/cli apps deploy --interactive",a=r?`
45
45
  To start spec-driven development:
46
46
  Run /speckit.specify in Claude Code or Cursor and describe your app.
@@ -67,7 +67,7 @@ ${i}
67
67
  cd "${t}"
68
68
  ${s}
69
69
  ${p}
70
- `)}o(Zi,"printSuccessMessage");async function Qi(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await yr(e)}catch(t){let r=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",r)}}o(Qi,"pullSkillsInto");function es(e,t={}){let{isGitInstalled:r=ve,isInsideGitRepo:n=Ce,gitInitAndCommit:i=rr}=t;if(!r()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!n(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(es,"maybeInitGit");async function ts(e,t){let r=e==="."||e==="./",n=Wi(e,r),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await zi(),c=Ee(p),l=r?Sr(process.cwd()):n?Sr(n):null;await lr(c,a,l);let d=cr({isCurrentDir:r,dirName:n,onAppName:o(y=>{i=y},"onAppName"),onUseSpecKit:o(y=>{s=y},"onUseSpecKit"),presets:a,specKit:t.specKit});await Ji(["app","new"],{templates:wr,cwd:process.cwd(),logger:new qi(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Xi(r,n,i);ke({target:"AGENTS.md",linkPath:xe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&ur({appDir:m.cwd}),await Qi(m.cwd),es(m.cwd),Zi(r,m.display,s)}o(ts,"handleCreate");function vr(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
70
+ `)}o(Qi,"printSuccessMessage");async function es(e){try{console.log("\u{1F9E0} Pulling skills into your app..."),await hr(e)}catch(t){let r=t instanceof Error?t.message:String(t);console.warn("\u26A0\uFE0F Could not pull skills:",r)}}o(es,"pullSkillsInto");function ts(e,t={}){let{isGitInstalled:r=ve,isInsideGitRepo:n=Ce,gitInitAndCommit:i=nr}=t;if(!r()){console.warn("git not found \u2014 skipping git repository initialisation");return}if(!n(e)){console.log("Initialising git repository...");try{i(e)}catch(s){let p=(s&&typeof s=="object"&&"stderr"in s&&s.stderr?String(s.stderr).trim():"")||(s instanceof Error?s.message:String(s));console.warn("Could not initialise git repository:",p)}}}o(ts,"maybeInitGit");async function rs(e,t){let r=e==="."||e==="./",n=Xi(e,r),i=null,s=!1,a={displayName:t.displayName,description:t.description,org:t.org,project:t.project,cluster:t.cluster,baseUrl:t.baseUrl},p=await Wi(),c=Ee(p),l=r?wr(process.cwd()):n?wr(n):null;await dr(c,a,l);let d=lr({isCurrentDir:r,dirName:n,onAppName:o(y=>{i=y},"onAppName"),onUseSpecKit:o(y=>{s=y},"onUseSpecKit"),presets:a,specKit:t.specKit});await zi(["app","new"],{templates:vr,cwd:process.cwd(),logger:new Ji(console.log.bind(console)),createPrompter:d,debug:!!process.env.DEBUG});let m=Zi(r,n,i);ke({target:"AGENTS.md",linkPath:xe(m.cwd,"CLAUDE.md"),label:"CLAUDE.md"}),s&&gr({appDir:m.cwd}),await es(m.cwd),ts(m.cwd),Qi(r,m.display,s)}o(rs,"handleCreate");function Cr(e){return e.command("create").description("Create a new application.").argument("[directory]","Target directory (. for current, or subdirectory name)").option("--display-name <name>","App display name (skips the prompt)").option("--description <description>","App description (skips the prompt)").option("--org <org>","Deployment org (skips the prompt)").option("--project <project>","Deployment project (skips the prompt)").option("--cluster <cluster>","CDF cluster, e.g. greenfield (skips the prompt)").option("--base-url <url>","CDF base URL, e.g. https://greenfield.cognitedata.com (skips the prompt; defaults to cluster-derived URL when omitted)").option("--spec-kit","Install spec-kit slash commands (skips the prompt)").option("--no-spec-kit","Skip spec-kit installation (skips the prompt)").addHelpText("after",`
71
71
  Non-interactive use (CI, scripts, AI agents):
72
72
  Pass [directory] plus --display-name, --description, --org, --project, --cluster, --base-url
73
73
  to skip every prompt. Missing flags fall back to the interactive prompt.
@@ -80,22 +80,22 @@ Examples:
80
80
  --display-name "My App" --description "My app" \\
81
81
  --org cog-atlas --project atlas-greenfield --cluster greenfield \\
82
82
  --base-url https://greenfield.cognitedata.com
83
- Fully non-interactive`).action(ts)}o(vr,"registerCreateCommand");import rs from"path";async function ns(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r,orgHint:t.org});return new E(n)}o(ns,"defaultGetApiClient");async function os(e,t,r={}){let{loadEnvFile:n=T,loadAppConfig:i=v,getApiClient:s=ns}=r,a=rs.resolve(process.cwd(),e);n(a);let p=i(a);F(p);let c=t.interactive?await R(p,t):b(p.deployments,t.deployment);if(!t.interactive){let y=$(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let l=await s(c,t,p.externalId),{externalId:d}=p,m=await l.getActiveVersion(d);if(!m){console.log(` ${d} has no active version \u2014 nothing to deactivate.`);return}await l.deactivateVersion(d,m.version),console.log(`\u2713 Deactivated ${d} @ ${m.version} \u2014 active alias removed`)}o(os,"handleDeactivate");function Cr(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
83
+ Fully non-interactive`).action(rs)}o(Cr,"registerCreateCommand");import ns from"path";async function os(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r,orgHint:t.org});return new E(n)}o(os,"defaultGetApiClient");async function is(e,t,r={}){let{loadEnvFile:n=T,loadAppConfig:i=v,getApiClient:s=os}=r,a=ns.resolve(process.cwd(),e);n(a);let p=i(a);F(p);let c=t.interactive?await R(p,t):b(p.deployments,t.deployment);if(!t.interactive){let y=$(c);if(y.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${y.join(" and ")} in app.json. Use \`npx @cognite/cli@latest apps deactivate --interactive\` for browser-based authentication instead.`)}let l=await s(c,t,p.externalId),{externalId:d}=p,m=await l.getActiveVersion(d);if(!m){console.log(` ${d} has no active version \u2014 nothing to deactivate.`);return}await l.deactivateVersion(d,m.version),console.log(`\u2713 Deactivated ${d} @ ${m.version} \u2014 active alias removed`)}o(is,"handleDeactivate");function Er(e){return e.command("deactivate").description("Deactivate the app by removing its active version from service").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
84
84
  Examples:
85
85
  npx @cognite/cli apps deactivate . Deactivate using env-var auth
86
- npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,r)=>os(t,r))}o(Cr,"registerDeactivateCommand");import{mkdir as ds,readFile as ms}from"fs/promises";import{basename as us,dirname as gs}from"path";import{execFileSync as Ae}from"child_process";import V from"fs";import P from"path";import{parseAndValidateManifestConfig as is}from"@cognite/app-sdk/vite";import{BlobReader as ss,Uint8ArrayWriter as as,ZipWriter as ps}from"@zip.js/zip.js";var it="package.json",st="package-lock.json",Er="manifest.json",at=".cognite",cs=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],pt=class pt{constructor(t="dist"){this.distPath=P.isAbsolute(t)?t:P.join(process.cwd(),t),this.appRoot=P.dirname(this.distPath)}validateBuildDirectory(){if(!V.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=P.join(this.appRoot,it);if(!V.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let r=P.join(this.appRoot,st);if(!V.existsSync(r))throw new Error(`"${r}" not found. It is required for deployment.`)}async createZip(t="app.zip",r=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let n=new ps(new as,{level:9}),i=o(async(c,l)=>{await n.add(l,new ss(await V.openAsBlob(c))),r&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await V.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=P.join(c,d.name);d.isDirectory()?await s(m):await i(m,P.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=P.join(this.appRoot,it);await i(c,P.posix.join(at,it));let l=P.join(this.appRoot,Er);if(V.existsSync(l)){let m=V.readFileSync(l,"utf-8");is(m,l),await i(l,P.posix.join(at,Er))}let d=P.join(this.appRoot,st);await i(d,P.posix.join(at,st)),a=await n.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await V.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let r;try{r=Ae("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let n=Ae("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=n?n.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(r,s);try{Ae("git",["-C",r,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(V.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${P.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,r){let n=Ae("git",["-C",t,"ls-tree","-r","--name-only",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
87
- `).filter(Boolean),i=o(a=>a.split("/").some(p=>cs.some(c=>c.test(p))),"isSensitive"),s=n.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
86
+ npx @cognite/cli apps deactivate . --interactive Deactivate using browser auth (no secrets needed)`).action((t,r)=>is(t,r))}o(Er,"registerDeactivateCommand");import{mkdir as ms,readFile as us}from"fs/promises";import{basename as gs,dirname as fs}from"path";import{execFileSync as Ae}from"child_process";import B from"fs";import P from"path";import{parseAndValidateManifestConfig as ss}from"@cognite/app-sdk/vite";import{BlobReader as as,Uint8ArrayWriter as ps,ZipWriter as cs}from"@zip.js/zip.js";var it="package.json",st="package-lock.json",kr="manifest.json",at=".cognite",ls=[/^\.env(\..+)?$/i,/^\.secrets?$/i,/^\.token/i,/^\.cognite/i,/\.(key|pem|p12|pfx|jks|crt)$/i],pt=class pt{constructor(t="dist"){this.distPath=P.isAbsolute(t)?t:P.join(process.cwd(),t),this.appRoot=P.dirname(this.distPath)}validateBuildDirectory(){if(!B.existsSync(this.distPath))throw new Error(`Build directory "${this.distPath}" not found. Run build first.`);let t=P.join(this.appRoot,it);if(!B.existsSync(t))throw new Error(`"${t}" not found. It is required for deployment.`);let r=P.join(this.appRoot,st);if(!B.existsSync(r))throw new Error(`"${r}" not found. It is required for deployment.`)}async createZip(t="app.zip",r=!1){this.validateBuildDirectory(),console.log("\u{1F4E6} Packaging application...");let n=new cs(new ps,{level:9}),i=o(async(c,l)=>{await n.add(l,new as(await B.openAsBlob(c))),r&&console.log(` \u{1F4C4} ${l}`)},"addFile"),s=o(async c=>{let l=await B.promises.readdir(c,{withFileTypes:!0});for(let d of l){let m=P.join(c,d.name);d.isDirectory()?await s(m):await i(m,P.relative(this.distPath,m).replace(/\\/g,"/"))}},"addDir"),a;try{await s(this.distPath);let c=P.join(this.appRoot,it);await i(c,P.posix.join(at,it));let l=P.join(this.appRoot,kr);if(B.existsSync(l)){let m=B.readFileSync(l,"utf-8");ss(m,l),await i(l,P.posix.join(at,kr))}let d=P.join(this.appRoot,st);await i(d,P.posix.join(at,st)),a=await n.close()}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create zip: ${l}`)}await B.promises.writeFile(t,a);let p=(a.byteLength/1024/1024).toFixed(2);return console.log(`\u2705 App packaged: ${t} (${p} MB)`),t}async createSourceArchive(t){console.log("\u{1F4E6} Packaging source for review...");let r;try{r=Ae("git",["-C",this.appRoot,"rev-parse","--show-toplevel"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch(c){throw c instanceof Error&&"code"in c&&c.code==="ENOENT"?new Error("git not found. Install git and ensure it is in your PATH."):new Error("Source packaging requires a git repository. Run `git init` first.")}let n=Ae("git",["-C",this.appRoot,"rev-parse","--show-prefix"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),i=n?n.replace(/\/$/,""):".",s=i==="."?"HEAD":`HEAD:${i}`;this.validateNoSensitiveFiles(r,s);try{Ae("git",["-C",r,"archive","--format=zip",`--output=${t}`,s])}catch(c){let l=c instanceof Error?c.message:String(c);throw new Error(`Failed to create source archive: ${l}`)}let p=(B.statSync(t).size/1024/1024).toFixed(2);return console.log(`\u2705 Source packaged: ${P.basename(t)} (${p} MB)`),t}validateNoSensitiveFiles(t,r){let n=Ae("git",["-C",t,"ls-tree","-r","--name-only",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().split(`
87
+ `).filter(Boolean),i=o(a=>a.split("/").some(p=>ls.some(c=>c.test(p))),"isSensitive"),s=n.filter(i);if(s.length>0)throw new Error(`Source archive would include sensitive files \u2014 remove them from git tracking first:
88
88
  `+s.map(a=>` ${a}`).join(`
89
89
  `)+`
90
- Hint: git rm --cached <file>`)}};o(pt,"ApplicationPackager");var X=pt;import ls from"path";var kr=".cognite-bundles";function Pr(e,t){return`${e}-${t}.zip`}o(Pr,"bundleFileName");function Z(e,t,r){return ls.join(e,kr,Pr(t,r))}o(Z,"bundlePath");async function De(e,t,r,n){let{externalId:i,name:s,description:a,versionTag:p}=t,c=Z(r,i,p);await ds(gs(c),{recursive:!0}),await new X(`${r}/dist`).createZip(c,!0);let l=await ms(c);await new E(e).deploy(i,s,a,p,l,us(c),n)}o(De,"packageAndUpload");var ct=o(async(e,t,r)=>{let n=await ce(e,r);await De(n,t,r,e.published)},"deploy");import{existsSync as fs,readFileSync as ys}from"fs";var br=[".dev.sig",".cert.sig"];function me(e,t={}){let r=t.existsSync??fs,n=t.readFileSync??((s,a)=>ys(s,a)),i=[];for(let s of br){let a=`${e}${s}`;if(!r(a))continue;let p=n(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(me,"discoverSignatures");import{execSync as hs}from"child_process";function lt(e,t=!0,r={execSync:hs}){console.log("\u{1F4E6} Building app with npm..."),r.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(lt,"buildApp");function xr(e,t){let{org:r,project:n,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${r}.fusion.cognite.com/${n}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(xr,"generateFusionUrl");function Ar(e,t,r){let n=r?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=r?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",n,"=".repeat(n.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
91
- `))}o(Ar,"printDeployInfo");function Dr(e,t){console.log(`
90
+ Hint: git rm --cached <file>`)}};o(pt,"ApplicationPackager");var Z=pt;import ds from"path";var Pr=".cognite-bundles";function br(e,t){return`${e}-${t}.zip`}o(br,"bundleFileName");function Q(e,t,r){return ds.join(e,Pr,br(t,r))}o(Q,"bundlePath");async function De(e,t,r,n){let{externalId:i,name:s,description:a,versionTag:p}=t,c=Q(r,i,p);await ms(fs(c),{recursive:!0}),await new Z(`${r}/dist`).createZip(c,!0);let l=await us(c);await new E(e).deploy(i,s,a,p,l,gs(c),n)}o(De,"packageAndUpload");var ct=o(async(e,t,r)=>{let n=await ce(e,r);await De(n,t,r,e.published)},"deploy");import{existsSync as ys,readFileSync as hs}from"fs";var xr=[".dev.sig",".cert.sig"];function me(e,t={}){let r=t.existsSync??ys,n=t.readFileSync??((s,a)=>hs(s,a)),i=[];for(let s of xr){let a=`${e}${s}`;if(!r(a))continue;let p=n(a,"utf8").trim();p.length>0&&i.push(p)}return i}o(me,"discoverSignatures");import{execSync as Ss}from"child_process";function lt(e,t=!0,r={execSync:Ss}){console.log("\u{1F4E6} Building app with npm..."),r.execSync("npm run build",{cwd:e,stdio:t?"inherit":"pipe"}),console.log("\u2705 Build successful")}o(lt,"buildApp");function Ar(e,t){let{org:r,project:n,baseUrl:i}=e,s;try{s=new URL(i).hostname}catch{return null}let{externalId:a,versionTag:p}=t,c=new URLSearchParams({cluster:s,customAppVersion:p,workspace:"industrial-tools"});return`https://${r}.fusion.cognite.com/${n}/flows-apps/app/${encodeURIComponent(a)}?${c}`}o(Ar,"generateFusionUrl");function Dr(e,t,r){let n=r?"\u{1F680} Deploy (Interactive)":"\u{1F680} Deploy",i=r?`${t.project} @ ${t.baseUrl}`:`${t.org}/${t.project}`;console.log(["",n,"=".repeat(n.length),`App: ${e.name} (${e.externalId})`,`Version: ${e.versionTag}`,`Target: ${i}`,""].join(`
91
+ `))}o(Dr,"printDeployInfo");function Ir(e,t){console.log(`
92
92
  \u2705 Successfully deployed ${e.name} version ${e.versionTag} to ${t.org?`${t.org}/`:""}${t.project}`),console.log("\u{1F512} App is deployed in draft mode");let r=e.deployments.length>1?` -d ${t.project}`:"";console.log(`
93
93
  To sign: npx @cognite/cli apps sign --interactive${r}`),console.log(`To publish: npx @cognite/cli apps publish .${r}`),console.log(`To activate: npx @cognite/cli apps activate .${r}`),console.log(`
94
- To submit for certification: npx @cognite/cli apps submit`);let n=xr(t,e);n&&console.log(`
94
+ To submit for certification: npx @cognite/cli apps submit`);let n=Ar(t,e);n&&console.log(`
95
95
  \u{1F517} Open your app:
96
- ${n}`)}o(Dr,"printDeployResult");async function Ss(e,t,r,n,i){let s=$(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Ar(e,t,!1),n.skipBuild||lt(r),console.log(`
97
- \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r),Dr(e,t)}o(Ss,"handleDeployNonInteractive");async function ws(e,t,r,n){Ar(e,t,!0),n.skipBuild||lt(r);let i=await I(t,{interactive:!0,appId:e.externalId,orgHint:n.org});console.log(`
98
- \u{1F4E4} Deploying to ${t.project}...`),await De(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r,!1),Dr(e,t)}o(ws,"handleDeployInteractive");async function vs(e,t=process.cwd(),r={}){let{loadEnvFile:n=T,loadAppConfig:i=v,deploy:s=ct}=r;n(t);let a=i(t);if(F(a),e.interactive){let c=await R(a,e);await ws(a,c,t,e);return}let p=b(a.deployments,e.deployment);await Ss(a,p,t,e,s)}o(vs,"handleDeploy");function Ir(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
96
+ ${n}`)}o(Ir,"printDeployResult");async function ws(e,t,r,n,i){let s=$(t);if(s.length>0)throw new Error(`Deployment ${t.org}/${t.project} is missing ${s.join(" and ")} in app.json. Use \`cognite apps deploy --interactive\` for browser-based authentication instead.`);Dr(e,t,!1),n.skipBuild||lt(r),console.log(`
97
+ \u{1F4E4} Deploying to ${t.org}/${t.project}...`),await i({...t,published:!1},{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r),Ir(e,t)}o(ws,"handleDeployNonInteractive");async function vs(e,t,r,n){Dr(e,t,!0),n.skipBuild||lt(r);let i=await I(t,{interactive:!0,appId:e.externalId,orgHint:n.org});console.log(`
98
+ \u{1F4E4} Deploying to ${t.project}...`),await De(i,{externalId:e.externalId,name:e.name,description:e.description,versionTag:e.versionTag},r,!1),Ir(e,t)}o(vs,"handleDeployInteractive");async function Cs(e,t=process.cwd(),r={}){let{loadEnvFile:n=T,loadAppConfig:i=v,deploy:s=ct}=r;n(t);let a=i(t);if(F(a),e.interactive){let c=await R(a,e);await vs(a,c,t,e);return}let p=b(a.deployments,e.deployment);await ws(a,p,t,e,s)}o(Cs,"handleDeploy");function $r(e){return e.command("deploy").description("Deploy your app to Cognite Data Fusion. Use --interactive for browser-based login (no env-var secrets required).").option("-d, --deployment <target>","Deployment target (index or project name)").option("--skip-build","Skip the build step",!1).option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
99
99
  Environment (non-interactive):
100
100
  deployClientId and deploySecretName are configured per deployment in app.json.
101
101
  deploySecretName is the name of the environment variable that holds the client
@@ -109,79 +109,79 @@ Examples:
109
109
  npx @cognite/cli apps deploy -d my-project Deploy to project by name
110
110
  npx @cognite/cli apps deploy --skip-build Deploy without rebuilding
111
111
  npx @cognite/cli apps deploy --interactive Browser auth, prompts for target
112
- npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>vs(t))}o(Ir,"registerDeployCommand");async function Cs(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r.externalId,orgHint:t.org});return new E(n)}o(Cs,"defaultBuildApiClient");async function Es(e,t={}){let r=t.loadEnvFile??T,n=t.loadAppConfig??v,i=t.buildApiClient??Cs,s=t.discoverSignatures??me,a=process.cwd();r(a);let p=n(a);F(p);let c=e.interactive?await R(p,e):b(p.deployments,e.deployment);if(!e.interactive){let u=$(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p),{externalId:d,versionTag:m}=p,y;try{y=await l.getVersion(d,m)}catch(u){throw u instanceof K?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):u}if(y.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${y.lifecycleState} (terminal).`);let g=s(Z(a,d,m));g.length>0&&await l.submitSignatures(d,m,g),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(Es,"handlePublish");function $r(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
112
+ npx @cognite/cli apps deploy --interactive -d 0 Browser auth, target chosen non-interactively`).action(t=>Cs(t))}o($r,"registerDeployCommand");async function Es(e,t,r){let n=await I(e,{interactive:t.interactive,appId:r.externalId,orgHint:t.org});return new E(n)}o(Es,"defaultBuildApiClient");async function ks(e,t={}){let r=t.loadEnvFile??T,n=t.loadAppConfig??v,i=t.buildApiClient??Es,s=t.discoverSignatures??me,a=process.cwd();r(a);let p=n(a);F(p);let c=e.interactive?await R(p,e):b(p.deployments,e.deployment);if(!e.interactive){let u=$(c);if(u.length>0)throw new Error(`Deployment ${c.org}/${c.project} is missing ${u.join(" and ")} in app.json. Use \`cognite apps publish --interactive\` for browser-based authentication instead.`)}let l=await i(c,e,p),{externalId:d,versionTag:m}=p,y;try{y=await l.getVersion(d,m)}catch(u){throw u instanceof j?new Error(`Version ${m} of ${d} has not been deployed yet. Run \`npx @cognite/cli apps deploy\` first.`):u}if(y.alias==="ACTIVE"){console.log(` ${d} @ ${m} is already ACTIVE \u2014 nothing to do.`);return}if(y.lifecycleState==="PUBLISHED"){console.log(` ${d} @ ${m} is already PUBLISHED \u2014 nothing to do.`);return}if(y.lifecycleState==="DEPRECATED"||y.lifecycleState==="ARCHIVED")throw new Error(`Cannot publish ${d} @ ${m}: version is ${y.lifecycleState} (terminal).`);let g=s(Q(a,d,m));g.length>0&&await l.submitSignatures(d,m,g),await l.publishVersion(d,m),console.log(`\u2713 Published ${d} @ ${m} is now PUBLISHED`),console.log(""),console.log("Run `npx @cognite/cli apps activate .` to make it active.")}o(ks,"handlePublish");function Rr(e){return e.command("publish").description("Publish the current app version (transition DRAFT \u2192 PUBLISHED)").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
113
113
  Examples:
114
114
  npx @cognite/cli apps publish . Publish using env-var auth
115
- npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>Es(r))}o($r,"registerPublishCommand");import{spawnSync as ks}from"child_process";import{mkdirSync as Ps}from"fs";import{resolve as dt}from"path";var bs=["localhost","local.cognite.ai","*.local.cognite.ai"],xs={info:o(e=>{process.stdout.write(`${e}
115
+ npx @cognite/cli apps publish . --interactive Publish using browser auth (no secrets needed)`).action((t,r)=>ks(r))}o(Rr,"registerPublishCommand");import{spawnSync as Ps}from"child_process";import{mkdirSync as bs}from"fs";import{resolve as dt}from"path";var xs=["localhost","local.cognite.ai","*.local.cognite.ai"],As={info:o(e=>{process.stdout.write(`${e}
116
116
  `)},"info"),error:o(e=>{process.stderr.write(`${e}
117
- `)},"error")},As={spawnSync:ks,mkdirSync:Ps,logger:xs};function Ds(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(Ds,"hasMkcert");function Is({certDir:e=dt(process.cwd(),"certificates/mkcert"),domains:t=bs,deps:r={}}={}){let n={...As,...r},{spawnSync:i,mkdirSync:s,logger:a}=n;if(!Ds(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=dt(e,"localhost.pem"),l=dt(e,"localhost-key.pem");if(i("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}o(Is,"setupHttps");function $s(e){Is({certDir:e.certDir})}o($s,"handleSetupHttps");function Rr(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
117
+ `)},"error")},Ds={spawnSync:Ps,mkdirSync:bs,logger:As};function Is(e){let t=e("mkcert",["-help"],{stdio:"ignore"});return t.status===0||t.status===1}o(Is,"hasMkcert");function $s({certDir:e=dt(process.cwd(),"certificates/mkcert"),domains:t=xs,deps:r={}}={}){let n={...Ds,...r},{spawnSync:i,mkdirSync:s,logger:a}=n;if(!Is(i))throw a.error("Error: mkcert is not installed."),a.error("Install it with: brew install mkcert (macOS, Linux, WSL)"),a.error("On Windows: choco install mkcert (or scoop install mkcert)"),a.error("See https://github.com/FiloSottile/mkcert#installation for other methods."),new Error("mkcert is not installed");if(a.info("\u2139\uFE0F Installing mkcert root CA into your local trust store."),a.info(" This allows your browser to trust locally-generated certificates."),a.info(" You may be prompted for your system password."),i("mkcert",["-install"],{stdio:"inherit"}).status!==0)throw new Error("`mkcert -install` failed");s(e,{recursive:!0});let c=dt(e,"localhost.pem"),l=dt(e,"localhost-key.pem");if(i("mkcert",["-cert-file",c,"-key-file",l,...t],{stdio:"inherit"}).status!==0)throw new Error("mkcert failed to generate certificates");return a.info(""),a.info("Certificates generated:"),a.info(` cert: ${c}`),a.info(` key: ${l}`),{certFile:c,keyFile:l}}o($s,"setupHttps");function Rs(e){$s({certDir:e.certDir})}o(Rs,"handleSetupHttps");function Tr(e){return e.command("setup-https").description("Generate trusted local HTTPS certificates via mkcert").option("--cert-dir <path>","Directory to write certs into (default: ./certificates/mkcert)").addHelpText("after",`
118
118
  Examples:
119
119
  npx @cognite/cli@latest apps setup-https Generate certs in ./certificates/mkcert
120
- npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>$s(t))}o(Rr,"registerSetupHttpsCommand");import{createReadStream as ua,existsSync as ga,writeFileSync as fa}from"fs";import{basename as ya,dirname as ha,join as Sa,resolve as wt}from"path";import{parseScope as wa,signBundle as va,validateScopes as Ca}from"@cognite/app-sdk/codesigning";import{existsSync as la,readFileSync as da}from"fs";import{execFile as Fs}from"child_process";import{promisify as Os}from"util";import{execFileSync as Tr}from"child_process";import{platform as Rs}from"os";import Ts from"path";function N(e,t={}){let{platform:r=Rs}=t;switch(r()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(N,"isOS");function Fr(e,t={}){let{exec:r=Tr,log:n=console.log}=t,[i,s]=N("macos",t)?["open",[e]]:N("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{r(i,s)}catch{n(`Could not open browser \u2014 open manually:
121
- ${e}`)}}o(Fr,"openInBrowser");function Or(e,t={}){let{exec:r=Tr,log:n=console.log}=t,[i,s]=N("macos",t)?["open",["-R",e]]:N("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Ts.dirname(e)]];try{r(i,s)}catch{n(`Could not open file manager \u2014 files are at:
122
- ${e}`)}}o(Or,"revealInFileManager");var Ur="cognite-flows",_s=Os(Fs),Lr=o((e,t)=>_s(e,t),"defaultExecFile"),Us=-25300,Ls=Us&255;function Ns(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Ls)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Ns,"isKeychainNotFoundError");async function Nr(e,t,r={}){if(!N("macos",r))throw new Error("Keychain storage is only supported on macOS");let{execFile:n=Lr}=r;await n("security",["add-generic-password","-a",e,"-s",Ur,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Nr,"storeKeyInKeychain");async function Ie(e,t={}){if(!N("macos",t))return null;let{execFile:r=Lr}=t;try{let{stdout:n}=await r("security",["find-generic-password","-a",e,"-s",Ur,"-w"]);return Buffer.from(n.trim(),"base64").toString("utf-8")}catch(n){if(Ns(n))return null;throw n}}o(Ie,"readKeyFromKeychain");import{homedir as Ks}from"os";import{join as Kr}from"path";function _(e={}){let{env:t=process.env,homedir:r=Ks}=e,n=t.COGNITE_CLI_HOME?.trim()||Kr(r(),".cognite-cli");return{home:n,keysDir:Kr(n,"keys")}}o(_,"getConfig");import{pbkdf2 as Hs,randomBytes as Vs}from"crypto";import{promisify as Bs}from"util";import{CompactEncrypt as Gs,base64url as jr,compactDecrypt as Ys}from"jose";var js=new TextEncoder,Ms=new TextDecoder,mt={encode:o(e=>js.encode(e),"encode"),decode:o(e=>Ms.decode(e),"decode")};var qs=Bs(Hs),ft=6e5,Js="sha512",ut="PBKDF2-HMAC-SHA512",gt=16,$e="A256GCM",zs=32,Re=2e6;async function Mr(e,t,r){return await qs(e,t,r,zs,Js)}o(Mr,"deriveKey");async function Hr(e,t,r=ft){if(!Number.isInteger(r)||r<1||r>Re)throw new Error(`Invalid iterations: must be an integer between 1 and ${Re}`);let n=Vs(gt),i=await Mr(t,n,r);return await new Gs(mt.encode(e)).setProtectedHeader({alg:"dir",enc:$e,kdf:ut,kdf_iter:r,kdf_salt:jr.encode(n)}).encrypt(i)}o(Hr,"encryptStringAsJwe");async function Vr(e,t){let{plaintext:r}=await Ys(e,async n=>{if(!e.length)throw new Error("Unexpected JWE empty value");if(t.length<15)throw new Error(`Invalid passphrase it should be at least ${15} but got ${t.length}`);if(n.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(n.alg)}"; only "dir" is supported`);if(n.enc!==$e)throw new Error(`Unexpected JWE enc "${String(n.enc)}"; only "${$e}" is supported`);if(n.kdf!==ut)throw new Error(`Unexpected KDF "${String(n.kdf)}"; only "${ut}" is supported`);let i=Number(n.kdf_iter);if(!Number.isInteger(i)||i<1||i>Re)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Re}`);if(typeof n.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=jr.decode(n.kdf_salt);if(s.length!==gt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${gt} bytes, got ${s.length}`);return await Mr(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[$e]});return mt.decode(r)}o(Vr,"decryptJweAsString");function Ws(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Ws,"isJweCompact");var Br=Ws;import{existsSync as Xs,readdirSync as Zs,readFileSync as Qs}from"fs";import{join as yt}from"path";var re=".pub.pem",ht=".key.jwe",St=".meta.json";function Te(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(Te,"formatLocalKeySource");function ea(e){return{existsSync:e.existsSync??Xs,readdirSync:e.readdirSync??Zs,readFileSync:e.readFileSync??((t,r)=>Qs(t,r)),isOS:e.isOS??(t=>N(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Ie(t))}}o(ea,"resolveDeps");function ta(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(ta,"readEmailFromMeta");function ra(e,t){return t.existsSync(e)?t.readdirSync(e).filter(r=>r.endsWith(re)):[]}o(ra,"publicKeyEntries");function na(e){return e.slice(0,-re.length)}o(na,"kidFromPublicKeyFilename");async function oa(e,t,r){if(r.isOS("macos")&&await r.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let n=yt(t,`${e}${ht}`);return r.existsSync(n)?{kind:"encrypted-file",path:n}:{kind:"public-only"}}o(oa,"resolveSource");async function Fe(e=_().keysDir,t={}){let r=ea(t),n=new Set,i=ra(e,r).flatMap(s=>{let a=na(s);return!a||n.has(a)?[]:(n.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await oa(s,e,r),c=yt(e,`${s}${St}`),l;try{l=ta(r.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:yt(e,a),email:l}}))}o(Fe,"discoverLocalKeys");import ia from"enquirer";async function sa(e){return ia.prompt(e)}o(sa,"defaultPrompt");async function Gr(e,t={}){let{prompt:r=sa}=t,{passphrase:n}=await r({type:"password",name:"passphrase",message:e});return n}o(Gr,"promptPassphrase");import pa from"enquirer";import{statSync as aa}from"fs";function Yr(e,t=aa){return e.map(r=>({key:r,mtime:t(r.publicKeyPath).mtimeMs})).sort((r,n)=>n.mtime-r.mtime).map(({key:r})=>r)}o(Yr,"sortByMtime");async function ca(e){return pa.prompt(e)}o(ca,"defaultPrompt");async function qr(e,t={}){if(e.length===1)return e[0];let{prompt:r=ca,sortByMtime:n=Yr}=t,i=n(e),s=i[0],{choice:a}=await r({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await r({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,Te(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(qr,"promptSigningIdentity");function ma(e){return{existsSync:e.existsSync??la,readFileSync:e.readFileSync??((t,r)=>da(t,r)),readKeyFromKeychain:e.readKeyFromKeychain??Ie,decryptJweAsString:e.decryptJweAsString??Vr,discoverLocalKeys:e.discoverLocalKeys??Fe,keysDir:e.keysDir??_().keysDir,promptPassphrase:e.promptPassphrase??Gr,promptSigningIdentity:e.promptSigningIdentity??qr}}o(ma,"resolveDeps");async function Jr(e,t={}){let r=ma(t);if(e.keyPath){if(!r.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=r.readFileSync(e.keyPath,"utf-8").trim();if(Br(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await r.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await r.decryptJweAsString(s,a),kid:e.kid}}return{privateKeyPem:s,kid:e.kid}}let n=await r.discoverLocalKeys(r.keysDir);if(n.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=n.find(s=>s.kid===e.kid);else if(e.interactive)i=await r.promptSigningIdentity(n);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await r.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await r.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await r.decryptJweAsString(r.readFileSync(i.source.path,"utf-8"),s),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(Jr,"resolvePrivateKey");var Ea=o(async(e,t,r,n,i)=>{let s=await I(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new E(s).submitSignatures(t,r,n)},"defaultSubmitSignatures");function ka(e){let t=ua(e);return new ReadableStream({start(r){t.on("data",n=>{let i=typeof n=="string"?Buffer.from(n):n;r.enqueue(new Uint8Array(i))}),t.on("end",()=>r.close()),t.on("error",n=>r.error(n))},cancel(){t.destroy()}})}o(ka,"createWebStreamFromFile");function Pa(e){return{existsSync:e.existsSync??ga,writeFileSync:e.writeFileSync??fa,createBundleStream:e.createBundleStream??ka,signBundle:e.signBundle??va,parseScope:e.parseScope??wa,validateScopes:e.validateScopes??Ca,loadAppConfig:e.loadAppConfig??v,resolvePrivateKey:e.resolvePrivateKey??(t=>Jr(t)),submitSignatures:e.submitSignatures??Ea,discoverSignatures:e.discoverSignatures??me}}o(Pa,"resolveDeps");async function zr(e,t,r={},n=process.cwd()){let i=Pa(r),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(n);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(f=>({org:f.org,project:f.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?wt(n,e):Z(n,s,a);if(!i.existsSync(l)){let f=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${f}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
120
+ npx @cognite/cli@latest apps setup-https --cert-dir certs Use a custom directory`).action(t=>Rs(t))}o(Tr,"registerSetupHttpsCommand");import{createReadStream as ga,existsSync as fa,writeFileSync as ya}from"fs";import{basename as ha,dirname as Sa,join as wa,resolve as wt}from"path";import{parseScope as va,signBundle as Ca,validateScopes as Ea}from"@cognite/app-sdk/codesigning";import{existsSync as da,readFileSync as ma}from"fs";import{execFile as Os}from"child_process";import{promisify as _s}from"util";import{execFileSync as Fr}from"child_process";import{platform as Ts}from"os";import Fs from"path";function K(e,t={}){let{platform:r=Ts}=t;switch(r()){case"darwin":return e==="macos";case"win32":return e==="windows";default:return e==="other"}}o(K,"isOS");function Or(e,t={}){let{exec:r=Fr,log:n=console.log}=t,[i,s]=K("macos",t)?["open",[e]]:K("windows",t)?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];try{r(i,s)}catch{n(`Could not open browser \u2014 open manually:
121
+ ${e}`)}}o(Or,"openInBrowser");function _r(e,t={}){let{exec:r=Fr,log:n=console.log}=t,[i,s]=K("macos",t)?["open",["-R",e]]:K("windows",t)?["explorer",[`/select,${e}`]]:["xdg-open",[Fs.dirname(e)]];try{r(i,s)}catch{n(`Could not open file manager \u2014 files are at:
122
+ ${e}`)}}o(_r,"revealInFileManager");var Lr="cognite-flows",Us=_s(Os),Nr=o((e,t)=>Us(e,t),"defaultExecFile"),Ls=-25300,Ns=Ls&255;function Ks(e){if(!(e instanceof Error)||!("code"in e)||e.code!==Ns)return!1;let t="stderr"in e?String(e.stderr):"";return/could not be found/i.test(t)||t===""}o(Ks,"isKeychainNotFoundError");async function Kr(e,t,r={}){if(!K("macos",r))throw new Error("Keychain storage is only supported on macOS");let{execFile:n=Nr}=r;await n("security",["add-generic-password","-a",e,"-s",Lr,"-w",Buffer.from(t,"utf-8").toString("base64"),"-U"])}o(Kr,"storeKeyInKeychain");async function Ie(e,t={}){if(!K("macos",t))return null;let{execFile:r=Nr}=t;try{let{stdout:n}=await r("security",["find-generic-password","-a",e,"-s",Lr,"-w"]);return Buffer.from(n.trim(),"base64").toString("utf-8")}catch(n){if(Ks(n))return null;throw n}}o(Ie,"readKeyFromKeychain");import{homedir as js}from"os";import{join as jr}from"path";function _(e={}){let{env:t=process.env,homedir:r=js}=e,n=t.COGNITE_CLI_HOME?.trim()||jr(r(),".cognite-cli");return{home:n,keysDir:jr(n,"keys")}}o(_,"getConfig");import{pbkdf2 as Vs,randomBytes as Bs}from"crypto";import{promisify as Gs}from"util";import{CompactEncrypt as Ys,base64url as Mr,compactDecrypt as qs}from"jose";var Ms=new TextEncoder,Hs=new TextDecoder,mt={encode:o(e=>Ms.encode(e),"encode"),decode:o(e=>Hs.decode(e),"decode")};var Js=Gs(Vs),ft=6e5,zs="sha512",ut="PBKDF2-HMAC-SHA512",gt=16,$e="A256GCM",Ws=32,Re=2e6;async function Hr(e,t,r){return await Js(e,t,r,Ws,zs)}o(Hr,"deriveKey");async function Vr(e,t,r=ft){if(!Number.isInteger(r)||r<1||r>Re)throw new Error(`Invalid iterations: must be an integer between 1 and ${Re}`);let n=Bs(gt),i=await Hr(t,n,r);return await new Ys(mt.encode(e)).setProtectedHeader({alg:"dir",enc:$e,kdf:ut,kdf_iter:r,kdf_salt:Mr.encode(n)}).encrypt(i)}o(Vr,"encryptStringAsJwe");async function Br(e,t){let{plaintext:r}=await qs(e,async n=>{if(!e.length)throw new Error("Unexpected JWE empty value");if(t.length<15)throw new Error(`Invalid passphrase it should be at least ${15} but got ${t.length}`);if(n.alg!=="dir")throw new Error(`Unexpected JWE alg "${String(n.alg)}"; only "dir" is supported`);if(n.enc!==$e)throw new Error(`Unexpected JWE enc "${String(n.enc)}"; only "${$e}" is supported`);if(n.kdf!==ut)throw new Error(`Unexpected KDF "${String(n.kdf)}"; only "${ut}" is supported`);let i=Number(n.kdf_iter);if(!Number.isInteger(i)||i<1||i>Re)throw new Error(`Invalid kdf_iter in JWE header: must be an integer between 1 and ${Re}`);if(typeof n.kdf_salt!="string")throw new Error("Missing kdf_salt in JWE header");let s=Mr.decode(n.kdf_salt);if(s.length!==gt)throw new Error(`Invalid kdf_salt length in JWE header: expected ${gt} bytes, got ${s.length}`);return await Hr(t,s,i)},{keyManagementAlgorithms:["dir"],contentEncryptionAlgorithms:[$e]});return mt.decode(r)}o(Br,"decryptJweAsString");function Xs(e){let t=e.trim();return t.startsWith("eyJ")&&t.split(".").length===5}o(Xs,"isJweCompact");var Gr=Xs;import{existsSync as Zs,readdirSync as Qs,readFileSync as ea}from"fs";import{join as yt}from"path";var re=".pub.pem",ht=".key.jwe",St=".meta.json";function Te(e){switch(e.kind){case"keychain":return"Keychain";case"encrypted-file":return e.path;case"public-only":return"public-only (private key missing)"}}o(Te,"formatLocalKeySource");function ta(e){return{existsSync:e.existsSync??Zs,readdirSync:e.readdirSync??Qs,readFileSync:e.readFileSync??((t,r)=>ea(t,r)),isOS:e.isOS??(t=>K(t)),readKeyFromKeychain:e.readKeyFromKeychain??(t=>Ie(t))}}o(ta,"resolveDeps");function ra(e){try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&!Array.isArray(t)&&"email"in t&&typeof t.email=="string")return t.email}catch{}}o(ra,"readEmailFromMeta");function na(e,t){return t.existsSync(e)?t.readdirSync(e).filter(r=>r.endsWith(re)):[]}o(na,"publicKeyEntries");function oa(e){return e.slice(0,-re.length)}o(oa,"kidFromPublicKeyFilename");async function ia(e,t,r){if(r.isOS("macos")&&await r.readKeyFromKeychain(e).catch(()=>null)!==null)return{kind:"keychain"};let n=yt(t,`${e}${ht}`);return r.existsSync(n)?{kind:"encrypted-file",path:n}:{kind:"public-only"}}o(ia,"resolveSource");async function Fe(e=_().keysDir,t={}){let r=ta(t),n=new Set,i=na(e,r).flatMap(s=>{let a=oa(s);return!a||n.has(a)?[]:(n.add(a),[{kid:a,entry:s}])});return Promise.all(i.map(async({kid:s,entry:a})=>{let p=await ia(s,e,r),c=yt(e,`${s}${St}`),l;try{l=ra(r.readFileSync(c,"utf8"))}catch{}return{kid:s,source:p,publicKeyPath:yt(e,a),email:l}}))}o(Fe,"discoverLocalKeys");import sa from"enquirer";async function aa(e){return sa.prompt(e)}o(aa,"defaultPrompt");async function Yr(e,t={}){let{prompt:r=aa}=t,{passphrase:n}=await r({type:"password",name:"passphrase",message:e});return n}o(Yr,"promptPassphrase");import ca from"enquirer";import{statSync as pa}from"fs";function qr(e,t=pa){return e.map(r=>({key:r,mtime:t(r.publicKeyPath).mtimeMs})).sort((r,n)=>n.mtime-r.mtime).map(({key:r})=>r)}o(qr,"sortByMtime");async function la(e){return ca.prompt(e)}o(la,"defaultPrompt");async function Jr(e,t={}){if(e.length===1)return e[0];let{prompt:r=la,sortByMtime:n=qr}=t,i=n(e),s=i[0],{choice:a}=await r({type:"select",name:"choice",message:"Select signing identity",choices:[{name:"latest",message:`Use latest: ${s.kid}`},{name:"pick",message:"Pick from list"}]});if(a==="latest")return s;if(a==="pick"){let{kid:p}=await r({type:"select",name:"kid",message:"Select signing identity",choices:i.map(l=>({name:l.kid,message:[l.kid,l.email,Te(l.source)].filter(Boolean).join(" \u2014 ")}))}),c=i.find(l=>l.kid===p);if(!c)throw new Error("No signing identity selected");return c}else throw new Error(`Unexpected choice: "${a}"`)}o(Jr,"promptSigningIdentity");function ua(e){return{existsSync:e.existsSync??da,readFileSync:e.readFileSync??((t,r)=>ma(t,r)),readKeyFromKeychain:e.readKeyFromKeychain??Ie,decryptJweAsString:e.decryptJweAsString??Br,discoverLocalKeys:e.discoverLocalKeys??Fe,keysDir:e.keysDir??_().keysDir,promptPassphrase:e.promptPassphrase??Yr,promptSigningIdentity:e.promptSigningIdentity??Jr}}o(ua,"resolveDeps");async function zr(e,t={}){let r=ua(t);if(e.keyPath){if(!r.existsSync(e.keyPath))throw new Error(`Key file not found: ${e.keyPath}`);if(!e.kid)throw new Error("--signing-identity <kid> is required when using --key");let s=r.readFileSync(e.keyPath,"utf-8").trim();if(Gr(s)){if(!e.interactive)throw new Error(`Key at ${e.keyPath} is passphrase-encrypted. Pass --interactive to enter the passphrase.`);let a=await r.promptPassphrase(`Passphrase for key ${e.kid}: `);return{privateKeyPem:await r.decryptJweAsString(s,a),kid:e.kid}}return{privateKeyPem:s,kid:e.kid}}let n=await r.discoverLocalKeys(r.keysDir);if(n.length===0)throw new Error("No signing keys found. Run `cognite keys generate` or pass --key.");let i;if(e.kid)i=n.find(s=>s.kid===e.kid);else if(e.interactive)i=await r.promptSigningIdentity(n);else throw new Error("--signing-identity <kid> is required. Pass --interactive to select it interactively.");if(!i)throw new Error(`No key found with kid "${e.kid}"`);switch(i.source.kind){case"keychain":{let s=await r.readKeyFromKeychain(i.kid);if(!s)throw new Error(`Key "${i.kid}" not found in Keychain`);return{privateKeyPem:s,kid:i.kid}}case"encrypted-file":{if(!e.interactive)throw new Error(`Key "${i.kid}" is passphrase-encrypted. Pass --interactive to enter the passphrase, or store the key in macOS Keychain for non-interactive use.`);let s=await r.promptPassphrase(`Passphrase for key ${i.kid}: `);return{privateKeyPem:await r.decryptJweAsString(r.readFileSync(i.source.path,"utf-8"),s),kid:i.kid}}case"public-only":throw new Error(`Key "${i.kid}" has no private key on this machine (public-only).`)}}o(zr,"resolvePrivateKey");var ka=o(async(e,t,r,n,i)=>{let s=await I(e,{interactive:i.browserAuth??!1,appId:t,orgHint:i.org});await new E(s).submitSignatures(t,r,n)},"defaultSubmitSignatures");function Pa(e){let t=ga(e);return new ReadableStream({start(r){t.on("data",n=>{let i=typeof n=="string"?Buffer.from(n):n;r.enqueue(new Uint8Array(i))}),t.on("end",()=>r.close()),t.on("error",n=>r.error(n))},cancel(){t.destroy()}})}o(Pa,"createWebStreamFromFile");function ba(e){return{existsSync:e.existsSync??fa,writeFileSync:e.writeFileSync??ya,createBundleStream:e.createBundleStream??Pa,signBundle:e.signBundle??Ca,parseScope:e.parseScope??va,validateScopes:e.validateScopes??Ea,loadAppConfig:e.loadAppConfig??v,resolvePrivateKey:e.resolvePrivateKey??(t=>zr(t)),submitSignatures:e.submitSignatures??ka,discoverSignatures:e.discoverSignatures??me}}o(ba,"resolveDeps");async function Wr(e,t,r={},n=process.cwd()){let i=ba(r),s=t.appid,a=t.appVersion,p=[],c=i.loadAppConfig(n);if(s=s??c.externalId,a=a??c.versionTag,t.scope&&t.scope.length>0?p=t.scope.map(i.parseScope):p=c.deployments.map(f=>({org:f.org,project:f.project})),!s)throw new Error("--appid is required (or set externalId in app.json)");if(!a)throw new Error("--app-version is required (or set versionTag in app.json)");let l=e?wt(n,e):Q(n,s,a);if(!i.existsSync(l)){let f=e?"":" (default derived from app.json \u2014 pass [bundle] explicitly to override, or run `cognite apps deploy` first to populate .cognite-bundles/)";throw new Error(`Bundle not found: ${l}${f}`)}let d=i.validateScopes(p);if(d.length>0)throw new Error(`Invalid scopes:
123
123
  ${d.join(`
124
- `)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?wt(n,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),g=i.createBundleStream(l),u=await i.signBundle({privateKeyPem:m,kid:y,appId:s,version:a,bundleStream:g,role:t.asCertifier?"certifier":"developer",scopes:p}),S=t.output?wt(n,t.output):Sa(ha(l),`${ya(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(S,u.token,"utf-8"),console.log(`\u2705 Signed: ${S}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(f=>`${f.org}/${f.project}`).join(", ")}`),t.verbose&&console.log(`
124
+ `)}`);let{privateKeyPem:m,kid:y}=await i.resolvePrivateKey({keyPath:t.key?wt(n,t.key):void 0,kid:t.signingIdentity,interactive:t.interactive}),g=i.createBundleStream(l),u=await i.signBundle({privateKeyPem:m,kid:y,appId:s,version:a,bundleStream:g,role:t.asCertifier?"certifier":"developer",scopes:p}),S=t.output?wt(n,t.output):wa(Sa(l),`${ha(l)}.${t.asCertifier?"cert":"dev"}.sig`);i.writeFileSync(S,u.token,"utf-8"),console.log(`\u2705 Signed: ${S}`),console.log(` kid: ${u.kid}`),console.log(` bundle: ${u.payload.bundleSha256}`),console.log(` scopes: ${u.payload.scopes.map(f=>`${f.org}/${f.project}`).join(", ")}`),t.verbose&&console.log(`
125
125
  Payload:`,JSON.stringify(u.payload,null,2));let h=Array.from(new Set([...i.discoverSignatures(l),u.token])),k=t.interactive?await R(c,{deployment:t.deployment,baseUrl:t.baseUrl,project:t.project,org:t.org}):b(c.deployments,t.deployment);if(!t.browserAuth){let f=$(k);if(f.length>0)throw new Error(`Deployment ${k.org}/${k.project} is missing ${f.join(" and ")} in app.json. Pass --browser-auth to authenticate via browser instead.`)}await i.submitSignatures(k,s,a,h,t),console.log(`
126
- To publish: npx @cognite/cli apps publish .`)}o(zr,"handleSign");function Wr(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((r,n)=>{let i={...n,appid:n.identifier??n.appid,scope:n.requirements??n.scope};return zr(r,i,t)})}o(Wr,"registerSignCommand");function ba(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(ba,"describeStatus");function xa(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let r of e){let n=r.status==="VALID"?"\u2705":"\u274C",i=new Date(r.signatureIat).toISOString();t.push(` ${n} ${r.signerKid} (${r.signerRole}, signed ${i}) \u2014 ${r.status}`)}return t}o(xa,"formatSignatures");async function Aa(e){let t=process.cwd();T(t);let r=v(t);F(r);let n=e.interactive?await R(r,e):b(r.deployments,e.deployment);if(!e.interactive){let a=$(n);if(a.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new E(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let a=await s.getVersion(r.externalId,r.versionTag);console.log(`Status: ${ba(a)}`);let p=await Da(s,r.externalId,r.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of xa(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof K){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(Aa,"handleStatus");async function Da(e,t,r){try{return await e.listSignatures(t,r)}catch(n){if(J(n)&&n.status===404||n instanceof Error&&/status code: 404/.test(n.message))return"endpoint-unavailable";throw n}}o(Da,"fetchSignatures");function Xr(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
126
+ To publish: npx @cognite/cli apps publish .`)}o(Wr,"handleSign");function Xr(e,t={}){return e.command("sign [bundle]").description("Sign an app bundle (defaults to .cognite-bundles/<app>-<version>.zip)").option("--key <path>","Private key PEM file path").option("-s, --signing-identity <kid>","Key ID for Keychain or file lookup").option("--appid <id>","Application ID (default: externalId from app.json)").option("-i, --identifier <id>","Alias for --appid").option("--app-version <version>","App version (default: versionTag from app.json)").option("--scope <org/project...>","Deployment scope(s) (default: deployments from app.json)").option("-r, --requirements <org/project...>","Alias for --scope").option("-o, --output <path>","Output file path (default: <bundle>.<dev|cert>.sig)").option("-v, --verbose","Display full payload after signing").option("--as-certifier","Counter-sign a developer signature as certifier").option("--interactive","Enable interactive prompts (key selection, passphrase, deployment target selection)",!1).option("--browser-auth","Use browser-based PKCE auth when submitting the signature",!1).option("-d, --deployment <target>","Deployment target from app.json (index or name; submit step only)").option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive or --browser-auth)").action((r,n)=>{let i={...n,appid:n.identifier??n.appid,scope:n.requirements??n.scope};return Wr(r,i,t)})}o(Xr,"registerSignCommand");function xa(e){return e.alias==="ACTIVE"?"ACTIVE":e.lifecycleState}o(xa,"describeStatus");function Aa(e){if(e.length===0)return["Signatures: none stored"];let t=["Signatures:"];for(let r of e){let n=r.status==="VALID"?"\u2705":"\u274C",i=new Date(r.signatureIat).toISOString();t.push(` ${n} ${r.signerKid} (${r.signerRole}, signed ${i}) \u2014 ${r.status}`)}return t}o(Aa,"formatSignatures");async function Da(e){let t=process.cwd();T(t);let r=v(t);F(r);let n=e.interactive?await R(r,e):b(r.deployments,e.deployment);if(!e.interactive){let a=$(n);if(a.length>0)throw new Error(`Deployment ${n.org}/${n.project} is missing ${a.join(" and ")} in app.json. Use \`cognite apps status --interactive\` for browser-based authentication instead.`)}let i=await I(n,{interactive:e.interactive,appId:r.externalId,orgHint:e.org}),s=new E(i);console.log(""),console.log(`App: ${r.name} (${r.externalId})`),console.log(`Version: ${r.versionTag} (local)`);try{let a=await s.getVersion(r.externalId,r.versionTag);console.log(`Status: ${xa(a)}`);let p=await Ia(s,r.externalId,r.versionTag);if(console.log(""),p==="endpoint-unavailable")console.log("Signatures: backend endpoint not available on this cluster yet");else for(let c of Aa(p))console.log(c);a.lifecycleState==="DRAFT"&&(console.log(""),console.log("Run `npx @cognite/cli apps publish .` to publish this version."))}catch(a){if(a instanceof j){console.log("Status: not deployed yet"),console.log(""),console.log("Run `npx @cognite/cli apps deploy` to upload this version.");return}throw a}}o(Da,"handleStatus");async function Ia(e,t,r){try{return await e.listSignatures(t,r)}catch(n){if(z(n)&&n.status===404||n instanceof Error&&/status code: 404/.test(n.message))return"endpoint-unavailable";throw n}}o(Ia,"fetchSignatures");function Zr(e){return e.command("status").description("Show the deployment status and signatures of the current app version").argument("[path]","Path to the app folder (only `.` is currently supported)",".").option("-d, --deployment <target>","Deployment target from app.json (index or name)").option("--interactive","Use browser-based authentication instead of env-var credentials",!1).option("--base-url <url>","CDF base URL (only with --interactive)").option("--project <project>","CDF project name (only with --interactive)").option("--org <org>","Organization hint for login (only with --interactive)").addHelpText("after",`
127
127
  Examples:
128
128
  npx @cognite/cli apps status . Status using env-var auth
129
- npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)=>Aa(r))}o(Xr,"registerStatusCommand");import{execFileSync as Et}from"child_process";import Ct from"fs";import ue from"path";import Ta from"readline";var Zr="https://cognite.zendesk.com",Ia="360001234312",$a="tf_360015295097",Ra="cognite_flows_certifications";function Qr(e,t,r){let n=new URLSearchParams({ticket_form_id:Ia,tf_priority:"normal",tf_subject:e,[$a]:Ra,tf_description:t});return`${r}/hc/en-us/requests/new?${n}`}o(Qr,"buildUrl");function en(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(en,"escapeHtml");function vt(e){return e.map(en).join("<br>")}o(vt,"toHtml");function tn(e,t=Zr){let{appName:r,externalId:n,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${r}`,`App external ID: ${n}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${n}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return Qr(`App Review Request: ${r}`,vt(l.filter(d=>d!==void 0)),t)}o(tn,"buildAppReviewUrl");function rn(e,t,r,n,i=Zr){let s=vt(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${r}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${en(n.replace(/\r\n/g,`
130
- `))}</pre>`,p=vt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return Qr(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(rn,"buildKeyRegistrationUrl");function Fa(){return new Promise(e=>{let t=Ta.createInterface({input:process.stdin,output:process.stdout});t.question(`
131
- Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(Fa,"defaultPressEnter");var Oa=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function _a(e){let t=Oa.filter(({pattern:r})=>Et("git",["-C",e,"ls-files","--",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let r=t.map(({label:n,skill:i})=>` ${n} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
129
+ npx @cognite/cli apps status . --interactive Status using browser auth (no secrets needed)`).action((t,r)=>Da(r))}o(Zr,"registerStatusCommand");import{execFileSync as Et}from"child_process";import Ct from"fs";import ue from"path";import Fa from"readline";var Qr="https://cognite.zendesk.com",$a="360001234312",Ra="tf_360015295097",Ta="cognite_flows_certifications";function en(e,t,r){let n=new URLSearchParams({ticket_form_id:$a,tf_priority:"normal",tf_subject:e,[Ra]:Ta,tf_description:t});return`${r}/hc/en-us/requests/new?${n}`}o(en,"buildUrl");function tn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(tn,"escapeHtml");function vt(e){return e.map(tn).join("<br>")}o(vt,"toHtml");function rn(e,t=Qr){let{appName:r,externalId:n,versionTag:i,archiveName:s,developerName:a,cdfProject:p,cdfCluster:c}=e,l=["Dear Cognite Platform Team,","","I would like to submit my Flows app for review and certification.","",`App name: ${r}`,`App external ID: ${n}`,`Version: ${i}`,p?`CDF project: ${p}`:void 0,c?`CDF cluster: ${c}`:void 0,"","`npx @cognite/cli apps submit` verified App-Brief.md,","code-review-report.md, and design-review-report.md are committed to git.","","Attached (all from dist/submit/):",`[ ] ${s??"src-<sha>.zip"} \u2014 source archive`,`[ ] ${n}-${i}.zip \u2014 deploy bundle`,"[ ] Screen recording of the application (required for design review)","","Best regards,",a??"[Your name]"];return en(`App Review Request: ${r}`,vt(l.filter(d=>d!==void 0)),t)}o(rn,"buildAppReviewUrl");function nn(e,t,r,n,i=Qr){let s=vt(["Dear Cognite Platform Team,","","I would like to register my Flows app signing key for certified deployments.","",`Key ID (kid): ${e}`,`Developer email: ${t}`,`Expires: ${r}`,"","Please add the following entry to public_keys.yaml:"]),a=`<pre>${tn(n.replace(/\r\n/g,`
130
+ `))}</pre>`,p=vt(["","Best Regards,","[Your name]","","(This registration request was generated by `npx @cognite/cli keys generate`.)"]);return en(`Public Key Registration: ${t}`,`${s}<br>${a}${p}`,i)}o(nn,"buildKeyRegistrationUrl");function Oa(){return new Promise(e=>{let t=Fa.createInterface({input:process.stdin,output:process.stdout});t.question(`
131
+ Press Enter to open the Zendesk form in your browser and reveal dist/submit/ in your file manager...`,()=>{t.close(),e()})})}o(Oa,"defaultPressEnter");var _a=[{pattern:"App-Brief.md",label:"App-Brief.md",skill:"flows-app-brief"},{pattern:"reviews/code-review/*/code-review-report.md",label:"reviews/code-review/feedback-round-<N>/code-review-report.md",skill:"flows-code-review"},{pattern:"reviews/design-review/*/design-review-report.md",label:"reviews/design-review/feedback-round-<N>/design-review-report.md",skill:"flows-design-review"}];function Ua(e){let t=_a.filter(({pattern:r})=>Et("git",["-C",e,"ls-files","--",r],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length===0);if(t.length>0){let r=t.map(({label:n,skill:i})=>` ${n} \u2192 /${i}`);throw new Error(`Certification files are missing or not committed. Run the required skills in Claude Code first:
132
132
 
133
133
  `+r.join(`
134
- `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(_a,"assertArtifactsCommitted");async function Ua(e=process.cwd(),t={}){let{openInBrowser:r=Fr,revealInFileManager:n=Or,pressEnter:i=Fa,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!ve())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!Ce(e))throw new Error("Not a git repository. Run this command from your app's root directory.");T(e);let a=v(e);F(a),_a(e);let p=ue.join(e,"dist","submit");Ct.mkdirSync(p,{recursive:!0});let c=Et("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Et("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
134
+ `)+"\n\nAfter running the skills, commit the generated files and re-run `apps submit`.")}}o(Ua,"assertArtifactsCommitted");async function La(e=process.cwd(),t={}){let{openInBrowser:r=Or,revealInFileManager:n=_r,pressEnter:i=Oa,isInteractive:s=o(()=>process.stdout.isTTY===!0,"isInteractive")}=t;if(!ve())throw new Error("git is not installed. Install git and ensure it is in your PATH.");if(!Ce(e))throw new Error("Not a git repository. Run this command from your app's root directory.");T(e);let a=v(e);F(a),Ua(e);let p=ue.join(e,"dist","submit");Ct.mkdirSync(p,{recursive:!0});let c=Et("git",["-C",e,"rev-parse","--short","HEAD"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(Et("git",["-C",e,"status","--porcelain"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().length>0)throw new Error(`Working tree has uncommitted changes. Commit or stash them before submitting for certification.
135
135
 
136
- The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=ue.join(p,d);await new X(ue.join(e,"dist")).createSourceArchive(m);let g=`${a.externalId}-${a.versionTag}.zip`,u=ue.join(e,".cognite-bundles",g),S=!1;Ct.existsSync(u)&&(Ct.copyFileSync(u,ue.join(p,g)),S=!0);let h=tn({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:nr(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
136
+ The source archive must exactly match the committed code so reviewers can verify what they receive.`);let d=`src-${c}.zip`,m=ue.join(p,d);await new Z(ue.join(e,"dist")).createSourceArchive(m);let g=`${a.externalId}-${a.versionTag}.zip`,u=ue.join(e,".cognite-bundles",g),S=!1;Ct.existsSync(u)&&(Ct.copyFileSync(u,ue.join(p,g)),S=!0);let h=rn({appName:a.name,externalId:a.externalId,versionTag:a.versionTag,archiveName:d,developerName:or(),cdfProject:a.deployments[0].project,cdfCluster:a.deployments[0].baseUrl});console.log(`
137
137
  \u2705 Certification package ready: dist/submit/`),console.log(` ${d} \u2014 source archive (commit ${c})`),console.log(S?` ${g} \u2014 deploy bundle`:" \u26A0 Deploy bundle missing \u2014 run `apps deploy` to generate it, then re-run submit"),console.log(" \u2190 add your screen recording to this folder"),console.log(`
138
138
  Attach all files from dist/submit/ to the Zendesk ticket.`),console.log(`
139
- \u{1F517} ${h}`),s()&&(await i(),r(h),n(m))}o(Ua,"handleSubmit");function nn(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
139
+ \u{1F517} ${h}`),s()&&(await i(),r(h),n(m))}o(La,"handleSubmit");function on(e){return e.command("submit").description("Package source and open a pre-filled Zendesk form for app certification submission").addHelpText("after",`
140
140
  Examples:
141
- npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>Ua())}o(nn,"registerSubmitCommand");function on(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return vr(t),Ir(t),Xr(t),$r(t),tr(t),Cr(t),Rr(t),nn(t),hr(t),Wr(t),t}o(on,"registerAppsCommand");import{existsSync as za,mkdirSync as Wa,writeFileSync as Xa}from"fs";import{dirname as It,join as ye}from"path";import{generateSigningKeyPair as Za}from"@cognite/app-sdk/codesigning";import Qa from"open";import bt from"enquirer";import{email as La,pipe as Na,safeParse as Ka,string as ja}from"valibot";var Ma=Na(ja(),La());function ne(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!Ka(Ma,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(ne,"parseEmail");function oe(e,t="--expires"){let r=Number(e);if(!Number.isInteger(r)||r<1||r>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return r}o(oe,"parseExpiryMonths");var Oe=3,sn="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",an=`Key expiry in months (${1}-${12})`,pn="Email address for the registry entry",cn=`Passphrase for the encrypted private key (min ${15} chars)`,ln="Confirm passphrase",dn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),mn=o(e=>`Passphrases do not match (attempt ${e}/${Oe}).
142
- `,"passphraseMismatchMsg"),un=`Passphrase confirmation failed after ${Oe} attempts`,gn=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),fn="How would you like to submit your key registration?",yn="Open in browser",hn="Copy link to clipboard";async function _e(e){return bt.prompt(e)}o(_e,"defaultPrompt");function xt(e){return t=>{try{return e(t),!0}catch(r){return r instanceof Error?r.message:"Invalid"}}}o(xt,"parserAsValidator");var Va=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function ge(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!Va.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}o(ge,"parseKid");async function Sn(e={}){let{prompt:t=_e}=e,{kid:r}=await t({type:"input",name:"kid",message:sn,validate:xt(ge)});return ge(r)}o(Sn,"promptKid");async function wn(e={}){let{prompt:t=o(n=>bt.prompt(n),"prompt")}=e,{action:r}=await t({type:"select",name:"action",message:fn,choices:[{name:"browser",message:yn},{name:"clipboard",message:hn}]});if(r!=="browser"&&r!=="clipboard")throw new Error(`Unexpected Zendesk action: ${r}`);return r}o(wn,"promptZendeskAction");async function vn(e={}){let{prompt:t=_e}=e,{months:r}=await t({type:"input",name:"months",message:an,initial:String(6),validate:xt(n=>oe(n,"expiry"))});return oe(r,"expiry")}o(vn,"promptExpiryMonths");async function Cn(e={}){let{prompt:t=_e,gitUserEmail:r=or}=e,{email:n}=await t({type:"input",name:"email",message:pn,initial:r(),validate:xt(i=>ne(i,"email"))});return ne(n,"email")}o(Cn,"promptEmail");async function En(e={}){let{prompt:t=_e,stderr:r=process.stderr}=e;for(let n=1;n<=Oe;n+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:cn,validate:o(a=>a.length>=15?!0:dn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:ln});if(i===s)return i;r.write(mn(n))}throw new Error(un)}o(En,"promptPassphrase");async function kn(e,t={}){let{prompt:r=o(i=>bt.prompt(i),"prompt")}=t,{confirmed:n}=await r({type:"confirm",name:"confirmed",message:gn(e),initial:!1});return n}o(kn,"promptConfirmOverwrite");function Pn(e,t){let r=e.getUTCFullYear(),n=e.getUTCMonth()+t,i=new Date(Date.UTC(r,n+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(r,n,s))}o(Pn,"addMonthsClamped");function At(e){return e.toISOString().slice(0,10)}o(At,"formatIsoDate");function bn(e=new Date){return At(e)}o(bn,"todayIso");import Ba,{Chalk as Ga}from"chalk";var fe=new Ga({level:0});function xn(e){return e.isTTY?Ba:fe}o(xn,"chalkForStream");var Ue=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),An=32,Dn=44,In=60,Ya="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function qa(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==Dn&&t.length!==In)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${Dn} (raw) or ${In} (X.509-wrapped)`);let r=Buffer.from(t,"base64");if(r.length===Ue.length+An&&r.subarray(0,Ue.length).equals(Ue))return r.subarray(Ue.length).toString("base64");if(r.length===An)return r.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${r.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(qa,"pemBodyOneLine");function Dt(e,t=fe,r=new Date){let n=$n(e.issuedAt??bn(r)),i=$n(e.expires),s=qa(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
141
+ npx @cognite/cli apps submit Package source, open browser + file manager`).action(()=>La())}o(on,"registerSubmitCommand");function sn(e){let t=e.command("apps").description("Manage Fusion Custom Apps \u2014 create, deploy, and manage version lifecycle");return Cr(t),$r(t),Zr(t),Rr(t),rr(t),Er(t),Tr(t),on(t),Sr(t),Xr(t),t}o(sn,"registerAppsCommand");import{existsSync as Wa,mkdirSync as Xa,writeFileSync as Za}from"fs";import{dirname as It,join as ye}from"path";import{generateSigningKeyPair as Qa}from"@cognite/app-sdk/codesigning";import ep from"open";import bt from"enquirer";import{email as Na,pipe as Ka,safeParse as ja,string as Ma}from"valibot";var Ha=Ka(Ma(),Na());function ne(e,t="email"){let r=e.trim();if(!r)throw new Error(`${t} is required`);if(!ja(Ha,r).success)throw new Error(`${t} must look like an email (user@example.com); got "${e}"`);return r}o(ne,"parseEmail");function oe(e,t="--expires"){let r=Number(e);if(!Number.isInteger(r)||r<1||r>12)throw new Error(`${t} must be an integer between 1 and 12 (months); got "${e}"`);return r}o(oe,"parseExpiryMonths");var Oe=3,an="Signing identity (kid) \u2014 e.g. jsmith-dev-001 (lowercase letters, digits, hyphens)",pn=`Key expiry in months (${1}-${12})`,cn="Email address for the registry entry",ln=`Passphrase for the encrypted private key (min ${15} chars)`,dn="Confirm passphrase",mn=o(()=>`Passphrase must be at least ${15} characters`,"passphraseTooShortMsg"),un=o(e=>`Passphrases do not match (attempt ${e}/${Oe}).
142
+ `,"passphraseMismatchMsg"),gn=`Passphrase confirmation failed after ${Oe} attempts`,fn=o(e=>`A signing key with kid "${e}" already exists. Overwrite it?`,"confirmOverwriteMsg"),yn="How would you like to submit your key registration?",hn="Open in browser",Sn="Copy link to clipboard";async function _e(e){return bt.prompt(e)}o(_e,"defaultPrompt");function xt(e){return t=>{try{return e(t),!0}catch(r){return r instanceof Error?r.message:"Invalid"}}}o(xt,"parserAsValidator");var Ba=/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;function ge(e){let t=e.trim();if(!t)throw new Error("--kid must not be empty");if(t.length>64)throw new Error("--kid must be 64 characters or fewer");if(!Ba.test(t))throw new Error("--kid must contain only lowercase letters, digits, and hyphens, and must not start or end with a hyphen (e.g. jsmith-dev-001)");return t}o(ge,"parseKid");async function wn(e={}){let{prompt:t=_e}=e,{kid:r}=await t({type:"input",name:"kid",message:an,validate:xt(ge)});return ge(r)}o(wn,"promptKid");async function vn(e={}){let{prompt:t=o(n=>bt.prompt(n),"prompt")}=e,{action:r}=await t({type:"select",name:"action",message:yn,choices:[{name:"browser",message:hn},{name:"clipboard",message:Sn}]});if(r!=="browser"&&r!=="clipboard")throw new Error(`Unexpected Zendesk action: ${r}`);return r}o(vn,"promptZendeskAction");async function Cn(e={}){let{prompt:t=_e}=e,{months:r}=await t({type:"input",name:"months",message:pn,initial:String(6),validate:xt(n=>oe(n,"expiry"))});return oe(r,"expiry")}o(Cn,"promptExpiryMonths");async function En(e={}){let{prompt:t=_e,gitUserEmail:r=ir}=e,{email:n}=await t({type:"input",name:"email",message:cn,initial:r(),validate:xt(i=>ne(i,"email"))});return ne(n,"email")}o(En,"promptEmail");async function kn(e={}){let{prompt:t=_e,stderr:r=process.stderr}=e;for(let n=1;n<=Oe;n+=1){let{passphrase:i}=await t({type:"password",name:"passphrase",message:ln,validate:o(a=>a.length>=15?!0:mn(),"validate")}),{confirm:s}=await t({type:"password",name:"confirm",message:dn});if(i===s)return i;r.write(un(n))}throw new Error(gn)}o(kn,"promptPassphrase");async function Pn(e,t={}){let{prompt:r=o(i=>bt.prompt(i),"prompt")}=t,{confirmed:n}=await r({type:"confirm",name:"confirmed",message:fn(e),initial:!1});return n}o(Pn,"promptConfirmOverwrite");function bn(e,t){let r=e.getUTCFullYear(),n=e.getUTCMonth()+t,i=new Date(Date.UTC(r,n+1,0)).getUTCDate(),s=Math.min(e.getUTCDate(),i);return new Date(Date.UTC(r,n,s))}o(bn,"addMonthsClamped");function At(e){return e.toISOString().slice(0,10)}o(At,"formatIsoDate");function xn(e=new Date){return At(e)}o(xn,"todayIso");import Ga,{Chalk as Ya}from"chalk";var fe=new Ya({level:0});function An(e){return e.isTTY?Ga:fe}o(An,"chalkForStream");var Ue=Uint8Array.from([48,42,48,5,6,3,43,101,112,3,33,0]),Dn=32,In=44,$n=60,qa="services/app-hosting/src/kotlin/com/cognite/apphosting/signing/public_keys.yaml";function Ja(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s+/g,"");if(t.length!==In&&t.length!==$n)throw new Error(`Unexpected Ed25519 public key base64 length: got ${t.length} chars, expected ${In} (raw) or ${$n} (X.509-wrapped)`);let r=Buffer.from(t,"base64");if(r.length===Ue.length+Dn&&r.subarray(0,Ue.length).equals(Ue))return r.subarray(Ue.length).toString("base64");if(r.length===Dn)return r.toString("base64");throw new Error(`Unexpected Ed25519 public key length: got ${r.length} bytes, expected 32 (raw) or 44 (X.509-wrapped)`)}o(Ja,"pemBodyOneLine");function Dt(e,t=fe,r=new Date){let n=Rn(e.issuedAt??xn(r)),i=Rn(e.expires),s=Ja(e.publicKeyPem),a=" ",p=o((l,d)=>`${a}${t.cyan(l)}${t.dim(":")} ${d}
143
143
  `,"kv"),c="";return c+=`
144
- ${t.bold("Add this entry to")} ${t.magenta(Ya)} ${t.bold("under")} ${t.cyan("publicKeys:")}
144
+ ${t.bold("Add this entry to")} ${t.magenta(qa)} ${t.bold("under")} ${t.cyan("publicKeys:")}
145
145
 
146
146
  `,c+=` ${t.dim("-")} ${t.cyan("kid")}${t.dim(":")} ${t.green(e.kid)}
147
- `,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(n)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(Dt,"renderRegistryYamlBlock");function $n(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let r=new Date(t);if(Number.isNaN(r.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return r.toISOString()}o($n,"toIsoInstant");import Ja from"clipboardy";function Rn(e){return Ja.write(e)}o(Rn,"copyToClipboard");function ep(e){return{writeFileSync:e.writeFileSync??Xa,mkdirSync:e.mkdirSync??Wa,existsSync:e.existsSync??za,generateSigningKeyPair:e.generateSigningKeyPair??Za,encryptStringAsJwe:e.encryptStringAsJwe??Hr,storeKeyInKeychain:e.storeKeyInKeychain??Nr,isOS:e.isOS??(t=>N(t)),promptKid:e.promptKid??Sn,promptExpiryMonths:e.promptExpiryMonths??vn,promptEmail:e.promptEmail??Cn,promptPassphrase:e.promptPassphrase??En,promptConfirmOverwrite:e.promptConfirmOverwrite??kn,discoverLocalKeys:e.discoverLocalKeys??(()=>Fe()),promptZendeskAction:e.promptZendeskAction??wn,openUrl:e.openUrl??(t=>Qa(t)),copyToClipboard:e.copyToClipboard??Rn}}o(ep,"resolveDeps");function Fn(e,t={}){let r=ep(t),n=e.command("keys").description("Manage code signing keys");n.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip macOS Keychain and write a passphrase-encrypted private key under ${_().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>op(i,r)),n.command("list").description("List local signing identities and their storage location").action(()=>tp(r))}o(Fn,"registerKeysCommand");async function tp(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
147
+ `,c+=p("publicKey",t.green(s)),c+=p("email",t.yellow(e.email)),c+=p("roles",`${t.dim("[")}${t.yellow("developer")}${t.dim("]")}`),c+=p("issuedAt",t.green(n)),c+=p("expiresAt",t.green(i)),c+=p("revokedAt",t.dim("null")),c}o(Dt,"renderRegistryYamlBlock");function Rn(e){let t=e.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return`${t}T00:00:00Z`;let r=new Date(t);if(Number.isNaN(r.getTime()))throw new Error(`Invalid date '${e}': expected YYYY-MM-DD or ISO-8601 instant`);return r.toISOString()}o(Rn,"toIsoInstant");import za from"clipboardy";function Tn(e){return za.write(e)}o(Tn,"copyToClipboard");function tp(e){return{writeFileSync:e.writeFileSync??Za,mkdirSync:e.mkdirSync??Xa,existsSync:e.existsSync??Wa,generateSigningKeyPair:e.generateSigningKeyPair??Qa,encryptStringAsJwe:e.encryptStringAsJwe??Vr,storeKeyInKeychain:e.storeKeyInKeychain??Kr,isOS:e.isOS??(t=>K(t)),promptKid:e.promptKid??wn,promptExpiryMonths:e.promptExpiryMonths??Cn,promptEmail:e.promptEmail??En,promptPassphrase:e.promptPassphrase??kn,promptConfirmOverwrite:e.promptConfirmOverwrite??Pn,discoverLocalKeys:e.discoverLocalKeys??(()=>Fe()),promptZendeskAction:e.promptZendeskAction??vn,openUrl:e.openUrl??(t=>ep(t)),copyToClipboard:e.copyToClipboard??Tn}}o(tp,"resolveDeps");function On(e,t={}){let r=tp(t),n=e.command("keys").description("Manage code signing keys");n.command("generate").description("Generate an Ed25519 keypair for code signing").option("-o, --output <path>","Encrypted private key output path (forces file storage even on macOS)").option("--no-keychain",`Skip macOS Keychain and write a passphrase-encrypted private key under ${_().keysDir} instead`).option("-e, --expires <months>",`Validity in months (${1}-${12}); skips the interactive prompt`).option("--email <address>","Email address for the registry entry; skips the interactive prompt").option("--kid <identifier>","Signing identity name for the registry (e.g. jsmith-dev-001); skips the interactive prompt").option("--force","Overwrite an existing key without prompting for confirmation").option("--copy-link","Copy the Zendesk registration link to the clipboard without prompting").option("--interactive","Prompt for any required flags that are not supplied",!1).action(i=>ip(i,r)),n.command("list").description("List local signing identities and their storage location").action(()=>rp(r))}o(On,"registerKeysCommand");async function rp(e){let t=await e.discoverLocalKeys();if(t.length===0){process.stdout.write(`No signing identities found.
148
148
  `),process.stdout.write(`Run \`cognite keys generate\` to create one (storage: ${_().keysDir}).
149
149
  `);return}let r=["KID","SOURCE","EMAIL"],n=t.map(a=>[a.kid,Te(a.source),a.email??"\u2014"]),i=r.map((a,p)=>Math.max(a.length,...n.map(c=>c[p].length))),s=o(a=>a.map((p,c)=>p.padEnd(i[c])).join(" ").trimEnd(),"fmt");process.stdout.write(`${s(r)}
150
150
  `);for(let a of n)process.stdout.write(`${s(a)}
151
- `)}o(tp,"handleList");function Tn(e,t,r){let n=ye(_().keysDir,`${e}${re}`);return r.mkdirSync(It(n),{recursive:!0}),r.writeFileSync(n,t),n}o(Tn,"writePublicKey");async function rp(e,t,r,n,i,{force:s=!1}={}){let a=n??ye(_().keysDir,`${e}${ht}`);if(i.mkdirSync(It(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,r);return i.writeFileSync(a,p,{mode:384}),a}o(rp,"writeEncryptedPrivateKey");function np(e,t,r){let n=[];if(e.expires===void 0)n.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{oe(e.expires)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)n.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=ge(e.kid),s=ye(_().keysDir,`${i}${re}`);r(s)&&!e.force&&n.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)n.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{ne(e.email,"--email")}catch(i){n.push(i instanceof Error?i.message:String(i))}return t||n.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),n}o(np,"collectNonInteractiveErrors");async function op(e,t,r=new Date){let{isOS:n,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:y,promptConfirmOverwrite:g}=t,u=e.interactive??!1,S=e.keychain!==!1&&n("macos")&&!e.output;if(!u){let A=np(e,S,i);if(A.length>0)throw new Error(A.join(`
152
- `))}let h;e.expires!==void 0?h=oe(e.expires):h=await l();let k=At(Pn(r,h)),f;e.kid!==void 0?f=ge(e.kid):f=await d();let U=ye(_().keysDir,`${f}${re}`),x=i(U);if(x&&!e.force&&!await g(f)){process.stderr.write(`Aborted.
151
+ `)}o(rp,"handleList");function Fn(e,t,r){let n=ye(_().keysDir,`${e}${re}`);return r.mkdirSync(It(n),{recursive:!0}),r.writeFileSync(n,t),n}o(Fn,"writePublicKey");async function np(e,t,r,n,i,{force:s=!1}={}){let a=n??ye(_().keysDir,`${e}${ht}`);if(i.mkdirSync(It(a),{recursive:!0}),!s&&i.existsSync(a))throw new Error(`Refusing to overwrite existing key at ${a}. Delete it first if you really want to regenerate: rm ${a}`);let p=await i.encryptStringAsJwe(t,r);return i.writeFileSync(a,p,{mode:384}),a}o(np,"writeEncryptedPrivateKey");function op(e,t,r){let n=[];if(e.expires===void 0)n.push("--expires <months> is required. Pass --interactive to enter it interactively.");else try{oe(e.expires)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.kid===void 0)n.push("--kid <identifier> is required. Pass --interactive to enter it interactively.");else try{let i=ge(e.kid),s=ye(_().keysDir,`${i}${re}`);r(s)&&!e.force&&n.push(`Key "${i}" already exists. Use --force to overwrite without prompting.`)}catch(i){n.push(i instanceof Error?i.message:String(i))}if(e.email===void 0)n.push("--email <address> is required. Pass --interactive to enter it interactively.");else try{ne(e.email,"--email")}catch(i){n.push(i instanceof Error?i.message:String(i))}return t||n.push("A passphrase is required for encrypted key storage. Pass --interactive to enter it interactively."),n}o(op,"collectNonInteractiveErrors");async function ip(e,t,r=new Date){let{isOS:n,existsSync:i,mkdirSync:s,writeFileSync:a,generateSigningKeyPair:p,storeKeyInKeychain:c,promptExpiryMonths:l,promptKid:d,promptEmail:m,promptPassphrase:y,promptConfirmOverwrite:g}=t,u=e.interactive??!1,S=e.keychain!==!1&&n("macos")&&!e.output;if(!u){let A=op(e,S,i);if(A.length>0)throw new Error(A.join(`
152
+ `))}let h;e.expires!==void 0?h=oe(e.expires):h=await l();let k=At(bn(r,h)),f;e.kid!==void 0?f=ge(e.kid):f=await d();let U=ye(_().keysDir,`${f}${re}`),x=i(U);if(x&&!e.force&&!await g(f)){process.stderr.write(`Aborted.
153
153
  `);return}let M;e.email!==void 0?M=ne(e.email,"--email"):M=await m();let ae=S?{kind:"keychain"}:{kind:"file",passphrase:await y()};process.stderr.write(`
154
154
  Generating Ed25519 keypair...
155
155
 
156
- `);let{privateKeyPem:w,publicKeyPem:H}=await p(f);if(ae.kind==="keychain"){await c(f,w);let A=Tn(f,H,t);process.stderr.write(`Public key: ${A}
156
+ `);let{privateKeyPem:w,publicKeyPem:H}=await p(f);if(ae.kind==="keychain"){await c(f,w);let A=Fn(f,H,t);process.stderr.write(`Public key: ${A}
157
157
  `),process.stderr.write(`Private key: macOS Keychain (service: cognite-dune, account: ${f})
158
- `)}else{let A=await rp(f,w,ae.passphrase,e.output,t,{force:x}),to=Tn(f,H,t);process.stderr.write(`Public key: ${to}
158
+ `)}else{let A=await np(f,w,ae.passphrase,e.output,t,{force:x}),ro=Fn(f,H,t);process.stderr.write(`Public key: ${ro}
159
159
  `),process.stderr.write(`Private key: ${A} (JWE, AES-256-GCM, PBKDF2-SHA512 x${ft.toLocaleString()})
160
160
  `),n("macos")||process.stderr.write(` (macOS Keychain integration is the default on darwin; on this OS we use the file.)
161
- `)}let ee=ye(_().keysDir,`${f}${St}`);s(It(ee),{recursive:!0}),a(ee,JSON.stringify({email:M}));let C=xn(process.stderr);process.stderr.write(`
161
+ `)}let te=ye(_().keysDir,`${f}${St}`);s(It(te),{recursive:!0}),a(te,JSON.stringify({email:M}));let C=An(process.stderr);process.stderr.write(`
162
162
  Signing identity (kid): ${C.green(f)}
163
163
  `),process.stderr.write(`Expires: ${k} (${h} month${h===1?"":"s"} from today)
164
- `);let G={kid:f,publicKeyPem:H,email:M,expires:k};u||(process.stderr.write(`
164
+ `);let Y={kid:f,publicKeyPem:H,email:M,expires:k};u||(process.stderr.write(`
165
165
  Key registration data:
166
166
 
167
- `),process.stderr.write(Dt(G,C,r)));let Y=rn(f,M,k,Dt(G,fe,r));process.stderr.write(`
167
+ `),process.stderr.write(Dt(Y,C,r)));let q=nn(f,M,k,Dt(Y,fe,r));process.stderr.write(`
168
168
  ${C.bold("Next:")}
169
169
  `),process.stderr.write(` 1. Register your signing key \u2014 submit this pre-filled Zendesk request:
170
- `);let q;if(e.copyLink?q="clipboard":u?q=await t.promptZendeskAction():q=null,q==="browser")try{await t.openUrl(Y),process.stderr.write(` Opening in browser...
171
- `)}catch{process.stderr.write(` URL: ${Y}
172
- `)}else if(q==="clipboard"){let A=!1;try{await t.copyToClipboard(Y),A=!0}catch{}process.stderr.write(A&&!e.copyLink?` Link copied to clipboard.
173
- `:` URL: ${Y}
174
- `)}else process.stderr.write(` URL: ${Y}
170
+ `);let J;if(e.copyLink?J="clipboard":u?J=await t.promptZendeskAction():J=null,J==="browser")try{await t.openUrl(q),process.stderr.write(` Opening in browser...
171
+ `)}catch{process.stderr.write(` URL: ${q}
172
+ `)}else if(J==="clipboard"){let A=!1;try{await t.copyToClipboard(q),A=!0}catch{}process.stderr.write(A&&!e.copyLink?` Link copied to clipboard.
173
+ `:` URL: ${q}
174
+ `)}else process.stderr.write(` URL: ${q}
175
175
  `);process.stderr.write(`
176
176
  2. Once your key is approved, sign your Dune app:
177
177
  `),process.stderr.write(` ${C.cyan(`cognite sign -s ${f}`)}
178
- `)}o(op,"handleGenerate");import{performance as On}from"perf_hooks";var _n=1e3,Le;function ip(){Le=On.now()}o(ip,"markActionStart");function sp(){Le=void 0}o(sp,"resetActionStart");function ap(){if(Le!==void 0)return Math.max(0,Math.round(On.now()-Le))}o(ap,"snapshotActionDurationMs");function Un(){let e=ap();return sp(),{...e!==void 0&&{actionDurationMs:e}}}o(Un,"takePerformanceFields");var pp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function cp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>typeof r=="boolean"?[t,r]:pp.has(t)?[t,r]:[t,"[REDACTED]"]))}o(cp,"sanitize");function lp(e){let t=[],r=e;for(;r;)r.parent&&t.unshift(r.name()),r=r.parent;return t.join(" ")}o(lp,"getCommandPath");function Ln(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Ln,"tryLoadAppConfig");function $t(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o($t,"commandFromArgv");function Nn(e,t,r=v){e.hook("preAction",()=>{ip()}),e.hook("postAction",async(n,i)=>{try{let s={command:lp(i),options:cp(i.opts()),success:!0,...Ln(r),...Un()};t.track("Flows.CLI.Command",{...s}),await t.flush(_n)}catch{}})}o(Nn,"instrument");async function Kn(e,t,r=v){try{let n={command:$t(t),options:{},success:!1,...Ln(r),...Un()};e.track("Flows.CLI.Command",{...n}),await e.flush(_n)}catch{}}o(Kn,"trackFailure");var dp="ERR_USE_AFTER_CLOSE";function Mn(e){return e instanceof Error&&"code"in e&&e.code===dp}o(Mn,"isReadlineClosedError");function mp(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(mp,"isPlainObject");function Rt(e){return e==null||Mn(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&mp(e)&&Object.keys(e).length===0)}o(Rt,"isPromptCancel");var jn=!1;function Hn(){jn||(jn=!0,process.on("uncaughtException",e=>{Mn(e)&&(console.error(`
178
+ `)}o(ip,"handleGenerate");import{performance as _n}from"perf_hooks";var Un=1e3,Le;function sp(){Le=_n.now()}o(sp,"markActionStart");function ap(){Le=void 0}o(ap,"resetActionStart");function pp(){if(Le!==void 0)return Math.max(0,Math.round(_n.now()-Le))}o(pp,"snapshotActionDurationMs");function Ln(){let e=pp();return ap(),{...e!==void 0&&{actionDurationMs:e}}}o(Ln,"takePerformanceFields");var cp=new Set(["baseUrl","url","project","deployment","source","path","name","displayName","description"]);function lp(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>typeof r=="boolean"?[t,r]:cp.has(t)?[t,r]:[t,"[REDACTED]"]))}o(lp,"sanitize");function dp(e){let t=[],r=e;for(;r;)r.parent&&t.unshift(r.name()),r=r.parent;return t.join(" ")}o(dp,"getCommandPath");function Nn(e){try{let t=e(process.cwd());return{appExternalId:t.externalId,appVersionTag:t.versionTag}}catch{return{}}}o(Nn,"tryLoadAppConfig");function $t(e){return e.filter(t=>!t.startsWith("-")).join(" ")||"unknown"}o($t,"commandFromArgv");function Kn(e,t,r=v){e.hook("preAction",()=>{sp()}),e.hook("postAction",async(n,i)=>{try{let s={command:dp(i),options:lp(i.opts()),success:!0,...Nn(r),...Ln()};t.track("Flows.CLI.Command",{...s}),await t.flush(Un)}catch{}})}o(Kn,"instrument");async function jn(e,t,r=v){try{let n={command:$t(t),options:{},success:!1,...Nn(r),...Ln()};e.track("Flows.CLI.Command",{...n}),await e.flush(Un)}catch{}}o(jn,"trackFailure");var mp="ERR_USE_AFTER_CLOSE";function Hn(e){return e instanceof Error&&"code"in e&&e.code===mp}o(Hn,"isReadlineClosedError");function up(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}o(up,"isPlainObject");function Rt(e){return e==null||Hn(e)?!0:e instanceof Error?!1:!!(typeof e=="object"&&e!==null&&up(e)&&Object.keys(e).length===0)}o(Rt,"isPromptCancel");var Mn=!1;function Vn(){Mn||(Mn=!0,process.on("uncaughtException",e=>{Hn(e)&&(console.error(`
179
179
  Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}),process.on("unhandledRejection",e=>{Rt(e)&&(console.error(`
180
- Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(Hn,"installCancelHandler");import{homedir as hp,userInfo as Sp}from"os";import Vn from"mixpanel";var up="5c4d853e7c3b77b1eb4468d5329b278c",he="cognite-cli",gp=2e3,Bn={env:process.env,init:Vn.init.bind(Vn)},fp={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Tt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Tt,"isTelemetryDisabled");function yp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(yp,"isDebug");function Gn(e={}){let t=e.env??Bn.env,r=e.init??Bn.init,n=e.packageName,i=e.cliVersion,s=yp(t);if(Tt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
181
- `),fp;let a,p=new Set;function c(){if(a)return a;try{return a=r(up,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let y={...d,applicationId:he,...n&&{packageName:n},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(y)}
182
- `);let g=o(()=>{},"finish"),u=new Promise(S=>{g=S});p.add(u);try{m.track(l,y,g)}catch{g()}u.finally(()=>p.delete(u))},async flush(l=gp){if(p.size===0)return;let d,m=new Promise(y=>{d=setTimeout(y,l),d.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{d&&clearTimeout(d)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
183
- `)}}}o(Gn,"createTelemetry");var wp=hp(),vp=(()=>{try{return Sp().username}catch{return""}})();function ie(e,t=wp){if(!t||t==="/")return e;let r=e.replaceAll(t,"~"),n=t.replaceAll("\\","/");return n!==t&&(r=r.replaceAll(n,"~")),r=r.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),r=r.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),r}o(ie,"redactHomedir");function Cp(e,t=vp){if(!t||t.length<3)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp("(^|[\\/\\s:])"+r+"(?=[\\/\\s:.@]|$)","g");return e.replace(n,"$1<user>")}o(Cp,"redactUsername");var Ep=1e3,kp="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",Pp={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function bp(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(bp,"buildRelease");var xp="192.0.2.0";function Ap(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:ie(t.filename)},...t.abs_path!==void 0&&{abs_path:ie(t.abs_path)},...t.module!==void 0&&{module:ie(t.module)}}))}o(Ap,"scrubStackFrames");function Ft(e){return Cp(ie(e))}o(Ft,"redactPii");function Dp(e){let t={...e.user,email:void 0,username:void 0,ip_address:xp,id:void 0},r=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Ft(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Ap(s.stacktrace.frames)}}})),n=e.contexts?.cli,i=n!==void 0?Object.fromEntries(Object.entries(n).map(([s,a])=>[s,typeof a=="string"?Ft(a):a])):void 0;return{...e,message:e.message!==void 0?Ft(e.message):e.message,user:t,server_name:void 0,...r!==void 0&&{exception:{...e.exception,values:r}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(Dp,"scrubPii");function Yn(e={}){let t=e.env??process.env;if(Tt(t))return Pp;let r=bp(e),n="production",i=null,s=null;function a(){return{dsn:kp,release:r,environment:n,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:he},contexts:{cli:{applicationId:he,node:process.version,platform:process.platform}}},beforeSend:Dp}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,Ip(c,l))}catch{}},async flush(c=Ep){try{if(!i)return;await i.flush(c)}catch{}}}}o(Yn,"createErrorReporter");function Ip(e,t){let r={level:"fatal"},n={applicationId:he,node:process.version,platform:process.platform};if(t?.command&&(r.tags={command:t.command},n.command=t.command),Nt(e)&&(e.hint&&(n.hint=e.hint),e.helpUrl&&(n.helpUrl=e.helpUrl),n.shouldReport=e.shouldReport),r.contexts={cli:n},Kt(e)&&(r.contexts.http={url:e.requestUrl!==void 0?ie(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);r.extra={responseBody:ie(i)}}return r}o(Ip,"buildCaptureContext");import{mkdirSync as $p,readFileSync as Rp,writeFileSync as Tp}from"fs";import{homedir as Fp}from"os";import{resolve as Ne}from"path";import{debuglog as Op}from"util";import{lt as _p,parse as qn}from"semver";var Up="https://registry.npmjs.org/@cognite/cli/latest",Lp=1500,Jn="upgrade-check.json",zn=Ne(process.env.XDG_CACHE_HOME||Ne(Fp(),".cache"),"@cognite","cli"),Ot=Op("cognite-flows");function Np(e,t){return!e||!t||!qn(e)||!qn(t)?!1:_p(e,t)}o(Np,"isOutdated");async function Kp({timeout:e=Lp,registryUrl:t=Up,fetchImpl:r=globalThis.fetch}={}){if(typeof r!="function")return null;try{let n=await r(t,{signal:AbortSignal.timeout(e)});if(!n?.ok)return null;let i=await n.json();return typeof i?.version=="string"?i.version:null}catch(n){return Ot("fetchLatestVersion failed (%s): %O",t,n),null}}o(Kp,"fetchLatestVersion");function jp(e=zn,t=864e5){try{let r=Rp(Ne(e,Jn),"utf-8"),n=JSON.parse(r);return typeof n.latest!="string"||typeof n.fetchedAt!="number"||Date.now()-n.fetchedAt>t?null:{latest:n.latest,fetchedAt:n.fetchedAt}}catch(r){return Ot("readUpgradeCheckCache failed (%s): %O",e,r),null}}o(jp,"readUpgradeCheckCache");function Mp(e,t){try{$p(e,{recursive:!0});let r={latest:t,fetchedAt:Date.now()};Tp(Ne(e,Jn),JSON.stringify(r))}catch(r){Ot("writeUpgradeCheckCache failed (%s): %O",e,r)}}o(Mp,"writeUpgradeCheckCache");async function Hp({cacheDir:e=zn,...t}={}){let r=await Kp(t);r&&Mp(e,r)}o(Hp,"startBackgroundUpgradeCheck");function Wn(e,{onOutdated:t,cacheDir:r,...n}={}){let i=jp(r);if(i){Np(e,i.latest)&&t?.(e,i.latest);return}Hp({cacheDir:r,...n})}o(Wn,"preActionUpgradeCheck");import{default as Of,chalkStderr as Xn}from"chalk";function Zn(e,t){let r=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],n=Math.max(...r.map(p=>[...p].length))+2,i="\u2500".repeat(n),s=o(p=>`\u2502 ${p}${" ".repeat(n-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...r.map(s),`\u2514${i}\u2518`].join(`
184
- `);return Xn.bold.yellow(a)}o(Zn,"formatUpgradeWarning");function Gp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Gp,"isDep0040Warning");var Ut=process,Yp=Ut.emit.bind(Ut);Ut.emit=function(e,...t){return e==="warning"&&Gp(t[0])?!1:Yp(e,...t)};Hn();var se=new Bp;se.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.4.1").showHelpAfterError().configureOutput({writeOut:o(e=>Vp(1,e),"writeOut")});se.hook("preAction",()=>{Wn("1.4.1",{onOutdated:o((e,t)=>{console.warn(`
185
- ${Zn(e,t)}
186
- `)},"onOutdated")})});on(se);Fn(se);var eo=Gn({packageName:"@cognite/cli",cliVersion:"1.4.1"}),Qn=Yn({packageName:"@cognite/cli",cliVersion:"1.4.1"});Nn(se,eo);var _t=process.argv.slice(2);se.parseAsync(_t,{from:"user"}).catch(async e=>{await Kn(eo,_t),Rt(e)&&(console.error(`
187
- Cancelled.`),process.exit(130)),(!(e instanceof D)||e.shouldReport)&&(await Qn.captureError(e,{command:$t(_t)}),await Qn.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof D&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
180
+ Cancelled.`),process.exit(130)),console.error(e),process.exit(1)}))}o(Vn,"installCancelHandler");import{homedir as Sp,userInfo as wp}from"os";import Bn from"mixpanel";var gp="5c4d853e7c3b77b1eb4468d5329b278c",he="cognite-cli",fp=2e3,Gn={env:process.env,init:Bn.init.bind(Bn)},yp={track:o(()=>{},"track"),flush:o(async()=>{},"flush")};function Tt(e=process.env){return e.COGNITE_TELEMETRY_DISABLED==="1"||e.DO_NOT_TRACK==="1"}o(Tt,"isTelemetryDisabled");function hp(e){return e.COGNITE_TELEMETRY_DEBUG==="1"}o(hp,"isDebug");function Yn(e={}){let t=e.env??Gn.env,r=e.init??Gn.init,n=e.packageName,i=e.cliVersion,s=hp(t);if(Tt(t))return s&&process.stderr.write(`[telemetry] disabled \u2014 noop tracker
181
+ `),yp;let a,p=new Set;function c(){if(a)return a;try{return a=r(gp,{geolocate:!1,keepAlive:!1}),a}catch{return}}return o(c,"getClient"),{track(l,d={}){let m=c();if(!m)return;let y={...d,applicationId:he,...n&&{packageName:n},...i&&{cliVersion:i},nodeVersion:process.version,platform:process.platform};s&&process.stderr.write(`[telemetry] track ${l} ${JSON.stringify(y)}
182
+ `);let g=o(()=>{},"finish"),u=new Promise(S=>{g=S});p.add(u);try{m.track(l,y,g)}catch{g()}u.finally(()=>p.delete(u))},async flush(l=fp){if(p.size===0)return;let d,m=new Promise(y=>{d=setTimeout(y,l),d.unref?.()});try{await Promise.race([Promise.allSettled([...p]),m])}finally{d&&clearTimeout(d)}s&&process.stderr.write(`[telemetry] flush done (${p.size} still pending)
183
+ `)}}}o(Yn,"createTelemetry");var vp=Sp(),Cp=(()=>{try{return wp().username}catch{return""}})();function ie(e,t=vp){if(!t||t==="/")return e;let r=e.replaceAll(t,"~"),n=t.replaceAll("\\","/");return n!==t&&(r=r.replaceAll(n,"~")),r=r.replace(/(?<![A-Za-z0-9_])[A-Za-z]:[/\\]Users[/\\][^\s/\\]+(?=[/\\]|$)/g,"~"),r=r.replace(/(?<![A-Za-z0-9_])\/(?:Users|home)\/[^\s/]+(?=[/\\]|$)/g,"~"),r}o(ie,"redactHomedir");function Ep(e,t=Cp){if(!t||t.length<3)return e;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp("(^|[\\/\\s:])"+r+"(?=[\\/\\s:.@]|$)","g");return e.replace(n,"$1<user>")}o(Ep,"redactUsername");var kp=1e3,Pp="https://0a118cb02e3be57b1838bcfb5783a2bf@o4508040730968064.ingest.de.sentry.io/4510719268290640",bp={captureError:o(async()=>{},"captureError"),flush:o(async()=>{},"flush")};function xp(e){return e.packageName&&e.cliVersion?`${e.packageName}@${e.cliVersion}`:e.cliVersion??"unknown"}o(xp,"buildRelease");var Ap="192.0.2.0";function Dp(e){return e?.map(t=>({...t,...t.filename!==void 0&&{filename:ie(t.filename)},...t.abs_path!==void 0&&{abs_path:ie(t.abs_path)},...t.module!==void 0&&{module:ie(t.module)}}))}o(Dp,"scrubStackFrames");function Ft(e){return Ep(ie(e))}o(Ft,"redactPii");function Ip(e){let t={...e.user,email:void 0,username:void 0,ip_address:Ap,id:void 0},r=e.exception?.values?.map(s=>({...s,value:s.value!==void 0?Ft(s.value):s.value,...s.stacktrace!==void 0&&{stacktrace:{...s.stacktrace,frames:Dp(s.stacktrace.frames)}}})),n=e.contexts?.cli,i=n!==void 0?Object.fromEntries(Object.entries(n).map(([s,a])=>[s,typeof a=="string"?Ft(a):a])):void 0;return{...e,message:e.message!==void 0?Ft(e.message):e.message,user:t,server_name:void 0,...r!==void 0&&{exception:{...e.exception,values:r}},...i!==void 0&&{contexts:{...e.contexts,cli:i}}}}o(Ip,"scrubPii");function qn(e={}){let t=e.env??process.env;if(Tt(t))return bp;let r=xp(e),n="production",i=null,s=null;function a(){return{dsn:Pp,release:r,environment:n,defaultIntegrations:!1,integrations:[],sendDefaultPii:!1,enableLogs:!1,initialScope:{tags:{component:"cli",applicationId:he},contexts:{cli:{applicationId:he,node:process.version,platform:process.platform}}},beforeSend:Ip}}o(a,"buildInitOptions");async function p(){return i||(s||(s=(async()=>{try{let c=e.sdk??await import("@sentry/node");return c.init(a()),i=c,c}catch{return null}})()),s)}return o(p,"ensureSdk"),{async captureError(c,l){try{let d=await p();if(!d)return;d.captureException(c,$p(c,l))}catch{}},async flush(c=kp){try{if(!i)return;await i.flush(c)}catch{}}}}o(qn,"createErrorReporter");function $p(e,t){let r={level:"fatal"},n={applicationId:he,node:process.version,platform:process.platform};if(t?.command&&(r.tags={command:t.command},n.command=t.command),Nt(e)&&(e.hint&&(n.hint=e.hint),e.helpUrl&&(n.helpUrl=e.helpUrl),n.shouldReport=e.shouldReport),r.contexts={cli:n},Kt(e)&&(r.contexts.http={url:e.requestUrl!==void 0?ie(e.requestUrl):void 0,status_code:e.httpStatusCode},e.responseBody!==void 0)){let i=typeof e.responseBody=="string"?e.responseBody:JSON.stringify(e.responseBody);r.extra={responseBody:ie(i)}}return r}o($p,"buildCaptureContext");import{mkdirSync as Rp,readFileSync as Tp,writeFileSync as Fp}from"fs";import{homedir as Op}from"os";import{resolve as Ne}from"path";import{debuglog as _p}from"util";import{lt as Up,parse as Jn}from"semver";var Lp="https://registry.npmjs.org/@cognite/cli/latest",Np=1500,zn="upgrade-check.json",Wn=Ne(process.env.XDG_CACHE_HOME||Ne(Op(),".cache"),"@cognite","cli"),Ot=_p("cognite-flows");function Kp(e,t){return!e||!t||!Jn(e)||!Jn(t)?!1:Up(e,t)}o(Kp,"isOutdated");async function jp({timeout:e=Np,registryUrl:t=Lp,fetchImpl:r=globalThis.fetch}={}){if(typeof r!="function")return null;try{let n=await r(t,{signal:AbortSignal.timeout(e)});if(!n?.ok)return null;let i=await n.json();return typeof i?.version=="string"?i.version:null}catch(n){return Ot("fetchLatestVersion failed (%s): %O",t,n),null}}o(jp,"fetchLatestVersion");function Mp(e=Wn,t=864e5){try{let r=Tp(Ne(e,zn),"utf-8"),n=JSON.parse(r);return typeof n.latest!="string"||typeof n.fetchedAt!="number"||Date.now()-n.fetchedAt>t?null:{latest:n.latest,fetchedAt:n.fetchedAt}}catch(r){return Ot("readUpgradeCheckCache failed (%s): %O",e,r),null}}o(Mp,"readUpgradeCheckCache");function Hp(e,t){try{Rp(e,{recursive:!0});let r={latest:t,fetchedAt:Date.now()};Fp(Ne(e,zn),JSON.stringify(r))}catch(r){Ot("writeUpgradeCheckCache failed (%s): %O",e,r)}}o(Hp,"writeUpgradeCheckCache");async function Vp({cacheDir:e=Wn,...t}={}){let r=await jp(t);r&&Hp(e,r)}o(Vp,"startBackgroundUpgradeCheck");function Xn(e,{onOutdated:t,cacheDir:r,...n}={}){let i=Mp(r);if(i){Kp(e,i.latest)&&t?.(e,i.latest);return}Vp({cacheDir:r,...n})}o(Xn,"preActionUpgradeCheck");import{default as _f,chalkStderr as Zn}from"chalk";function Qn(e,t){let r=[`\u26A0 Update available: ${e} -> ${t}`," Run npx @cognite/cli@latest"],n=Math.max(...r.map(p=>[...p].length))+2,i="\u2500".repeat(n),s=o(p=>`\u2502 ${p}${" ".repeat(n-1-[...p].length)}\u2502`,"pad"),a=[`\u250C${i}\u2510`,...r.map(s),`\u2514${i}\u2518`].join(`
184
+ `);return Zn.bold.yellow(a)}o(Qn,"formatUpgradeWarning");function Yp(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code==="DEP0040"}o(Yp,"isDep0040Warning");var Ut=process,qp=Ut.emit.bind(Ut);Ut.emit=function(e,...t){return e==="warning"&&Yp(t[0])?!1:qp(e,...t)};Vn();var se=new Gp;se.name("cognite").description("Build and deploy React apps to Cognite Data Fusion").version("1.5.0").showHelpAfterError().configureOutput({writeOut:o(e=>Bp(1,e),"writeOut")});se.hook("preAction",()=>{Xn("1.5.0",{onOutdated:o((e,t)=>{console.warn(`
185
+ ${Qn(e,t)}
186
+ `)},"onOutdated")})});sn(se);On(se);var to=Yn({packageName:"@cognite/cli",cliVersion:"1.5.0"}),eo=qn({packageName:"@cognite/cli",cliVersion:"1.5.0"});Kn(se,to);var _t=process.argv.slice(2);se.parseAsync(_t,{from:"user"}).catch(async e=>{await jn(to,_t),Rt(e)&&(console.error(`
187
+ Cancelled.`),process.exit(130)),(!(e instanceof D)||e.shouldReport)&&(await eo.captureError(e,{command:$t(_t)}),await eo.flush());let t=e instanceof Error?e.message:String(e);console.error(`\u274C ${t}`),e instanceof D&&(e.hint||e.helpUrl)&&(console.error(""),e.hint&&console.error(`\u{1F4A1} ${e.hint}`),e.helpUrl&&console.error(`\u{1F4DA} ${e.helpUrl}`)),process.exit(1)});
@@ -96,6 +96,10 @@ type Deployment = {
96
96
  idpType?: 'cdf' | 'entra_id';
97
97
  /** Tenant ID for Entra ID authentication. Required when idpType is "entra_id" */
98
98
  tenantId?: string;
99
+ /** OAuth scopes to request. When omitted, token retrieval derives
100
+ * `https://<cluster>.cognitedata.com/.default` from `baseUrl`. When set to `[]`,
101
+ * an empty scope string is sent. */
102
+ scopes?: string[];
99
103
  };
100
104
  type App = {
101
105
  externalId: string;
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-MXGPBSSS.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"../chunk-5ABVQYYD.js";export{a as AppHostingClient,b as ApplicationPackager,c as BUNDLE_DIR,j as SIGNATURE_SUFFIXES,d as bundleFileName,e as bundlePath,i as deploy,k as discoverSignatures,g as getSdk,f as getToken,h as packageAndUpload};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-MXGPBSSS.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
1
+ import{a as o,b as r,c as e,d as f,e as m,f as p,g as t,h as x,i as a,j as b,k as c}from"./chunk-5ABVQYYD.js";export{o as AppHostingClient,r as ApplicationPackager,e as BUNDLE_DIR,b as SIGNATURE_SUFFIXES,f as bundleFileName,m as bundlePath,a as deploy,c as discoverSignatures,t as getSdk,p as getToken,x as packageAndUpload};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognite/cli",
3
- "version": "1.4.1",
3
+ "version": "1.5.0",
4
4
  "description": "CLI for Cognite Data Fusion",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "Cognite",
@@ -30,7 +30,8 @@
30
30
  "files": [
31
31
  "dist",
32
32
  "_templates",
33
- "_vendor"
33
+ "_vendor",
34
+ "_cognite-spec-extensions"
34
35
  ],
35
36
  "scripts": {
36
37
  "build": "tsup",
@@ -45,7 +46,7 @@
45
46
  "refresh-spec-kit": "bash scripts/refresh-spec-kit.sh"
46
47
  },
47
48
  "dependencies": {
48
- "@cognite/app-sdk": "^0.5.1",
49
+ "@cognite/app-sdk": "^0.6.0",
49
50
  "@cognite/sdk": "^10.10.0",
50
51
  "@sentry/node": "^10.51.0",
51
52
  "@zip.js/zip.js": "^2.7.0",