bktide 0.0.1 → 1.0.1755267617

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,8 @@ A command-line tool for interacting with Buildkite's GraphQL API.
8
8
  npm install -g bktide
9
9
  ```
10
10
 
11
+ Once installed, use the `bktide` binary directly from your shell.
12
+
11
13
  ## Documentation
12
14
 
13
15
  - [Development Guide](docs/development.md) - Information about running and developing the CLI
@@ -22,64 +24,67 @@ npm install -g bktide
22
24
  ### Show Your Login Information
23
25
 
24
26
  ```bash
25
- npm run dev -- viewer
27
+ bktide viewer
26
28
  ```
27
29
 
28
30
  ### List Your Organizations
29
31
 
30
32
  ```bash
31
- npm run dev -- orgs
33
+ bktide orgs
32
34
  ```
33
35
 
34
36
  ### List Pipelines in an Organization
35
37
 
36
38
  ```bash
37
- npm run dev -- pipelines
39
+ bktide pipelines
38
40
  ```
39
41
 
40
42
  Additional options:
41
43
  ```bash
42
44
  # Filter by organization
43
- npm run dev -- pipelines --org your-org-slug
45
+ bktide pipelines --org your-org-slug
44
46
 
45
47
  # Limit the number of results
46
- npm run dev -- pipelines --count 20
48
+ bktide pipelines --count 20
49
+
50
+ # Filter pipelines by name
51
+ bktide pipelines --filter payments
47
52
  ```
48
53
 
49
54
  ### List Your Builds
50
55
 
51
56
  ```bash
52
- npm run dev -- builds
57
+ bktide builds
53
58
  ```
54
59
 
55
60
  Additional options:
56
61
  ```bash
57
62
  # Filter by organization
58
- npm run dev -- builds --org your-org-slug
63
+ bktide builds --org your-org-slug
59
64
 
60
65
  # Filter by pipeline
61
- npm run dev -- builds --pipeline pipeline-slug
66
+ bktide builds --pipeline pipeline-slug
62
67
 
63
68
  # Filter by branch
64
- npm run dev -- builds --branch main
69
+ bktide builds --branch main
65
70
 
66
71
  # Filter by state
67
- npm run dev -- builds --state passed
72
+ bktide builds --state passed
68
73
 
69
74
  # Pagination
70
- npm run dev -- builds --count 20 --page 2
75
+ bktide builds --count 20 --page 2
71
76
 
72
77
  # Output in JSON format
73
- npm run dev -- builds --json
78
+ bktide builds --format json
74
79
 
75
80
  # Output in Alfred-compatible JSON format
76
- npm run dev -- builds --alfred
81
+ bktide builds --format alfred
77
82
  ```
78
83
 
79
84
  ### Show Build Annotations
80
85
 
81
86
  ```bash
82
- npm run dev -- annotations <build>
87
+ bktide annotations <build>
83
88
  ```
84
89
 
85
90
  The build reference can be specified in two formats:
@@ -89,16 +94,16 @@ The build reference can be specified in two formats:
89
94
  Additional options:
90
95
  ```bash
91
96
  # Filter by context
92
- npm run dev -- annotations gusto/zenpayroll/1287418 --context rspec
97
+ bktide annotations gusto/zenpayroll/1287418 --context rspec
93
98
 
94
99
  # Output in JSON format
95
- npm run dev -- annotations gusto/zenpayroll/1287418 --format json
100
+ bktide annotations gusto/zenpayroll/1287418 --format json
96
101
 
97
102
  # Output in plain text format (default)
98
- npm run dev -- annotations https://buildkite.com/gusto/zenpayroll/builds/1287418 --format plain
103
+ bktide annotations https://buildkite.com/gusto/zenpayroll/builds/1287418 --format plain
99
104
 
100
105
  # Combine filtering and formatting
