@lightdash-tools/client 0.8.0 → 0.11.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.
@@ -13,9 +13,14 @@ export declare class AiAgentsDiscoveryClient extends BaseApiClient {
13
13
  evaluateAgentReadiness(projectUuid: string, agentUuid: string): Promise<ReadinessScore>;
14
14
  /**
15
15
  * Summarize explore access for tag-filtered explores
16
- * (POST …/explore-access-summary).
16
+ * (POST …/explore-access-summary). Project-scoped; no agent path segment.
17
17
  */
18
- getExploreAccessSummary(projectUuid: string, _agentUuid: string, body?: ExploreAccessSummaryBody): Promise<AiAgentExploreAccessSummary[]>;
18
+ getExploreAccessSummary(projectUuid: string, body?: ExploreAccessSummaryBody): Promise<AiAgentExploreAccessSummary[]>;
19
+ /**
20
+ * @deprecated `agentUuid` is ignored; the endpoint is project-scoped.
21
+ * Prefer `getExploreAccessSummary(projectUuid, body?)`.
22
+ */
23
+ getExploreAccessSummary(projectUuid: string, agentUuid: string, body?: ExploreAccessSummaryBody): Promise<AiAgentExploreAccessSummary[]>;
19
24
  /**
20
25
  * Get user default agent preferences (GET …/preferences).
21
26
  * Returns null when the user has not set preferences (`ApiSuccessEmpty`).
@@ -19,12 +19,9 @@ class AiAgentsDiscoveryClient extends base_client_1.BaseApiClient {
19
19
  async evaluateAgentReadiness(projectUuid, agentUuid) {
20
20
  return this.http.post(`/projects/${projectUuid}/aiAgents/${agentUuid}/evaluateReadiness`, {});
21
21
  }
22
- /**
23
- * Summarize explore access for tag-filtered explores
24
- * (POST …/explore-access-summary).
25
- */
26
- async getExploreAccessSummary(projectUuid, _agentUuid, body) {
27
- return this.http.post(`/projects/${projectUuid}/aiAgents/explore-access-summary`, body !== null && body !== void 0 ? body : { tags: null });
22
+ async getExploreAccessSummary(projectUuid, agentUuidOrBody, body) {
23
+ const resolvedBody = typeof agentUuidOrBody === 'string' ? body : agentUuidOrBody;
24
+ return this.http.post(`/projects/${projectUuid}/aiAgents/explore-access-summary`, resolvedBody !== null && resolvedBody !== void 0 ? resolvedBody : { tags: null });
28
25
  }
29
26
  /**
30
27
  * Get user default agent preferences (GET …/preferences).
@@ -46,13 +46,29 @@ const discovery_1 = require("./discovery");
46
46
  const client = new discovery_1.AiAgentsDiscoveryClient(mockHttp);
47
47
  const summary = [{ exploreName: 'orders', metrics: [], dimensions: [], joinedTables: [] }];
48
48
  vitest_1.vi.mocked(mockHttp.post).mockResolvedValue(summary);
49
- const result = await client.getExploreAccessSummary('proj1', 'a1', { tags: ['ai'] });
49
+ const result = await client.getExploreAccessSummary('proj1', { tags: ['ai'] });
50
50
  (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
51
51
  tags: ['ai'],
52
52
  });
53
53
  (0, vitest_1.expect)(result).toEqual(summary);
54
54
  });
55
55
  (0, vitest_1.it)('getExploreAccessSummary without body should default tags to null', async () => {
56
+ const client = new discovery_1.AiAgentsDiscoveryClient(mockHttp);
57
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue([]);
58
+ await client.getExploreAccessSummary('proj1');
59
+ (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
60
+ tags: null,
61
+ });
62
+ });
63
+ (0, vitest_1.it)('getExploreAccessSummary legacy (project, agentUuid, body) ignores agentUuid', async () => {
64
+ const client = new discovery_1.AiAgentsDiscoveryClient(mockHttp);
65
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue([]);
66
+ await client.getExploreAccessSummary('proj1', 'a1', { tags: ['ai'] });
67
+ (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/explore-access-summary', {
68
+ tags: ['ai'],
69
+ });
70
+ });
71
+ (0, vitest_1.it)('getExploreAccessSummary legacy (project, agentUuid) defaults tags to null', async () => {
56
72
  const client = new discovery_1.AiAgentsDiscoveryClient(mockHttp);
57
73
  vitest_1.vi.mocked(mockHttp.post).mockResolvedValue([]);
58
74
  await client.getExploreAccessSummary('proj1', 'a1');
@@ -30,6 +30,11 @@ export declare class AiAgentsClient extends BaseApiClient {
30
30
  getAgentModelOptions(projectUuid: string, agentUuid: string): Promise<AiModelOption[]>;
31
31
  getAgentSuggestions(projectUuid: string, agentUuid: string, params?: GetAgentSuggestionsParams): Promise<AgentSuggestions>;
32
32
  evaluateAgentReadiness(projectUuid: string, agentUuid: string): Promise<ReadinessScore>;
33
+ getExploreAccessSummary(projectUuid: string, body?: ExploreAccessSummaryBody): Promise<AiAgentExploreAccessSummary[]>;
34
+ /**
35
+ * @deprecated `agentUuid` is ignored; the endpoint is project-scoped.
36
+ * Prefer `getExploreAccessSummary(projectUuid, body?)`.
37
+ */
33
38
  getExploreAccessSummary(projectUuid: string, agentUuid: string, body?: ExploreAccessSummaryBody): Promise<AiAgentExploreAccessSummary[]>;
34
39
  getUserAgentPreferences(projectUuid: string): Promise<AiAgentUserPreferences | null>;
35
40
  setUserAgentPreferences(projectUuid: string, body: AiAgentUserPreferences): Promise<void>;
@@ -67,8 +67,11 @@ class AiAgentsClient extends base_client_1.BaseApiClient {
67
67
  evaluateAgentReadiness(projectUuid, agentUuid) {
68
68
  return this.discovery.evaluateAgentReadiness(projectUuid, agentUuid);
69
69
  }
70
- getExploreAccessSummary(projectUuid, agentUuid, body) {
71
- return this.discovery.getExploreAccessSummary(projectUuid, agentUuid, body);
70
+ getExploreAccessSummary(projectUuid, agentUuidOrBody, body) {
71
+ if (typeof agentUuidOrBody === 'string') {
72
+ return this.discovery.getExploreAccessSummary(projectUuid, agentUuidOrBody, body);
73
+ }
74
+ return this.discovery.getExploreAccessSummary(projectUuid, agentUuidOrBody);
72
75
  }
73
76
  getUserAgentPreferences(projectUuid) {
74
77
  return this.discovery.getUserAgentPreferences(projectUuid);
@@ -12,6 +12,15 @@ export interface GetChartsAsCodeOptions {
12
12
  export type ChartHistoryResults = components['schemas']['ApiGetChartHistoryResponse']['results'];
13
13
  /** Results of GET saved/{chartUuid}/version/{versionUuid} (a single chart version). */
14
14
  export type ChartVersionResults = components['schemas']['ApiGetChartVersionResponse']['results'];
15
+ /** Headless chart PNG export can take longer than the default HTTP timeout. */
16
+ export declare const CHART_IMAGE_EXPORT_TIMEOUT_MS = 120000;
17
+ /** Hard cap on downloaded PNG size (8 MiB). */
18
+ export declare const CHART_IMAGE_MAX_BYTES: number;
19
+ export type ChartImagePng = {
20
+ imageUrl: string;
21
+ bytes: Buffer;
22
+ mimeType: string;
23
+ };
15
24
  export declare class ChartsClient extends BaseApiClient {
16
25
  /**
17
26
  * List charts in a project (returns SpaceQuery array).
@@ -26,4 +35,14 @@ export declare class ChartsClient extends BaseApiClient {
26
35
  getChartHistory(chartUuid: string): Promise<ChartHistoryResults>;
27
36
  /** Get a single chart version by UUID. */
28
37
  getChartVersion(chartUuid: string, versionUuid: string): Promise<ChartVersionResults>;
38
+ /**
39
+ * Export a saved chart as a PNG via headless render.
40
+ * @returns Image URL string from `ApiExportChartImageResponse.results`.
41
+ */
42
+ exportChartImage(chartUuid: string, projectUuid?: string): Promise<string>;
43
+ /**
44
+ * Export a saved chart PNG and download the image bytes.
45
+ * Requires Lightdash headless browser support on the instance.
46
+ */
47
+ exportChartImagePng(chartUuid: string, projectUuid?: string): Promise<ChartImagePng>;
29
48
  }
@@ -3,8 +3,14 @@
3
3
  * Charts API client. Endpoints for saved charts and chart-as-code operations.
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ChartsClient = void 0;
6
+ exports.ChartsClient = exports.CHART_IMAGE_MAX_BYTES = exports.CHART_IMAGE_EXPORT_TIMEOUT_MS = void 0;
7
+ const errors_1 = require("../../errors");
8
+ const http_client_1 = require("../../http/http-client");
7
9
  const base_client_1 = require("../base-client");
10
+ /** Headless chart PNG export can take longer than the default HTTP timeout. */
11
+ exports.CHART_IMAGE_EXPORT_TIMEOUT_MS = 120000;
12
+ /** Hard cap on downloaded PNG size (8 MiB). */
13
+ exports.CHART_IMAGE_MAX_BYTES = http_client_1.DEFAULT_BINARY_MAX_BYTES;
8
14
  class ChartsClient extends base_client_1.BaseApiClient {
9
15
  /**
10
16
  * List charts in a project (returns SpaceQuery array).
@@ -37,5 +43,41 @@ class ChartsClient extends base_client_1.BaseApiClient {
37
43
  async getChartVersion(chartUuid, versionUuid) {
38
44
  return this.http.get(`/saved/${chartUuid}/version/${versionUuid}`);
39
45
  }
46
+ /**
47
+ * Export a saved chart as a PNG via headless render.
48
+ * @returns Image URL string from `ApiExportChartImageResponse.results`.
49
+ */
50
+ async exportChartImage(chartUuid, projectUuid) {
51
+ return this.http.post(`/saved/${encodeURIComponent(chartUuid)}/export`, undefined, {
52
+ params: projectUuid ? { projectUuid } : undefined,
53
+ timeout: exports.CHART_IMAGE_EXPORT_TIMEOUT_MS,
54
+ });
55
+ }
56
+ /**
57
+ * Export a saved chart PNG and download the image bytes.
58
+ * Requires Lightdash headless browser support on the instance.
59
+ */
60
+ async exportChartImagePng(chartUuid, projectUuid) {
61
+ const imageUrl = await this.exportChartImage(chartUuid, projectUuid);
62
+ let bytes;
63
+ let mimeType;
64
+ try {
65
+ ({ bytes, mimeType } = await this.http.getBytes(imageUrl, {
66
+ maxBytes: exports.CHART_IMAGE_MAX_BYTES,
67
+ timeout: exports.CHART_IMAGE_EXPORT_TIMEOUT_MS,
68
+ }));
69
+ }
70
+ catch (err) {
71
+ if (err instanceof errors_1.BinarySizeLimitError) {
72
+ throw new errors_1.ChartImageSizeError(err.maxBytes, err.byteLength);
73
+ }
74
+ throw err;
75
+ }
76
+ return {
77
+ imageUrl,
78
+ bytes,
79
+ mimeType: mimeType === 'application/octet-stream' ? 'image/png' : mimeType,
80
+ };
81
+ }
40
82
  }
41
83
  exports.ChartsClient = ChartsClient;
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const vitest_1 = require("vitest");
4
- const charts_1 = require("./charts");
4
+ const errors_js_1 = require("../../errors.js");
5
+ const charts_js_1 = require("./charts.js");
5
6
  (0, vitest_1.describe)('ChartsClient', () => {
6
7
  let mockHttp;
7
8
  (0, vitest_1.beforeEach)(() => {
@@ -11,10 +12,11 @@ const charts_1 = require("./charts");
11
12
  put: vitest_1.vi.fn(),
12
13
  patch: vitest_1.vi.fn(),
13
14
  delete: vitest_1.vi.fn(),
15
+ getBytes: vitest_1.vi.fn(),
14
16
  };
15
17
  });
16
18
  (0, vitest_1.it)('listCharts should call GET /projects/{projectUuid}/charts', async () => {
17
- const client = new charts_1.ChartsClient(mockHttp);
19
+ const client = new charts_js_1.ChartsClient(mockHttp);
18
20
  const charts = [{ uuid: 'c1', name: 'Chart 1', projectUuid: 'p1' }];
19
21
  vitest_1.vi.mocked(mockHttp.get).mockResolvedValue(charts);
20
22
  const result = await client.listCharts('p1');
@@ -22,7 +24,7 @@ const charts_1 = require("./charts");
22
24
  (0, vitest_1.expect)(result).toEqual(charts);
23
25
  });
24
26
  (0, vitest_1.it)('getChartsAsCode should call GET /projects/{projectUuid}/code/charts with no params when no options', async () => {
25
- const client = new charts_1.ChartsClient(mockHttp);
27
+ const client = new charts_js_1.ChartsClient(mockHttp);
26
28
  const results = { offset: 0, total: 1, missingIds: [], charts: [] };
27
29
  vitest_1.vi.mocked(mockHttp.get).mockResolvedValue(results);
28
30
  const result = await client.getChartsAsCode('p1');
@@ -30,7 +32,7 @@ const charts_1 = require("./charts");
30
32
  (0, vitest_1.expect)(result).toEqual(results);
31
33
  });
32
34
  (0, vitest_1.it)('getChartsAsCode should call GET with query params when options provided', async () => {
33
- const client = new charts_1.ChartsClient(mockHttp);
35
+ const client = new charts_js_1.ChartsClient(mockHttp);
34
36
  const results = { offset: 0, total: 0, missingIds: [], charts: [] };
35
37
  vitest_1.vi.mocked(mockHttp.get).mockResolvedValue(results);
36
38
  await client.getChartsAsCode('p1', {
@@ -43,7 +45,7 @@ const charts_1 = require("./charts");
43
45
  });
44
46
  });
45
47
  (0, vitest_1.it)('upsertChartAsCode should call POST /projects/{projectUuid}/code/charts/{slug} with body', async () => {
46
- const client = new charts_1.ChartsClient(mockHttp);
48
+ const client = new charts_js_1.ChartsClient(mockHttp);
47
49
  const body = {
48
50
  name: 'My Chart',
49
51
  slug: 'my-chart',
@@ -70,7 +72,7 @@ const charts_1 = require("./charts");
70
72
  (0, vitest_1.expect)(result).toEqual(apiResult);
71
73
  });
72
74
  (0, vitest_1.it)('upsertChartAsCode should encode slug in path', async () => {
73
- const client = new charts_1.ChartsClient(mockHttp);
75
+ const client = new charts_js_1.ChartsClient(mockHttp);
74
76
  const body = {
75
77
  name: 'Chart',
76
78
  slug: 'chart/slug',
@@ -95,7 +97,7 @@ const charts_1 = require("./charts");
95
97
  (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/projects/p1/code/charts/chart%2Fslug', body);
96
98
  });
97
99
  (0, vitest_1.it)('getChartHistory should call GET /saved/{chartUuid}/history', async () => {
98
- const client = new charts_1.ChartsClient(mockHttp);
100
+ const client = new charts_js_1.ChartsClient(mockHttp);
99
101
  const history = { chartUuid: 'c1', history: [] };
100
102
  vitest_1.vi.mocked(mockHttp.get).mockResolvedValue(history);
101
103
  const result = await client.getChartHistory('c1');
@@ -103,11 +105,46 @@ const charts_1 = require("./charts");
103
105
  (0, vitest_1.expect)(result).toEqual(history);
104
106
  });
105
107
  (0, vitest_1.it)('getChartVersion should call GET /saved/{chartUuid}/version/{versionUuid}', async () => {
106
- const client = new charts_1.ChartsClient(mockHttp);
108
+ const client = new charts_js_1.ChartsClient(mockHttp);
107
109
  const version = { chartUuid: 'c1', versionUuid: 'v1' };
108
110
  vitest_1.vi.mocked(mockHttp.get).mockResolvedValue(version);
109
111
  const result = await client.getChartVersion('c1', 'v1');
110
112
  (0, vitest_1.expect)(mockHttp.get).toHaveBeenCalledWith('/saved/c1/version/v1');
111
113
  (0, vitest_1.expect)(result).toEqual(version);
112
114
  });
115
+ (0, vitest_1.it)('exportChartImage should POST /saved/{chartUuid}/export and return URL', async () => {
116
+ const client = new charts_js_1.ChartsClient(mockHttp);
117
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
118
+ const result = await client.exportChartImage('c1', 'p1');
119
+ (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/saved/c1/export', undefined, {
120
+ params: { projectUuid: 'p1' },
121
+ timeout: 120000,
122
+ });
123
+ (0, vitest_1.expect)(result).toBe('https://cdn.example/chart.png');
124
+ });
125
+ (0, vitest_1.it)('exportChartImagePng should export then download bytes', async () => {
126
+ const client = new charts_js_1.ChartsClient(mockHttp);
127
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
128
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
129
+ vitest_1.vi.mocked(mockHttp.getBytes).mockResolvedValue({ bytes: png, mimeType: 'image/png' });
130
+ const result = await client.exportChartImagePng('c1');
131
+ (0, vitest_1.expect)(mockHttp.getBytes).toHaveBeenCalledWith('https://cdn.example/chart.png', {
132
+ maxBytes: 8 * 1024 * 1024,
133
+ timeout: 120000,
134
+ });
135
+ (0, vitest_1.expect)(result).toEqual({
136
+ imageUrl: 'https://cdn.example/chart.png',
137
+ bytes: png,
138
+ mimeType: 'image/png',
139
+ });
140
+ });
141
+ (0, vitest_1.it)('exportChartImagePng maps BinarySizeLimitError to ChartImageSizeError', async () => {
142
+ const client = new charts_js_1.ChartsClient(mockHttp);
143
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue('https://cdn.example/chart.png');
144
+ vitest_1.vi.mocked(mockHttp.getBytes).mockRejectedValue(new errors_js_1.BinarySizeLimitError(8 * 1024 * 1024));
145
+ await (0, vitest_1.expect)(client.exportChartImagePng('c1')).rejects.toMatchObject({
146
+ code: 'IMAGE_TOO_LARGE',
147
+ maxBytes: 8 * 1024 * 1024,
148
+ });
149
+ });
113
150
  });
package/dist/errors.d.ts CHANGED
@@ -2,6 +2,10 @@
2
2
  * Error types for the Lightdash HTTP client.
3
3
  */
4
4
  import type { AxiosRequestConfig, AxiosResponse } from 'axios';
5
+ /** HttpClient name when the response body is not a Lightdash success/error envelope. */
6
+ export declare const CONTRACT_ERROR_NAME = "ContractError";
7
+ /** Human-readable message for {@link CONTRACT_ERROR_NAME}. */
8
+ export declare const CONTRACT_ERROR_MESSAGE = "Unexpected Lightdash API response shape";
5
9
  /** API error payload shape (from Lightdash ApiErrorPayload). */
6
10
  export interface ApiErrorPayload {
7
11
  error: {
@@ -37,3 +41,21 @@ export declare class NetworkError extends Error {
37
41
  readonly originalError: Error;
38
42
  constructor(message: string, originalError: Error);
39
43
  }
44
+ /**
45
+ * Thrown when a binary download exceeds the configured byte limit.
46
+ */
47
+ export declare class BinarySizeLimitError extends Error {
48
+ readonly maxBytes: number;
49
+ readonly byteLength?: number | undefined;
50
+ readonly code: "PAYLOAD_TOO_LARGE";
51
+ constructor(maxBytes: number, byteLength?: number | undefined);
52
+ }
53
+ /**
54
+ * Thrown when a chart PNG export exceeds the configured byte limit.
55
+ */
56
+ export declare class ChartImageSizeError extends Error {
57
+ readonly maxBytes: number;
58
+ readonly byteLength?: number | undefined;
59
+ readonly code: "IMAGE_TOO_LARGE";
60
+ constructor(maxBytes: number, byteLength?: number | undefined);
61
+ }
package/dist/errors.js CHANGED
@@ -3,7 +3,11 @@
3
3
  * Error types for the Lightdash HTTP client.
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.NetworkError = exports.RateLimitError = exports.LightdashApiError = void 0;
6
+ exports.ChartImageSizeError = exports.BinarySizeLimitError = exports.NetworkError = exports.RateLimitError = exports.LightdashApiError = exports.CONTRACT_ERROR_MESSAGE = exports.CONTRACT_ERROR_NAME = void 0;
7
+ /** HttpClient name when the response body is not a Lightdash success/error envelope. */
8
+ exports.CONTRACT_ERROR_NAME = 'ContractError';
9
+ /** Human-readable message for {@link CONTRACT_ERROR_NAME}. */
10
+ exports.CONTRACT_ERROR_MESSAGE = 'Unexpected Lightdash API response shape';
7
11
  /**
8
12
  * Base error for Lightdash API failures.
9
13
  */
@@ -44,3 +48,35 @@ class NetworkError extends Error {
44
48
  }
45
49
  }
46
50
  exports.NetworkError = NetworkError;
51
+ /**
52
+ * Thrown when a binary download exceeds the configured byte limit.
53
+ */
54
+ class BinarySizeLimitError extends Error {
55
+ constructor(maxBytes, byteLength) {
56
+ super(byteLength === undefined
57
+ ? `Binary payload exceeds size limit (≥ ${maxBytes} bytes)`
58
+ : `Binary payload exceeds size limit (${byteLength} > ${maxBytes} bytes)`);
59
+ this.maxBytes = maxBytes;
60
+ this.byteLength = byteLength;
61
+ this.code = 'PAYLOAD_TOO_LARGE';
62
+ this.name = 'BinarySizeLimitError';
63
+ Object.setPrototypeOf(this, BinarySizeLimitError.prototype);
64
+ }
65
+ }
66
+ exports.BinarySizeLimitError = BinarySizeLimitError;
67
+ /**
68
+ * Thrown when a chart PNG export exceeds the configured byte limit.
69
+ */
70
+ class ChartImageSizeError extends Error {
71
+ constructor(maxBytes, byteLength) {
72
+ super(byteLength === undefined
73
+ ? `Chart image exceeds size limit (≥ ${maxBytes} bytes)`
74
+ : `Chart image exceeds size limit (${byteLength} > ${maxBytes} bytes)`);
75
+ this.maxBytes = maxBytes;
76
+ this.byteLength = byteLength;
77
+ this.code = 'IMAGE_TOO_LARGE';
78
+ this.name = 'ChartImageSizeError';
79
+ Object.setPrototypeOf(this, ChartImageSizeError.prototype);
80
+ }
81
+ }
82
+ exports.ChartImageSizeError = ChartImageSizeError;
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Unit tests for binary download URL guards and getBytes error mapping.
3
+ */
4
+ export {};
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ /**
3
+ * Unit tests for binary download URL guards and getBytes error mapping.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const axios_1 = require("axios");
7
+ const vitest_1 = require("vitest");
8
+ const http_client_js_1 = require("./http-client.js");
9
+ (0, vitest_1.describe)('isBlockedBinaryHostname', () => {
10
+ (0, vitest_1.it)('blocks loopback and private IPv4 hosts', () => {
11
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('localhost')).toBe(true);
12
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('127.0.0.1')).toBe(true);
13
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('10.0.0.1')).toBe(true);
14
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('192.168.1.1')).toBe(true);
15
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('172.16.0.1')).toBe(true);
16
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('169.254.169.254')).toBe(true);
17
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('metadata.google.internal')).toBe(true);
18
+ });
19
+ (0, vitest_1.it)('allows public hostnames', () => {
20
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('cdn.example.com')).toBe(false);
21
+ (0, vitest_1.expect)((0, http_client_js_1.isBlockedBinaryHostname)('s3.amazonaws.com')).toBe(false);
22
+ });
23
+ });
24
+ (0, vitest_1.describe)('assertSafeBinaryFetchUrl', () => {
25
+ (0, vitest_1.it)('rejects same-host HTTPS to HTTP downgrades', () => {
26
+ (0, vitest_1.expect)(() => (0, http_client_js_1.assertSafeBinaryFetchUrl)('http://app.lightdash.com/export/chart.png', 'https://app.lightdash.com')).toThrow(/must not downgrade HTTPS to HTTP/);
27
+ });
28
+ (0, vitest_1.it)('allows same-host HTTPS URLs', () => {
29
+ (0, vitest_1.expect)(() => (0, http_client_js_1.assertSafeBinaryFetchUrl)('https://app.lightdash.com/export/chart.png', 'https://app.lightdash.com')).not.toThrow();
30
+ });
31
+ (0, vitest_1.it)('allows relative URLs without validation', () => {
32
+ (0, vitest_1.expect)(() => (0, http_client_js_1.assertSafeBinaryFetchUrl)('/api/v1/export.png', 'https://app.lightdash.com')).not.toThrow();
33
+ });
34
+ });
35
+ (0, vitest_1.describe)('HttpClient.getBytes', () => {
36
+ function makeClient(getImpl) {
37
+ const axiosInstance = { get: getImpl };
38
+ const rateLimiter = {
39
+ schedule: (fn) => fn(),
40
+ };
41
+ const config = {
42
+ baseUrl: 'https://app.lightdash.com',
43
+ timeout: 30000,
44
+ retry: { maxRetries: 0 },
45
+ };
46
+ return new http_client_js_1.HttpClient(axiosInstance, rateLimiter, config);
47
+ }
48
+ (0, vitest_1.it)('maps axios maxContentLength errors to BinarySizeLimitError', async () => {
49
+ const maxBytes = 1024;
50
+ const axiosError = new axios_1.AxiosError('maxContentLength size of 1024 exceeded');
51
+ const client = makeClient(vitest_1.vi.fn().mockRejectedValue(axiosError));
52
+ await (0, vitest_1.expect)(client.getBytes('/chart.png', { maxBytes })).rejects.toMatchObject({
53
+ code: 'PAYLOAD_TOO_LARGE',
54
+ maxBytes,
55
+ });
56
+ });
57
+ (0, vitest_1.it)('rejects same-host HTTP downgrade before fetching', async () => {
58
+ const client = makeClient(vitest_1.vi.fn());
59
+ await (0, vitest_1.expect)(client.getBytes('http://app.lightdash.com/chart.png')).rejects.toThrow(/must not downgrade HTTPS to HTTP/);
60
+ });
61
+ });
@@ -5,6 +5,22 @@
5
5
  import { type RateLimiter } from './rate-limiter';
6
6
  import type { ResolvedLightdashClientConfig } from '../config';
7
7
  import type { AxiosInstance, AxiosRequestConfig } from 'axios';
8
+ /** Default max raw bytes for chart PNG downloads (8 MiB). */
9
+ export declare const DEFAULT_BINARY_MAX_BYTES: number;
10
+ export type GetBytesOptions = {
11
+ /** Hard cap on response body size in bytes. */
12
+ maxBytes?: number;
13
+ /** Per-request timeout override (ms). */
14
+ timeout?: number;
15
+ };
16
+ export type GetBytesResult = {
17
+ bytes: Buffer;
18
+ mimeType: string;
19
+ };
20
+ /** True when hostname is loopback, link-local, or RFC1918 (cross-host SSRF guard). */
21
+ export declare function isBlockedBinaryHostname(hostname: string): boolean;
22
+ /** Reject unsafe absolute binary download URLs (exported for unit tests). */
23
+ export declare function assertSafeBinaryFetchUrl(url: string, baseUrl: string): void;
8
24
  /**
9
25
  * HTTP client that wraps Axios with rate limiting and retry.
10
26
  */
@@ -19,4 +35,11 @@ export declare class HttpClient {
19
35
  put<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T>;
20
36
  patch<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T>;
21
37
  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
38
+ /**
39
+ * Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
40
+ * authenticated API client; absolute URLs on a different host (e.g. signed S3)
41
+ * are fetched without Lightdash Authorization. Cross-host fetches require https,
42
+ * disallow private/link-local hosts, and follow no redirects.
43
+ */
44
+ getBytes(url: string, options?: GetBytesOptions): Promise<GetBytesResult>;
22
45
  }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Unit tests for HttpClient success-envelope harden.
3
+ */
4
+ export {};
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /**
3
+ * Unit tests for HttpClient success-envelope harden.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const vitest_1 = require("vitest");
7
+ const errors_js_1 = require("../errors.js");
8
+ const http_client_js_1 = require("./http-client.js");
9
+ (0, vitest_1.describe)('HttpClient envelope harden', () => {
10
+ function makeClient(requestImpl) {
11
+ const axiosInstance = { request: requestImpl };
12
+ const rateLimiter = {
13
+ schedule: (fn) => fn(),
14
+ };
15
+ const config = {
16
+ baseUrl: 'https://app.lightdash.com',
17
+ timeout: 30000,
18
+ retry: { maxRetries: 0 },
19
+ };
20
+ return new http_client_js_1.HttpClient(axiosInstance, rateLimiter, config);
21
+ }
22
+ (0, vitest_1.it)('returns results for ok envelopes', async () => {
23
+ const client = makeClient(vitest_1.vi.fn().mockResolvedValue({
24
+ status: 200,
25
+ data: { status: 'ok', results: { id: '1' } },
26
+ config: {},
27
+ }));
28
+ await (0, vitest_1.expect)(client.get('/x')).resolves.toEqual({ id: '1' });
29
+ });
30
+ (0, vitest_1.it)('throws LightdashApiError for error envelopes', async () => {
31
+ const client = makeClient(vitest_1.vi.fn().mockResolvedValue({
32
+ status: 200,
33
+ data: {
34
+ status: 'error',
35
+ error: { name: 'Bad', statusCode: 400, message: 'nope' },
36
+ },
37
+ config: {},
38
+ }));
39
+ await (0, vitest_1.expect)(client.get('/x')).rejects.toMatchObject({
40
+ statusCode: 400,
41
+ error: { message: 'nope' },
42
+ });
43
+ });
44
+ (0, vitest_1.it)('throws ContractError for malformed 200 bodies', async () => {
45
+ const client = makeClient(vitest_1.vi.fn().mockResolvedValue({
46
+ status: 200,
47
+ data: { foo: 1 },
48
+ config: {},
49
+ }));
50
+ await (0, vitest_1.expect)(client.get('/x')).rejects.toSatisfy((err) => {
51
+ (0, vitest_1.expect)(err).toBeInstanceOf(errors_js_1.LightdashApiError);
52
+ const apiErr = err;
53
+ (0, vitest_1.expect)(apiErr.statusCode).toBe(502);
54
+ (0, vitest_1.expect)(apiErr.error.name).toBe(errors_js_1.CONTRACT_ERROR_NAME);
55
+ (0, vitest_1.expect)(apiErr.error.message).toBe(errors_js_1.CONTRACT_ERROR_MESSAGE);
56
+ return true;
57
+ });
58
+ });
59
+ });