infrahub-sdk 0.0.1 → 0.0.2

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.
Files changed (45) hide show
  1. package/.github/workflows/publish.yml +21 -0
  2. package/package.json +1 -1
  3. package/src/index.ts +0 -3
  4. package/dist/branch.d.ts +0 -36
  5. package/dist/branch.js +0 -136
  6. package/dist/cjs/index.js +0 -65
  7. package/dist/cjs/index.js.map +0 -7
  8. package/dist/client.d.ts +0 -6
  9. package/dist/client.js +0 -35
  10. package/dist/constants.d.ts +0 -0
  11. package/dist/constants.js +0 -1
  12. package/dist/esm/index.js +0 -32
  13. package/dist/esm/index.js.map +0 -7
  14. package/dist/graphql.d.ts +0 -31
  15. package/dist/graphql.js +0 -174
  16. package/dist/index.d.ts +0 -47
  17. package/dist/index.js +0 -115
  18. package/dist/index.test.d.ts +0 -1
  19. package/dist/index.test.js +0 -62
  20. package/dist/types/client.d.ts +0 -7
  21. package/dist/types/client.d.ts.map +0 -1
  22. package/dist/types/constants.d.ts +0 -1
  23. package/dist/types/constants.d.ts.map +0 -1
  24. package/dist/types/index.d.ts +0 -2
  25. package/dist/types/index.d.ts.map +0 -1
  26. package/dist/types/utils/auth.d.ts +0 -1
  27. package/dist/types/utils/auth.d.ts.map +0 -1
  28. package/dist/types/utils/error-handling.d.ts +0 -1
  29. package/dist/types/utils/error-handling.d.ts.map +0 -1
  30. package/dist/types/utils/index.d.ts +0 -1
  31. package/dist/types/utils/index.d.ts.map +0 -1
  32. package/dist/types/utils/validation.d.ts +0 -1
  33. package/dist/types/utils/validation.d.ts.map +0 -1
  34. package/dist/types.d.ts +0 -3144
  35. package/dist/types.js +0 -6
  36. package/dist/utils/auth.d.ts +0 -0
  37. package/dist/utils/auth.js +0 -1
  38. package/dist/utils/error-handling.d.ts +0 -0
  39. package/dist/utils/error-handling.js +0 -1
  40. package/dist/utils/index.d.ts +0 -0
  41. package/dist/utils/index.js +0 -1
  42. package/dist/utils/validation.d.ts +0 -0
  43. package/dist/utils/validation.js +0 -1
  44. package/src/branch.ts +0 -161
  45. package/src/graphql.ts +0 -266
@@ -0,0 +1,21 @@
1
+ name: Publish Package to npmjs
2
+ on:
3
+ release:
4
+ types: [published]
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ permissions:
9
+ contents: read
10
+ id-token: write
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ # Setup .npmrc file to publish to npm
14
+ - uses: actions/setup-node@v4
15
+ with:
16
+ node-version: '20.x'
17
+ registry-url: 'https://registry.npmjs.org'
18
+ - run: npm ci
19
+ - run: npm publish
20
+ env:
21
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "infrahub-sdk",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "A client SDK for the Infrahub API.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
package/src/index.ts CHANGED
@@ -6,7 +6,6 @@ export type SafeResult<T> =
6
6
  import createClient from 'openapi-fetch';
7
7
  import { GraphQLClient, Variables } from 'graphql-request';
8
8
  import type { paths } from './types';
9
- import { InfrahubBranchManager } from './branch';
10
9
 
11
10
  // Re-export gql and all exports from graphql-request
12
11
  export * from 'graphql-request';
