@kopai/cli 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Kopai Authors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # @kopai/cli
2
+
3
+ CLI for querying OpenTelemetry data from Kopai - traces, logs, and metrics.
4
+
5
+ Works with [@kopai/app](https://github.com/kopai-app/kopai-mono/tree/main/packages/app) or any compatible backend.
6
+
7
+ ## Usage
8
+
9
+ ```bash
10
+ npx @kopai/cli traces search --service my-api
11
+ ```
12
+
13
+ ### Global Install (optional)
14
+
15
+ ```bash
16
+ npm install -g @kopai/cli
17
+ kopai traces search --service my-api
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```bash
23
+ # Search for error traces
24
+ kopai traces search --status-code ERROR --limit 10
25
+
26
+ # Get all spans for a trace
27
+ kopai traces get <traceId>
28
+
29
+ # Search logs by service
30
+ kopai logs search --service my-api --limit 20
31
+
32
+ # Discover available metrics
33
+ kopai metrics discover
34
+ ```
35
+
36
+ By default connects to `http://localhost:8000/signals`.
37
+
38
+ ## Configuration
39
+
40
+ ### Global Options
41
+
42
+ | Option | Description |
43
+ | ------------------------ | ---------------- |
44
+ | `--url <url>` | API base URL |
45
+ | `--token <token>` | Auth token |
46
+ | `--config <path>` / `-c` | Config file path |
47
+ | `--timeout <ms>` | Request timeout |
48
+
49
+ ### Config File
50
+
51
+ Create `.kopairc` in project root or home directory:
52
+
53
+ ```json
54
+ {
55
+ "url": "https://your-kopai-server.com/signals",
56
+ "token": "your-token"
57
+ }
58
+ ```
59
+
60
+ **Priority:** CLI flags → local `.kopairc` → `~/.kopairc` → defaults
61
+
62
+ ## Commands
63
+
64
+ ### traces
65
+
66
+ #### `traces get <traceId>`
67
+
68
+ Get all spans for a trace.
69
+
70
+ ```bash
71
+ kopai traces get abc123def456
72
+ ```
73
+
74
+ #### `traces search`
75
+
76
+ Search traces with filters.
77
+
78
+ ```bash
79
+ kopai traces search --service my-api --status-code ERROR
80
+ kopai traces search --span-name "POST /users" --duration-min 1000000000
81
+ kopai traces search --span-attr "http.method=GET" --resource-attr "k8s.pod.name=web-1"
82
+ ```
83
+
84
+ **Filters:**
85
+
86
+ - `--trace-id`, `--span-id`, `--parent-span-id`
87
+ - `-s, --service` - service name
88
+ - `--span-name` - span name
89
+ - `--span-kind` - CLIENT, SERVER, PRODUCER, CONSUMER, INTERNAL
90
+ - `--status-code` - OK, ERROR, UNSET
91
+ - `--scope` - instrumentation scope
92
+ - `--timestamp-min`, `--timestamp-max` - nanoseconds
93
+ - `--duration-min`, `--duration-max` - nanoseconds
94
+ - `--span-attr <key=value>` - repeatable
95
+ - `--resource-attr <key=value>` - repeatable
96
+ - `--sort` - ASC or DESC
97
+
98
+ **Fields:** SpanId, TraceId, Timestamp, Duration, ParentSpanId, ServiceName, SpanName, SpanKind, StatusCode, StatusMessage, SpanAttributes, ResourceAttributes, ScopeName, ScopeVersion, TraceState, Events, Links
99
+
100
+ ### logs
101
+
102
+ #### `logs search`
103
+
104
+ Search logs with filters.
105
+
106
+ ```bash
107
+ kopai logs search --service my-api --severity-text ERROR
108
+ kopai logs search --trace-id abc123 --body "connection failed"
109
+ kopai logs search --log-attr "user.id=123"
110
+ ```
111
+
112
+ **Filters:**
113
+
114
+ - `--trace-id`, `--span-id` - correlate with traces
115
+ - `-s, --service` - service name
116
+ - `--scope` - scope name
117
+ - `--severity-text` - DEBUG, INFO, WARN, ERROR, FATAL
118
+ - `--severity-min`, `--severity-max` - 0-24
119
+ - `-b, --body` - body content substring
120
+ - `--timestamp-min`, `--timestamp-max` - nanoseconds
121
+ - `--log-attr <key=value>` - repeatable
122
+ - `--resource-attr <key=value>` - repeatable
123
+ - `--scope-attr <key=value>` - repeatable
124
+ - `--sort` - ASC or DESC
125
+
126
+ **Fields:** Timestamp, TraceId, SpanId, ServiceName, SeverityText, SeverityNumber, Body, LogAttributes, ResourceAttributes, ScopeName, ScopeVersion, ScopeAttributes, TraceFlags
127
+
128
+ ### metrics
129
+
130
+ #### `metrics search --type <type>`
131
+
132
+ Search metrics by type.
133
+
134
+ ```bash
135
+ kopai metrics search --type Gauge --name cpu_usage
136
+ kopai metrics search --type Histogram --service my-api
137
+ kopai metrics search --type Sum --attr "host=server1"
138
+ ```
139
+
140
+ **Types:** Gauge, Sum, Histogram, ExponentialHistogram, Summary
141
+
142
+ **Filters:**
143
+
144
+ - `-n, --name` - metric name
145
+ - `-s, --service` - service name
146
+ - `--scope` - scope name
147
+ - `--time-min`, `--time-max` - nanoseconds
148
+ - `-a, --attr <key=value>` - repeatable
149
+ - `--resource-attr <key=value>` - repeatable
150
+ - `--scope-attr <key=value>` - repeatable
151
+ - `--sort` - ASC or DESC
152
+
153
+ **Fields:** TimeUnix, StartTimeUnix, MetricType, MetricName, MetricDescription, MetricUnit, ServiceName, Value, Count, Sum, Min, Max, Attributes, ResourceAttributes, ScopeName, ScopeAttributes, Exemplars, BucketCounts, ExplicitBounds
154
+
155
+ #### `metrics discover`
156
+
157
+ List available metrics.
158
+
159
+ ```bash
160
+ kopai metrics discover
161
+ kopai metrics discover --json
162
+ ```
163
+
164
+ **Fields:** name, type, unit, description, attributes, resourceAttributes
165
+
166
+ ## Output Options
167
+
168
+ | Option | Description |
169
+ | ---------------------- | ---------------------- |
170
+ | `-j, --json` | JSON output |
171
+ | `-t, --table` | Table output |
172
+ | `-f, --fields <f1,f2>` | Select specific fields |
173
+ | `-l, --limit <n>` | Max results |
174
+
175
+ **Auto-detection:** TTY outputs table, piped output defaults to JSON.
176
+
177
+ ```bash
178
+ # Select specific fields
179
+ kopai traces search --fields "SpanId,ServiceName,Duration"
180
+
181
+ # Pipe JSON to jq
182
+ kopai logs search --json --service my-api | jq '.[] | .Body'
183
+ ```
184
+
185
+ ## Exit Codes
186
+
187
+ | Code | Meaning |
188
+ | ---- | ----------------- |
189
+ | 0 | Success |
190
+ | 1 | API/runtime error |
191
+ | 2 | Invalid arguments |
192
+ | 3 | Config error |
193
+
194
+ ## Examples
195
+
196
+ ```bash
197
+ # Find slow traces (>1s duration)
198
+ kopai traces search --duration-min 1000000000 --json
199
+
200
+ # Get logs correlated with a trace
201
+ kopai traces get abc123 --fields TraceId
202
+ kopai logs search --trace-id abc123
203
+
204
+ # Export error logs as JSON
205
+ kopai logs search --severity-text ERROR --json > errors.json
206
+
207
+ # Monitor specific service
208
+ kopai traces search --service payment-api --status-code ERROR --limit 50
209
+ ```
@@ -0,0 +1 @@
1
+ export { };
package/dist/index.mjs ADDED
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import { KopaiClient } from "@kopai/sdk";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ //#region src/config.ts
9
+ const CONFIG_FILENAME = ".kopairc";
10
+ function loadConfigFile(path) {
11
+ if (!existsSync(path)) return null;
12
+ try {
13
+ const content = readFileSync(path, "utf-8");
14
+ return JSON.parse(content);
15
+ } catch {
16
+ return null;
17
+ }
18
+ }
19
+ function loadConfig(configPath) {
20
+ const paths = configPath ? [configPath] : [join(process.cwd(), CONFIG_FILENAME), join(homedir(), CONFIG_FILENAME)];
21
+ for (const path of paths) {
22
+ const config = loadConfigFile(path);
23
+ if (config) return config;
24
+ }
25
+ return {};
26
+ }
27
+
28
+ //#endregion
29
+ //#region src/client.ts
30
+ const DEFAULT_URL = "http://localhost:8000/signals";
31
+ function createClient(opts) {
32
+ const fileConfig = loadConfig(opts.config);
33
+ return new KopaiClient({
34
+ baseUrl: opts.url ?? fileConfig.url ?? DEFAULT_URL,
35
+ token: opts.token ?? fileConfig.token,
36
+ timeout: opts.timeout
37
+ });
38
+ }
39
+ function parseAttributes(attrs) {
40
+ if (!attrs || attrs.length === 0) return {};
41
+ const result = {};
42
+ for (const attr of attrs) {
43
+ const idx = attr.indexOf("=");
44
+ if (idx === -1) {
45
+ console.error(`Invalid attribute format: ${attr}. Use key=value`);
46
+ process.exit(2);
47
+ }
48
+ result[attr.slice(0, idx)] = attr.slice(idx + 1);
49
+ }
50
+ return result;
51
+ }
52
+
53
+ //#endregion
54
+ //#region src/output.ts
55
+ function detectFormat(json, table) {
56
+ if (json) return "json";
57
+ if (table) return "table";
58
+ return process.stdout.isTTY ? "table" : "json";
59
+ }
60
+ function countAttributes(attr) {
61
+ return Object.keys(attr.values).length;
62
+ }
63
+ function filterFields(data, fields) {
64
+ return Object.fromEntries(Object.entries(data).filter(([key]) => fields.includes(key)));
65
+ }
66
+ function parseFields(fieldsStr) {
67
+ if (!fieldsStr) return void 0;
68
+ return fieldsStr.split(",").map((f) => f.trim());
69
+ }
70
+ function isMetricsDiscoverData(data) {
71
+ return data.length > 0 && typeof data[0] === "object" && data[0] !== null && "attributes" in data[0] && "resourceAttributes" in data[0] && typeof data[0].attributes === "object" && data[0].attributes !== null && "values" in data[0].attributes;
72
+ }
73
+ function output(data, opts) {
74
+ let outputData = data;
75
+ if (opts.fields && opts.fields.length > 0) {
76
+ if (Array.isArray(data)) outputData = data.map((item) => typeof item === "object" && item !== null ? filterFields(item, opts.fields) : item);
77
+ else if (typeof data === "object" && data !== null) outputData = filterFields(data, opts.fields);
78
+ }
79
+ if (opts.format === "json") console.log(JSON.stringify(outputData, null, 2));
80
+ else if (Array.isArray(outputData)) if (outputData.length === 0) console.log("No results found.");
81
+ else if (!opts.fields && isMetricsDiscoverData(outputData)) {
82
+ const transformed = outputData.map((m) => ({
83
+ name: m.name,
84
+ type: m.type,
85
+ unit: m.unit,
86
+ description: m.description,
87
+ attrs: countAttributes(m.attributes),
88
+ resourceAttrs: countAttributes(m.resourceAttributes)
89
+ }));
90
+ console.table(transformed);
91
+ console.log("\nUse --json for full attribute details.");
92
+ } else console.table(outputData);
93
+ else console.log(outputData);
94
+ }
95
+ function outputError(error, json) {
96
+ const err = error instanceof Error ? {
97
+ name: error.name,
98
+ message: error.message
99
+ } : { message: String(error) };
100
+ if (json) console.error(JSON.stringify({ error: err }));
101
+ else console.error(`Error: ${err.message}`);
102
+ }
103
+
104
+ //#endregion
105
+ //#region src/commands/traces.ts
106
+ function createTracesCommand() {
107
+ const traces = new Command("traces").description("Query traces");
108
+ traces.command("get").description("Get all spans for a trace by ID").argument("<traceId>", "Trace ID").option("-j, --json", "JSON output").option("-t, --table", "Table output").option("-f, --fields <fields>", "Comma-separated fields to include").option("--timeout <ms>", "Request timeout").option("-c, --config <path>", "Config file path").option("--url <url>", "API base URL").option("--token <token>", "Auth token").action(async (traceId, opts) => {
109
+ const format = detectFormat(opts.json, opts.table);
110
+ const fields = parseFields(opts.fields);
111
+ try {
112
+ output(await createClient(opts).getTrace(traceId), {
113
+ format,
114
+ fields
115
+ });
116
+ } catch (err) {
117
+ outputError(err, format === "json");
118
+ process.exit(1);
119
+ }
120
+ });
121
+ traces.command("search").description("Search traces").option("-j, --json", "JSON output").option("-t, --table", "Table output").option("-f, --fields <fields>", "Comma-separated fields to include").option("-l, --limit <n>", "Max results").option("--trace-id <id>", "Filter by trace ID").option("--span-id <id>", "Filter by span ID").option("--parent-span-id <id>", "Filter by parent span ID").option("-s, --service <name>", "Filter by service name").option("--span-name <name>", "Filter by span name").option("--span-kind <kind>", "Filter by span kind").option("--status-code <code>", "Filter by status code").option("--scope <name>", "Filter by scope name").option("--timestamp-min <ns>", "Min timestamp (nanoseconds)").option("--timestamp-max <ns>", "Max timestamp (nanoseconds)").option("--duration-min <ns>", "Min duration (nanoseconds)").option("--duration-max <ns>", "Max duration (nanoseconds)").option("--span-attr <key=value>", "Span attribute filter (repeatable)", collect$2, []).option("--resource-attr <key=value>", "Resource attribute filter (repeatable)", collect$2, []).option("--sort <order>", "Sort order (ASC|DESC)").option("--timeout <ms>", "Request timeout").option("-c, --config <path>", "Config file path").option("--url <url>", "API base URL").option("--token <token>", "Auth token").action(async (opts) => {
122
+ const format = detectFormat(opts.json, opts.table);
123
+ const fields = parseFields(opts.fields);
124
+ try {
125
+ const client = createClient(opts);
126
+ const limit = opts.limit ? parseInt(opts.limit, 10) : void 0;
127
+ const filter = {
128
+ traceId: opts.traceId,
129
+ spanId: opts.spanId,
130
+ parentSpanId: opts.parentSpanId,
131
+ serviceName: opts.service,
132
+ spanName: opts.spanName,
133
+ spanKind: opts.spanKind,
134
+ statusCode: opts.statusCode,
135
+ scopeName: opts.scope,
136
+ timestampMin: opts.timestampMin,
137
+ timestampMax: opts.timestampMax,
138
+ durationMin: opts.durationMin,
139
+ durationMax: opts.durationMax,
140
+ spanAttributes: parseAttributes(opts.spanAttr),
141
+ resourceAttributes: parseAttributes(opts.resourceAttr),
142
+ limit,
143
+ sortOrder: opts.sort
144
+ };
145
+ output((await client.searchTracesPage(filter)).data, {
146
+ format,
147
+ fields
148
+ });
149
+ } catch (err) {
150
+ outputError(err, format === "json");
151
+ process.exit(1);
152
+ }
153
+ });
154
+ return traces;
155
+ }
156
+ function collect$2(value, previous) {
157
+ return previous.concat([value]);
158
+ }
159
+
160
+ //#endregion
161
+ //#region src/commands/logs.ts
162
+ function createLogsCommand() {
163
+ const logs = new Command("logs").description("Query logs");
164
+ logs.command("search").description("Search logs").option("-j, --json", "JSON output").option("-t, --table", "Table output").option("-f, --fields <fields>", "Comma-separated fields to include").option("-l, --limit <n>", "Max results").option("--trace-id <id>", "Filter by trace ID").option("--span-id <id>", "Filter by span ID").option("-s, --service <name>", "Filter by service name").option("--scope <name>", "Filter by scope name").option("--severity-text <level>", "Filter by severity text").option("--severity-min <n>", "Min severity number").option("--severity-max <n>", "Max severity number").option("-b, --body <text>", "Filter by body contains").option("--timestamp-min <ns>", "Min timestamp (nanoseconds)").option("--timestamp-max <ns>", "Max timestamp (nanoseconds)").option("--log-attr <key=value>", "Log attribute filter (repeatable)", collect$1, []).option("--resource-attr <key=value>", "Resource attribute filter (repeatable)", collect$1, []).option("--scope-attr <key=value>", "Scope attribute filter (repeatable)", collect$1, []).option("--sort <order>", "Sort order (ASC|DESC)").option("--timeout <ms>", "Request timeout").option("-c, --config <path>", "Config file path").option("--url <url>", "API base URL").option("--token <token>", "Auth token").action(async (opts) => {
165
+ const format = detectFormat(opts.json, opts.table);
166
+ const fields = parseFields(opts.fields);
167
+ try {
168
+ const client = createClient(opts);
169
+ const limit = opts.limit ? parseInt(opts.limit, 10) : void 0;
170
+ const filter = {
171
+ traceId: opts.traceId,
172
+ spanId: opts.spanId,
173
+ serviceName: opts.service,
174
+ scopeName: opts.scope,
175
+ severityText: opts.severityText,
176
+ severityNumberMin: opts.severityMin ? parseInt(opts.severityMin, 10) : void 0,
177
+ severityNumberMax: opts.severityMax ? parseInt(opts.severityMax, 10) : void 0,
178
+ bodyContains: opts.body,
179
+ timestampMin: opts.timestampMin,
180
+ timestampMax: opts.timestampMax,
181
+ logAttributes: parseAttributes(opts.logAttr),
182
+ resourceAttributes: parseAttributes(opts.resourceAttr),
183
+ scopeAttributes: parseAttributes(opts.scopeAttr),
184
+ limit,
185
+ sortOrder: opts.sort
186
+ };
187
+ output((await client.searchLogsPage(filter)).data, {
188
+ format,
189
+ fields
190
+ });
191
+ } catch (err) {
192
+ outputError(err, format === "json");
193
+ process.exit(1);
194
+ }
195
+ });
196
+ return logs;
197
+ }
198
+ function collect$1(value, previous) {
199
+ return previous.concat([value]);
200
+ }
201
+
202
+ //#endregion
203
+ //#region src/commands/metrics.ts
204
+ function createMetricsCommand() {
205
+ const metrics = new Command("metrics").description("Query metrics");
206
+ metrics.command("search").description("Search metrics").requiredOption("--type <type>", "Metric type (Gauge|Sum|Histogram|ExponentialHistogram|Summary)").option("-j, --json", "JSON output").option("-t, --table", "Table output").option("-f, --fields <fields>", "Comma-separated fields to include").option("-l, --limit <n>", "Max results").option("-n, --name <name>", "Filter by metric name").option("-s, --service <name>", "Filter by service name").option("--scope <name>", "Filter by scope name").option("--time-min <ns>", "Min time (nanoseconds)").option("--time-max <ns>", "Max time (nanoseconds)").option("-a, --attr <key=value>", "Attribute filter (repeatable)", collect, []).option("--resource-attr <key=value>", "Resource attribute filter (repeatable)", collect, []).option("--scope-attr <key=value>", "Scope attribute filter (repeatable)", collect, []).option("--sort <order>", "Sort order (ASC|DESC)").option("--timeout <ms>", "Request timeout").option("-c, --config <path>", "Config file path").option("--url <url>", "API base URL").option("--token <token>", "Auth token").action(async (opts) => {
207
+ const format = detectFormat(opts.json, opts.table);
208
+ const fields = parseFields(opts.fields);
209
+ try {
210
+ const client = createClient(opts);
211
+ const limit = opts.limit ? parseInt(opts.limit, 10) : void 0;
212
+ const filter = {
213
+ metricType: opts.type,
214
+ metricName: opts.name,
215
+ serviceName: opts.service,
216
+ scopeName: opts.scope,
217
+ timeUnixMin: opts.timeMin,
218
+ timeUnixMax: opts.timeMax,
219
+ attributes: parseAttributes(opts.attr),
220
+ resourceAttributes: parseAttributes(opts.resourceAttr),
221
+ scopeAttributes: parseAttributes(opts.scopeAttr),
222
+ limit,
223
+ sortOrder: opts.sort
224
+ };
225
+ output((await client.searchMetricsPage(filter)).data, {
226
+ format,
227
+ fields
228
+ });
229
+ } catch (err) {
230
+ outputError(err, format === "json");
231
+ process.exit(1);
232
+ }
233
+ });
234
+ metrics.command("discover").description("List available metrics").option("-j, --json", "JSON output").option("-t, --table", "Table output").option("-f, --fields <fields>", "Comma-separated fields to include").option("--timeout <ms>", "Request timeout").option("-c, --config <path>", "Config file path").option("--url <url>", "API base URL").option("--token <token>", "Auth token").action(async (opts) => {
235
+ const format = detectFormat(opts.json, opts.table);
236
+ const fields = parseFields(opts.fields);
237
+ try {
238
+ output((await createClient(opts).discoverMetrics()).metrics, {
239
+ format,
240
+ fields
241
+ });
242
+ } catch (err) {
243
+ outputError(err, format === "json");
244
+ process.exit(1);
245
+ }
246
+ });
247
+ return metrics;
248
+ }
249
+ function collect(value, previous) {
250
+ return previous.concat([value]);
251
+ }
252
+
253
+ //#endregion
254
+ //#region package.json
255
+ var version = "0.0.0";
256
+
257
+ //#endregion
258
+ //#region src/index.ts
259
+ const program = new Command();
260
+ program.name("@kopai/cli").description("Kopai CLI - Query OpenTelemetry data").version(version).addCommand(createTracesCommand()).addCommand(createLogsCommand()).addCommand(createMetricsCommand());
261
+ program.parse();
262
+
263
+ //#endregion
264
+ export { };
265
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["collect","collect","pkg.version"],"sources":["../src/config.ts","../src/client.ts","../src/output.ts","../src/commands/traces.ts","../src/commands/logs.ts","../src/commands/metrics.ts","../package.json","../src/index.ts"],"sourcesContent":["import { readFileSync, existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface Config {\n url?: string;\n token?: string;\n}\n\nconst CONFIG_FILENAME = \".kopairc\";\n\nfunction loadConfigFile(path: string): Config | null {\n if (!existsSync(path)) return null;\n try {\n const content = readFileSync(path, \"utf-8\");\n return JSON.parse(content) as Config;\n } catch {\n return null;\n }\n}\n\nexport function loadConfig(configPath?: string): Config {\n // Priority: --config flag > ./.kopairc > ~/.kopairc\n const paths = configPath\n ? [configPath]\n : [join(process.cwd(), CONFIG_FILENAME), join(homedir(), CONFIG_FILENAME)];\n\n for (const path of paths) {\n const config = loadConfigFile(path);\n if (config) return config;\n }\n\n return {};\n}\n","import { KopaiClient } from \"@kopai/sdk\";\nimport { loadConfig } from \"./config.js\";\n\nexport interface ClientOptions {\n config?: string;\n url?: string;\n token?: string;\n timeout?: number;\n}\n\nconst DEFAULT_URL = \"http://localhost:8000/signals\";\n\nexport function createClient(opts: ClientOptions): KopaiClient {\n const fileConfig = loadConfig(opts.config);\n\n const url = opts.url ?? fileConfig.url ?? DEFAULT_URL;\n const token = opts.token ?? fileConfig.token;\n\n return new KopaiClient({\n baseUrl: url,\n token,\n timeout: opts.timeout,\n });\n}\n\nexport function parseAttributes(attrs?: string[]): Record<string, string> {\n if (!attrs || attrs.length === 0) return {};\n const result: Record<string, string> = {};\n for (const attr of attrs) {\n const idx = attr.indexOf(\"=\");\n if (idx === -1) {\n console.error(`Invalid attribute format: ${attr}. Use key=value`);\n process.exit(2);\n }\n result[attr.slice(0, idx)] = attr.slice(idx + 1);\n }\n return result;\n}\n","export type OutputFormat = \"json\" | \"table\";\n\nexport interface OutputOptions {\n format: OutputFormat;\n fields?: string[];\n}\n\nexport function detectFormat(json?: boolean, table?: boolean): OutputFormat {\n if (json) return \"json\";\n if (table) return \"table\";\n // Default: table for TTY, JSON for pipes\n return process.stdout.isTTY ? \"table\" : \"json\";\n}\n\nfunction countAttributes(attr: { values: Record<string, string[]> }): number {\n return Object.keys(attr.values).length;\n}\n\nfunction filterFields<T extends object>(data: T, fields: string[]): Partial<T> {\n return Object.fromEntries(\n Object.entries(data).filter(([key]) => fields.includes(key))\n ) as Partial<T>;\n}\n\nexport function parseFields(fieldsStr?: string): string[] | undefined {\n if (!fieldsStr) return undefined;\n return fieldsStr.split(\",\").map((f) => f.trim());\n}\n\nfunction isMetricsDiscoverData(data: unknown[]): data is Array<{\n attributes: { values: Record<string, string[]> };\n resourceAttributes: { values: Record<string, string[]> };\n}> {\n return (\n data.length > 0 &&\n typeof data[0] === \"object\" &&\n data[0] !== null &&\n \"attributes\" in data[0] &&\n \"resourceAttributes\" in data[0] &&\n typeof (data[0] as Record<string, unknown>).attributes === \"object\" &&\n (data[0] as Record<string, unknown>).attributes !== null &&\n \"values\" in ((data[0] as Record<string, unknown>).attributes as object)\n );\n}\n\nexport function output<T>(data: T, opts: OutputOptions): void {\n let outputData = data;\n\n // Apply field filtering\n if (opts.fields && opts.fields.length > 0) {\n if (Array.isArray(data)) {\n outputData = data.map((item) =>\n typeof item === \"object\" && item !== null\n ? filterFields(item as object, opts.fields!)\n : item\n ) as T;\n } else if (typeof data === \"object\" && data !== null) {\n outputData = filterFields(data as object, opts.fields) as T;\n }\n }\n\n if (opts.format === \"json\") {\n console.log(JSON.stringify(outputData, null, 2));\n } else {\n if (Array.isArray(outputData)) {\n if (outputData.length === 0) {\n console.log(\"No results found.\");\n } else if (!opts.fields && isMetricsDiscoverData(outputData)) {\n const transformed = outputData.map((m) => ({\n name: m.name,\n type: m.type,\n unit: m.unit,\n description: m.description,\n attrs: countAttributes(m.attributes),\n resourceAttrs: countAttributes(m.resourceAttributes),\n }));\n console.table(transformed);\n console.log(\"\\nUse --json for full attribute details.\");\n } else {\n console.table(outputData);\n }\n } else {\n console.log(outputData);\n }\n }\n}\n\nexport function outputError(error: unknown, json: boolean): void {\n const err =\n error instanceof Error\n ? { name: error.name, message: error.message }\n : { message: String(error) };\n\n if (json) {\n console.error(JSON.stringify({ error: err }));\n } else {\n console.error(`Error: ${err.message}`);\n }\n}\n","import { Command } from \"commander\";\nimport {\n createClient,\n parseAttributes,\n type ClientOptions,\n} from \"../client.js\";\nimport { detectFormat, output, outputError, parseFields } from \"../output.js\";\n\ninterface TracesGetOptions extends ClientOptions {\n json?: boolean;\n table?: boolean;\n fields?: string;\n}\n\ninterface TracesSearchOptions extends ClientOptions {\n json?: boolean;\n table?: boolean;\n fields?: string;\n limit?: string;\n traceId?: string;\n spanId?: string;\n parentSpanId?: string;\n service?: string;\n spanName?: string;\n spanKind?: string;\n statusCode?: string;\n scope?: string;\n timestampMin?: string;\n timestampMax?: string;\n durationMin?: string;\n durationMax?: string;\n spanAttr?: string[];\n resourceAttr?: string[];\n sort?: string;\n}\n\nexport function createTracesCommand(): Command {\n const traces = new Command(\"traces\").description(\"Query traces\");\n\n traces\n .command(\"get\")\n .description(\"Get all spans for a trace by ID\")\n .argument(\"<traceId>\", \"Trace ID\")\n .option(\"-j, --json\", \"JSON output\")\n .option(\"-t, --table\", \"Table output\")\n .option(\"-f, --fields <fields>\", \"Comma-separated fields to include\")\n .option(\"--timeout <ms>\", \"Request timeout\")\n .option(\"-c, --config <path>\", \"Config file path\")\n .option(\"--url <url>\", \"API base URL\")\n .option(\"--token <token>\", \"Auth token\")\n .action(async (traceId: string, opts: TracesGetOptions) => {\n const format = detectFormat(opts.json, opts.table);\n const fields = parseFields(opts.fields);\n try {\n const client = createClient(opts);\n const spans = await client.getTrace(traceId);\n output(spans, { format, fields });\n } catch (err) {\n outputError(err, format === \"json\");\n process.exit(1);\n }\n });\n\n traces\n .command(\"search\")\n .description(\"Search traces\")\n .option(\"-j, --json\", \"JSON output\")\n .option(\"-t, --table\", \"Table output\")\n .option(\"-f, --fields <fields>\", \"Comma-separated fields to include\")\n .option(\"-l, --limit <n>\", \"Max results\")\n .option(\"--trace-id <id>\", \"Filter by trace ID\")\n .option(\"--span-id <id>\", \"Filter by span ID\")\n .option(\"--parent-span-id <id>\", \"Filter by parent span ID\")\n .option(\"-s, --service <name>\", \"Filter by service name\")\n .option(\"--span-name <name>\", \"Filter by span name\")\n .option(\"--span-kind <kind>\", \"Filter by span kind\")\n .option(\"--status-code <code>\", \"Filter by status code\")\n .option(\"--scope <name>\", \"Filter by scope name\")\n .option(\"--timestamp-min <ns>\", \"Min timestamp (nanoseconds)\")\n .option(\"--timestamp-max <ns>\", \"Max timestamp (nanoseconds)\")\n .option(\"--duration-min <ns>\", \"Min duration (nanoseconds)\")\n .option(\"--duration-max <ns>\", \"Max duration (nanoseconds)\")\n .option(\n \"--span-attr <key=value>\",\n \"Span attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\n \"--resource-attr <key=value>\",\n \"Resource attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\"--sort <order>\", \"Sort order (ASC|DESC)\")\n .option(\"--timeout <ms>\", \"Request timeout\")\n .option(\"-c, --config <path>\", \"Config file path\")\n .option(\"--url <url>\", \"API base URL\")\n .option(\"--token <token>\", \"Auth token\")\n .action(async (opts: TracesSearchOptions) => {\n const format = detectFormat(opts.json, opts.table);\n const fields = parseFields(opts.fields);\n try {\n const client = createClient(opts);\n const limit = opts.limit ? parseInt(opts.limit, 10) : undefined;\n\n const filter = {\n traceId: opts.traceId,\n spanId: opts.spanId,\n parentSpanId: opts.parentSpanId,\n serviceName: opts.service,\n spanName: opts.spanName,\n spanKind: opts.spanKind,\n statusCode: opts.statusCode,\n scopeName: opts.scope,\n timestampMin: opts.timestampMin,\n timestampMax: opts.timestampMax,\n durationMin: opts.durationMin,\n durationMax: opts.durationMax,\n spanAttributes: parseAttributes(opts.spanAttr),\n resourceAttributes: parseAttributes(opts.resourceAttr),\n limit,\n sortOrder: opts.sort as \"ASC\" | \"DESC\" | undefined,\n };\n\n const result = await client.searchTracesPage(filter);\n output(result.data, { format, fields });\n } catch (err) {\n outputError(err, format === \"json\");\n process.exit(1);\n }\n });\n\n return traces;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import { Command } from \"commander\";\nimport {\n createClient,\n parseAttributes,\n type ClientOptions,\n} from \"../client.js\";\nimport { detectFormat, output, outputError, parseFields } from \"../output.js\";\n\ninterface LogsSearchOptions extends ClientOptions {\n json?: boolean;\n table?: boolean;\n fields?: string;\n limit?: string;\n traceId?: string;\n spanId?: string;\n service?: string;\n scope?: string;\n severityText?: string;\n severityMin?: string;\n severityMax?: string;\n body?: string;\n timestampMin?: string;\n timestampMax?: string;\n logAttr?: string[];\n resourceAttr?: string[];\n scopeAttr?: string[];\n sort?: string;\n}\n\nexport function createLogsCommand(): Command {\n const logs = new Command(\"logs\").description(\"Query logs\");\n\n logs\n .command(\"search\")\n .description(\"Search logs\")\n .option(\"-j, --json\", \"JSON output\")\n .option(\"-t, --table\", \"Table output\")\n .option(\"-f, --fields <fields>\", \"Comma-separated fields to include\")\n .option(\"-l, --limit <n>\", \"Max results\")\n .option(\"--trace-id <id>\", \"Filter by trace ID\")\n .option(\"--span-id <id>\", \"Filter by span ID\")\n .option(\"-s, --service <name>\", \"Filter by service name\")\n .option(\"--scope <name>\", \"Filter by scope name\")\n .option(\"--severity-text <level>\", \"Filter by severity text\")\n .option(\"--severity-min <n>\", \"Min severity number\")\n .option(\"--severity-max <n>\", \"Max severity number\")\n .option(\"-b, --body <text>\", \"Filter by body contains\")\n .option(\"--timestamp-min <ns>\", \"Min timestamp (nanoseconds)\")\n .option(\"--timestamp-max <ns>\", \"Max timestamp (nanoseconds)\")\n .option(\n \"--log-attr <key=value>\",\n \"Log attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\n \"--resource-attr <key=value>\",\n \"Resource attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\n \"--scope-attr <key=value>\",\n \"Scope attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\"--sort <order>\", \"Sort order (ASC|DESC)\")\n .option(\"--timeout <ms>\", \"Request timeout\")\n .option(\"-c, --config <path>\", \"Config file path\")\n .option(\"--url <url>\", \"API base URL\")\n .option(\"--token <token>\", \"Auth token\")\n .action(async (opts: LogsSearchOptions) => {\n const format = detectFormat(opts.json, opts.table);\n const fields = parseFields(opts.fields);\n try {\n const client = createClient(opts);\n const limit = opts.limit ? parseInt(opts.limit, 10) : undefined;\n\n const filter = {\n traceId: opts.traceId,\n spanId: opts.spanId,\n serviceName: opts.service,\n scopeName: opts.scope,\n severityText: opts.severityText,\n severityNumberMin: opts.severityMin\n ? parseInt(opts.severityMin, 10)\n : undefined,\n severityNumberMax: opts.severityMax\n ? parseInt(opts.severityMax, 10)\n : undefined,\n bodyContains: opts.body,\n timestampMin: opts.timestampMin,\n timestampMax: opts.timestampMax,\n logAttributes: parseAttributes(opts.logAttr),\n resourceAttributes: parseAttributes(opts.resourceAttr),\n scopeAttributes: parseAttributes(opts.scopeAttr),\n limit,\n sortOrder: opts.sort as \"ASC\" | \"DESC\" | undefined,\n };\n\n const result = await client.searchLogsPage(filter);\n output(result.data, { format, fields });\n } catch (err) {\n outputError(err, format === \"json\");\n process.exit(1);\n }\n });\n\n return logs;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","import { Command } from \"commander\";\nimport {\n createClient,\n parseAttributes,\n type ClientOptions,\n} from \"../client.js\";\nimport { detectFormat, output, outputError, parseFields } from \"../output.js\";\n\ninterface MetricsSearchOptions extends ClientOptions {\n json?: boolean;\n table?: boolean;\n fields?: string;\n limit?: string;\n type: string;\n name?: string;\n service?: string;\n scope?: string;\n timeMin?: string;\n timeMax?: string;\n attr?: string[];\n resourceAttr?: string[];\n scopeAttr?: string[];\n sort?: string;\n}\n\ninterface MetricsDiscoverOptions extends ClientOptions {\n json?: boolean;\n table?: boolean;\n fields?: string;\n}\n\nexport function createMetricsCommand(): Command {\n const metrics = new Command(\"metrics\").description(\"Query metrics\");\n\n metrics\n .command(\"search\")\n .description(\"Search metrics\")\n .requiredOption(\n \"--type <type>\",\n \"Metric type (Gauge|Sum|Histogram|ExponentialHistogram|Summary)\"\n )\n .option(\"-j, --json\", \"JSON output\")\n .option(\"-t, --table\", \"Table output\")\n .option(\"-f, --fields <fields>\", \"Comma-separated fields to include\")\n .option(\"-l, --limit <n>\", \"Max results\")\n .option(\"-n, --name <name>\", \"Filter by metric name\")\n .option(\"-s, --service <name>\", \"Filter by service name\")\n .option(\"--scope <name>\", \"Filter by scope name\")\n .option(\"--time-min <ns>\", \"Min time (nanoseconds)\")\n .option(\"--time-max <ns>\", \"Max time (nanoseconds)\")\n .option(\n \"-a, --attr <key=value>\",\n \"Attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\n \"--resource-attr <key=value>\",\n \"Resource attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\n \"--scope-attr <key=value>\",\n \"Scope attribute filter (repeatable)\",\n collect,\n []\n )\n .option(\"--sort <order>\", \"Sort order (ASC|DESC)\")\n .option(\"--timeout <ms>\", \"Request timeout\")\n .option(\"-c, --config <path>\", \"Config file path\")\n .option(\"--url <url>\", \"API base URL\")\n .option(\"--token <token>\", \"Auth token\")\n .action(async (opts: MetricsSearchOptions) => {\n const format = detectFormat(opts.json, opts.table);\n const fields = parseFields(opts.fields);\n try {\n const client = createClient(opts);\n const limit = opts.limit ? parseInt(opts.limit, 10) : undefined;\n\n const filter = {\n metricType: opts.type as\n | \"Gauge\"\n | \"Sum\"\n | \"Histogram\"\n | \"ExponentialHistogram\"\n | \"Summary\",\n metricName: opts.name,\n serviceName: opts.service,\n scopeName: opts.scope,\n timeUnixMin: opts.timeMin,\n timeUnixMax: opts.timeMax,\n attributes: parseAttributes(opts.attr),\n resourceAttributes: parseAttributes(opts.resourceAttr),\n scopeAttributes: parseAttributes(opts.scopeAttr),\n limit,\n sortOrder: opts.sort as \"ASC\" | \"DESC\" | undefined,\n };\n\n const result = await client.searchMetricsPage(filter);\n output(result.data, { format, fields });\n } catch (err) {\n outputError(err, format === \"json\");\n process.exit(1);\n }\n });\n\n metrics\n .command(\"discover\")\n .description(\"List available metrics\")\n .option(\"-j, --json\", \"JSON output\")\n .option(\"-t, --table\", \"Table output\")\n .option(\"-f, --fields <fields>\", \"Comma-separated fields to include\")\n .option(\"--timeout <ms>\", \"Request timeout\")\n .option(\"-c, --config <path>\", \"Config file path\")\n .option(\"--url <url>\", \"API base URL\")\n .option(\"--token <token>\", \"Auth token\")\n .action(async (opts: MetricsDiscoverOptions) => {\n const format = detectFormat(opts.json, opts.table);\n const fields = parseFields(opts.fields);\n try {\n const client = createClient(opts);\n const result = await client.discoverMetrics();\n output(result.metrics, { format, fields });\n } catch (err) {\n outputError(err, format === \"json\");\n process.exit(1);\n }\n });\n\n return metrics;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n","","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport { createTracesCommand } from \"./commands/traces.js\";\nimport { createLogsCommand } from \"./commands/logs.js\";\nimport { createMetricsCommand } from \"./commands/metrics.js\";\nimport pkg from \"../package.json\" with { type: \"json\" };\n\nconst program = new Command();\n\nprogram\n .name(\"@kopai/cli\")\n .description(\"Kopai CLI - Query OpenTelemetry data\")\n .version(pkg.version)\n .addCommand(createTracesCommand())\n .addCommand(createLogsCommand())\n .addCommand(createMetricsCommand());\n\nprogram.parse();\n"],"mappings":";;;;;;;;AASA,MAAM,kBAAkB;AAExB,SAAS,eAAe,MAA6B;AACnD,KAAI,CAAC,WAAW,KAAK,CAAE,QAAO;AAC9B,KAAI;EACF,MAAM,UAAU,aAAa,MAAM,QAAQ;AAC3C,SAAO,KAAK,MAAM,QAAQ;SACpB;AACN,SAAO;;;AAIX,SAAgB,WAAW,YAA6B;CAEtD,MAAM,QAAQ,aACV,CAAC,WAAW,GACZ,CAAC,KAAK,QAAQ,KAAK,EAAE,gBAAgB,EAAE,KAAK,SAAS,EAAE,gBAAgB,CAAC;AAE5E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AACZ,eAAY,KAAK,WAAW,OAAO;AACnC,WAAQ,KAAK,EAAE;;GAEjB;AAEJ,SACG,QAAQ,WAAW,CACnB,YAAY,yBAAyB,CACrC,OAAO,cAAc,cAAc,CACnC,OAAO,eAAe,eAAe,CACrC,OAAO,yBAAyB,oCAAoC,CACpE,OAAO,kBAAkB,kBAAkB,CAC3C,OAAO,uBAAuB,mBAAmB,CACjD,OAAO,eAAe,eAAe,CACrC,OAAO,mBAAmB,aAAa,CACvC,OAAO,OAAO,SAAiC;EAC9C,MAAM,SAAS,aAAa,KAAK,MAAM,KAAK,MAAM;EAClD,MAAM,SAAS,YAAY,KAAK,OAAO;AACvC,MAAI;AAGF,WADe,MADA,aAAa,KAAK,CACL,iBAAiB,EAC/B,SAAS;IAAE;IAAQ;IAAQ,CAAC;WACnC,KAAK;AACZ,eAAY,KAAK,WAAW,OAAO;AACnC,WAAQ,KAAK,EAAE;;GAEjB;AAEJ,QAAO;;AAGT,SAAS,QAAQ,OAAe,UAA8B;AAC5D,QAAO,SAAS,OAAO,CAAC,MAAM,CAAC;;;;;;;;;AE9HjC,MAAM,UAAU,IAAI,SAAS;AAE7B,QACG,KAAK,aAAa,CAClB,YAAY,uCAAuC,CACnD,QAAQC,QAAY,CACpB,WAAW,qBAAqB,CAAC,CACjC,WAAW,mBAAmB,CAAC,CAC/B,WAAW,sBAAsB,CAAC;AAErC,QAAQ,OAAO"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@kopai/cli",
3
+ "version": "0.0.0",
4
+ "description": "CLI for querying OpenTelemetry data from Kopai - traces, logs, and metrics",
5
+ "keywords": [
6
+ "opentelemetry",
7
+ "otlp",
8
+ "tracing",
9
+ "metrics",
10
+ "logs",
11
+ "observability",
12
+ "cli",
13
+ "query",
14
+ "debugging"
15
+ ],
16
+ "license": "Apache-2.0",
17
+ "author": "Vladimir Adamic",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/kopai-app/kopai-mono.git",
21
+ "directory": "packages/cli"
22
+ },
23
+ "homepage": "https://github.com/kopai-app/kopai-mono/tree/main/packages/cli#readme",
24
+ "bugs": {
25
+ "url": "https://github.com/kopai-app/kopai-mono/issues"
26
+ },
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "type": "module",
31
+ "bin": {
32
+ "kopai": "./dist/index.mjs"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "dependencies": {
38
+ "commander": "^14.0.2",
39
+ "@kopai/core": "0.0.0",
40
+ "@kopai/sdk": "0.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsdown": "^0.20.1",
44
+ "@kopai/tsconfig": "0.0.0"
45
+ },
46
+ "scripts": {
47
+ "build": "tsdown",
48
+ "dev": "tsdown --watch",
49
+ "lint": "eslint src",
50
+ "type-check": "tsc --noEmit",
51
+ "test": "vitest run"
52
+ }
53
+ }