@lightdash-tools/client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +144 -0
- package/dist/api/base-client.d.ts +13 -0
- package/dist/api/base-client.js +17 -0
- package/dist/api/v1/ai-agents.d.ts +17 -0
- package/dist/api/v1/ai-agents.js +47 -0
- package/dist/api/v1/ai-agents.test.d.ts +1 -0
- package/dist/api/v1/ai-agents.test.js +77 -0
- package/dist/api/v1/charts.d.ts +18 -0
- package/dist/api/v1/charts.js +45 -0
- package/dist/api/v1/charts.test.d.ts +1 -0
- package/dist/api/v1/charts.test.js +106 -0
- package/dist/api/v1/dashboards.d.ts +9 -0
- package/dist/api/v1/dashboards.js +25 -0
- package/dist/api/v1/dashboards.test.d.ts +1 -0
- package/dist/api/v1/dashboards.test.js +33 -0
- package/dist/api/v1/explores.d.ts +11 -0
- package/dist/api/v1/explores.js +31 -0
- package/dist/api/v1/explores.test.d.ts +1 -0
- package/dist/api/v1/explores.test.js +46 -0
- package/dist/api/v1/groups.d.ts +42 -0
- package/dist/api/v1/groups.js +81 -0
- package/dist/api/v1/groups.test.d.ts +1 -0
- package/dist/api/v1/groups.test.js +107 -0
- package/dist/api/v1/organizations.d.ts +9 -0
- package/dist/api/v1/organizations.js +25 -0
- package/dist/api/v1/organizations.test.d.ts +1 -0
- package/dist/api/v1/organizations.test.js +33 -0
- package/dist/api/v1/project-access.d.ts +40 -0
- package/dist/api/v1/project-access.js +88 -0
- package/dist/api/v1/project-access.test.d.ts +1 -0
- package/dist/api/v1/project-access.test.js +109 -0
- package/dist/api/v1/projects.d.ts +13 -0
- package/dist/api/v1/projects.js +37 -0
- package/dist/api/v1/projects.test.d.ts +1 -0
- package/dist/api/v1/projects.test.js +49 -0
- package/dist/api/v1/query.d.ts +11 -0
- package/dist/api/v1/query.js +31 -0
- package/dist/api/v1/query.test.d.ts +1 -0
- package/dist/api/v1/query.test.js +51 -0
- package/dist/api/v1/spaces.d.ts +25 -0
- package/dist/api/v1/spaces.js +73 -0
- package/dist/api/v1/spaces.test.d.ts +1 -0
- package/dist/api/v1/spaces.test.js +91 -0
- package/dist/api/v1/users.d.ts +35 -0
- package/dist/api/v1/users.js +66 -0
- package/dist/api/v1/users.test.d.ts +1 -0
- package/dist/api/v1/users.test.js +122 -0
- package/dist/api/v2/organization-roles.d.ts +45 -0
- package/dist/api/v2/organization-roles.js +81 -0
- package/dist/api/v2/organization-roles.test.d.ts +1 -0
- package/dist/api/v2/organization-roles.test.js +112 -0
- package/dist/api/v2/project-role-assignments.d.ts +23 -0
- package/dist/api/v2/project-role-assignments.js +55 -0
- package/dist/api/v2/project-role-assignments.test.d.ts +1 -0
- package/dist/api/v2/project-role-assignments.test.js +66 -0
- package/dist/api/v2/query.d.ts +17 -0
- package/dist/api/v2/query.js +49 -0
- package/dist/api/v2/query.test.d.ts +1 -0
- package/dist/api/v2/query.test.js +78 -0
- package/dist/client.d.ts +118 -0
- package/dist/client.js +113 -0
- package/dist/client.test.d.ts +1 -0
- package/dist/client.test.js +94 -0
- package/dist/config.d.ts +83 -0
- package/dist/config.js +22 -0
- package/dist/errors.d.ts +39 -0
- package/dist/errors.js +46 -0
- package/dist/errors.test.d.ts +1 -0
- package/dist/errors.test.js +29 -0
- package/dist/http/axios-client.d.ts +22 -0
- package/dist/http/axios-client.js +51 -0
- package/dist/http/http-client.d.ts +33 -0
- package/dist/http/http-client.js +69 -0
- package/dist/http/interceptors.d.ts +13 -0
- package/dist/http/interceptors.js +82 -0
- package/dist/http/rate-limiter.d.ts +23 -0
- package/dist/http/rate-limiter.js +60 -0
- package/dist/http/rate-limiter.test.d.ts +1 -0
- package/dist/http/rate-limiter.test.js +40 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +41 -0
- package/dist/index.test.d.ts +1 -0
- package/dist/index.test.js +65 -0
- package/dist/pagination/fetch-all-pages.d.ts +15 -0
- package/dist/pagination/fetch-all-pages.js +41 -0
- package/dist/pagination/fetch-all-pages.test.d.ts +1 -0
- package/dist/pagination/fetch-all-pages.test.js +70 -0
- package/dist/pagination/types.d.ts +14 -0
- package/dist/pagination/types.js +6 -0
- package/dist/types/api.d.ts +22 -0
- package/dist/types/api.js +8 -0
- package/dist/utils/env.d.ts +20 -0
- package/dist/utils/env.js +59 -0
- package/dist/utils/env.test.d.ts +1 -0
- package/dist/utils/env.test.js +73 -0
- package/dist/utils/logger.d.ts +8 -0
- package/dist/utils/logger.js +20 -0
- package/dist/utils/retry.d.ts +14 -0
- package/dist/utils/retry.js +67 -0
- package/dist/utils/retry.test.d.ts +1 -0
- package/dist/utils/retry.test.js +53 -0
- package/package.json +21 -0
- package/src/api/base-client.ts +14 -0
- package/src/api/v1/ai-agents.test.ts +74 -0
- package/src/api/v1/ai-agents.ts +41 -0
- package/src/api/v1/charts.test.ts +103 -0
- package/src/api/v1/charts.ts +51 -0
- package/src/api/v1/dashboards.test.ts +26 -0
- package/src/api/v1/dashboards.ts +15 -0
- package/src/api/v1/explores.test.ts +40 -0
- package/src/api/v1/explores.ts +18 -0
- package/src/api/v1/groups.test.ts +108 -0
- package/src/api/v1/groups.ts +100 -0
- package/src/api/v1/organizations.test.ts +26 -0
- package/src/api/v1/organizations.ts +13 -0
- package/src/api/v1/project-access.test.ts +110 -0
- package/src/api/v1/project-access.ts +102 -0
- package/src/api/v1/projects.test.ts +44 -0
- package/src/api/v1/projects.ts +23 -0
- package/src/api/v1/query.test.ts +46 -0
- package/src/api/v1/query.ts +37 -0
- package/src/api/v1/spaces.test.ts +92 -0
- package/src/api/v1/spaces.ts +83 -0
- package/src/api/v1/users.test.ts +125 -0
- package/src/api/v1/users.ts +76 -0
- package/src/api/v2/organization-roles.test.ts +115 -0
- package/src/api/v2/organization-roles.ts +90 -0
- package/src/api/v2/project-role-assignments.test.ts +75 -0
- package/src/api/v2/project-role-assignments.ts +63 -0
- package/src/api/v2/query.test.ts +81 -0
- package/src/api/v2/query.ts +69 -0
- package/src/client.test.ts +105 -0
- package/src/client.ts +182 -0
- package/src/config.ts +113 -0
- package/src/errors.test.ts +45 -0
- package/src/errors.ts +67 -0
- package/src/http/axios-client.ts +59 -0
- package/src/http/http-client.ts +79 -0
- package/src/http/interceptors.ts +110 -0
- package/src/http/rate-limiter.test.ts +34 -0
- package/src/http/rate-limiter.ts +54 -0
- package/src/index.test.ts +91 -0
- package/src/index.ts +41 -0
- package/src/pagination/fetch-all-pages.test.ts +75 -0
- package/src/pagination/fetch-all-pages.ts +39 -0
- package/src/pagination/types.ts +16 -0
- package/src/types/api.ts +28 -0
- package/src/utils/env.test.ts +88 -0
- package/src/utils/env.ts +69 -0
- package/src/utils/logger.ts +21 -0
- package/src/utils/retry.test.ts +49 -0
- package/src/utils/retry.ts +60 -0
- package/tsconfig.json +13 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate limiter wrapping Bottleneck for centralized request throttling.
|
|
3
|
+
* Uses token bucket algorithm; handles 429 retries via Bottleneck options.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import Bottleneck from 'bottleneck';
|
|
7
|
+
import type { RateLimitConfig } from '../config';
|
|
8
|
+
import { DEFAULT_RATE_LIMIT } from '../config';
|
|
9
|
+
|
|
10
|
+
export type RateLimiterOptions = RateLimitConfig;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Wraps Bottleneck to provide configurable rate limiting for API requests.
|
|
14
|
+
*/
|
|
15
|
+
export class RateLimiter {
|
|
16
|
+
private readonly limiter: Bottleneck;
|
|
17
|
+
|
|
18
|
+
constructor(options: RateLimiterOptions = {}) {
|
|
19
|
+
const minTime = options.minTime ?? DEFAULT_RATE_LIMIT.minTime;
|
|
20
|
+
const maxConcurrent = options.maxConcurrent ?? DEFAULT_RATE_LIMIT.maxConcurrent;
|
|
21
|
+
const reservoir = options.reservoir ?? DEFAULT_RATE_LIMIT.reservoir;
|
|
22
|
+
const reservoirRefreshInterval =
|
|
23
|
+
options.reservoirRefreshInterval ?? DEFAULT_RATE_LIMIT.reservoirRefreshInterval;
|
|
24
|
+
const reservoirRefreshAmount =
|
|
25
|
+
options.reservoirRefreshAmount ?? DEFAULT_RATE_LIMIT.reservoirRefreshAmount;
|
|
26
|
+
|
|
27
|
+
this.limiter = new Bottleneck({
|
|
28
|
+
minTime,
|
|
29
|
+
maxConcurrent,
|
|
30
|
+
reservoir,
|
|
31
|
+
reservoirRefreshInterval,
|
|
32
|
+
reservoirRefreshAmount,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Schedules a function to run when the rate limit allows.
|
|
38
|
+
*/
|
|
39
|
+
schedule<T>(fn: () => Promise<T>): Promise<T> {
|
|
40
|
+
return this.limiter.schedule(fn);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Wraps an async function so that each call goes through the rate limiter.
|
|
45
|
+
*/
|
|
46
|
+
wrap<T extends unknown[], R>(fn: (...args: T) => Promise<R>): (...args: T) => Promise<R> {
|
|
47
|
+
return (...args: T) => this.limiter.schedule(() => fn(...args));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Stops the limiter and drains remaining jobs. */
|
|
51
|
+
async disconnect(): Promise<void> {
|
|
52
|
+
return this.limiter.disconnect(true);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
LightdashClient,
|
|
4
|
+
mergeConfig,
|
|
5
|
+
loadConfigFromEnv,
|
|
6
|
+
LightdashApiError,
|
|
7
|
+
RateLimitError,
|
|
8
|
+
NetworkError,
|
|
9
|
+
} from './index';
|
|
10
|
+
|
|
11
|
+
describe('LightdashClient', () => {
|
|
12
|
+
it('should export LightdashClient', () => {
|
|
13
|
+
expect(LightdashClient).toBeDefined();
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('should instantiate with explicit config', () => {
|
|
17
|
+
const client = new LightdashClient({
|
|
18
|
+
baseUrl: 'https://app.lightdash.cloud',
|
|
19
|
+
personalAccessToken: 'test-token',
|
|
20
|
+
});
|
|
21
|
+
expect(client.getHttpClient()).toBeDefined();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
it('should throw when baseUrl and personalAccessToken are missing and not in env', () => {
|
|
25
|
+
expect(() => new LightdashClient({})).toThrow(
|
|
26
|
+
/baseUrl and personalAccessToken|LIGHTDASH_URL and LIGHTDASH_API_KEY/,
|
|
27
|
+
);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe('mergeConfig', () => {
|
|
32
|
+
it('should merge explicit config with env (explicit wins)', () => {
|
|
33
|
+
const explicit = {
|
|
34
|
+
baseUrl: 'https://custom.example.com',
|
|
35
|
+
personalAccessToken: 'explicit-token',
|
|
36
|
+
};
|
|
37
|
+
const merged = mergeConfig(explicit);
|
|
38
|
+
expect(merged.baseUrl).toBe('https://custom.example.com');
|
|
39
|
+
expect(merged.personalAccessToken).toBe('explicit-token');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('should require baseUrl and personalAccessToken', () => {
|
|
43
|
+
expect(() => mergeConfig({})).toThrow();
|
|
44
|
+
expect(() => mergeConfig({ baseUrl: 'https://x.com' })).toThrow();
|
|
45
|
+
expect(() => mergeConfig({ personalAccessToken: 't' })).toThrow();
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
describe('loadConfigFromEnv', () => {
|
|
50
|
+
it('should return empty object when env vars are not set', () => {
|
|
51
|
+
const config = loadConfigFromEnv();
|
|
52
|
+
expect(config).toEqual({});
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('LightdashApiError', () => {
|
|
57
|
+
it('should have statusCode and error payload', () => {
|
|
58
|
+
const err = new LightdashApiError(
|
|
59
|
+
404,
|
|
60
|
+
{ name: 'NotFound', statusCode: 404, message: 'Not found' },
|
|
61
|
+
{ url: '/test', method: 'GET' },
|
|
62
|
+
);
|
|
63
|
+
expect(err.name).toBe('LightdashApiError');
|
|
64
|
+
expect(err.statusCode).toBe(404);
|
|
65
|
+
expect(err.error.name).toBe('NotFound');
|
|
66
|
+
expect(err.message).toContain('Not found');
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
describe('RateLimitError', () => {
|
|
71
|
+
it('should extend LightdashApiError and have retryAfter', () => {
|
|
72
|
+
const err = new RateLimitError(
|
|
73
|
+
429,
|
|
74
|
+
{ name: 'TooManyRequests', statusCode: 429 },
|
|
75
|
+
{ url: '/test', method: 'GET' },
|
|
76
|
+
undefined,
|
|
77
|
+
60,
|
|
78
|
+
);
|
|
79
|
+
expect(err).toBeInstanceOf(LightdashApiError);
|
|
80
|
+
expect(err.retryAfter).toBe(60);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
describe('NetworkError', () => {
|
|
85
|
+
it('should wrap original error', () => {
|
|
86
|
+
const original = new Error('ECONNRESET');
|
|
87
|
+
const err = new NetworkError('Connection reset', original);
|
|
88
|
+
expect(err.originalError).toBe(original);
|
|
89
|
+
expect(err.message).toBe('Connection reset');
|
|
90
|
+
});
|
|
91
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export { LightdashClient, V1ApiClients, V2ApiClients } from './client';
|
|
2
|
+
export { UsersClient } from './api/v1/users';
|
|
3
|
+
export { GroupsClient } from './api/v1/groups';
|
|
4
|
+
export { OrganizationRolesClient } from './api/v2/organization-roles';
|
|
5
|
+
export { ProjectRoleAssignmentsClient } from './api/v2/project-role-assignments';
|
|
6
|
+
export { AiAgentsClient } from './api/v1/ai-agents';
|
|
7
|
+
export { ProjectAccessClient } from './api/v1/project-access';
|
|
8
|
+
export type { ListMembersParams, ListAllMembersParams } from './api/v1/users';
|
|
9
|
+
export type {
|
|
10
|
+
ListGroupsParams,
|
|
11
|
+
ListAllGroupsParams,
|
|
12
|
+
GetGroupParams,
|
|
13
|
+
GroupOrGroupWithMembers,
|
|
14
|
+
} from './api/v1/groups';
|
|
15
|
+
export type {
|
|
16
|
+
GetRolesResult,
|
|
17
|
+
GetRolesParams,
|
|
18
|
+
AssignOrgRoleToUserBody,
|
|
19
|
+
} from './api/v2/organization-roles';
|
|
20
|
+
export type { PartialLightdashClientConfig } from './config';
|
|
21
|
+
export type {
|
|
22
|
+
LightdashClientConfig,
|
|
23
|
+
RateLimitConfig,
|
|
24
|
+
RetryConfig,
|
|
25
|
+
Logger,
|
|
26
|
+
ObservabilityHooks,
|
|
27
|
+
} from './config';
|
|
28
|
+
export { noopLogger, consoleLogger } from './utils/logger';
|
|
29
|
+
export { DEFAULT_RATE_LIMIT, DEFAULT_TIMEOUT, DEFAULT_RETRY } from './config';
|
|
30
|
+
export { LightdashApiError, RateLimitError, NetworkError } from './errors';
|
|
31
|
+
export type { ApiErrorPayload } from './errors';
|
|
32
|
+
export { loadConfigFromEnv, mergeConfig } from './utils/env';
|
|
33
|
+
export {
|
|
34
|
+
ENV_LIGHTDASH_API_KEY,
|
|
35
|
+
ENV_LIGHTDASH_URL,
|
|
36
|
+
ENV_LIGHTDASH_PROXY_AUTHORIZATION,
|
|
37
|
+
} from './utils/env';
|
|
38
|
+
export { HttpClient } from './http/http-client';
|
|
39
|
+
export { RateLimiter } from './http/rate-limiter';
|
|
40
|
+
export type { ApiResponseOk, ApiResponseError, ApiResponseBody, ApiError } from './types/api';
|
|
41
|
+
export type { paths, components, operations } from './types/api';
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { fetchAllPages } from './fetch-all-pages';
|
|
3
|
+
import type { KnexPage } from './types';
|
|
4
|
+
|
|
5
|
+
describe('fetchAllPages', () => {
|
|
6
|
+
it('returns concatenated data from multiple pages', async () => {
|
|
7
|
+
const fetchPage = vi
|
|
8
|
+
.fn()
|
|
9
|
+
.mockResolvedValueOnce({
|
|
10
|
+
data: [{ id: 1 }, { id: 2 }],
|
|
11
|
+
pagination: { page: 1, pageSize: 2, totalResults: 6, totalPageCount: 3 },
|
|
12
|
+
})
|
|
13
|
+
.mockResolvedValueOnce({
|
|
14
|
+
data: [{ id: 3 }, { id: 4 }],
|
|
15
|
+
pagination: { page: 2, pageSize: 2, totalResults: 6, totalPageCount: 3 },
|
|
16
|
+
})
|
|
17
|
+
.mockResolvedValueOnce({
|
|
18
|
+
data: [{ id: 5 }, { id: 6 }],
|
|
19
|
+
pagination: { page: 3, pageSize: 2, totalResults: 6, totalPageCount: 3 },
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const result = await fetchAllPages<{ id: number }>({ fetchPage, pageSize: 2 });
|
|
23
|
+
|
|
24
|
+
expect(result).toHaveLength(6);
|
|
25
|
+
expect(result).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }]);
|
|
26
|
+
expect(fetchPage).toHaveBeenCalledTimes(3);
|
|
27
|
+
expect(fetchPage).toHaveBeenNthCalledWith(1, 1, 2);
|
|
28
|
+
expect(fetchPage).toHaveBeenNthCalledWith(2, 2, 2);
|
|
29
|
+
expect(fetchPage).toHaveBeenNthCalledWith(3, 3, 2);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('returns single page when no pagination', async () => {
|
|
33
|
+
const fetchPage = vi.fn().mockResolvedValueOnce({
|
|
34
|
+
data: [{ x: 'a' }],
|
|
35
|
+
} as KnexPage<{ x: string }>);
|
|
36
|
+
|
|
37
|
+
const result = await fetchAllPages<{ x: string }>({ fetchPage });
|
|
38
|
+
|
|
39
|
+
expect(result).toEqual([{ x: 'a' }]);
|
|
40
|
+
expect(fetchPage).toHaveBeenCalledTimes(1);
|
|
41
|
+
expect(fetchPage).toHaveBeenCalledWith(1, 100);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('returns single page when totalPageCount is 1', async () => {
|
|
45
|
+
const fetchPage = vi.fn().mockResolvedValueOnce({
|
|
46
|
+
data: [{ a: 1 }],
|
|
47
|
+
pagination: { page: 1, pageSize: 10, totalResults: 1, totalPageCount: 1 },
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const result = await fetchAllPages<{ a: number }>({ fetchPage, pageSize: 10 });
|
|
51
|
+
|
|
52
|
+
expect(result).toEqual([{ a: 1 }]);
|
|
53
|
+
expect(fetchPage).toHaveBeenCalledTimes(1);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('returns empty array when first page has no data and no pagination', async () => {
|
|
57
|
+
const fetchPage = vi.fn().mockResolvedValueOnce({ data: [] } as KnexPage<unknown>);
|
|
58
|
+
|
|
59
|
+
const result = await fetchAllPages({ fetchPage });
|
|
60
|
+
|
|
61
|
+
expect(result).toEqual([]);
|
|
62
|
+
expect(fetchPage).toHaveBeenCalledTimes(1);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('uses default page size when not provided', async () => {
|
|
66
|
+
const fetchPage = vi.fn().mockResolvedValueOnce({
|
|
67
|
+
data: [],
|
|
68
|
+
pagination: { page: 1, pageSize: 100, totalResults: 0, totalPageCount: 1 },
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
await fetchAllPages({ fetchPage });
|
|
72
|
+
|
|
73
|
+
expect(fetchPage).toHaveBeenCalledWith(1, 100);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic helper to fetch all pages of a Knex-paginated API and return a single array.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { KnexPage } from './types';
|
|
6
|
+
|
|
7
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
8
|
+
|
|
9
|
+
export interface FetchAllPagesOptions<T> {
|
|
10
|
+
/** Fetches one page. Called with 1-based page number and page size. */
|
|
11
|
+
fetchPage: (page: number, pageSize: number) => Promise<KnexPage<T>>;
|
|
12
|
+
/** Page size per request. Default 100. */
|
|
13
|
+
pageSize?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Fetches all pages by repeatedly calling fetchPage until no more pages, then returns
|
|
18
|
+
* the concatenated data array.
|
|
19
|
+
*/
|
|
20
|
+
export async function fetchAllPages<T>(options: FetchAllPagesOptions<T>): Promise<T[]> {
|
|
21
|
+
const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
22
|
+
const all: T[] = [];
|
|
23
|
+
let page = 1;
|
|
24
|
+
let totalPageCount: number | undefined;
|
|
25
|
+
|
|
26
|
+
do {
|
|
27
|
+
const result = await options.fetchPage(page, pageSize);
|
|
28
|
+
all.push(...result.data);
|
|
29
|
+
|
|
30
|
+
if (result.pagination) {
|
|
31
|
+
totalPageCount = result.pagination.totalPageCount;
|
|
32
|
+
page += 1;
|
|
33
|
+
} else {
|
|
34
|
+
totalPageCount = undefined;
|
|
35
|
+
}
|
|
36
|
+
} while (totalPageCount !== undefined && page <= totalPageCount);
|
|
37
|
+
|
|
38
|
+
return all;
|
|
39
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal type for one page of Knex-paginated API results.
|
|
3
|
+
* Matches the shape returned by list endpoints (e.g. /org/users, /org/groups).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface KnexPagePagination {
|
|
7
|
+
page: number;
|
|
8
|
+
pageSize: number;
|
|
9
|
+
totalResults: number;
|
|
10
|
+
totalPageCount: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface KnexPage<T> {
|
|
14
|
+
data: T[];
|
|
15
|
+
pagination?: KnexPagePagination;
|
|
16
|
+
}
|
package/src/types/api.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Helper types for Lightdash API. Re-exports generated OpenAPI types and adds response helpers.
|
|
3
|
+
*
|
|
4
|
+
* Note: Domain models (Project, Organization, etc.) are available from @lightdash-tools/common.
|
|
5
|
+
* Use this module for advanced types (paths, components, operations) or response helpers.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { components } from '@lightdash-tools/common';
|
|
9
|
+
|
|
10
|
+
export type { paths, components, operations } from '@lightdash-tools/common';
|
|
11
|
+
|
|
12
|
+
/** API error schema from OpenAPI. */
|
|
13
|
+
export type ApiError = components['schemas']['ApiErrorPayload'];
|
|
14
|
+
|
|
15
|
+
/** Successful API response wrapper (status ok + results). */
|
|
16
|
+
export interface ApiResponseOk<T> {
|
|
17
|
+
status: 'ok';
|
|
18
|
+
results: T;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Failed API response wrapper (status error + error). */
|
|
22
|
+
export interface ApiResponseError {
|
|
23
|
+
status: 'error';
|
|
24
|
+
error: ApiError['error'];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Discriminated union for API response body. */
|
|
28
|
+
export type ApiResponseBody<T> = ApiResponseOk<T> | ApiResponseError;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
loadConfigFromEnv,
|
|
4
|
+
mergeConfig,
|
|
5
|
+
ENV_LIGHTDASH_API_KEY,
|
|
6
|
+
ENV_LIGHTDASH_URL,
|
|
7
|
+
ENV_LIGHTDASH_PROXY_AUTHORIZATION,
|
|
8
|
+
} from './env';
|
|
9
|
+
|
|
10
|
+
const originalEnv = { ...process.env };
|
|
11
|
+
|
|
12
|
+
beforeEach(() => {
|
|
13
|
+
delete process.env[ENV_LIGHTDASH_API_KEY];
|
|
14
|
+
delete process.env[ENV_LIGHTDASH_URL];
|
|
15
|
+
delete process.env[ENV_LIGHTDASH_PROXY_AUTHORIZATION];
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
process.env = { ...originalEnv };
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
describe('loadConfigFromEnv', () => {
|
|
23
|
+
it('should read LIGHTDASH_API_KEY', () => {
|
|
24
|
+
process.env[ENV_LIGHTDASH_API_KEY] = 'my-token';
|
|
25
|
+
const config = loadConfigFromEnv();
|
|
26
|
+
expect(config.personalAccessToken).toBe('my-token');
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('should read LIGHTDASH_URL', () => {
|
|
30
|
+
process.env[ENV_LIGHTDASH_URL] = 'https://app.lightdash.cloud';
|
|
31
|
+
const config = loadConfigFromEnv();
|
|
32
|
+
expect(config.baseUrl).toBe('https://app.lightdash.cloud');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('should strip trailing slash from LIGHTDASH_URL in mergeConfig', () => {
|
|
36
|
+
process.env[ENV_LIGHTDASH_URL] = 'https://app.lightdash.cloud/';
|
|
37
|
+
const merged = mergeConfig({ personalAccessToken: 't' });
|
|
38
|
+
expect(merged.baseUrl).toBe('https://app.lightdash.cloud');
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('should read LIGHTDASH_PROXY_AUTHORIZATION', () => {
|
|
42
|
+
process.env[ENV_LIGHTDASH_PROXY_AUTHORIZATION] = 'Bearer proxy-token';
|
|
43
|
+
const config = loadConfigFromEnv();
|
|
44
|
+
expect(config.proxyAuthorization).toBe('Bearer proxy-token');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('should not set keys for empty env values', () => {
|
|
48
|
+
process.env[ENV_LIGHTDASH_API_KEY] = '';
|
|
49
|
+
const config = loadConfigFromEnv();
|
|
50
|
+
expect(config.personalAccessToken).toBeUndefined();
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
describe('mergeConfig', () => {
|
|
55
|
+
it('should prefer explicit config over env', () => {
|
|
56
|
+
process.env[ENV_LIGHTDASH_URL] = 'https://env.example.com';
|
|
57
|
+
process.env[ENV_LIGHTDASH_API_KEY] = 'env-token';
|
|
58
|
+
const merged = mergeConfig({
|
|
59
|
+
baseUrl: 'https://explicit.example.com',
|
|
60
|
+
personalAccessToken: 'explicit-token',
|
|
61
|
+
});
|
|
62
|
+
expect(merged.baseUrl).toBe('https://explicit.example.com');
|
|
63
|
+
expect(merged.personalAccessToken).toBe('explicit-token');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('should use env when explicit config omits a field', () => {
|
|
67
|
+
process.env[ENV_LIGHTDASH_URL] = 'https://env.example.com';
|
|
68
|
+
process.env[ENV_LIGHTDASH_API_KEY] = 'env-token';
|
|
69
|
+
const merged = mergeConfig({ baseUrl: 'https://explicit.example.com' });
|
|
70
|
+
expect(merged.baseUrl).toBe('https://explicit.example.com');
|
|
71
|
+
expect(merged.personalAccessToken).toBe('env-token');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('should throw when baseUrl and personalAccessToken cannot be resolved', () => {
|
|
75
|
+
expect(() => mergeConfig(undefined)).toThrow(/baseUrl and personalAccessToken/);
|
|
76
|
+
expect(() => mergeConfig({})).toThrow();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('should preserve observability when provided in explicit config', () => {
|
|
80
|
+
const onRequestComplete = vi.fn();
|
|
81
|
+
const merged = mergeConfig({
|
|
82
|
+
baseUrl: 'https://app.lightdash.cloud',
|
|
83
|
+
personalAccessToken: 'test-token',
|
|
84
|
+
observability: { onRequestComplete },
|
|
85
|
+
});
|
|
86
|
+
expect(merged.observability?.onRequestComplete).toBe(onRequestComplete);
|
|
87
|
+
});
|
|
88
|
+
});
|
package/src/utils/env.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment variable loading for Lightdash client configuration.
|
|
3
|
+
* Supports LIGHTDASH_API_KEY, LIGHTDASH_URL, LIGHTDASH_PROXY_AUTHORIZATION.
|
|
4
|
+
* Priority: explicit config > environment variables > no default for required fields.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { LightdashClientConfig, PartialLightdashClientConfig } from '../config';
|
|
8
|
+
|
|
9
|
+
/** Environment variable names (aligned with Lightdash CLI). */
|
|
10
|
+
export const ENV_LIGHTDASH_API_KEY = 'LIGHTDASH_API_KEY';
|
|
11
|
+
export const ENV_LIGHTDASH_URL = 'LIGHTDASH_URL';
|
|
12
|
+
export const ENV_LIGHTDASH_PROXY_AUTHORIZATION = 'LIGHTDASH_PROXY_AUTHORIZATION';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Reads configuration from environment variables.
|
|
16
|
+
* Returns only the fields that are set in the environment.
|
|
17
|
+
*/
|
|
18
|
+
export function loadConfigFromEnv(): PartialLightdashClientConfig {
|
|
19
|
+
const env = typeof process !== 'undefined' ? process.env : {};
|
|
20
|
+
const out: PartialLightdashClientConfig = {};
|
|
21
|
+
|
|
22
|
+
const apiKey = env[ENV_LIGHTDASH_API_KEY];
|
|
23
|
+
if (apiKey !== undefined && apiKey !== '') {
|
|
24
|
+
out.personalAccessToken = apiKey;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const url = env[ENV_LIGHTDASH_URL];
|
|
28
|
+
if (url !== undefined && url !== '') {
|
|
29
|
+
out.baseUrl = url.replace(/\/$/, '');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const proxyAuth = env[ENV_LIGHTDASH_PROXY_AUTHORIZATION];
|
|
33
|
+
if (proxyAuth !== undefined && proxyAuth !== '') {
|
|
34
|
+
out.proxyAuthorization = proxyAuth;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Merges explicit config with environment-derived config.
|
|
42
|
+
* Explicit config takes priority over environment variables.
|
|
43
|
+
*/
|
|
44
|
+
export function mergeConfig(
|
|
45
|
+
explicit: PartialLightdashClientConfig | undefined,
|
|
46
|
+
): LightdashClientConfig {
|
|
47
|
+
const fromEnv = loadConfigFromEnv();
|
|
48
|
+
|
|
49
|
+
const baseUrl = explicit?.baseUrl ?? fromEnv.baseUrl ?? '';
|
|
50
|
+
const personalAccessToken = explicit?.personalAccessToken ?? fromEnv.personalAccessToken ?? '';
|
|
51
|
+
|
|
52
|
+
if (!baseUrl || !personalAccessToken) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
'Lightdash client requires baseUrl and personalAccessToken. ' +
|
|
55
|
+
'Set them in config or via LIGHTDASH_URL and LIGHTDASH_API_KEY.',
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
baseUrl,
|
|
61
|
+
personalAccessToken,
|
|
62
|
+
proxyAuthorization: explicit?.proxyAuthorization ?? fromEnv.proxyAuthorization,
|
|
63
|
+
rateLimit: explicit?.rateLimit,
|
|
64
|
+
timeout: explicit?.timeout,
|
|
65
|
+
retry: explicit?.retry,
|
|
66
|
+
logger: explicit?.logger,
|
|
67
|
+
observability: explicit?.observability,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logging utilities. Optional logger can be passed in client config.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import type { Logger } from '../config';
|
|
6
|
+
|
|
7
|
+
/** No-op logger for when logging is disabled. */
|
|
8
|
+
export const noopLogger: Logger = {
|
|
9
|
+
debug: () => {},
|
|
10
|
+
info: () => {},
|
|
11
|
+
warn: () => {},
|
|
12
|
+
error: () => {},
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Console-based logger. */
|
|
16
|
+
export const consoleLogger: Logger = {
|
|
17
|
+
debug: (...args) => console.debug('[Lightdash]', ...args),
|
|
18
|
+
info: (...args) => console.info('[Lightdash]', ...args),
|
|
19
|
+
warn: (...args) => console.warn('[Lightdash]', ...args),
|
|
20
|
+
error: (...args) => console.error('[Lightdash]', ...args),
|
|
21
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { withRetry, isRetryableError } from './retry';
|
|
3
|
+
|
|
4
|
+
describe('isRetryableError', () => {
|
|
5
|
+
it('should return true for 5xx response', () => {
|
|
6
|
+
expect(isRetryableError({ response: { status: 500 } })).toBe(true);
|
|
7
|
+
expect(isRetryableError({ response: { status: 503 } })).toBe(true);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
it('should return false for 4xx response', () => {
|
|
11
|
+
expect(isRetryableError({ response: { status: 400 } })).toBe(false);
|
|
12
|
+
expect(isRetryableError({ response: { status: 404 } })).toBe(false);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('should return true for network-like errors', () => {
|
|
16
|
+
expect(isRetryableError(new Error('ECONNRESET'))).toBe(true);
|
|
17
|
+
expect(isRetryableError(new Error('ETIMEDOUT'))).toBe(true);
|
|
18
|
+
expect(isRetryableError(Object.assign(new Error('x'), { code: 'ECONNRESET' }))).toBe(true);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('should return false for generic Error', () => {
|
|
22
|
+
expect(isRetryableError(new Error('something else'))).toBe(false);
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
describe('withRetry', () => {
|
|
27
|
+
it('should return result on first success', async () => {
|
|
28
|
+
const fn = vi.fn().mockResolvedValue(42);
|
|
29
|
+
const result = await withRetry(fn);
|
|
30
|
+
expect(result).toBe(42);
|
|
31
|
+
expect(fn).toHaveBeenCalledTimes(1);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('should retry on retryable error then succeed', async () => {
|
|
35
|
+
const fn = vi
|
|
36
|
+
.fn()
|
|
37
|
+
.mockRejectedValueOnce(Object.assign(new Error('ECONNRESET'), { code: 'ECONNRESET' }))
|
|
38
|
+
.mockResolvedValueOnce('ok');
|
|
39
|
+
const result = await withRetry(fn, { maxRetries: 2, retryDelay: 1 });
|
|
40
|
+
expect(result).toBe('ok');
|
|
41
|
+
expect(fn).toHaveBeenCalledTimes(2);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('should not retry on non-retryable error', async () => {
|
|
45
|
+
const fn = vi.fn().mockRejectedValue({ response: { status: 400 } });
|
|
46
|
+
await expect(withRetry(fn)).rejects.toMatchObject({ response: { status: 400 } });
|
|
47
|
+
expect(fn).toHaveBeenCalledTimes(1);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retry logic with exponential backoff for transient failures.
|
|
3
|
+
* Retries on 5xx and network errors; no retry for 4xx (except 429 handled by rate limiter).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { RetryConfig } from '../config';
|
|
7
|
+
import { DEFAULT_RETRY } from '../config';
|
|
8
|
+
|
|
9
|
+
export type RetryOptions = RetryConfig;
|
|
10
|
+
|
|
11
|
+
function delay(ms: number): Promise<void> {
|
|
12
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Determines if an error is retryable (5xx or network/ECONNRESET/timeout).
|
|
17
|
+
*/
|
|
18
|
+
export function isRetryableError(error: unknown): boolean {
|
|
19
|
+
if (error && typeof error === 'object' && 'response' in error) {
|
|
20
|
+
const res = (error as { response?: { status?: number } }).response;
|
|
21
|
+
if (res && typeof res.status === 'number') {
|
|
22
|
+
return res.status >= 500;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (error instanceof Error) {
|
|
26
|
+
const msg = error.message.toLowerCase();
|
|
27
|
+
const code = (error as Error & { code?: string }).code;
|
|
28
|
+
return (
|
|
29
|
+
msg.includes('econnreset') ||
|
|
30
|
+
msg.includes('etimedout') ||
|
|
31
|
+
msg.includes('network') ||
|
|
32
|
+
code === 'ECONNRESET' ||
|
|
33
|
+
code === 'ETIMEDOUT'
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Executes an async function with exponential backoff retries.
|
|
41
|
+
*/
|
|
42
|
+
export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions = {}): Promise<T> {
|
|
43
|
+
const maxRetries = options.maxRetries ?? DEFAULT_RETRY.maxRetries;
|
|
44
|
+
const retryDelay = options.retryDelay ?? DEFAULT_RETRY.retryDelay;
|
|
45
|
+
|
|
46
|
+
let lastError: unknown;
|
|
47
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
48
|
+
try {
|
|
49
|
+
return await fn();
|
|
50
|
+
} catch (err) {
|
|
51
|
+
lastError = err;
|
|
52
|
+
if (attempt === maxRetries || !isRetryableError(err)) {
|
|
53
|
+
throw err;
|
|
54
|
+
}
|
|
55
|
+
const wait = retryDelay * Math.pow(2, attempt);
|
|
56
|
+
await delay(wait);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
throw lastError;
|
|
60
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "es2016",
|
|
4
|
+
"module": "commonjs",
|
|
5
|
+
"declaration": true,
|
|
6
|
+
"outDir": "./dist",
|
|
7
|
+
"strict": true,
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"skipLibCheck": true,
|
|
10
|
+
"forceConsistentCasingInFileNames": true
|
|
11
|
+
},
|
|
12
|
+
"include": ["src"]
|
|
13
|
+
}
|