@takaro/apiclient 0.0.0-dev.fdd3e46 → 0.0.0-dev.fe2b054

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.
@@ -1,91 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
- /**
4
- * Takaro API
5
- * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
6
- *
7
- * The version of the OpenAPI document: 0.0.0
8
- * Contact: support@takaro.io
9
- *
10
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
- * https://openapi-generator.tech
12
- * Do not edit the class manually.
13
- */
14
-
15
- import type { Configuration } from './configuration.js';
16
- // Some imports not used depending on template conditions
17
- // @ts-ignore
18
- import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios';
19
- import globalAxios from 'axios';
20
-
21
- export const BASE_PATH = 'http://localhost'.replace(/\/+$/, '');
22
-
23
- /**
24
- *
25
- * @export
26
- */
27
- export const COLLECTION_FORMATS = {
28
- csv: ',',
29
- ssv: ' ',
30
- tsv: '\t',
31
- pipes: '|',
32
- };
33
-
34
- /**
35
- *
36
- * @export
37
- * @interface RequestArgs
38
- */
39
- export interface RequestArgs {
40
- url: string;
41
- options: RawAxiosRequestConfig;
42
- }
43
-
44
- /**
45
- *
46
- * @export
47
- * @class BaseAPI
48
- */
49
- export class BaseAPI {
50
- protected configuration: Configuration | undefined;
51
-
52
- constructor(
53
- configuration?: Configuration,
54
- protected basePath: string = BASE_PATH,
55
- protected axios: AxiosInstance = globalAxios,
56
- ) {
57
- if (configuration) {
58
- this.configuration = configuration;
59
- this.basePath = configuration.basePath ?? basePath;
60
- }
61
- }
62
- }
63
-
64
- /**
65
- *
66
- * @export
67
- * @class RequiredError
68
- * @extends {Error}
69
- */
70
- export class RequiredError extends Error {
71
- constructor(
72
- public field: string,
73
- msg?: string,
74
- ) {
75
- super(msg);
76
- this.name = 'RequiredError';
77
- }
78
- }
79
-
80
- interface ServerMap {
81
- [key: string]: {
82
- url: string;
83
- description: string;
84
- }[];
85
- }
86
-
87
- /**
88
- *
89
- * @export
90
- */
91
- export const operationServerMap: ServerMap = {};
@@ -1,164 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
- /**
4
- * Takaro API
5
- * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
6
- *
7
- * The version of the OpenAPI document: 0.0.0
8
- * Contact: support@takaro.io
9
- *
10
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
- * https://openapi-generator.tech
12
- * Do not edit the class manually.
13
- */
14
-
15
- import type { Configuration } from './configuration.js';
16
- import type { RequestArgs } from './base.js';
17
- import type { AxiosInstance, AxiosResponse } from 'axios';
18
- import { RequiredError } from './base.js';
19
-
20
- /**
21
- *
22
- * @export
23
- */
24
- export const DUMMY_BASE_URL = 'https://example.com';
25
-
26
- /**
27
- *
28
- * @throws {RequiredError}
29
- * @export
30
- */
31
- export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) {
32
- if (paramValue === null || paramValue === undefined) {
33
- throw new RequiredError(
34
- paramName,
35
- `Required parameter ${paramName} was null or undefined when calling ${functionName}.`,
36
- );
37
- }
38
- };
39
-
40
- /**
41
- *
42
- * @export
43
- */
44
- export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) {
45
- if (configuration && configuration.apiKey) {
46
- const localVarApiKeyValue =
47
- typeof configuration.apiKey === 'function'
48
- ? await configuration.apiKey(keyParamName)
49
- : await configuration.apiKey;
50
- object[keyParamName] = localVarApiKeyValue;
51
- }
52
- };
53
-
54
- /**
55
- *
56
- * @export
57
- */
58
- export const setBasicAuthToObject = function (object: any, configuration?: Configuration) {
59
- if (configuration && (configuration.username || configuration.password)) {
60
- object['auth'] = { username: configuration.username, password: configuration.password };
61
- }
62
- };
63
-
64
- /**
65
- *
66
- * @export
67
- */
68
- export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) {
69
- if (configuration && configuration.accessToken) {
70
- const accessToken =
71
- typeof configuration.accessToken === 'function'
72
- ? await configuration.accessToken()
73
- : await configuration.accessToken;
74
- object['Authorization'] = 'Bearer ' + accessToken;
75
- }
76
- };
77
-
78
- /**
79
- *
80
- * @export
81
- */
82
- export const setOAuthToObject = async function (
83
- object: any,
84
- name: string,
85
- scopes: string[],
86
- configuration?: Configuration,
87
- ) {
88
- if (configuration && configuration.accessToken) {
89
- const localVarAccessTokenValue =
90
- typeof configuration.accessToken === 'function'
91
- ? await configuration.accessToken(name, scopes)
92
- : await configuration.accessToken;
93
- object['Authorization'] = 'Bearer ' + localVarAccessTokenValue;
94
- }
95
- };
96
-
97
- function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ''): void {
98
- if (parameter == null) return;
99
- if (typeof parameter === 'object') {
100
- if (Array.isArray(parameter)) {
101
- (parameter as any[]).forEach((item) => setFlattenedQueryParams(urlSearchParams, item, key));
102
- } else {
103
- Object.keys(parameter).forEach((currentKey) =>
104
- setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`),
105
- );
106
- }
107
- } else {
108
- if (urlSearchParams.has(key)) {
109
- urlSearchParams.append(key, parameter);
110
- } else {
111
- urlSearchParams.set(key, parameter);
112
- }
113
- }
114
- }
115
-
116
- /**
117
- *
118
- * @export
119
- */
120
- export const setSearchParams = function (url: URL, ...objects: any[]) {
121
- const searchParams = new URLSearchParams(url.search);
122
- setFlattenedQueryParams(searchParams, objects);
123
- url.search = searchParams.toString();
124
- };
125
-
126
- /**
127
- *
128
- * @export
129
- */
130
- export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) {
131
- const nonString = typeof value !== 'string';
132
- const needsSerialization =
133
- nonString && configuration && configuration.isJsonMime
134
- ? configuration.isJsonMime(requestOptions.headers['Content-Type'])
135
- : nonString;
136
- return needsSerialization ? JSON.stringify(value !== undefined ? value : {}) : value || '';
137
- };
138
-
139
- /**
140
- *
141
- * @export
142
- */
143
- export const toPathString = function (url: URL) {
144
- return url.pathname + url.search + url.hash;
145
- };
146
-
147
- /**
148
- *
149
- * @export
150
- */
151
- export const createRequestFunction = function (
152
- axiosArgs: RequestArgs,
153
- globalAxios: AxiosInstance,
154
- BASE_PATH: string,
155
- configuration?: Configuration,
156
- ) {
157
- return <T = unknown, R = AxiosResponse<T>>(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => {
158
- const axiosRequestArgs = {
159
- ...axiosArgs.options,
160
- url: (axios.defaults.baseURL ? '' : (configuration?.basePath ?? basePath)) + axiosArgs.url,
161
- };
162
- return axios.request<T, R>(axiosRequestArgs);
163
- };
164
- };
@@ -1,123 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
- /**
4
- * Takaro API
5
- * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
6
- *
7
- * The version of the OpenAPI document: 0.0.0
8
- * Contact: support@takaro.io
9
- *
10
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
- * https://openapi-generator.tech
12
- * Do not edit the class manually.
13
- */
14
-
15
- export interface ConfigurationParameters {
16
- apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
17
- username?: string;
18
- password?: string;
19
- accessToken?:
20
- | string
21
- | Promise<string>
22
- | ((name?: string, scopes?: string[]) => string)
23
- | ((name?: string, scopes?: string[]) => Promise<string>);
24
- basePath?: string;
25
- serverIndex?: number;
26
- baseOptions?: any;
27
- formDataCtor?: new () => any;
28
- }
29
-
30
- export class Configuration {
31
- /**
32
- * parameter for apiKey security
33
- * @param name security name
34
- * @memberof Configuration
35
- */
36
- apiKey?: string | Promise<string> | ((name: string) => string) | ((name: string) => Promise<string>);
37
- /**
38
- * parameter for basic security
39
- *
40
- * @type {string}
41
- * @memberof Configuration
42
- */
43
- username?: string;
44
- /**
45
- * parameter for basic security
46
- *
47
- * @type {string}
48
- * @memberof Configuration
49
- */
50
- password?: string;
51
- /**
52
- * parameter for oauth2 security
53
- * @param name security name
54
- * @param scopes oauth2 scope
55
- * @memberof Configuration
56
- */
57
- accessToken?:
58
- | string
59
- | Promise<string>
60
- | ((name?: string, scopes?: string[]) => string)
61
- | ((name?: string, scopes?: string[]) => Promise<string>);
62
- /**
63
- * override base path
64
- *
65
- * @type {string}
66
- * @memberof Configuration
67
- */
68
- basePath?: string;
69
- /**
70
- * override server index
71
- *
72
- * @type {number}
73
- * @memberof Configuration
74
- */
75
- serverIndex?: number;
76
- /**
77
- * base options for axios calls
78
- *
79
- * @type {any}
80
- * @memberof Configuration
81
- */
82
- baseOptions?: any;
83
- /**
84
- * The FormData constructor that will be used to create multipart form data
85
- * requests. You can inject this here so that execution environments that
86
- * do not support the FormData class can still run the generated client.
87
- *
88
- * @type {new () => FormData}
89
- */
90
- formDataCtor?: new () => any;
91
-
92
- constructor(param: ConfigurationParameters = {}) {
93
- this.apiKey = param.apiKey;
94
- this.username = param.username;
95
- this.password = param.password;
96
- this.accessToken = param.accessToken;
97
- this.basePath = param.basePath;
98
- this.serverIndex = param.serverIndex;
99
- this.baseOptions = {
100
- headers: {
101
- ...param.baseOptions?.headers,
102
- 'User-Agent': 'OpenAPI-Generator/typescript-axios',
103
- },
104
- ...param.baseOptions,
105
- };
106
- this.formDataCtor = param.formDataCtor;
107
- }
108
-
109
- /**
110
- * Check if the given MIME is a JSON MIME.
111
- * JSON MIME examples:
112
- * application/json
113
- * application/json; charset=UTF8
114
- * APPLICATION/JSON
115
- * application/vnd.company+json
116
- * @param mime - MIME (Multipurpose Internet Mail Extensions)
117
- * @return True if the given MIME is JSON, false otherwise.
118
- */
119
- public isJsonMime(mime: string): boolean {
120
- const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
121
- return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
122
- }
123
- }
@@ -1,57 +0,0 @@
1
- #!/bin/sh
2
- # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
3
- #
4
- # Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
5
-
6
- git_user_id=$1
7
- git_repo_id=$2
8
- release_note=$3
9
- git_host=$4
10
-
11
- if [ "$git_host" = "" ]; then
12
- git_host="github.com"
13
- echo "[INFO] No command line input provided. Set \$git_host to $git_host"
14
- fi
15
-
16
- if [ "$git_user_id" = "" ]; then
17
- git_user_id="GIT_USER_ID"
18
- echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
19
- fi
20
-
21
- if [ "$git_repo_id" = "" ]; then
22
- git_repo_id="GIT_REPO_ID"
23
- echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
24
- fi
25
-
26
- if [ "$release_note" = "" ]; then
27
- release_note="Minor update"
28
- echo "[INFO] No command line input provided. Set \$release_note to $release_note"
29
- fi
30
-
31
- # Initialize the local directory as a Git repository
32
- git init
33
-
34
- # Adds the files in the local repository and stages them for commit.
35
- git add .
36
-
37
- # Commits the tracked changes and prepares them to be pushed to a remote repository.
38
- git commit -m "$release_note"
39
-
40
- # Sets the new remote
41
- git_remote=$(git remote)
42
- if [ "$git_remote" = "" ]; then # git remote not defined
43
-
44
- if [ "$GIT_TOKEN" = "" ]; then
45
- echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
46
- git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
47
- else
48
- git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
49
- fi
50
-
51
- fi
52
-
53
- git pull origin master
54
-
55
- # Pushes (Forces) the changes in the local repository up to the remote repository
56
- echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
57
- git push origin master 2>&1 | grep -v 'To https'
@@ -1,16 +0,0 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
- /**
4
- * Takaro API
5
- * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
6
- *
7
- * The version of the OpenAPI document: 0.0.0
8
- * Contact: support@takaro.io
9
- *
10
- * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
- * https://openapi-generator.tech
12
- * Do not edit the class manually.
13
- */
14
-
15
- export * from './api.js';
16
- export * from './configuration.js';
@@ -1,17 +0,0 @@
1
- import { describe, it } from 'node:test';
2
- import { expect } from '@takaro/test';
3
- import { BaseApiClient, DEFAULT_REQUEST_TIMEOUT_MS } from '../baseClient.js';
4
-
5
- describe('BaseApiClient timeouts', () => {
6
- it('sets a default request timeout so a stalled request cannot hang forever', () => {
7
- const client = new BaseApiClient({ url: 'http://localhost:3000', log: false });
8
-
9
- expect(client.axiosInstance.defaults.timeout).to.equal(DEFAULT_REQUEST_TIMEOUT_MS);
10
- });
11
-
12
- it('lets a caller override the timeout', () => {
13
- const client = new BaseApiClient({ url: 'http://localhost:3000', log: false, timeoutMs: 5000 });
14
-
15
- expect(client.axiosInstance.defaults.timeout).to.equal(5000);
16
- });
17
- });
@@ -1,37 +0,0 @@
1
- import { DomainApi } from '../generated/index.js';
2
- import { BaseApiClient, IBaseApiClientConfig } from './baseClient.js';
3
- import { AxiosInstance } from 'axios';
4
-
5
- export interface IAdminApiClientConfig extends IBaseApiClientConfig {
6
- auth: {
7
- clientSecret: string;
8
- };
9
- }
10
-
11
- export class AdminClient extends BaseApiClient<IAdminApiClientConfig> {
12
- constructor(config: IAdminApiClientConfig) {
13
- super(config);
14
- this.addAuthInterceptor(config.auth.clientSecret, this.axios);
15
- }
16
-
17
- private addAuthInterceptor(token: string, axios: AxiosInstance): AxiosInstance {
18
- axios.interceptors.request.use(async (request) => {
19
- if (request.url?.includes('health')) return request;
20
-
21
- request.headers['X-Takaro-Admin-Token'] = token;
22
- return request;
23
- });
24
-
25
- return axios;
26
- }
27
-
28
- get domain() {
29
- return new DomainApi(
30
- {
31
- isJsonMime: this.isJsonMime,
32
- },
33
- '',
34
- this.axios,
35
- );
36
- }
37
- }
@@ -1,175 +0,0 @@
1
- import { MetaApi } from '../generated/api.js';
2
- import axios, { AxiosError, AxiosInstance, AxiosRequestConfig } from 'axios';
3
-
4
- /**
5
- * Axios defaults to NO timeout, so a request whose TCP connection stalls blocks its
6
- * await forever. During incident run-29688761260 a single POST hung for ~80 minutes
7
- * (Tempo trace 15f5708701c38676355a0e42cb9f7ffe: a client span with no server span),
8
- * freezing 3 of 4 CI shards until the 53-minute job timeout.
9
- *
10
- * 120s is deliberately generous — the goal is "not infinite", not "tight". The slowest
11
- * legitimate single call is a domain create under full 4-shard CI load at roughly 30s.
12
- * Individual long-running calls should pass a per-request `{ timeout }` override rather
13
- * than raising this.
14
- */
15
- export const DEFAULT_REQUEST_TIMEOUT_MS = 120_000;
16
-
17
- export interface IBaseApiClientConfig {
18
- url: string;
19
- log?: Logger | false;
20
- /** Per-request timeout in ms. Defaults to DEFAULT_REQUEST_TIMEOUT_MS. */
21
- timeoutMs?: number;
22
- }
23
-
24
- interface Logger {
25
- info: (msg: string, meta?: unknown) => void;
26
- warn: (msg: string, meta?: unknown) => void;
27
- error: (msg: string, meta?: unknown) => void;
28
- debug: (msg: string, meta?: unknown) => void;
29
- }
30
-
31
- export class BaseApiClient<T extends IBaseApiClientConfig> {
32
- protected axios: AxiosInstance;
33
- protected log: Logger = {
34
- error: () => {},
35
- info: () => {},
36
- warn: () => {},
37
- debug: () => {},
38
- };
39
-
40
- constructor(protected readonly config: T) {
41
- // Browsers refuse to let JS set the User-Agent header (it's a "forbidden header").
42
- // Only include it when running outside a browser context (Node.js / server-side).
43
- // Use globalThis so this compiles under both DOM and non-DOM TypeScript lib targets.
44
- const isBrowser =
45
- typeof (globalThis as Record<string, unknown>)['window'] !== 'undefined' &&
46
- typeof (globalThis as Record<string, unknown>)['document'] !== 'undefined';
47
- const axiosConfig: AxiosRequestConfig = {
48
- baseURL: this.config.url,
49
- headers: {
50
- 'Content-Type': 'application/json',
51
- ...(!isBrowser && { 'User-Agent': 'Takaro-API-Client' }),
52
- },
53
- withCredentials: true,
54
- timeout: this.config.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
55
- };
56
- this.axios = this.addLoggers(axios.create(axiosConfig));
57
-
58
- if (this.config.log) this.log = this.config.log;
59
- }
60
-
61
- setHeader(key: string, value: string) {
62
- this.axios.defaults.headers.common[key] = value;
63
- }
64
-
65
- setDomain(domainId: string) {
66
- this.axios.defaults.headers.common['X-Takaro-Domain'] = domainId;
67
- }
68
-
69
- get axiosInstance() {
70
- return this.axios;
71
- }
72
-
73
- isJsonMime(mime: string) {
74
- return mime === 'application/json';
75
- }
76
-
77
- private addLoggers(axios: AxiosInstance): AxiosInstance {
78
- if (this.config.log === false) {
79
- return axios;
80
- }
81
-
82
- axios.interceptors.request.use((request) => {
83
- let prettyBody = null;
84
-
85
- if (request.data) {
86
- try {
87
- prettyBody = JSON.parse(request.data);
88
- } catch {
89
- prettyBody = 'Could not parse body';
90
- }
91
- }
92
-
93
- this.log.info(`➡️ ${request.method?.toUpperCase()} ${request.url}`, {
94
- method: request.method,
95
- url: request.url,
96
- body: prettyBody ?? undefined,
97
- });
98
- return request;
99
- });
100
-
101
- axios.interceptors.response.use(
102
- (response) => {
103
- this.log.info(
104
- `⬅️ ${response.request.method?.toUpperCase()} ${response.request.path} ${response.status} ${
105
- response.statusText
106
- }`,
107
- {
108
- status: response.status,
109
- statusText: response.statusText,
110
- method: response.request.method,
111
- url: response.request.url,
112
- },
113
- );
114
-
115
- return response;
116
- },
117
- (error: AxiosError) => {
118
- let details = {};
119
-
120
- if (error.response?.data) {
121
- const data = error.response.data as Record<string, unknown>;
122
- details = JSON.stringify(data.meta);
123
- }
124
-
125
- this.log.error('☠️ Request errored', {
126
- traceId: error.response?.headers['x-trace-id'],
127
- details,
128
- status: error.response?.status,
129
- statusText: error.response?.statusText,
130
- method: error.config?.method,
131
- url: error.config?.url,
132
- response: error.response?.data,
133
- });
134
- return Promise.reject(error);
135
- },
136
- );
137
-
138
- return axios;
139
- }
140
-
141
- /**
142
- * Wait until the API reports that it is healthy
143
- * @param timeout in milliseconds
144
- */
145
- async waitUntilHealthy(timeout = 600000) {
146
- const start = Date.now();
147
- let isHealthy = false;
148
- while (!isHealthy) {
149
- try {
150
- const { data } = await this.meta.metaGetHealth();
151
- if (data.healthy) {
152
- isHealthy = true;
153
- }
154
- } catch {
155
- // ignore
156
- }
157
-
158
- if (Date.now() - start > timeout) {
159
- throw new Error('API did not become healthy in time');
160
- }
161
-
162
- await new Promise((resolve) => setTimeout(resolve, 1000));
163
- }
164
- }
165
-
166
- get meta() {
167
- return new MetaApi(
168
- {
169
- isJsonMime: this.isJsonMime,
170
- },
171
- '',
172
- this.axios,
173
- );
174
- }
175
- }