@@ -27,13 +26,11 @@ export class InfrahubClient {
27
26
  private baseUrl: string;
28
27
  private token?: string;
29
28
  public defaultBranch: string;
30
- public branch: InfrahubBranchManager;
31
29
 
32
30
  constructor(options: InfrahubClientOptions) {
33
31
  this.baseUrl = options.address;
34
32
  this.token = options.token;
35
33
  this.defaultBranch = options.branch || DEFAULT_BRANCH_NAME;
36
- this.branch = new InfrahubBranchManager(this);
37
34
 
38
35
  // Initialize the openapi-fetch client
39
36
 
package/dist/branch.d.ts DELETED
@@ -1,36 +0,0 @@
1
- import { InfrahubClient } from './index';
2
- interface Branch {
3
- id: string;
4
- name: string;
5
- description: string;
6
- origin_branch: string;
7
- branched_from: string;
8
- is_default: boolean;
9
- sync_with_git: boolean;
10
- has_schema_changes: boolean;
11
- }
12
- export interface BranchCreateInput {
13
- name: string;
14
- description?: string;
15
- sync_with_git?: boolean;
16
- wait_until_completion?: boolean;
17
- }
18
- export declare class BranchNotFoundError extends Error {
19
- constructor(identifier: string);
20
- }
21
- export declare class InfrahubBranchManager {
22
- private client;
23
- constructor(client: InfrahubClient);
24
- /**
25
- * Fetches all branches using GraphQL and returns an object mapping branch names to branch data.
26
- */
27
- all(): Promise<Record<string, Branch>>;
28
- /**
29
- * Fetches a specific branch by name.
30
- * @param branchName The name of the branch to fetch.
31
- */
32
- get(branchName: string): Promise<Branch | null>;
33
- create(input: BranchCreateInput): Promise<Branch>;
34
- delete(branchName: string): Promise<boolean>;
35
- }
36
- export {};
package/dist/branch.js DELETED
@@ -1,136 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InfrahubBranchManager = exports.BranchNotFoundError = void 0;
4
- const index_1 = require("./index");
5
- const graphql_1 = require("./graphql");
6
- class BranchNotFoundError extends Error {
7
- constructor(identifier) {
8
- super(`Branch not found: ${identifier}`);
9
- this.name = 'BranchNotFoundError';
10
- }
11
- }
12
- exports.BranchNotFoundError = BranchNotFoundError;
13
- const MUTATION_QUERY_TASK = { ok: null, task: { id: null } };
14
- const MUTATION_QUERY_DATA = {
15
- ok: null,
16
- object: {
17
- id: null,
18
- name: null,
19
- description: null,
20
- origin_branch: null,
21
- branched_from: null,
22
- is_default: null,
23
- sync_with_git: null,
24
- has_schema_changes: null
25
- }
26
- };
27
- // InfrahubBranchManager class to manage branches via GraphQL
28
- class InfrahubBranchManager {
29
- constructor(client) {
30
- this.client = client;
31
- }
32
- /**
33
- * Fetches all branches using GraphQL and returns an object mapping branch names to branch data.
34
- */
35
- async all() {
36
- const query = (0, index_1.gql) `
37
- query BranchQuery {
38
- Branch {
39
- id
40
- name
41
- description
42
- origin_branch
43
- branched_from
44
- is_default
45
- sync_with_git
46
- has_schema_changes
47
- }
48
- }
49
- `;
50
- const response = await this.client.executeGraphQL(query);
51
- const branches = response.Branch || [];
52
- const result = {};
53
- for (const branch of branches) {
54
- result[branch.name] = branch;
55
- }
56
- return result;
57
- }
58
- /**
59
- * Fetches a specific branch by name.
60
- * @param branchName The name of the branch to fetch.
61
- */
62
- async get(branchName) {
63
- const query = (0, index_1.gql) `
64
- query BranchQuery($name: String!) {
65
- Branch(name: $name) {
66
- id
67
- name
68
- description
69
- origin_branch
70
- branched_from
71
- is_default
72
- sync_with_git
73
- has_schema_changes
74
- }
75
- }
76
- `;
77
- const response = await this.client.executeGraphQL(query, {
78
- name: branchName
79
- });
80
- const branchArr = response.Branch || [];
81
- if (!branchArr.length) {
82
- throw new BranchNotFoundError(branchName);
83
- }
84
- return branchArr[0];
85
- }
86
- async create(input) {
87
- const inputData = {
88
- background_execution: input.wait_until_completion,
89
- data: {
90
- name: input.name,
91
- description: input.description,
92
- sync_with_git: input.sync_with_git
93
- }
94
- };
95
- // set mutation query to MUTATION_QUERY_TASK if brackground_execution is true
96
- const mutationQuery = input.wait_until_completion
97
- ? MUTATION_QUERY_TASK
98
- : MUTATION_QUERY_DATA;
99
- const mutation = new graphql_1.Mutation({
100
- mutation: 'BranchCreate',
101
- inputData: inputData,
102
- query: mutationQuery,
103
- name: 'CreateBranch'
104
- });
105
- // You may want to remove this log in production
106
- console.log(mutation.render());
107
- const response = await this.client.executeGraphQL(mutation.render(), {
108
- input: inputData
109
- });
110
- // Adjust the response path as needed based on your API
111
- const branchData = response.BranchCreate?.object || response.BranchCreate?.task || null;
112
- if (!branchData) {
113
- throw new Error('Branch creation failed');
114
- }
115
- return branchData;
116
- }
117
- async delete(branchName) {
118
- const inputData = {
119
- data: {
120
- name: branchName
121
- }
122
- };
123
- const mutation = new graphql_1.Mutation({
124
- mutation: 'BranchDelete',
125
- inputData: inputData,
126
- query: { ok: null },
127
- name: 'DeleteBranch'
128
- });
129
- const response = await this.client.executeGraphQL(mutation.render(), {
130
- input: inputData
131
- });
132
- console.log(response);
133
- return !!(response.BranchDelete && response.BranchDelete.ok);
134
- }
135
- }
136
- exports.InfrahubBranchManager = InfrahubBranchManager;
package/dist/cjs/index.js DELETED
@@ -1,65 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- InfrahubClient: () => InfrahubClient
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
-
37
- // src/client.ts
38
- var import_axios = __toESM(require("axios"), 1);
39
- var InfrahubClient = class {
40
- constructor(baseURL, token) {
41
- this.axiosInstance = import_axios.default.create({
42
- baseURL,
43
- headers: {
44
- "Content-Type": "application/json"
45
- }
46
- });
47
- if (token) {
48
- this.setAuthToken(token);
49
- }
50
- }
51
- setAuthToken(token) {
52
- this.axiosInstance.defaults.headers.common["X-INFRAHUB-KEY"] = token;
53
- }
54
- // get info from /api/info endpoint
55
- async getInfo() {
56
- try {
57
- const response = await this.axiosInstance.get("/api/info");
58
- return response.data;
59
- } catch (error) {
60
- console.error("Error fetching info:", error);
61
- throw error;
62
- }
63
- }
64
- };
65
- //# sourceMappingURL=index.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/index.ts", "../../src/client.ts"],
4
- "sourcesContent": ["export * from './client';", "import axios, { AxiosInstance } from 'axios';\n\nexport class InfrahubClient {\n private axiosInstance: AxiosInstance;\n\n constructor(baseURL: string, token?: string) {\n this.axiosInstance = axios.create({\n baseURL,\n headers: {\n 'Content-Type': 'application/json',\n }\n });\n if (token) {\n this.setAuthToken(token);\n }\n\n }\n\n public setAuthToken(token: string) {\n this.axiosInstance.defaults.headers.common[\"X-INFRAHUB-KEY\"] = token;\n }\n\n // get info from /api/info endpoint\n public async getInfo() {\n try {\n const response = await this.axiosInstance.get('/api/info');\n return response.data;\n } catch (error) {\n console.error('Error fetching info:', error);\n throw error;\n }\n }\n}"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAqC;AAE9B,IAAM,iBAAN,MAAqB;AAAA,EAGxB,YAAY,SAAiB,OAAgB;AACzC,SAAK,gBAAgB,aAAAA,QAAM,OAAO;AAAA,MAC9B;AAAA,MACA,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,IACJ,CAAC;AACD,QAAI,OAAO;AACP,WAAK,aAAa,KAAK;AAAA,IAC3B;AAAA,EAEJ;AAAA,EAEO,aAAa,OAAe;AAC/B,SAAK,cAAc,SAAS,QAAQ,OAAO,gBAAgB,IAAI;AAAA,EACnE;AAAA;AAAA,EAGA,MAAa,UAAU;AACnB,QAAI;AACA,YAAM,WAAW,MAAM,KAAK,cAAc,IAAI,WAAW;AACzD,aAAO,SAAS;AAAA,IACpB,SAAS,OAAO;AACZ,cAAQ,MAAM,wBAAwB,KAAK;AAC3C,YAAM;AAAA,IACV;AAAA,EACJ;AACJ;",
6
- "names": ["axios"]
7
- }
package/dist/client.d.ts DELETED
@@ -1,6 +0,0 @@
1
- export declare class InfrahubClient {
2
- private axiosInstance;
3
- constructor(baseURL: string, token?: string);
4
- setAuthToken(token: string): void;
5
- getInfo(): Promise<any>;
6
- }
package/dist/client.js DELETED
@@ -1,35 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.InfrahubClient = void 0;
7
- const axios_1 = __importDefault(require("axios"));
8
- class InfrahubClient {
9
- constructor(baseURL, token) {
10
- this.axiosInstance = axios_1.default.create({
11
- baseURL,
12
- headers: {
13
- 'Content-Type': 'application/json',
14
- }
15
- });
16
- if (token) {
17
- this.setAuthToken(token);
18
- }
19
- }
20
- setAuthToken(token) {
21
- this.axiosInstance.defaults.headers.common["X-INFRAHUB-KEY"] = token;
22
- }
23
- // get info from /api/info endpoint
24
- async getInfo() {
25
- try {
26
- const response = await this.axiosInstance.get('/api/info');
27
- return response.data;
28
- }
29
- catch (error) {
30
- console.error('Error fetching info:', error);
31
- throw error;
32
- }
33
- }
34
- }
35
- exports.InfrahubClient = InfrahubClient;
File without changes
package/dist/constants.js DELETED
@@ -1 +0,0 @@
1
- "use strict";
package/dist/esm/index.js DELETED
@@ -1,32 +0,0 @@
1
- // src/client.ts
2
- import axios from "axios";
3
- var InfrahubClient = class {
4
- constructor(baseURL, token) {
5
- this.axiosInstance = axios.create({
6
- baseURL,
7
- headers: {
8
- "Content-Type": "application/json"
9
- }
10
- });
11
- if (token) {
12
- this.setAuthToken(token);
13
- }
14
- }
15
- setAuthToken(token) {
16
- this.axiosInstance.defaults.headers.common["X-INFRAHUB-KEY"] = token;
17
- }
18
- // get info from /api/info endpoint
19
- async getInfo() {
20
- try {
21
- const response = await this.axiosInstance.get("/api/info");
22
- return response.data;
23
- } catch (error) {
24
- console.error("Error fetching info:", error);
25
- throw error;
26
- }
27
- }
28
- };
29
- export {
30
- InfrahubClient
31
- };
32
- //# sourceMappingURL=index.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/client.ts"],
4
- "sourcesContent": ["import axios, { AxiosInstance } from 'axios';\n\nexport class InfrahubClient {\n private axiosInstance: AxiosInstance;\n\n constructor(baseURL: string, token?: string) {\n this.axiosInstance = axios.create({\n baseURL,\n headers: {\n 'Content-Type': 'application/json',\n }\n });\n if (token) {\n this.setAuthToken(token);\n }\n\n }\n\n public setAuthToken(token: string) {\n this.axiosInstance.defaults.headers.common[\"X-INFRAHUB-KEY\"] = token;\n }\n\n // get info from /api/info endpoint\n public async getInfo() {\n try {\n const response = await this.axiosInstance.get('/api/info');\n return response.data;\n } catch (error) {\n console.error('Error fetching info:', error);\n throw error;\n }\n }\n}"],
5
- "mappings": ";AAAA,OAAO,WAA8B;AAE9B,IAAM,iBAAN,MAAqB;AAAA,EAGxB,YAAY,SAAiB,OAAgB;AACzC,SAAK,gBAAgB,MAAM,OAAO;AAAA,MAC9B;AAAA,MACA,SAAS;AAAA,QACL,gBAAgB;AAAA,MACpB;AAAA,IACJ,CAAC;AACD,QAAI,OAAO;AACP,WAAK,aAAa,KAAK;AAAA,IAC3B;AAAA,EAEJ;AAAA,EAEO,aAAa,OAAe;AAC/B,SAAK,cAAc,SAAS,QAAQ,OAAO,gBAAgB,IAAI;AAAA,EACnE;AAAA;AAAA,EAGA,MAAa,UAAU;AACnB,QAAI;AACA,YAAM,WAAW,MAAM,KAAK,cAAc,IAAI,WAAW;AACzD,aAAO,SAAS;AAAA,IACpB,SAAS,OAAO;AACZ,cAAQ,MAAM,wBAAwB,KAAK;AAC3C,YAAM;AAAA,IACV;AAAA,EACJ;AACJ;",
6
- "names": []
7
- }
package/dist/graphql.d.ts DELETED
@@ -1,31 +0,0 @@
1
- export type VariableType = string | number | boolean | null | undefined | VariableType[] | Record<string, any>;
2
- export declare function convertToGraphqlAsString(value: VariableType, convertEnum?: boolean): string;
3
- export declare function renderVariablesToString(data: Record<string, any>): string;
4
- export declare function renderQueryBlock(data: Record<string, any>, offset?: number, indentation?: number, convertEnum?: boolean): string[];
5
- export declare function renderInputBlock(data: Record<string, any>, offset?: number, indentation?: number, convertEnum?: boolean): string[];
6
- export declare class BaseGraphQLQuery {
7
- queryType: string;
8
- indentation: number;
9
- query: Record<string, any>;
10
- variables?: Record<string, any>;
11
- name: string;
12
- constructor(query: Record<string, any>, variables?: Record<string, any>, name?: string);
13
- renderFirstLine(): string;
14
- }
15
- export declare class Query extends BaseGraphQLQuery {
16
- queryType: string;
17
- render(convertEnum?: boolean): string;
18
- }
19
- export declare class Mutation extends BaseGraphQLQuery {
20
- queryType: string;
21
- inputData: Record<string, any>;
22
- mutation: string;
23
- constructor({ mutation, inputData, query, variables, name }: {
24
- mutation: string;
25
- inputData: Record<string, any>;
26
- query: Record<string, any>;
27
- variables?: Record<string, any>;
28
- name?: string;
29
- });
30
- render(convertEnum?: boolean): string;
31
- }
package/dist/graphql.js DELETED
@@ -1,174 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Mutation = exports.Query = exports.BaseGraphQLQuery = void 0;
4
- exports.convertToGraphqlAsString = convertToGraphqlAsString;
5
- exports.renderVariablesToString = renderVariablesToString;
6
- exports.renderQueryBlock = renderQueryBlock;
7
- exports.renderInputBlock = renderInputBlock;
8
- function convertToGraphqlAsString(value, convertEnum = false) {
9
- if (typeof value === 'string' && value.startsWith('$')) {
10
- return value;
11
- }
12
- if (typeof value === 'object' &&
13
- value &&
14
- 'constructor' in value &&
15
- value.constructor.name === 'Enum') {
16
- // TypeScript enums are not runtime objects, so you may need to handle this differently
17
- return convertEnum
18
- ? convertToGraphqlAsString(value.value, true)
19
- : value.name;
20
- }
21
- if (typeof value === 'string') {
22
- return `"${value}"`;
23
- }
24
- if (typeof value === 'boolean') {
25
- return value ? 'true' : 'false';
26
- }
27
- if (Array.isArray(value)) {
28
- const valuesAsString = value.map((item) => convertToGraphqlAsString(item, convertEnum));
29
- return `[${valuesAsString.join(', ')}]`;
30
- }
31
- if (typeof value === 'object' && value !== null) {
32
- const entries = Object.entries(value).map(([key, val]) => `${key}: ${convertToGraphqlAsString(val, convertEnum)}`);
33
- return `{ ${entries.join(', ')} }`;
34
- }
35
- return String(value);
36
- }
37
- const VARIABLE_TYPE_MAPPING = [
38
- [String, 'String!'],
39
- [Number, 'Int!'],
40
- [Boolean, 'Boolean!']
41
- ];
42
- function renderVariablesToString(data) {
43
- const varsDict = {};
44
- for (const [key, value] of Object.entries(data)) {
45
- for (const [classType, varString] of VARIABLE_TYPE_MAPPING) {
46
- if (value === classType) {
47
- varsDict[`$${key}`] = varString;
48
- }
49
- }
50
- }
51
- return Object.entries(varsDict)
52
- .map(([key, value]) => `${key}: ${value}`)
53
- .join(', ');
54
- }
55
- function renderQueryBlock(data, offset = 4, indentation = 4, convertEnum = false) {
56
- const FILTERS_KEY = '@filters';
57
- const ALIAS_KEY = '@alias';
58
- const KEYWORDS_TO_SKIP = [FILTERS_KEY, ALIAS_KEY];
59
- const offsetStr = ' '.repeat(offset);
60
- const lines = [];
61
- for (const [key, value] of Object.entries(data)) {
62
- if (KEYWORDS_TO_SKIP.includes(key))
63
- continue;
64
- if (value === null || value === undefined) {
65
- lines.push(`${offsetStr}${key}`);
66
- }
67
- else if (typeof value === 'object' &&
68
- value !== null &&
69
- Object.keys(value).length === 1 &&
70
- value[ALIAS_KEY]) {
71
- lines.push(`${offsetStr}${value[ALIAS_KEY]}: ${key}`);
72
- }
73
- else if (typeof value === 'object' && value !== null) {
74
- const keyStr = value[ALIAS_KEY] ? `${value[ALIAS_KEY]}: ${key}` : key;
75
- if (value[FILTERS_KEY]) {
76
- const filtersStr = Object.entries(value[FILTERS_KEY])
77
- .map(([k2, v2]) => `${k2}: ${convertToGraphqlAsString(v2, convertEnum)}`)
78
- .join(', ');
79
- lines.push(`${offsetStr}${keyStr}(${filtersStr}) {`);
80
- }
81
- else {
82
- lines.push(`${offsetStr}${keyStr} {`);
83
- }
84
- lines.push(...renderQueryBlock(value, offset + indentation, indentation, convertEnum));
85
- lines.push(offsetStr + '}');
86
- }
87
- else {
88
- lines.push(`${offsetStr}${key}`);
89
- }
90
- }
91
- return lines;
92
- }
93
- function renderInputBlock(data, offset = 4, indentation = 4, convertEnum = false) {
94
- const offsetStr = ' '.repeat(offset);
95
- const lines = [];
96
- for (const [key, value] of Object.entries(data)) {
97
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
98
- lines.push(`${offsetStr}${key}: {`);
99
- lines.push(...renderInputBlock(value, offset + indentation, indentation, convertEnum));
100
- lines.push(offsetStr + '}');
101
- }
102
- else if (Array.isArray(value)) {
103
- lines.push(`${offsetStr}${key}: [`);
104
- for (const item of value) {
105
- if (typeof item === 'object' && item !== null) {
106
- lines.push(`${offsetStr}${' '.repeat(indentation)}{`);
107
- lines.push(...renderInputBlock(item, offset + indentation * 2, indentation, convertEnum));
108
- lines.push(`${offsetStr}${' '.repeat(indentation)}},`);
109
- }
110
- else {
111
- lines.push(`${offsetStr}${' '.repeat(indentation)}${convertToGraphqlAsString(item, convertEnum)},`);
112
- }
113
- }
114
- lines.push(offsetStr + ']');
115
- }
116
- else {
117
- lines.push(`${offsetStr}${key}: ${convertToGraphqlAsString(value, convertEnum)}`);
118
- }
119
- }
120
- return lines;
121
- }
122
- class BaseGraphQLQuery {
123
- constructor(query, variables, name) {
124
- this.queryType = 'not-defined';
125
- this.indentation = 4;
126
- this.query = query;
127
- this.variables = variables;
128
- this.name = name || '';
129
- }
130
- renderFirstLine() {
131
- let firstLine = this.queryType;
132
- if (this.name) {
133
- firstLine += ' ' + this.name;
134
- }
135
- if (this.variables) {
136
- firstLine += ` (${renderVariablesToString(this.variables)})`;
137
- }
138
- firstLine += ' {';
139
- return firstLine;
140
- }
141
- }
142
- exports.BaseGraphQLQuery = BaseGraphQLQuery;
143
- class Query extends BaseGraphQLQuery {
144
- constructor() {
145
- super(...arguments);
146
- this.queryType = 'query';
147
- }
148
- render(convertEnum = false) {
149
- const lines = [this.renderFirstLine()];
150
- lines.push(...renderQueryBlock(this.query, this.indentation, this.indentation, convertEnum));
151
- lines.push('}');
152
- return '\n' + lines.join('\n') + '\n';
153
- }
154
- }
155
- exports.Query = Query;
156
- class Mutation extends BaseGraphQLQuery {
157
- constructor({ mutation, inputData, query, variables, name }) {
158
- super(query, variables, name);
159
- this.queryType = 'mutation';
160
- this.inputData = inputData;
161
- this.mutation = mutation;
162
- }
163
- render(convertEnum = false) {
164
- const lines = [this.renderFirstLine()];
165
- lines.push(' '.repeat(this.indentation) + `${this.mutation}(`);
166
- lines.push(...renderInputBlock(this.inputData, this.indentation, this.indentation * 2, convertEnum));
167
- lines.push(' '.repeat(this.indentation) + '){');
168
- lines.push(...renderQueryBlock(this.query, this.indentation, this.indentation * 2, convertEnum));
169
- lines.push(' '.repeat(this.indentation) + '}');
170
- lines.push('}');
171
- return '\n' + lines.join('\n') + '\n';
172
- }
173
- }
174
- exports.Mutation = Mutation;
package/dist/index.d.ts DELETED
@@ -1,47 +0,0 @@
1
- export type SafeResult<T> = {
2
- data: T;
3
- error: undefined;
4
- } | {
5
- data: undefined;
6
- error: Error;
7
- };
8
- import createClient from 'openapi-fetch';
9
- import { Variables } from 'graphql-request';
10
- import type { paths } from './types';
11
- import { InfrahubBranchManager } from './branch';
12
- export * from 'graphql-request';
13
- export * from './types';
14
- export interface InfrahubClientOptions {
15
- address: string;
16
- token?: string;
17
- branch?: string;
18
- }
19
- export declare class InfrahubClient {
20
- rest: ReturnType<typeof createClient<paths>>;
21
- private graphqlClient;
22
- private baseUrl;
23
- private token?;
24
- defaultBranch: string;
25
- branch: InfrahubBranchManager;
26
- constructor(options: InfrahubClientOptions);
27
- /**
28
- * Executes a GraphQL query or mutation and returns a discriminated union for ergonomic error handling.
29
- * @param query The GraphQL query string.
30
- * @param variables Optional variables for the query.
31
- * @param branchName Optional branch name to target a specific branch.
32
- */
33
- safeExecuteGraphQL<TData = any, TVariables extends Variables = Variables>(query: string, variables?: TVariables, branchName?: string): Promise<SafeResult<TData>>;
34
- /**
35
- * Returns the GraphQL endpoint URL, optionally for a specific branch.
36
- * @param branchName Optional branch name. Defaults to this.defaultBranch if not provided.
37
- */
38
- private _graphqlUrl;
39
- setAuthToken(token: string): void;
40
- /**
41
- * Executes a GraphQL query or mutation against the Infrahub API.
42
- * @param query The GraphQL query string.
43
- * @param variables Optional variables for the query.
44
- * @param branchName Optional branch name to target a specific branch.
45
- */
46
- executeGraphQL<TData = any, TVariables extends Variables = Variables>(query: string, variables?: TVariables, branchName?: string): Promise<TData>;
47
- }