101
- npm run dev -- annotations gusto/zenpayroll/1287418 --context build-resources --format json
106
+ bktide annotations gusto/zenpayroll/1287418 --context build-resources --format json
102
107
  ```
103
108
 
104
109
  ## API Token
@@ -106,6 +111,34 @@ npm run dev -- annotations gusto/zenpayroll/1287418 --context build-resources --
106
111
  You'll need a Buildkite API token with GraphQL scopes. Create one at:
107
112
  https://buildkite.com/user/api-access-tokens
108
113
 
114
+ ### Providing your token
115
+
116
+ You can provide your token in one of these ways:
117
+
118
+ - `-t, --token <token>`: e.g. `bktide orgs --token abc123`
119
+ - `BK_TOKEN` environment variable: e.g. `BK_TOKEN=abc123 bktide orgs`
120
+ - Store once and reuse: `bktide token --store`
121
+
122
+ Manage stored token:
123
+
124
+ ```bash
125
+ bktide token --check # See if a token is stored
126
+ bktide token --reset # Remove stored token
127
+ ```
128
+
129
+ ## Global Options
130
+
131
+ These flags work with all commands:
132
+
133
+ - `--log-level <level>`: trace|debug|info|warn|error|fatal (default: info)
134
+ - `-d, --debug`: verbose debug output and detailed errors
135
+ - `--no-cache`: disable API response caching
136
+ - `--cache-ttl <ms>`: set cache TTL in milliseconds
137
+ - `--clear-cache`: clear cached data before running
138
+ - `-t, --token <token>`: provide Buildkite API token (or use `BK_TOKEN`)
139
+ - `--save-token`: save token to system keychain
140
+ - `-f, --format <format>`: plain|json|alfred (affects output and errors)
141
+
109
142
  # Logging System
110
143
 
111
144
  The CLI uses a structured logging system based on Pino. This provides several benefits:
package/dist/index.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bktide",
3
- "version": "0.0.1",
3
+ "version": "1.0.1755267617",
4
4
  "description": "Buildkite CLI tool",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -33,6 +33,14 @@
33
33
  ],
34
34
  "author": "Josh Nichols <josh@technicalpickles.com>",
35
35
  "license": "ISC",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/technicalpickles/bktide"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/technicalpickles/bktide/issues"
42
+ },
43
+ "homepage": "https://github.com/technicalpickles/bktide#readme",
36
44
  "engines": {
37
45
  "node": ">=20"
38
46
  },
@@ -50,6 +58,9 @@
50
58
  "access": "public",
51
59
  "provenance": true
52
60
  },
61
+ "overrides": {
62
+ "glob": "^10"
63
+ },
53
64
  "dependencies": {
54
65
  "@napi-rs/keyring": "^1.1.6",
55
66
  "chalk": "^5.5.0",
@@ -69,11 +80,11 @@
69
80
  "typescript": "^5.8.3"
70
81
  },
71
82
  "devDependencies": {
72
- "@graphql-codegen/cli": "^5.0.0",
73
- "@graphql-codegen/client-preset": "^4.1.0",
83
+ "@graphql-codegen/cli": "^5.0.7",
84
+ "@graphql-codegen/client-preset": "^4.8.3",
74
85
  "@graphql-codegen/typescript": "^4.0.1",
75
86
  "@graphql-codegen/typescript-graphql-request": "^6.3.0",
76
- "@graphql-codegen/typescript-operations": "^4.0.1",
87
+ "@graphql-codegen/typescript-operations": "^4.6.1",
77
88
  "@parcel/watcher": "^2.4.1",
78
89
  "@types/html-to-text": "^9.0.4",
79
90
  "@types/node": "^22.14.1",
@@ -1,80 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BuildkiteClient } from '../services/BuildkiteClient.js';
11
- export class BaseCommandHandler {
12
- constructor(token, options) {
13
- this.initialized = false;
14
- this.token = token;
15
- this.options = options || {};
16
- if (options === null || options === void 0 ? void 0 : options.debug) {
17
- console.log('Debug: BaseCommandHandler options:', JSON.stringify(options));
18
- }
19
- this.client = new BuildkiteClient(token);
20
- this.initialized = true; // Client is initialized in constructor
21
- }
22
- ensureInitialized() {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- // No additional initialization needed
25
- return Promise.resolve();
26
- });
27
- }
28
- handleError(error, debug = false) {
29
- var _a;
30
- console.error('\x1b[31m%s\x1b[0m', '🔥 Error Details:');
31
- if (error instanceof Error) {
32
- console.error('\x1b[31m%s\x1b[0m', `Message: ${error.message}`);
33
- // Always print the stack trace for proper debugging
34
- if (error.stack) {
35
- console.error('\x1b[33m%s\x1b[0m', 'Stack Trace:');
36
- console.error('\x1b[33m%s\x1b[0m', error.stack);
37
- }
38
- // If it's a GraphQL error or API error, show more details
39
- const apiError = error;
40
- if ((_a = apiError.response) === null || _a === void 0 ? void 0 : _a.errors) {
41
- console.error('\x1b[33m%s\x1b[0m', 'GraphQL Errors:');
42
- apiError.response.errors.forEach((gqlError, index) => {
43
- console.error(` Error ${index + 1}: ${gqlError.message}`);
44
- if (gqlError.path)
45
- console.error(` Path: ${gqlError.path.join('.')}`);
46
- if (gqlError.locations)
47
- console.error(` Locations: ${JSON.stringify(gqlError.locations)}`);
48
- console.error('');
49
- });
50
- }
51
- // Show request details if available and in debug mode
52
- if (debug && apiError.request) {
53
- console.error('\x1b[36m%s\x1b[0m', 'Request Details:');
54
- console.error(` URL: ${apiError.request.url || 'N/A'}`);
55
- console.error(` Method: ${apiError.request.method || 'N/A'}`);
56
- }
57
- }
58
- else if (typeof error === 'object') {
59
- console.error('\x1b[31m%s\x1b[0m', JSON.stringify(error, null, 2));
60
- }
61
- else {
62
- console.error('\x1b[31m%s\x1b[0m', 'An unknown error occurred:', error);
63
- }
64
- if (debug) {
65
- console.error('\x1b[36m%s\x1b[0m', '\nDebug Information:');
66
- console.error('\x1b[36m%s\x1b[0m', `⏰ Timestamp: ${new Date().toISOString()}`);
67
- console.error('\x1b[36m%s\x1b[0m', `🔧 Node Version: ${process.version}`);
68
- console.error('\x1b[36m%s\x1b[0m', `💻 Platform: ${process.platform} (${process.arch})`);
69
- }
70
- }
71
- // Static helper to get token from options or environment
72
- static getToken(options) {
73
- const token = options.token || process.env.BK_TOKEN;
74
- if (!token) {
75
- throw new Error('API token required. Set via --token or BK_TOKEN environment variable.');
76
- }
77
- return token;
78
- }
79
- }
80
- //# sourceMappingURL=BaseCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BaseCommandHandler.js","sourceRoot":"/","sources":["commands/BaseCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AA2BjE,MAAM,OAAgB,kBAAkB;IAMtC,YAAY,KAAa,EAAE,OAAqC;QAFtD,gBAAW,GAAY,KAAK,CAAC;QAGrC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IA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C,CAAC;YAC/E,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,oBAAoB,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;YAC1E,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,gBAAgB,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC;QAC3F,CAAC;IACH,CAAC;IAED,yDAAyD;IACzD,MAAM,CAAC,QAAQ,CAAC,OAAY;QAC1B,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;QACpD,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;QAC3F,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import { BuildkiteClient } from '../services/BuildkiteClient.js';\n\nexport interface BaseCommandOptions {\n cacheTTL?: number;\n clearCache?: boolean;\n debug?: boolean;\n filter?: string;\n format?: string;\n noCache?: boolean;\n token?: string;\n}\n\n// Extended Error interface for API and GraphQL errors\ninterface ApiError extends Error {\n response?: {\n errors?: Array<{\n message: string;\n path?: string[];\n locations?: Array<{line: number; column: number}>;\n }>;\n };\n request?: {\n url?: string;\n method?: string;\n };\n}\n\nexport abstract class BaseCommandHandler {\n protected token: string;\n protected client: BuildkiteClient;\n protected options: Partial<BaseCommandOptions>;\n protected initialized: boolean = false;\n\n constructor(token: string, options?: Partial<BaseCommandOptions>) {\n this.token = token;\n this.options = options || {};\n if (options?.debug) {\n console.log('Debug: BaseCommandHandler options:', JSON.stringify(options));\n }\n this.client = new BuildkiteClient(token);\n this.initialized = true; // Client is initialized in constructor\n }\n\n protected async ensureInitialized(): Promise<void> {\n // No additional initialization needed\n return Promise.resolve();\n }\n\n protected handleError(error: any, debug: boolean = false): void {\n console.error('\\x1b[31m%s\\x1b[0m', '🔥 Error Details:');\n \n if (error instanceof Error) {\n console.error('\\x1b[31m%s\\x1b[0m', `Message: ${error.message}`);\n \n // Always print the stack trace for proper debugging\n if (error.stack) {\n console.error('\\x1b[33m%s\\x1b[0m', 'Stack Trace:');\n console.error('\\x1b[33m%s\\x1b[0m', error.stack);\n }\n \n // If it's a GraphQL error or API error, show more details\n const apiError = error as ApiError;\n if (apiError.response?.errors) {\n console.error('\\x1b[33m%s\\x1b[0m', 'GraphQL Errors:');\n apiError.response.errors.forEach((gqlError, index) => {\n console.error(` Error ${index + 1}: ${gqlError.message}`);\n if (gqlError.path) console.error(` Path: ${gqlError.path.join('.')}`);\n if (gqlError.locations) console.error(` Locations: ${JSON.stringify(gqlError.locations)}`);\n console.error('');\n });\n }\n \n // Show request details if available and in debug mode\n if (debug && apiError.request) {\n console.error('\\x1b[36m%s\\x1b[0m', 'Request Details:');\n console.error(` URL: ${apiError.request.url || 'N/A'}`);\n console.error(` Method: ${apiError.request.method || 'N/A'}`);\n }\n } else if (typeof error === 'object') {\n console.error('\\x1b[31m%s\\x1b[0m', JSON.stringify(error, null, 2));\n } else {\n console.error('\\x1b[31m%s\\x1b[0m', 'An unknown error occurred:', error);\n }\n \n if (debug) {\n console.error('\\x1b[36m%s\\x1b[0m', '\\nDebug Information:');\n console.error('\\x1b[36m%s\\x1b[0m', `⏰ Timestamp: ${new Date().toISOString()}`);\n console.error('\\x1b[36m%s\\x1b[0m', `🔧 Node Version: ${process.version}`);\n console.error('\\x1b[36m%s\\x1b[0m', `💻 Platform: ${process.platform} (${process.arch})`);\n }\n }\n\n // Static helper to get token from options or environment\n static getToken(options: any): string {\n const token = options.token || process.env.BK_TOKEN;\n if (!token) {\n throw new Error('API token required. Set via --token or BK_TOKEN environment variable.');\n }\n return token;\n }\n} "]}
@@ -1,28 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- export class BuildCommandHandler extends BaseCommandHandler {
12
- triggerBuild(options) {
13
- return __awaiter(this, void 0, void 0, function* () {
14
- try {
15
- // Currently just logging, but would implement the actual API call
16
- console.log('Triggering build with options:', options);
17
- // Implementation would go here
18
- // TODO: Implement build triggering logic using the Buildkite API
19
- }
20
- catch (error) {
21
- console.error('Error triggering build:');
22
- this.handleError(error, options.debug);
23
- process.exit(1);
24
- }
25
- });
26
- }
27
- }
28
- //# sourceMappingURL=BuildCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"BuildCommandHandler.js","sourceRoot":"","sources":["../../src/commands/BuildCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAW7D,MAAM,OAAO,mBAAoB,SAAQ,kBAAkB;IACnD,YAAY,CAAC,OAAqB;;YACtC,IAAI,CAAC;gBACH,kEAAkE;gBAClE,OAAO,CAAC,GAAG,CAAC,gCAAgC,EAAE,OAAO,CAAC,CAAC;gBAEvD,+BAA+B;gBAC/B,iEAAiE;YAEnE,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;gBACzC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF"}
@@ -1,6 +0,0 @@
1
- export class HelloCommandHandler {
2
- execute() {
3
- console.log('Hello from bk-cli!');
4
- }
5
- }
6
- //# sourceMappingURL=HelloCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"HelloCommandHandler.js","sourceRoot":"","sources":["../../src/commands/HelloCommandHandler.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,mBAAmB;IAC9B,OAAO;QACL,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACpC,CAAC;CACF"}
@@ -1,53 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- import { GET_ORGANIZATIONS } from '../graphql/queries.js';
12
- export class OrganizationCommandHandler extends BaseCommandHandler {
13
- constructor(token, options) {
14
- super(token, options);
15
- }
16
- listOrganizations(options) {
17
- return __awaiter(this, void 0, void 0, function* () {
18
- var _a, _b;
19
- try {
20
- // Ensure initialization is complete
21
- yield this.ensureInitialized();
22
- const data = yield this.client.query(GET_ORGANIZATIONS);
23
- // Debug output if debug option is enabled
24
- if (options.debug) {
25
- console.debug('API Response:', JSON.stringify(data, null, 2));
26
- }
27
- console.log('Your organizations:');
28
- // Safely check if data and required properties exist
29
- if (((_b = (_a = data === null || data === void 0 ? void 0 : data.viewer) === null || _a === void 0 ? void 0 : _a.organizations) === null || _b === void 0 ? void 0 : _b.edges) && Array.isArray(data.viewer.organizations.edges)) {
30
- if (data.viewer.organizations.edges.length === 0) {
31
- console.log('No organizations found.');
32
- return;
33
- }
34
- data.viewer.organizations.edges.forEach((edge) => {
35
- console.log(`- ${edge.node.name} (${edge.node.slug})`);
36
- });
37
- }
38
- else {
39
- console.log('No organizations data returned from API.');
40
- if (options.debug) {
41
- console.debug('Received data structure:', Object.keys(data || {}).join(', '));
42
- }
43
- }
44
- }
45
- catch (error) {
46
- console.error('Error fetching organizations:');
47
- this.handleError(error, options.debug);
48
- process.exit(1);
49
- }
50
- });
51
- }
52
- }
53
- //# sourceMappingURL=OrganizationCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"OrganizationCommandHandler.js","sourceRoot":"/","sources":["commands/OrganizationCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAsB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAM1D,MAAM,OAAO,0BAA2B,SAAQ,kBAAkB;IAChE,YAAY,KAAa,EAAE,OAAsC;QAC/D,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxB,CAAC;IAEK,iBAAiB,CAAC,OAA4B;;;YAClD,IAAI,CAAC;gBACH,oCAAoC;gBACpC,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAE/B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAA6B,iBAAiB,CAAC,CAAC;gBAEpF,0CAA0C;gBAC1C,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;oBAClB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;gBAChE,CAAC;gBAED,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;gBAEnC,qDAAqD;gBACrD,IAAI,CAAA,MAAA,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,0CAAE,aAAa,0CAAE,KAAK,KAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;oBACzF,IAAI,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;wBACjD,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;wBACvC,OAAO;oBACT,CAAC;oBAED,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAA+B,EAAE,EAAE;wBAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;oBACzD,CAAC,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC;oBACxD,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;wBAClB,OAAO,CAAC,KAAK,CAAC,0BAA0B,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;oBAChF,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;gBAC/C,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { BaseCommandHandler, BaseCommandOptions } from './BaseCommandHandler.js';\nimport { GET_ORGANIZATIONS } from '../graphql/queries.js';\nimport { OrganizationsQueryResponse, Organization, GraphQLEdge } from '../types/index.js';\n\nexport interface OrganizationOptions extends BaseCommandOptions {\n}\n\nexport class OrganizationCommandHandler extends BaseCommandHandler {\n constructor(token: string, options?: Partial<OrganizationOptions>) {\n super(token, options);\n }\n \n async listOrganizations(options: OrganizationOptions): Promise<void> {\n try {\n // Ensure initialization is complete\n await this.ensureInitialized();\n \n const data = await this.client.query<OrganizationsQueryResponse>(GET_ORGANIZATIONS);\n \n // Debug output if debug option is enabled\n if (options.debug) {\n console.debug('API Response:', JSON.stringify(data, null, 2));\n }\n \n console.log('Your organizations:');\n \n // Safely check if data and required properties exist\n if (data?.viewer?.organizations?.edges && Array.isArray(data.viewer.organizations.edges)) {\n if (data.viewer.organizations.edges.length === 0) {\n console.log('No organizations found.');\n return;\n }\n \n data.viewer.organizations.edges.forEach((edge: GraphQLEdge<Organization>) => {\n console.log(`- ${edge.node.name} (${edge.node.slug})`);\n });\n } else {\n console.log('No organizations data returned from API.');\n if (options.debug) {\n console.debug('Received data structure:', Object.keys(data || {}).join(', '));\n }\n }\n } catch (error: any) {\n console.error('Error fetching organizations:');\n this.handleError(error, options.debug);\n process.exit(1);\n }\n }\n} "]}
@@ -1,142 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- import { GET_PIPELINES } from '../graphql/queries.js';
12
- import { getPipelineFormatter } from '../formatters/index.js';
13
- import Fuse from 'fuse.js';
14
- export class PipelineCommandHandler extends BaseCommandHandler {
15
- constructor(token, options) {
16
- super(token, options);
17
- }
18
- listPipelines(options) {
19
- return __awaiter(this, void 0, void 0, function* () {
20
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
21
- try {
22
- // Ensure initialization is complete
23
- yield this.ensureInitialized();
24
- // If organization is not specified, we need to fetch organizations first
25
- let orgs = [];
26
- if (!options.org) {
27
- // Try to fetch the user's organizations
28
- try {
29
- orgs = yield this.client.getViewerOrganizationSlugs();
30
- }
31
- catch (error) {
32
- console.error('Error fetching organizations:', error);
33
- throw new Error('Failed to determine your organizations. Please specify an organization with --org');
34
- }
35
- }
36
- else {
37
- orgs = [options.org];
38
- }
39
- // Initialize results array
40
- let allPipelines = [];
41
- // Fetch pipelines for each organization
42
- for (const org of orgs) {
43
- try {
44
- const batchSize = 500;
45
- let hasNextPage = true;
46
- let cursor = null;
47
- const limitResults = options.count !== undefined;
48
- const resultLimit = limitResults ? parseInt(options.count, 10) : Infinity;
49
- while (hasNextPage && allPipelines.length < resultLimit) {
50
- const variables = {
51
- organizationSlug: org,
52
- first: batchSize
53
- };
54
- if (cursor) {
55
- variables.after = cursor;
56
- }
57
- const data = yield this.client.query(GET_PIPELINES, variables);
58
- if ((_b = (_a = data === null || data === void 0 ? void 0 : data.organization) === null || _a === void 0 ? void 0 : _a.pipelines) === null || _b === void 0 ? void 0 : _b.edges) {
59
- // Add org information to each pipeline for display
60
- const pipelines = data.organization.pipelines.edges.map((edge) => (Object.assign(Object.assign({}, edge.node), { organization: org })));
61
- allPipelines = allPipelines.concat(pipelines);
62
- }
63
- // Check if we need to fetch more pages
64
- hasNextPage = ((_e = (_d = (_c = data === null || data === void 0 ? void 0 : data.organization) === null || _c === void 0 ? void 0 : _c.pipelines) === null || _d === void 0 ? void 0 : _d.pageInfo) === null || _e === void 0 ? void 0 : _e.hasNextPage) || false;
65
- cursor = ((_h = (_g = (_f = data === null || data === void 0 ? void 0 : data.organization) === null || _f === void 0 ? void 0 : _f.pipelines) === null || _g === void 0 ? void 0 : _g.pageInfo) === null || _h === void 0 ? void 0 : _h.endCursor) || null;
66
- if (options.debug) {
67
- console.log(`Debug: Fetched batch of ${((_l = (_k = (_j = data === null || data === void 0 ? void 0 : data.organization) === null || _j === void 0 ? void 0 : _j.pipelines) === null || _k === void 0 ? void 0 : _k.edges) === null || _l === void 0 ? void 0 : _l.length) || 0} pipelines from org ${org}`);
68
- if (hasNextPage) {
69
- console.log(`Debug: More pages available, cursor: ${cursor}`);
70
- }
71
- }
72
- // If we're limiting results, stop after getting enough
73
- if (limitResults && allPipelines.length >= resultLimit) {
74
- break;
75
- }
76
- }
77
- }
78
- catch (error) {
79
- if (options.debug) {
80
- console.error(`Error fetching pipelines for org ${org}:`, error);
81
- }
82
- // Continue to the next organization
83
- }
84
- }
85
- // Limit to the requested number of pipelines if specified
86
- if (options.count !== undefined) {
87
- allPipelines = allPipelines.slice(0, parseInt(options.count, 10));
88
- }
89
- // Filter pipelines by name if filter is specified
90
- if (options.filter) {
91
- if (options.debug) {
92
- console.log(`Debug: Applying fuzzy filter '${options.filter}' to ${allPipelines.length} pipelines`);
93
- }
94
- // Configure Fuse for fuzzy searching
95
- const fuse = new Fuse(allPipelines, {
96
- keys: ['name', 'slug'],
97
- threshold: 0.4, // Lower threshold = more strict matching
98
- includeScore: true,
99
- shouldSort: true
100
- });
101
- // Perform the fuzzy search
102
- const searchResults = fuse.search(options.filter);
103
- allPipelines = searchResults.map(result => result.item);
104
- if (options.debug) {
105
- console.log(`Debug: Filtered to ${allPipelines.length} pipelines matching '${options.filter}'`);
106
- }
107
- }
108
- try {
109
- // Get the appropriate formatter
110
- // Format precedence: command line option > constructor option > default
111
- const format = options.format || this.options.format || 'plain';
112
- if (options.debug) {
113
- console.log(`Debug: Using ${format} formatter`);
114
- }
115
- const formatter = getPipelineFormatter(format);
116
- // Format and output the results
117
- const output = formatter.formatPipelines(allPipelines, orgs, { debug: options.debug });
118
- console.log(output);
119
- }
120
- catch (formatterError) {
121
- console.error('Error formatting output:', formatterError);
122
- if (options.debug) {
123
- console.error('Error details:', formatterError);
124
- }
125
- // Fallback to simple output if formatter fails
126
- if (allPipelines.length === 0) {
127
- console.log('No pipelines found.');
128
- }
129
- else {
130
- console.log(`Found ${allPipelines.length} pipelines.`);
131
- }
132
- }
133
- }
134
- catch (error) {
135
- console.error('Error fetching pipelines:');
136
- this.handleError(error, options.debug);
137
- process.exit(1);
138
- }
139
- });
140
- }
141
- }
142
- //# sourceMappingURL=PipelineCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"PipelineCommandHandler.js","sourceRoot":"/","sources":["commands/PipelineCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAsB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,IAAI,MAAM,SAAS,CAAC;AAQ3B,MAAM,OAAO,sBAAuB,SAAQ,kBAAkB;IAC5D,YAAY,KAAa,EAAE,OAAkC;QAC3D,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxB,CAAC;IAEK,aAAa,CAAC,OAAwB;;;YAC1C,IAAI,CAAC;gBACH,oCAAoC;gBACpC,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAE/B,yEAAyE;gBACzE,IAAI,IAAI,GAAa,EAAE,CAAC;gBACxB,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;oBACjB,wCAAwC;oBACxC,IAAI,CAAC;wBACH,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,0BAA0B,EAAE,CAAC;oBACxD,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,OAAO,CAAC,KAAK,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;wBACtD,MAAM,IAAI,KAAK,CAAC,mFAAmF,CAAC,CAAC;oBACvG,CAAC;gBACH,CAAC;qBAAM,CAAC;oBACN,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;gBACvB,CAAC;gBAED,2BAA2B;gBAC3B,IAAI,YAAY,GAAe,EAAE,CAAC;gBAElC,wCAAw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,KAAK,CAAC,0BAA0B,EAAE,cAAc,CAAC,CAAC;oBAC1D,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;wBAClB,OAAO,CAAC,KAAK,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC;oBAClD,CAAC;oBACD,+CAA+C;oBAC/C,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;wBAC9B,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;oBACrC,CAAC;yBAAM,CAAC;wBACN,OAAO,CAAC,GAAG,CAAC,SAAS,YAAY,CAAC,MAAM,aAAa,CAAC,CAAC;oBACzD,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;gBAC3C,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { BaseCommandHandler, BaseCommandOptions } from './BaseCommandHandler.js';\nimport { GET_PIPELINES } from '../graphql/queries.js';\nimport { getPipelineFormatter } from '../formatters/index.js';\nimport Fuse from 'fuse.js';\nimport { Pipeline, PipelineQueryResponse } from '../types/index.js';\n\nexport interface PipelineOptions extends BaseCommandOptions {\n org?: string;\n count?: string;\n}\n\nexport class PipelineCommandHandler extends BaseCommandHandler {\n constructor(token: string, options?: Partial<PipelineOptions>) {\n super(token, options);\n }\n\n async listPipelines(options: PipelineOptions): Promise<void> {\n try {\n // Ensure initialization is complete\n await this.ensureInitialized();\n \n // If organization is not specified, we need to fetch organizations first\n let orgs: string[] = [];\n if (!options.org) {\n // Try to fetch the user's organizations\n try {\n orgs = await this.client.getViewerOrganizationSlugs();\n } catch (error) {\n console.error('Error fetching organizations:', error);\n throw new Error('Failed to determine your organizations. Please specify an organization with --org');\n }\n } else {\n orgs = [options.org];\n }\n \n // Initialize results array\n let allPipelines: Pipeline[] = [];\n \n // Fetch pipelines for each organization\n for (const org of orgs) {\n try {\n const batchSize = 500;\n let hasNextPage = true;\n let cursor: string | null = null;\n const limitResults = options.count !== undefined;\n const resultLimit = limitResults ? parseInt(options.count as string, 10) : Infinity;\n \n while (hasNextPage && allPipelines.length < resultLimit) {\n const variables: { \n organizationSlug: string;\n first: number;\n after?: string;\n } = {\n organizationSlug: org,\n first: batchSize\n };\n \n if (cursor) {\n variables.after = cursor;\n }\n \n const data = await this.client.query<PipelineQueryResponse>(GET_PIPELINES, variables);\n \n if (data?.organization?.pipelines?.edges) {\n // Add org information to each pipeline for display\n const pipelines: Pipeline[] = data.organization.pipelines.edges.map((edge) => ({\n ...edge.node,\n organization: org\n }));\n \n allPipelines = allPipelines.concat(pipelines);\n }\n \n // Check if we need to fetch more pages\n hasNextPage = data?.organization?.pipelines?.pageInfo?.hasNextPage || false;\n cursor = data?.organization?.pipelines?.pageInfo?.endCursor || null;\n \n if (options.debug) {\n console.log(`Debug: Fetched batch of ${data?.organization?.pipelines?.edges?.length || 0} pipelines from org ${org}`);\n if (hasNextPage) {\n console.log(`Debug: More pages available, cursor: ${cursor}`);\n }\n }\n \n // If we're limiting results, stop after getting enough\n if (limitResults && allPipelines.length >= resultLimit) {\n break;\n }\n }\n } catch (error) {\n if (options.debug) {\n console.error(`Error fetching pipelines for org ${org}:`, error);\n }\n // Continue to the next organization\n }\n }\n \n // Limit to the requested number of pipelines if specified\n if (options.count !== undefined) {\n allPipelines = allPipelines.slice(0, parseInt(options.count as string, 10));\n }\n \n // Filter pipelines by name if filter is specified\n if (options.filter) {\n if (options.debug) {\n console.log(`Debug: Applying fuzzy filter '${options.filter}' to ${allPipelines.length} pipelines`);\n }\n \n // Configure Fuse for fuzzy searching\n const fuse = new Fuse(allPipelines, {\n keys: ['name', 'slug'],\n threshold: 0.4, // Lower threshold = more strict matching\n includeScore: true,\n shouldSort: true\n });\n \n // Perform the fuzzy search\n const searchResults = fuse.search(options.filter);\n allPipelines = searchResults.map(result => result.item);\n \n if (options.debug) {\n console.log(`Debug: Filtered to ${allPipelines.length} pipelines matching '${options.filter}'`);\n }\n }\n \n try {\n // Get the appropriate formatter\n // Format precedence: command line option > constructor option > default\n const format = options.format || this.options.format || 'plain';\n if (options.debug) {\n console.log(`Debug: Using ${format} formatter`);\n }\n const formatter = getPipelineFormatter(format);\n \n // Format and output the results\n const output = formatter.formatPipelines(allPipelines, orgs, { debug: options.debug });\n console.log(output);\n } catch (formatterError) {\n console.error('Error formatting output:', formatterError);\n if (options.debug) {\n console.error('Error details:', formatterError);\n }\n // Fallback to simple output if formatter fails\n if (allPipelines.length === 0) {\n console.log('No pipelines found.');\n } else {\n console.log(`Found ${allPipelines.length} pipelines.`);\n }\n }\n } catch (error: any) {\n console.error('Error fetching pipelines:');\n this.handleError(error, options.debug);\n process.exit(1);\n }\n }\n} "]}
@@ -1,61 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- import { BuildkiteRestClient } from '../services/BuildkiteRestClient.js';
12
- export class UserBuildsCommandHandler extends BaseCommandHandler {
13
- constructor(token) {
14
- super(token);
15
- this.restClient = new BuildkiteRestClient(token);
16
- }
17
- execute(options) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- try {
20
- // Parse options
21
- const perPage = options.count || '10';
22
- const page = options.page || '1';
23
- // Call the REST API to get builds by user
24
- const builds = yield this.restClient.getBuilds(options.org, {
25
- creator: options.user,
26
- pipeline: options.pipeline,
27
- branch: options.branch,
28
- state: options.state,
29
- per_page: perPage,
30
- page: page
31
- });
32
- if (builds.length === 0) {
33
- console.log(`No builds found for user "${options.user}" in organization "${options.org}".`);
34
- return;
35
- }
36
- console.log(`Builds for user "${options.user}" in "${options.org}":"`);
37
- console.log('==========================================');
38
- builds.forEach((build) => {
39
- console.log(`Pipeline: ${build.pipeline.slug} #${build.number}`);
40
- console.log(`State: ${build.state}`);
41
- console.log(`Branch: ${build.branch}`);
42
- console.log(`Message: ${build.message || 'No message'}`);
43
- console.log(`Created: ${new Date(build.created_at).toLocaleString()}`);
44
- console.log(`URL: ${build.web_url}`);
45
- console.log('------------------');
46
- });
47
- console.log(`Page ${page} with ${builds.length} results. Use --page and --count options to navigate.`);
48
- }
49
- catch (error) {
50
- console.error('Error fetching builds by user:');
51
- this.handleError(error, options.debug);
52
- // Show additional debug info
53
- if (options.debug) {
54
- console.error('UserBuildsCommandHandler Error Details:', error);
55
- }
56
- process.exit(1);
57
- }
58
- });
59
- }
60
- }
61
- //# sourceMappingURL=UserBuildsCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"UserBuildsCommandHandler.js","sourceRoot":"/","sources":["commands/UserBuildsCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAczE,MAAM,OAAO,wBAAyB,SAAQ,kBAAkB;IAG9D,YAAY,KAAa;QACvB,KAAK,CAAC,KAAK,CAAC,CAAC;QACb,IAAI,CAAC,UAAU,GAAG,IAAI,mBAAmB,CAAC,KAAK,CAAC,CAAC;IACnD,CAAC;IAEK,OAAO,CAAC,OAA0B;;YACtC,IAAI,CAAC;gBACH,gBAAgB;gBAChB,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,IAAI,CAAC;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,CAAC,CAAC;oBACvE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;oBACrC,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;gBACpC,CAAC,CAAC,CAAC;gBAEH,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,SAAS,MAAM,CAAC,MAAM,uDAAuD,CAAC,CAAC;YACzG,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;gBAChD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBAEvC,6BAA6B;gBAC7B,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;oBAClB,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE,KAAK,CAAC,CAAC;gBAClE,CAAC;gBAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { BaseCommandHandler } from './BaseCommandHandler.js';\nimport { BuildkiteRestClient } from '../services/BuildkiteRestClient.js';\n\nexport interface UserBuildsOptions {\n token?: string;\n org: string;\n user: string;\n count?: string;\n page?: string;\n pipeline?: string;\n branch?: string;\n state?: string;\n debug?: boolean;\n}\n\nexport class UserBuildsCommandHandler extends BaseCommandHandler {\n private restClient: BuildkiteRestClient;\n\n constructor(token: string) {\n super(token);\n this.restClient = new BuildkiteRestClient(token);\n }\n\n async execute(options: UserBuildsOptions): Promise<void> {\n try {\n // Parse options\n const perPage = options.count || '10';\n const page = options.page || '1';\n \n // Call the REST API to get builds by user\n const builds = await this.restClient.getBuilds(options.org, {\n creator: options.user,\n pipeline: options.pipeline,\n branch: options.branch,\n state: options.state,\n per_page: perPage,\n page: page\n });\n \n if (builds.length === 0) {\n console.log(`No builds found for user \"${options.user}\" in organization \"${options.org}\".`);\n return;\n }\n \n console.log(`Builds for user \"${options.user}\" in \"${options.org}\":\"`);\n console.log('==========================================');\n \n builds.forEach((build: any) => {\n console.log(`Pipeline: ${build.pipeline.slug} #${build.number}`);\n console.log(`State: ${build.state}`);\n console.log(`Branch: ${build.branch}`);\n console.log(`Message: ${build.message || 'No message'}`);\n console.log(`Created: ${new Date(build.created_at).toLocaleString()}`);\n console.log(`URL: ${build.web_url}`);\n console.log('------------------');\n });\n \n console.log(`Page ${page} with ${builds.length} results. Use --page and --count options to navigate.`);\n } catch (error: any) {\n console.error('Error fetching builds by user:');\n this.handleError(error, options.debug);\n \n // Show additional debug info\n if (options.debug) {\n console.error('UserBuildsCommandHandler Error Details:', error);\n }\n \n process.exit(1);\n }\n }\n} "]}
@@ -1,176 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- import { GET_VIEWER } from '../graphql/queries.js';
12
- import { BuildkiteRestClient } from '../services/BuildkiteRestClient.js';
13
- import { getBuildFormatter } from '../formatters/index.js';
14
- import Fuse from 'fuse.js';
15
- // Add a custom console.debug that respects the debug flag
16
- const createDebugLogger = (isDebugEnabled) => {
17
- return (...args) => {
18
- if (isDebugEnabled) {
19
- console.log('[DEBUG]', ...args);
20
- }
21
- };
22
- };
23
- export class ViewerBuildsCommandHandler extends BaseCommandHandler {
24
- constructor(token, options) {
25
- super(token, options);
26
- // Configure REST client with the same caching options
27
- const restClientOptions = {
28
- debug: options === null || options === void 0 ? void 0 : options.debug,
29
- caching: !(options === null || options === void 0 ? void 0 : options.noCache),
30
- };
31
- // If a specific cache TTL is provided, apply it to REST client
32
- if (options === null || options === void 0 ? void 0 : options.cacheTTL) {
33
- restClientOptions.cacheTTLs = {
34
- default: options.cacheTTL,
35
- builds: options.cacheTTL,
36
- };
37
- }
38
- this.restClient = new BuildkiteRestClient(token, restClientOptions);
39
- }
40
- execute(options) {
41
- return __awaiter(this, void 0, void 0, function* () {
42
- var _a, _b;
43
- // Declare originalDebug outside the try block so it's accessible in catch
44
- const originalDebug = console.debug;
45
- try {
46
- // Override console.debug to respect the debug flag
47
- console.debug = createDebugLogger(!!options.debug);
48
- // Ensure initialization is complete
49
- yield this.ensureInitialized();
50
- const executeStartTime = process.hrtime.bigint();
51
- if (options.debug) {
52
- console.log('[DEBUG] Starting ViewerBuildsCommandHandler execution');
53
- }
54
- // First, get the current user's information using GraphQL
55
- const viewerData = yield this.client.query(GET_VIEWER);
56
- if (!((_b = (_a = viewerData === null || viewerData === void 0 ? void 0 : viewerData.viewer) === null || _a === void 0 ? void 0 : _a.user) === null || _b === void 0 ? void 0 : _b.uuid)) {
57
- throw new Error('Failed to get current user UUID information');
58
- }
59
- const userId = viewerData.viewer.user.uuid;
60
- const userName = viewerData.viewer.user.name || 'Current user';
61
- const userEmail = viewerData.viewer.user.email;
62
- // Use the REST API to get builds by the current user
63
- const perPage = options.count || '10';
64
- const page = options.page || '1';
65
- // If organization is not specified, we need to fetch organizations first
66
- let orgs = [];
67
- if (!options.org) {
68
- // Try to fetch the user's organizations
69
- try {
70
- orgs = yield this.client.getViewerOrganizationSlugs();
71
- }
72
- catch (error) {
73
- console.error('Error fetching organizations:', error);
74
- throw new Error('Failed to determine your organizations. Please specify an organization with --org');
75
- }
76
- }
77
- else {
78
- orgs = [options.org];
79
- }
80
- // Initialize results array
81
- let allBuilds = [];
82
- for (const org of orgs) {
83
- try {
84
- const builds = yield this.restClient.getBuilds(org, {
85
- creator: userId,
86
- pipeline: options.pipeline,
87
- branch: options.branch,
88
- state: options.state,
89
- per_page: perPage,
90
- page: page
91
- });
92
- if (options.debug) {
93
- console.log(`Debug: Received ${builds.length} builds from org ${org}`);
94
- }
95
- allBuilds = allBuilds.concat(builds);
96
- }
97
- catch (error) {
98
- if (options.debug) {
99
- console.error(`Error fetching builds for org ${org}:`, error);
100
- }
101
- // Continue to the next organization
102
- }
103
- }
104
- // Limit to the requested number of builds
105
- allBuilds = allBuilds.slice(0, parseInt(perPage, 10));
106
- // Apply fuzzy filter if specified
107
- if (options.filter) {
108
- if (options.debug) {
109
- console.log(`Debug: Applying fuzzy filter '${options.filter}' to ${allBuilds.length} builds`);
110
- }
111
- // Configure Fuse for fuzzy searching
112
- const fuse = new Fuse(allBuilds, {
113
- keys: ['pipeline.name', 'branch', 'message', 'creator.name', 'state'],
114
- threshold: 0.4,
115
- includeScore: true,
116
- shouldSort: true
117
- });
118
- // Perform the fuzzy search
119
- const searchResults = fuse.search(options.filter);
120
- allBuilds = searchResults.map(result => result.item);
121
- if (options.debug) {
122
- console.log(`Debug: Filtered to ${allBuilds.length} builds matching '${options.filter}'`);
123
- }
124
- }
125
- if (allBuilds.length === 0) {
126
- // Determine the format type based on options
127
- const format = options.format || 'plain';
128
- if (format === 'alfred') {
129
- // Return empty Alfred JSON format
130
- console.log(JSON.stringify({ items: [] }));
131
- return;
132
- }
133
- else if (format === 'json') {
134
- console.log(JSON.stringify([]));
135
- return;
136
- }
137
- console.log(`No builds found for ${userName} (${userEmail || userId}).`);
138
- if (!options.org) {
139
- console.log('Try specifying an organization with --org to narrow your search.');
140
- }
141
- return;
142
- }
143
- // Get the appropriate formatter based on format option
144
- const format = options.format || 'plain';
145
- const formatter = getBuildFormatter(format);
146
- const output = formatter.formatBuilds(allBuilds, { debug: options.debug });
147
- // Print the output
148
- console.log(output);
149
- if (format === 'plain') {
150
- console.log(`Showing ${allBuilds.length} builds. Use --count and --page options to see more.`);
151
- if (!options.org && orgs.length > 1) {
152
- console.log(`Searched across ${orgs.length} organizations. Use --org to filter to a specific organization.`);
153
- }
154
- }
155
- if (options.debug) {
156
- const executeDuration = Number(process.hrtime.bigint() - executeStartTime) / 1000000;
157
- console.log(`[DEBUG] ViewerBuildsCommandHandler execution completed in ${executeDuration.toFixed(2)}ms`);
158
- }
159
- // Restore original console.debug
160
- console.debug = originalDebug;
161
- }
162
- catch (error) {
163
- // Restore original console.debug in case of error
164
- console.debug = originalDebug;
165
- console.error('Error fetching builds:');
166
- this.handleError(error, options.debug);
167
- // Show additional debug info
168
- if (options.debug) {
169
- console.error('ViewerBuildsCommandHandler Error Details:', error);
170
- }
171
- process.exit(1);
172
- }
173
- });
174
- }
175
- }
176
- //# sourceMappingURL=ViewerBuildsCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ViewerBuildsCommandHandler.js","sourceRoot":"/","sources":["commands/ViewerBuildsCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAsB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,UAAU,EAAqB,MAAM,uBAAuB,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAA8B,MAAM,oCAAoC,CAAC;AAErG,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,IAAI,MAAM,SAAS,CAAC;AAG3B,0DAA0D;AAC1D,MAAM,iBAAiB,GAAG,CAAC,cAAuB,EAAE,EAAE;IACpD,OAAO,CAAC,GAAG,IAAW,EAAE,EAAE;QACxB,IAAI,cAAc,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;QAClC,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AAWF,MAAM,OAAO,0BAA2B,SAAQ,kBAAkB;IAGhE,YAAY,KAAa,EAAE,OAAsC;QAC/D,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QAEtB,sDAAsD;QACtD,MAAM,iBAAiB,GAA+B;YACpD,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CAAC,WAAW,SAAS,CAAC,MAAM,sDAAsD,CAAC,CAAC;oBAE/F,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;wBACpC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,CAAC,MAAM,iEAAiE,CAAC,CAAC;oBAC/G,CAAC;gBACH,CAAC;gBAED,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;oBAClB,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,gBAAgB,CAAC,GAAG,OAAO,CAAC;oBACrF,OAAO,CAAC,GAAG,CAAC,6DAA6D,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;gBAC3G,CAAC;gBAED,iCAAiC;gBACjC,OAAO,CAAC,KAAK,GAAG,aAAa,CAAC;YAChC,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,kDAAkD;gBAClD,OAAO,CAAC,KAAK,GAAG,aAAa,CAAC;gBAE9B,OAAO,CAAC,KAAK,CAAC,wBAAwB,CAAC,CAAC;gBACxC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBAEvC,6BAA6B;gBAC7B,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;oBAClB,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,KAAK,CAAC,CAAC;gBACpE,CAAC;gBAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { BaseCommandHandler, BaseCommandOptions } from './BaseCommandHandler.js';\nimport { GET_VIEWER, GET_VIEWER_BUILDS } from '../graphql/queries.js';\nimport { BuildkiteRestClient, BuildkiteRestClientOptions } from '../services/BuildkiteRestClient.js';\nimport { BuildkiteClient } from '../services/BuildkiteClient.js';\nimport { getBuildFormatter } from '../formatters/index.js';\nimport Fuse from 'fuse.js';\nimport { Build, ViewerBuildsQueryResponse, ViewerData } from '../types/index.js';\n\n// Add a custom console.debug that respects the debug flag\nconst createDebugLogger = (isDebugEnabled: boolean) => {\n return (...args: any[]) => {\n if (isDebugEnabled) {\n console.log('[DEBUG]', ...args);\n }\n };\n};\n\nexport interface ViewerBuildsOptions extends BaseCommandOptions {\n count?: string;\n page?: string;\n org?: string;\n pipeline?: string;\n branch?: string;\n state?: string;\n}\n\nexport class ViewerBuildsCommandHandler extends BaseCommandHandler {\n private restClient: BuildkiteRestClient;\n\n constructor(token: string, options?: Partial<ViewerBuildsOptions>) {\n super(token, options);\n \n // Configure REST client with the same caching options\n const restClientOptions: BuildkiteRestClientOptions = {\n debug: options?.debug,\n caching: !options?.noCache,\n };\n \n // If a specific cache TTL is provided, apply it to REST client\n if (options?.cacheTTL) {\n restClientOptions.cacheTTLs = {\n default: options.cacheTTL,\n builds: options.cacheTTL,\n };\n }\n \n this.restClient = new BuildkiteRestClient(token, restClientOptions);\n }\n\n async execute(options: ViewerBuildsOptions): Promise<void> {\n // Declare originalDebug outside the try block so it's accessible in catch\n const originalDebug = console.debug;\n \n try {\n // Override console.debug to respect the debug flag\n console.debug = createDebugLogger(!!options.debug);\n \n // Ensure initialization is complete\n await this.ensureInitialized();\n \n const executeStartTime = process.hrtime.bigint();\n if (options.debug) {\n console.log('[DEBUG] Starting ViewerBuildsCommandHandler execution');\n }\n \n // First, get the current user's information using GraphQL\n const viewerData = await this.client.query<ViewerData>(GET_VIEWER);\n \n if (!viewerData?.viewer?.user?.uuid) {\n throw new Error('Failed to get current user UUID information');\n }\n \n const userId = viewerData.viewer.user.uuid;\n const userName = viewerData.viewer.user.name || 'Current user';\n const userEmail = viewerData.viewer.user.email;\n \n // Use the REST API to get builds by the current user\n const perPage = options.count || '10';\n const page = options.page || '1';\n \n // If organization is not specified, we need to fetch organizations first\n let orgs: string[] = [];\n if (!options.org) {\n // Try to fetch the user's organizations\n try {\n orgs = await this.client.getViewerOrganizationSlugs();\n } catch (error) {\n console.error('Error fetching organizations:', error);\n throw new Error('Failed to determine your organizations. Please specify an organization with --org');\n }\n } else {\n orgs = [options.org];\n }\n \n // Initialize results array\n let allBuilds: Build[] = [];\n \n for (const org of orgs) {\n try {\n const builds = await this.restClient.getBuilds(org, {\n creator: userId,\n pipeline: options.pipeline,\n branch: options.branch,\n state: options.state,\n per_page: perPage,\n page: page\n });\n \n if (options.debug) {\n console.log(`Debug: Received ${builds.length} builds from org ${org}`);\n }\n \n allBuilds = allBuilds.concat(builds);\n } catch (error) {\n if (options.debug) {\n console.error(`Error fetching builds for org ${org}:`, error);\n }\n // Continue to the next organization\n }\n }\n \n // Limit to the requested number of builds\n allBuilds = allBuilds.slice(0, parseInt(perPage, 10));\n \n // Apply fuzzy filter if specified\n if (options.filter) {\n if (options.debug) {\n console.log(`Debug: Applying fuzzy filter '${options.filter}' to ${allBuilds.length} builds`);\n }\n \n // Configure Fuse for fuzzy searching\n const fuse = new Fuse(allBuilds, {\n keys: ['pipeline.name', 'branch', 'message', 'creator.name', 'state'],\n threshold: 0.4,\n includeScore: true,\n shouldSort: true\n });\n \n // Perform the fuzzy search\n const searchResults = fuse.search(options.filter);\n allBuilds = searchResults.map(result => result.item);\n \n if (options.debug) {\n console.log(`Debug: Filtered to ${allBuilds.length} builds matching '${options.filter}'`);\n }\n }\n \n if (allBuilds.length === 0) {\n // Determine the format type based on options\n const format = options.format || 'plain';\n \n if (format === 'alfred') {\n // Return empty Alfred JSON format\n console.log(JSON.stringify({ items: [] }));\n return;\n } else if (format === 'json') {\n console.log(JSON.stringify([]));\n return;\n }\n console.log(`No builds found for ${userName} (${userEmail || userId}).`);\n if (!options.org) {\n console.log('Try specifying an organization with --org to narrow your search.');\n }\n return;\n }\n \n // Get the appropriate formatter based on format option\n const format = options.format || 'plain';\n const formatter = getBuildFormatter(format);\n const output = formatter.formatBuilds(allBuilds, { debug: options.debug });\n \n // Print the output\n console.log(output);\n \n if (format === 'plain') {\n console.log(`Showing ${allBuilds.length} builds. Use --count and --page options to see more.`);\n \n if (!options.org && orgs.length > 1) {\n console.log(`Searched across ${orgs.length} organizations. Use --org to filter to a specific organization.`);\n }\n }\n \n if (options.debug) {\n const executeDuration = Number(process.hrtime.bigint() - executeStartTime) / 1000000;\n console.log(`[DEBUG] ViewerBuildsCommandHandler execution completed in ${executeDuration.toFixed(2)}ms`);\n }\n \n // Restore original console.debug\n console.debug = originalDebug;\n } catch (error: any) {\n // Restore original console.debug in case of error\n console.debug = originalDebug;\n \n console.error('Error fetching builds:');\n this.handleError(error, options.debug);\n \n // Show additional debug info\n if (options.debug) {\n console.error('ViewerBuildsCommandHandler Error Details:', error);\n }\n \n process.exit(1);\n }\n }\n}"]}
@@ -1,46 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseCommandHandler } from './BaseCommandHandler.js';
11
- import { GET_VIEWER } from '../graphql/queries.js';
12
- import { getViewerFormatter } from '../formatters/index.js';
13
- export class ViewerCommandHandler extends BaseCommandHandler {
14
- constructor(token, options) {
15
- super(token, options);
16
- }
17
- execute(options) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- try {
20
- // Ensure initialization is complete
21
- yield this.ensureInitialized();
22
- const data = yield this.client.query(GET_VIEWER);
23
- // Check if we have the expected data structure
24
- if (!(data === null || data === void 0 ? void 0 : data.viewer)) {
25
- throw new Error('Invalid response format: missing viewer data');
26
- }
27
- // Get the formatter based on the format option
28
- const format = options.format || 'plain';
29
- const formatter = getViewerFormatter(format);
30
- const output = formatter.formatViewer(data, { debug: options.debug });
31
- // Print the output
32
- console.log(output);
33
- }
34
- catch (error) {
35
- console.error('Error fetching user information:');
36
- this.handleError(error, options.debug);
37
- // Show additional debug info specific to this command
38
- if (options.debug) {
39
- console.error('Query:', GET_VIEWER);
40
- }
41
- process.exit(1);
42
- }
43
- });
44
- }
45
- }
46
- //# sourceMappingURL=ViewerCommandHandler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ViewerCommandHandler.js","sourceRoot":"/","sources":["commands/ViewerCommandHandler.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAsB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAM5D,MAAM,OAAO,oBAAqB,SAAQ,kBAAkB;IAC1D,YAAY,KAAa,EAAE,OAAgC;QACzD,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxB,CAAC;IAEK,OAAO,CAAC,OAAsB;;YAClC,IAAI,CAAC;gBACH,oCAAoC;gBACpC,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBAE/B,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAa,UAAU,CAAC,CAAC;gBAE7D,+CAA+C;gBAC/C,IAAI,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,CAAA,EAAE,CAAC;oBAClB,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBAClE,CAAC;gBAED,+CAA+C;gBAC/C,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC;gBACzC,MAAM,SAAS,GAAG,kBAAkB,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,MAAM,GAAG,SAAS,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;gBAEtE,mBAAmB;gBACnB,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACtB,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,OAAO,CAAC,KAAK,CAAC,kCAAkC,CAAC,CAAC;gBAClD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;gBAEvC,sDAAsD;gBACtD,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;oBAClB,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;gBACtC,CAAC;gBAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAClB,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { BaseCommandHandler, BaseCommandOptions } from './BaseCommandHandler.js';\nimport { GET_VIEWER } from '../graphql/queries.js';\nimport { getViewerFormatter } from '../formatters/index.js';\nimport { ViewerData } from '../types/index.js';\n\nexport interface ViewerOptions extends BaseCommandOptions {\n}\n\nexport class ViewerCommandHandler extends BaseCommandHandler {\n constructor(token: string, options?: Partial<ViewerOptions>) {\n super(token, options);\n }\n \n async execute(options: ViewerOptions): Promise<void> {\n try {\n // Ensure initialization is complete\n await this.ensureInitialized();\n \n const data = await this.client.query<ViewerData>(GET_VIEWER);\n \n // Check if we have the expected data structure\n if (!data?.viewer) {\n throw new Error('Invalid response format: missing viewer data');\n }\n \n // Get the formatter based on the format option\n const format = options.format || 'plain';\n const formatter = getViewerFormatter(format);\n const output = formatter.formatViewer(data, { debug: options.debug });\n \n // Print the output\n console.log(output);\n } catch (error: any) {\n console.error('Error fetching user information:');\n this.handleError(error, options.debug);\n \n // Show additional debug info specific to this command\n if (options.debug) {\n console.error('Query:', GET_VIEWER);\n }\n \n process.exit(1);\n }\n }\n} "]}
@@ -1,297 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { GraphQLClient } from 'graphql-request';
11
- import { CacheManager } from './CacheManager.js';
12
- import { GET_VIEWER, GET_ORGANIZATIONS, GET_PIPELINES, GET_BUILDS, GET_VIEWER_BUILDS } from '../graphql/queries.js';
13
- // These imports will be available after running GraphQL codegen
14
- import { getSdk } from '../graphql/generated/sdk.js';
15
- /**
16
- * EnhancedBuildkiteClient provides strongly-typed methods to interact with the Buildkite GraphQL API
17
- */
18
- export class EnhancedBuildkiteClient {
19
- /**
20
- * Create a new EnhancedBuildkiteClient
21
- * @param token Your Buildkite API token
22
- * @param options Configuration options
23
- */
24
- constructor(token, options, debug) {
25
- this.baseUrl = 'https://graphql.buildkite.com/v1';
26
- this.cacheManager = null;
27
- this.debug = false;
28
- this.token = token;
29
- this.debug = debug || (options === null || options === void 0 ? void 0 : options.debug) || false;
30
- if (options === null || options === void 0 ? void 0 : options.baseUrl) {
31
- this.baseUrl = options.baseUrl;
32
- }
33
- this.client = new GraphQLClient(this.baseUrl, {
34
- headers: {
35
- Authorization: `Bearer ${this.token}`,
36
- },
37
- });
38
- // Initialize the typed SDK
39
- this.typedSdk = getSdk(this.client);
40
- // Initialize cache if caching is enabled
41
- if ((options === null || options === void 0 ? void 0 : options.caching) !== false) {
42
- this.cacheManager = new CacheManager(options === null || options === void 0 ? void 0 : options.cacheTTLs);
43
- // Initialize cache and set token hash (async, but we don't wait)
44
- this.initCache();
45
- }
46
- }
47
- /**
48
- * Initialize cache asynchronously
49
- */
50
- initCache() {
51
- return __awaiter(this, void 0, void 0, function* () {
52
- if (this.cacheManager) {
53
- yield this.cacheManager.init();
54
- yield this.cacheManager.setTokenHash(this.token);
55
- }
56
- });
57
- }
58
- /**
59
- * Get the current viewer information
60
- * @returns The viewer data
61
- */
62
- getViewer() {
63
- return __awaiter(this, void 0, void 0, function* () {
64
- if (this.debug) {
65
- console.debug(`🕒 Starting GraphQL query: GetViewer`);
66
- }
67
- // Check if result is in cache
68
- if (this.cacheManager) {
69
- const cachedResult = yield this.cacheManager.get(GET_VIEWER.toString(), {});
70
- if (cachedResult) {
71
- if (this.debug) {
72
- console.debug(`✅ Served from cache: GetViewer`);
73
- }
74
- return cachedResult;
75
- }
76
- }
77
- const startTime = process.hrtime.bigint();
78
- const result = yield this.typedSdk.GetViewer();
79
- // Store result in cache if caching is enabled
80
- if (this.cacheManager) {
81
- yield this.cacheManager.set(GET_VIEWER.toString(), result, {});
82
- }
83
- const endTime = process.hrtime.bigint();
84
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
85
- if (this.debug) {
86
- console.debug(`✅ GraphQL query completed: GetViewer (${duration.toFixed(2)}ms)`);
87
- }
88
- return result;
89
- });
90
- }
91
- /**
92
- * Get the organizations for the current viewer
93
- * @returns The organizations data
94
- */
95
- getOrganizations() {
96
- return __awaiter(this, void 0, void 0, function* () {
97
- if (this.debug) {
98
- console.debug(`🕒 Starting GraphQL query: GetOrganizations`);
99
- }
100
- // Check if result is in cache
101
- if (this.cacheManager) {
102
- const cachedResult = yield this.cacheManager.get(GET_ORGANIZATIONS.toString(), {});
103
- if (cachedResult) {
104
- if (this.debug) {
105
- console.debug(`✅ Served from cache: GetOrganizations`);
106
- }
107
- return cachedResult;
108
- }
109
- }
110
- const startTime = process.hrtime.bigint();
111
- const result = yield this.typedSdk.GetOrganizations();
112
- // Store result in cache if caching is enabled
113
- if (this.cacheManager) {
114
- yield this.cacheManager.set(GET_ORGANIZATIONS.toString(), result, {});
115
- }
116
- const endTime = process.hrtime.bigint();
117
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
118
- if (this.debug) {
119
- console.debug(`✅ GraphQL query completed: GetOrganizations (${duration.toFixed(2)}ms)`);
120
- }
121
- return result;
122
- });
123
- }
124
- /**
125
- * Get the organization slugs for the current viewer
126
- * @returns An array of organization slugs the current user belongs to
127
- */
128
- getViewerOrganizationSlugs() {
129
- return __awaiter(this, void 0, void 0, function* () {
130
- var _a, _b;
131
- try {
132
- const startTime = process.hrtime.bigint();
133
- if (this.debug) {
134
- console.debug(`🕒 Starting GraphQL query: getViewerOrganizationSlugs`);
135
- }
136
- const data = yield this.getOrganizations();
137
- if (!((_b = (_a = data === null || data === void 0 ? void 0 : data.viewer) === null || _a === void 0 ? void 0 : _a.organizations) === null || _b === void 0 ? void 0 : _b.edges)) {
138
- throw new Error('Failed to fetch organizations from the API');
139
- }
140
- const orgs = data.viewer.organizations.edges.map((edge) => edge.node.slug);
141
- if (orgs.length === 0) {
142
- throw new Error('No organizations found for the current user');
143
- }
144
- const endTime = process.hrtime.bigint();
145
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
146
- if (this.debug) {
147
- console.debug(`✅ Found ${orgs.length} organizations (${duration.toFixed(2)}ms)`);
148
- }
149
- return orgs;
150
- }
151
- catch (error) {
152
- console.error('Error fetching viewer organizations:', error);
153
- throw new Error('Failed to determine your organizations');
154
- }
155
- });
156
- }
157
- /**
158
- * Get pipelines for an organization
159
- * @param organizationSlug The organization slug
160
- * @param first Number of pipelines to retrieve
161
- * @param after Cursor for pagination
162
- * @returns The pipelines data
163
- */
164
- getPipelines(organizationSlug, first, after) {
165
- return __awaiter(this, void 0, void 0, function* () {
166
- const variables = {
167
- organizationSlug,
168
- first,
169
- after,
170
- };
171
- if (this.debug) {
172
- console.debug(`🕒 Starting GraphQL query: GetPipelines for ${organizationSlug}`);
173
- }
174
- // Check if result is in cache
175
- if (this.cacheManager) {
176
- const cachedResult = yield this.cacheManager.get(GET_PIPELINES.toString(), variables);
177
- if (cachedResult) {
178
- if (this.debug) {
179
- console.debug(`✅ Served from cache: GetPipelines`);
180
- }
181
- return cachedResult;
182
- }
183
- }
184
- const startTime = process.hrtime.bigint();
185
- const result = yield this.typedSdk.GetPipelines(variables);
186
- // Store result in cache if caching is enabled
187
- if (this.cacheManager) {
188
- yield this.cacheManager.set(GET_PIPELINES.toString(), result, variables);
189
- }
190
- const endTime = process.hrtime.bigint();
191
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
192
- if (this.debug) {
193
- console.debug(`✅ GraphQL query completed: GetPipelines (${duration.toFixed(2)}ms)`);
194
- }
195
- return result;
196
- });
197
- }
198
- /**
199
- * Get builds for a pipeline
200
- * @param pipelineSlug The pipeline slug
201
- * @param organizationSlug The organization slug
202
- * @param first Number of builds to retrieve
203
- * @returns The builds data
204
- */
205
- getBuilds(pipelineSlug, organizationSlug, first) {
206
- return __awaiter(this, void 0, void 0, function* () {
207
- const variables = {
208
- pipelineSlug,
209
- organizationSlug,
210
- first,
211
- };
212
- if (this.debug) {
213
- console.debug(`🕒 Starting GraphQL query: GetBuilds for ${pipelineSlug} in ${organizationSlug}`);
214
- }
215
- // Check if result is in cache
216
- if (this.cacheManager) {
217
- const cachedResult = yield this.cacheManager.get(GET_BUILDS.toString(), variables);
218
- if (cachedResult) {
219
- if (this.debug) {
220
- console.debug(`✅ Served from cache: GetBuilds`);
221
- }
222
- return cachedResult;
223
- }
224
- }
225
- const startTime = process.hrtime.bigint();
226
- const result = yield this.typedSdk.GetBuilds(variables);
227
- // Store result in cache if caching is enabled
228
- if (this.cacheManager) {
229
- yield this.cacheManager.set(GET_BUILDS.toString(), result, variables);
230
- }
231
- const endTime = process.hrtime.bigint();
232
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
233
- if (this.debug) {
234
- console.debug(`✅ GraphQL query completed: GetBuilds (${duration.toFixed(2)}ms)`);
235
- }
236
- return result;
237
- });
238
- }
239
- /**
240
- * Get builds for the current viewer
241
- * @param first Number of builds to retrieve
242
- * @returns The viewer builds data
243
- */
244
- getViewerBuilds(first) {
245
- return __awaiter(this, void 0, void 0, function* () {
246
- const variables = {
247
- first,
248
- };
249
- if (this.debug) {
250
- console.debug(`🕒 Starting GraphQL query: GetViewerBuilds`);
251
- }
252
- // Check if result is in cache
253
- if (this.cacheManager) {
254
- const cachedResult = yield this.cacheManager.get(GET_VIEWER_BUILDS.toString(), variables);
255
- if (cachedResult) {
256
- if (this.debug) {
257
- console.debug(`✅ Served from cache: GetViewerBuilds`);
258
- }
259
- return cachedResult;
260
- }
261
- }
262
- const startTime = process.hrtime.bigint();
263
- const result = yield this.typedSdk.GetViewerBuilds(variables);
264
- // Store result in cache if caching is enabled
265
- if (this.cacheManager) {
266
- yield this.cacheManager.set(GET_VIEWER_BUILDS.toString(), result, variables);
267
- }
268
- const endTime = process.hrtime.bigint();
269
- const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds
270
- if (this.debug) {
271
- console.debug(`✅ GraphQL query completed: GetViewerBuilds (${duration.toFixed(2)}ms)`);
272
- }
273
- return result;
274
- });
275
- }
276
- /**
277
- * Clear all cache entries
278
- */
279
- clearCache() {
280
- return __awaiter(this, void 0, void 0, function* () {
281
- if (this.cacheManager) {
282
- yield this.cacheManager.clear();
283
- }
284
- });
285
- }
286
- /**
287
- * Invalidate a specific cache type
288
- */
289
- invalidateCache(type) {
290
- return __awaiter(this, void 0, void 0, function* () {
291
- if (this.cacheManager) {
292
- yield this.cacheManager.invalidateType(type);
293
- }
294
- });
295
- }
296
- }
297
- //# sourceMappingURL=EnhancedBuildkiteClient.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"EnhancedBuildkiteClient.js","sourceRoot":"/","sources":["services/EnhancedBuildkiteClient.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB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OAAO,GAAG,SAAS,CAAC,GAAG,OAAO,CAAC,CAAC,0BAA0B;YAClF,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,+CAA+C,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;YACzF,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KAAA;IAED;;OAEG;IACU,UAAU;;YACrB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;gBACtB,MAAM,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;YAClC,CAAC;QACH,CAAC;KAAA;IAED;;OAEG;IACU,eAAe,CAAC,IAAY;;YACvC,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;gBACtB,MAAM,IAAI,CAAC,YAAY,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC;KAAA;CACF","sourcesContent":["import { GraphQLClient } from 'graphql-request';\nimport { CacheManager } from './CacheManager.js';\nimport { BuildkiteClientOptions } from './BuildkiteClient.js';\nimport { \n GET_VIEWER, \n GET_ORGANIZATIONS, \n GET_PIPELINES, \n GET_BUILDS, \n GET_VIEWER_BUILDS \n} from '../graphql/queries.js';\n// These imports will be available after running GraphQL codegen\nimport { \n GetViewerQuery, \n GetOrganizationsQuery, \n GetPipelinesQuery,\n GetPipelinesQueryVariables,\n GetBuildsQuery,\n GetBuildsQueryVariables,\n GetViewerBuildsQuery,\n GetViewerBuildsQueryVariables,\n getSdk\n} from '../graphql/generated/sdk.js';\n\n/**\n * EnhancedBuildkiteClient provides strongly-typed methods to interact with the Buildkite GraphQL API\n */\nexport class EnhancedBuildkiteClient {\n private client: GraphQLClient;\n private typedSdk: ReturnType<typeof getSdk>;\n private token: string;\n private baseUrl: string = 'https://graphql.buildkite.com/v1';\n private cacheManager: CacheManager | null = null;\n private debug: boolean = false;\n\n /**\n * Create a new EnhancedBuildkiteClient\n * @param token Your Buildkite API token\n * @param options Configuration options\n */\n constructor(token: string, options?: BuildkiteClientOptions, debug?: boolean) {\n this.token = token;\n this.debug = debug || options?.debug || false;\n if (options?.baseUrl) {\n this.baseUrl = options.baseUrl;\n }\n\n this.client = new GraphQLClient(this.baseUrl, {\n headers: {\n Authorization: `Bearer ${this.token}`,\n },\n });\n\n // Initialize the typed SDK\n this.typedSdk = getSdk(this.client);\n\n // Initialize cache if caching is enabled\n if (options?.caching !== false) {\n this.cacheManager = new CacheManager(options?.cacheTTLs);\n // Initialize cache and set token hash (async, but we don't wait)\n this.initCache();\n }\n }\n\n /**\n * Initialize cache asynchronously\n */\n private async initCache(): Promise<void> {\n if (this.cacheManager) {\n await this.cacheManager.init();\n await this.cacheManager.setTokenHash(this.token);\n }\n }\n\n /**\n * Get the current viewer information\n * @returns The viewer data\n */\n public async getViewer(): Promise<GetViewerQuery> {\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: GetViewer`);\n }\n\n // Check if result is in cache\n if (this.cacheManager) {\n const cachedResult = await this.cacheManager.get<GetViewerQuery>(GET_VIEWER.toString(), {});\n if (cachedResult) {\n if (this.debug) {\n console.debug(`✅ Served from cache: GetViewer`);\n }\n return cachedResult;\n }\n }\n\n const startTime = process.hrtime.bigint();\n const result = await this.typedSdk.GetViewer();\n\n // Store result in cache if caching is enabled\n if (this.cacheManager) {\n await this.cacheManager.set(GET_VIEWER.toString(), result, {});\n }\n\n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ GraphQL query completed: GetViewer (${duration.toFixed(2)}ms)`);\n }\n\n return result;\n }\n\n /**\n * Get the organizations for the current viewer\n * @returns The organizations data\n */\n public async getOrganizations(): Promise<GetOrganizationsQuery> {\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: GetOrganizations`);\n }\n\n // Check if result is in cache\n if (this.cacheManager) {\n const cachedResult = await this.cacheManager.get<GetOrganizationsQuery>(GET_ORGANIZATIONS.toString(), {});\n if (cachedResult) {\n if (this.debug) {\n console.debug(`✅ Served from cache: GetOrganizations`);\n }\n return cachedResult;\n }\n }\n\n const startTime = process.hrtime.bigint();\n const result = await this.typedSdk.GetOrganizations();\n\n // Store result in cache if caching is enabled\n if (this.cacheManager) {\n await this.cacheManager.set(GET_ORGANIZATIONS.toString(), result, {});\n }\n\n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ GraphQL query completed: GetOrganizations (${duration.toFixed(2)}ms)`);\n }\n\n return result;\n }\n\n /**\n * Get the organization slugs for the current viewer\n * @returns An array of organization slugs the current user belongs to\n */\n public async getViewerOrganizationSlugs(): Promise<string[]> {\n try {\n const startTime = process.hrtime.bigint();\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: getViewerOrganizationSlugs`);\n }\n \n const data = await this.getOrganizations();\n \n if (!data?.viewer?.organizations?.edges) {\n throw new Error('Failed to fetch organizations from the API');\n }\n \n const orgs = data.viewer.organizations.edges.map((edge: { node: { slug: string } }) => edge.node.slug);\n \n if (orgs.length === 0) {\n throw new Error('No organizations found for the current user');\n }\n \n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ Found ${orgs.length} organizations (${duration.toFixed(2)}ms)`);\n }\n \n return orgs;\n } catch (error) {\n console.error('Error fetching viewer organizations:', error);\n throw new Error('Failed to determine your organizations');\n }\n }\n\n /**\n * Get pipelines for an organization\n * @param organizationSlug The organization slug\n * @param first Number of pipelines to retrieve\n * @param after Cursor for pagination\n * @returns The pipelines data\n */\n public async getPipelines(\n organizationSlug: string, \n first?: number, \n after?: string\n ): Promise<GetPipelinesQuery> {\n const variables: GetPipelinesQueryVariables = {\n organizationSlug,\n first,\n after,\n };\n\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: GetPipelines for ${organizationSlug}`);\n }\n\n // Check if result is in cache\n if (this.cacheManager) {\n const cachedResult = await this.cacheManager.get<GetPipelinesQuery>(GET_PIPELINES.toString(), variables);\n if (cachedResult) {\n if (this.debug) {\n console.debug(`✅ Served from cache: GetPipelines`);\n }\n return cachedResult;\n }\n }\n\n const startTime = process.hrtime.bigint();\n const result = await this.typedSdk.GetPipelines(variables);\n\n // Store result in cache if caching is enabled\n if (this.cacheManager) {\n await this.cacheManager.set(GET_PIPELINES.toString(), result, variables);\n }\n\n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ GraphQL query completed: GetPipelines (${duration.toFixed(2)}ms)`);\n }\n\n return result;\n }\n\n /**\n * Get builds for a pipeline\n * @param pipelineSlug The pipeline slug\n * @param organizationSlug The organization slug\n * @param first Number of builds to retrieve\n * @returns The builds data\n */\n public async getBuilds(\n pipelineSlug: string,\n organizationSlug: string,\n first?: number\n ): Promise<GetBuildsQuery> {\n const variables: GetBuildsQueryVariables = {\n pipelineSlug,\n organizationSlug,\n first,\n };\n\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: GetBuilds for ${pipelineSlug} in ${organizationSlug}`);\n }\n\n // Check if result is in cache\n if (this.cacheManager) {\n const cachedResult = await this.cacheManager.get<GetBuildsQuery>(GET_BUILDS.toString(), variables);\n if (cachedResult) {\n if (this.debug) {\n console.debug(`✅ Served from cache: GetBuilds`);\n }\n return cachedResult;\n }\n }\n\n const startTime = process.hrtime.bigint();\n const result = await this.typedSdk.GetBuilds(variables);\n\n // Store result in cache if caching is enabled\n if (this.cacheManager) {\n await this.cacheManager.set(GET_BUILDS.toString(), result, variables);\n }\n\n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ GraphQL query completed: GetBuilds (${duration.toFixed(2)}ms)`);\n }\n\n return result;\n }\n\n /**\n * Get builds for the current viewer\n * @param first Number of builds to retrieve\n * @returns The viewer builds data\n */\n public async getViewerBuilds(first: number): Promise<GetViewerBuildsQuery> {\n const variables: GetViewerBuildsQueryVariables = {\n first,\n };\n\n if (this.debug) {\n console.debug(`🕒 Starting GraphQL query: GetViewerBuilds`);\n }\n\n // Check if result is in cache\n if (this.cacheManager) {\n const cachedResult = await this.cacheManager.get<GetViewerBuildsQuery>(GET_VIEWER_BUILDS.toString(), variables);\n if (cachedResult) {\n if (this.debug) {\n console.debug(`✅ Served from cache: GetViewerBuilds`);\n }\n return cachedResult;\n }\n }\n\n const startTime = process.hrtime.bigint();\n const result = await this.typedSdk.GetViewerBuilds(variables);\n\n // Store result in cache if caching is enabled\n if (this.cacheManager) {\n await this.cacheManager.set(GET_VIEWER_BUILDS.toString(), result, variables);\n }\n\n const endTime = process.hrtime.bigint();\n const duration = Number(endTime - startTime) / 1000000; // Convert to milliseconds\n if (this.debug) {\n console.debug(`✅ GraphQL query completed: GetViewerBuilds (${duration.toFixed(2)}ms)`);\n }\n\n return result;\n }\n\n /**\n * Clear all cache entries\n */\n public async clearCache(): Promise<void> {\n if (this.cacheManager) {\n await this.cacheManager.clear();\n }\n }\n\n /**\n * Invalidate a specific cache type\n */\n public async invalidateCache(type: string): Promise<void> {\n if (this.cacheManager) {\n await this.cacheManager.invalidateType(type);\n }\n }\n} "]}