@superdurable/connector-clickhouse 0.0.0-stage → 0.2.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.
@@ -0,0 +1,216 @@
1
+ import { L as ListColumnsInput, C as ColumnsPage, a as Connection$1, b as ListDatabasesInput, D as DatabasesPage, c as ListTablesInput, T as TablesPage, O as Operations, d as Config, e as Credentials } from './connection-IQqDAR8z.js';
2
+ export { f as Column, g as ColumnSchema, h as ColumnsPageSchema, i as ConfigSchema, j as CredentialMaterialError, k as CredentialSource, l as DatabasesPageSchema, m as ListColumnsInputSchema, n as ListDatabasesInputSchema, o as ListTablesInputSchema, p as TablesPageSchema, q as decodeCredentials, r as isCredentialMaterialError } from './connection-IQqDAR8z.js';
3
+ import { QueryDefinition, QueryStepConfig, Query, QueryResult, QueryStep, CredentialProvider, Call, QueryAttempt, ConnectionRef } from '@superdurable/connectors-sdk';
4
+ import { StepTarget } from '@superdurable/dex';
5
+ import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
6
+ import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
7
+ import 'zod';
8
+
9
+ /** Stable connector identity. */
10
+ declare const ConnectorID = "clickhouse";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "clickhouse";
13
+ /** Branch IDs for listDatabases. */
14
+ declare const ListDatabasesBranch: {
15
+ readonly Listed: "listed";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** ClickHouse returned the database names. */
21
+ declare const ListDatabasesBranchListed: "listed";
22
+ /** ClickHouse conclusively rejected the metadata query. */
23
+ declare const ListDatabasesBranchProviderRejected: "providerRejected";
24
+ /** ClickHouse returned malformed or oversized JSON. */
25
+ declare const ListDatabasesBranchInvalidResponse: "invalidResponse";
26
+ /** Local connection credentials are invalid. */
27
+ declare const ListDatabasesBranchDefect: "defect";
28
+ /** Manifest definition for listDatabases. */
29
+ declare const ListDatabasesDefinition: QueryDefinition;
30
+ /** Manifest metadata for listDatabases. */
31
+ declare const ListDatabasesMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+ /** Branch IDs for listTables. */
37
+ declare const ListTablesBranch: {
38
+ readonly Listed: "listed";
39
+ readonly ProviderRejected: "providerRejected";
40
+ readonly InvalidResponse: "invalidResponse";
41
+ readonly Defect: "defect";
42
+ };
43
+ /** ClickHouse returned the table names. */
44
+ declare const ListTablesBranchListed: "listed";
45
+ /** ClickHouse conclusively rejected the metadata query. */
46
+ declare const ListTablesBranchProviderRejected: "providerRejected";
47
+ /** ClickHouse returned malformed or oversized JSON. */
48
+ declare const ListTablesBranchInvalidResponse: "invalidResponse";
49
+ /** Local input or connection credentials are invalid. */
50
+ declare const ListTablesBranchDefect: "defect";
51
+ /** Manifest definition for listTables. */
52
+ declare const ListTablesDefinition: QueryDefinition;
53
+ /** Manifest metadata for listTables. */
54
+ declare const ListTablesMetadata: {
55
+ readonly kind: "query";
56
+ readonly idempotency: "none";
57
+ readonly authorization: "required";
58
+ };
59
+ /** Branch IDs for listColumns. */
60
+ declare const ListColumnsBranch: {
61
+ readonly Listed: "listed";
62
+ readonly ProviderRejected: "providerRejected";
63
+ readonly InvalidResponse: "invalidResponse";
64
+ readonly Defect: "defect";
65
+ };
66
+ /** ClickHouse returned the table columns. */
67
+ declare const ListColumnsBranchListed: "listed";
68
+ /** ClickHouse conclusively rejected the metadata query. */
69
+ declare const ListColumnsBranchProviderRejected: "providerRejected";
70
+ /** ClickHouse returned malformed or oversized JSON. */
71
+ declare const ListColumnsBranchInvalidResponse: "invalidResponse";
72
+ /** Local input or connection credentials are invalid. */
73
+ declare const ListColumnsBranchDefect: "defect";
74
+ /** Manifest definition for listColumns. */
75
+ declare const ListColumnsDefinition: QueryDefinition;
76
+ /** Manifest metadata for listColumns. */
77
+ declare const ListColumnsMetadata: {
78
+ readonly kind: "query";
79
+ readonly idempotency: "none";
80
+ readonly authorization: "required";
81
+ };
82
+
83
+ /** Configuration for the listDatabases connector Step. */
84
+ interface ListDatabasesStepConfig<StepInput, OperationInput = ListDatabasesInput, OperationOutput = DatabasesPage> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
85
+ /** Named connection supplying this operation. */
86
+ connection: Connection$1<{
87
+ listDatabases(): Query<OperationInput, OperationOutput>;
88
+ }>;
89
+ /** Name matching the bound connection. */
90
+ connectionName: string;
91
+ /** ClickHouse returned the database names. */
92
+ listed: StepTarget<QueryResult<OperationOutput>>;
93
+ /** ClickHouse conclusively rejected the metadata query. */
94
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
95
+ /** ClickHouse returned malformed or oversized JSON. */
96
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
97
+ /** Local connection credentials are invalid. */
98
+ defect?: StepTarget<QueryResult<OperationOutput>>;
99
+ }
100
+ /** Build the listDatabases Step from a named connection. */
101
+ declare function newListDatabasesStep<StepInput, OperationInput = ListDatabasesInput, OperationOutput = DatabasesPage>(configuration: ListDatabasesStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
102
+ /** Configuration for the listTables connector Step. */
103
+ interface ListTablesStepConfig<StepInput, OperationInput = ListTablesInput, OperationOutput = TablesPage> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
104
+ /** Named connection supplying this operation. */
105
+ connection: Connection$1<{
106
+ listTables(): Query<OperationInput, OperationOutput>;
107
+ }>;
108
+ /** Name matching the bound connection. */
109
+ connectionName: string;
110
+ /** ClickHouse returned the table names. */
111
+ listed: StepTarget<QueryResult<OperationOutput>>;
112
+ /** ClickHouse conclusively rejected the metadata query. */
113
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
114
+ /** ClickHouse returned malformed or oversized JSON. */
115
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
116
+ /** Local input or connection credentials are invalid. */
117
+ defect?: StepTarget<QueryResult<OperationOutput>>;
118
+ }
119
+ /** Build the listTables Step from a named connection. */
120
+ declare function newListTablesStep<StepInput, OperationInput = ListTablesInput, OperationOutput = TablesPage>(configuration: ListTablesStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
121
+ /** Configuration for the listColumns connector Step. */
122
+ interface ListColumnsStepConfig<StepInput, OperationInput = ListColumnsInput, OperationOutput = ColumnsPage> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
123
+ /** Named connection supplying this operation. */
124
+ connection: Connection$1<{
125
+ listColumns(): Query<OperationInput, OperationOutput>;
126
+ }>;
127
+ /** Name matching the bound connection. */
128
+ connectionName: string;
129
+ /** ClickHouse returned the table columns. */
130
+ listed: StepTarget<QueryResult<OperationOutput>>;
131
+ /** ClickHouse conclusively rejected the metadata query. */
132
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
133
+ /** ClickHouse returned malformed or oversized JSON. */
134
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
135
+ /** Local input or connection credentials are invalid. */
136
+ defect?: StepTarget<QueryResult<OperationOutput>>;
137
+ }
138
+ /** Build the listColumns Step from a named connection. */
139
+ declare function newListColumnsStep<StepInput, OperationInput = ListColumnsInput, OperationOutput = ColumnsPage>(configuration: ListColumnsStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
140
+
141
+ /** Open one named ClickHouse connection from Dex project configuration. */
142
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection$1<Operations>;
143
+
144
+ /** Injectable provider sender for tests and local applications. */
145
+ interface ClickHouseClientOptions {
146
+ /** Provider sender; omitted uses the SDK transport. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
147
+ }
148
+ interface Exchange {
149
+ status: number;
150
+ body: Uint8Array;
151
+ retryAfterMs: number;
152
+ error?: 'credential' | 'request' | 'tooLarge';
153
+ }
154
+ /** Authenticated ClickHouse HTTP client for database, table, and column metadata. */
155
+ declare class ClickHouseClient {
156
+ private readonly credentials;
157
+ private readonly baseURL;
158
+ private readonly timeoutMs;
159
+ private readonly maxResponseBytes;
160
+ private readonly send;
161
+ /** Validate provider configuration without contacting ClickHouse. */
162
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: ClickHouseClientOptions);
163
+ /** Bind the listTables Query. */ listTables(): ListTablesOperation;
164
+ /** Bind the database catalog Query. */
165
+ listDatabases(): ListDatabasesOperation;
166
+ /** Bind the ordered column metadata Query. */
167
+ listColumns(): ListColumnsOperation;
168
+ /** Resolve credentials and send one bounded database query. */
169
+ getDatabases(call: Call): Promise<Exchange>;
170
+ /** Resolve credentials and send one bounded column query. */
171
+ getColumns(call: Call, database: string, table: string): Promise<Exchange>;
172
+ /** Resolve credentials and send one bounded table query. */
173
+ get(call: Call, database: string): Promise<Exchange>;
174
+ private readMetadata;
175
+ }
176
+ /** Read up to 100 databases from ClickHouse system metadata. */
177
+ declare class ListDatabasesOperation implements Query<ListDatabasesInput, DatabasesPage> {
178
+ private readonly client;
179
+ /** Bind the metadata client. */
180
+ constructor(client: ClickHouseClient);
181
+ /** Return the manifest-generated definition. */
182
+ definition(): QueryDefinition;
183
+ /** Read and validate one metadata page. */
184
+ invoke(call: Call, _input: ListDatabasesInput): Promise<QueryAttempt<DatabasesPage>>;
185
+ }
186
+ /** Read up to 100 tables from ClickHouse system metadata. */
187
+ declare class ListTablesOperation implements Query<ListTablesInput, TablesPage> {
188
+ private readonly client;
189
+ /** Bind the metadata client. */
190
+ constructor(client: ClickHouseClient);
191
+ /** Return the manifest-generated definition. */
192
+ definition(): QueryDefinition;
193
+ /** Read and validate one metadata page. */
194
+ invoke(call: Call, input: ListTablesInput): Promise<QueryAttempt<TablesPage>>;
195
+ }
196
+ /** Read up to 100 columns from ClickHouse system metadata. */
197
+ declare class ListColumnsOperation implements Query<ListColumnsInput, ColumnsPage> {
198
+ private readonly client;
199
+ /** Bind the metadata client. */
200
+ constructor(client: ClickHouseClient);
201
+ /** Return the manifest-generated definition. */
202
+ definition(): QueryDefinition;
203
+ /** Read and validate one metadata page. */
204
+ invoke(call: Call, input: ListColumnsInput): Promise<QueryAttempt<ColumnsPage>>;
205
+ }
206
+
207
+ /** A named binding whose default shape accepts historical table-only clients. */
208
+ type Connection<Bound = Pick<Operations, 'listTables'>> = Connection$1<Bound>;
209
+ /** Construct a named ClickHouse binding with an explicit operation set. */
210
+ declare const Connection: typeof Connection$1;
211
+ /** Bind the supplied operations and retain the concrete client's type for typed Steps. */
212
+ declare function newConnection<Bound extends Pick<Operations, 'listTables'>>(client: Bound, reference: ConnectionRef): Connection<Bound>;
213
+ /** Bind a scripted table query and any additional metadata operations it provides. */
214
+ declare function newConnectionWithOperations<Bound extends Pick<Operations, 'listTables'>>(operations: Bound, reference: ConnectionRef): Connection<Bound>;
215
+
216
+ export { ClickHouseClient, type ClickHouseClientOptions, ColumnsPage, Config, Connection, ConnectorID, Credentials, DatabasesPage, ListColumnsBranch, ListColumnsBranchDefect, ListColumnsBranchInvalidResponse, ListColumnsBranchListed, ListColumnsBranchProviderRejected, ListColumnsDefinition, ListColumnsInput, ListColumnsMetadata, ListColumnsOperation, type ListColumnsStepConfig, ListDatabasesBranch, ListDatabasesBranchDefect, ListDatabasesBranchInvalidResponse, ListDatabasesBranchListed, ListDatabasesBranchProviderRejected, ListDatabasesDefinition, ListDatabasesInput, ListDatabasesMetadata, ListDatabasesOperation, type ListDatabasesStepConfig, ListTablesBranch, ListTablesBranchDefect, ListTablesBranchInvalidResponse, ListTablesBranchListed, ListTablesBranchProviderRejected, ListTablesDefinition, ListTablesInput, ListTablesMetadata, ListTablesOperation, type ListTablesStepConfig, Operations, ProviderID, TablesPage, newConnection, newConnectionWithOperations, newListColumnsStep, newListDatabasesStep, newListTablesStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,410 @@
1
+ import {
2
+ ColumnSchema,
3
+ ColumnsPageSchema,
4
+ ConfigSchema,
5
+ Connection,
6
+ ConnectorID,
7
+ CredentialMaterialError,
8
+ DatabasesPageSchema,
9
+ ListColumnsBranch,
10
+ ListColumnsBranchDefect,
11
+ ListColumnsBranchInvalidResponse,
12
+ ListColumnsBranchListed,
13
+ ListColumnsBranchProviderRejected,
14
+ ListColumnsDefinition,
15
+ ListColumnsInputSchema,
16
+ ListColumnsMetadata,
17
+ ListDatabasesBranch,
18
+ ListDatabasesBranchDefect,
19
+ ListDatabasesBranchInvalidResponse,
20
+ ListDatabasesBranchListed,
21
+ ListDatabasesBranchProviderRejected,
22
+ ListDatabasesDefinition,
23
+ ListDatabasesInputSchema,
24
+ ListDatabasesMetadata,
25
+ ListTablesBranch,
26
+ ListTablesBranchDefect,
27
+ ListTablesBranchInvalidResponse,
28
+ ListTablesBranchListed,
29
+ ListTablesBranchProviderRejected,
30
+ ListTablesDefinition,
31
+ ListTablesInputSchema,
32
+ ListTablesMetadata,
33
+ ProviderID,
34
+ TablesPageSchema,
35
+ decodeCredentials,
36
+ isCredentialMaterialError,
37
+ newProjectConnection
38
+ } from "./chunk-23BBEJPR.js";
39
+
40
+ // src/generated/steps.ts
41
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
42
+ function newListDatabasesStep(configuration) {
43
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
44
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
45
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listDatabases(), connection: connection.reference, branches: [
46
+ goToBranch("listed", listed),
47
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
48
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
49
+ ...defect ? [goToBranch("defect", defect)] : []
50
+ ] });
51
+ }
52
+ function newListTablesStep(configuration) {
53
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
54
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
55
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listTables(), connection: connection.reference, branches: [
56
+ goToBranch("listed", listed),
57
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
58
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
59
+ ...defect ? [goToBranch("defect", defect)] : []
60
+ ] });
61
+ }
62
+ function newListColumnsStep(configuration) {
63
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
64
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
65
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listColumns(), connection: connection.reference, branches: [
66
+ goToBranch("listed", listed),
67
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
68
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
69
+ ...defect ? [goToBranch("defect", defect)] : []
70
+ ] });
71
+ }
72
+
73
+ // src/project.ts
74
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
75
+ import { z } from "zod";
76
+
77
+ // src/client.ts
78
+ import {
79
+ SecretString,
80
+ newQueryBranch,
81
+ newQueryRetry
82
+ } from "@superdurable/connectors-sdk";
83
+ import {
84
+ BodyTooLargeError,
85
+ isHeaderSafeCredential,
86
+ parseRetryAfter,
87
+ sendProviderRequest,
88
+ validateBaseURL
89
+ } from "@superdurable/connectors-sdk/providerhttp";
90
+ var listTablesSQL = "SELECT name FROM system.tables WHERE database = {database:String} ORDER BY name LIMIT 101 FORMAT JSON";
91
+ var listDatabasesSQL = "SELECT name FROM system.databases ORDER BY name LIMIT 101 FORMAT JSON";
92
+ var listColumnsSQL = "SELECT name, type FROM system.columns WHERE database = {database:String} AND table = {table:String} ORDER BY position LIMIT 101 FORMAT JSON";
93
+ var emptyTables = () => ({ database: "", names: [], hasMore: false });
94
+ var ClickHouseClient = class {
95
+ /** Validate provider configuration without contacting ClickHouse. */
96
+ constructor(config, credentials, options = {}) {
97
+ this.credentials = credentials;
98
+ if (!config || !credentials) throw new TypeError("ClickHouse configuration and credentials are required");
99
+ this.baseURL = validateBaseURL(config.baseUrl).replace(/\/$/, "");
100
+ this.timeoutMs = config.timeoutMs ?? 15e3;
101
+ this.maxResponseBytes = config.maxResponseBytes ?? 1048576;
102
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
103
+ throw new TypeError("ClickHouse request limits must be positive integers");
104
+ this.send = options.send ?? sendProviderRequest;
105
+ }
106
+ credentials;
107
+ baseURL;
108
+ timeoutMs;
109
+ maxResponseBytes;
110
+ send;
111
+ /** Bind the listTables Query. */
112
+ listTables() {
113
+ return new ListTablesOperation(this);
114
+ }
115
+ /** Bind the database catalog Query. */
116
+ listDatabases() {
117
+ return new ListDatabasesOperation(this);
118
+ }
119
+ /** Bind the ordered column metadata Query. */
120
+ listColumns() {
121
+ return new ListColumnsOperation(this);
122
+ }
123
+ /** Resolve credentials and send one bounded database query. */
124
+ getDatabases(call) {
125
+ return this.readMetadata(call, listDatabasesSQL, {});
126
+ }
127
+ /** Resolve credentials and send one bounded column query. */
128
+ getColumns(call, database, table) {
129
+ return this.readMetadata(call, listColumnsSQL, { param_database: database, param_table: table });
130
+ }
131
+ /** Resolve credentials and send one bounded table query. */
132
+ async get(call, database) {
133
+ return this.readMetadata(call, listTablesSQL, { param_database: database });
134
+ }
135
+ async readMetadata(call, sql, parameters) {
136
+ let username;
137
+ let password;
138
+ try {
139
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
140
+ username = credentials.username;
141
+ password = credentials.password instanceof SecretString ? credentials.password.reveal() : "";
142
+ } catch {
143
+ return emptyExchange("credential");
144
+ }
145
+ if (!isHeaderSafeCredential(username) || !isHeaderSafeCredential(password))
146
+ return emptyExchange("credential");
147
+ const url = new URL(`${this.baseURL}/`);
148
+ url.searchParams.set("query", sql);
149
+ for (const [name, value] of Object.entries(parameters)) url.searchParams.set(name, value);
150
+ const request = {
151
+ url: url.toString(),
152
+ method: "GET",
153
+ headers: { Accept: "application/json", "X-ClickHouse-User": username, "X-ClickHouse-Key": password },
154
+ maxResponseBytes: this.maxResponseBytes,
155
+ timeoutMs: this.timeoutMs,
156
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
157
+ signal: call.context.cancellationSignal
158
+ };
159
+ let response;
160
+ let isTooLarge = false;
161
+ try {
162
+ response = await this.send(request);
163
+ } catch (error) {
164
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
165
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
166
+ isTooLarge = true;
167
+ } else return emptyExchange("request");
168
+ }
169
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
170
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
171
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
172
+ return { status: response.status, body: response.body, retryAfterMs };
173
+ }
174
+ };
175
+ var ListDatabasesOperation = class {
176
+ /** Bind the metadata client. */
177
+ constructor(client) {
178
+ this.client = client;
179
+ }
180
+ client;
181
+ /** Return the manifest-generated definition. */
182
+ definition() {
183
+ return ListDatabasesDefinition;
184
+ }
185
+ /** Read and validate one metadata page. */
186
+ async invoke(call, _input) {
187
+ void _input;
188
+ const empty = { names: [], hasMore: false };
189
+ const exchange = await this.client.getDatabases(call);
190
+ return metadataAttempt(exchange, "listDatabases", empty, (rows) => {
191
+ return { names: rows.slice(0, 100).map((row) => row.name), hasMore: rows.length > 100 };
192
+ });
193
+ }
194
+ };
195
+ var ListTablesOperation = class {
196
+ /** Bind the metadata client. */
197
+ constructor(client) {
198
+ this.client = client;
199
+ }
200
+ client;
201
+ /** Return the manifest-generated definition. */
202
+ definition() {
203
+ return ListTablesDefinition;
204
+ }
205
+ /** Read and validate one metadata page. */
206
+ async invoke(call, input) {
207
+ const empty = emptyTables();
208
+ if (!isValidDatabase(input?.database))
209
+ return newQueryBranch(
210
+ "defect",
211
+ empty,
212
+ {},
213
+ failure("listTables", "VALIDATION", "Invalid ClickHouse metadata identifier")
214
+ );
215
+ const exchange = await this.client.get(call, input.database);
216
+ return metadataAttempt(exchange, "listTables", empty, (rows) => {
217
+ return {
218
+ database: input.database,
219
+ names: rows.slice(0, 100).map((row) => row.name),
220
+ hasMore: rows.length > 100
221
+ };
222
+ });
223
+ }
224
+ };
225
+ var ListColumnsOperation = class {
226
+ /** Bind the metadata client. */
227
+ constructor(client) {
228
+ this.client = client;
229
+ }
230
+ client;
231
+ /** Return the manifest-generated definition. */
232
+ definition() {
233
+ return ListColumnsDefinition;
234
+ }
235
+ /** Read and validate one metadata page. */
236
+ async invoke(call, input) {
237
+ const empty = { database: "", table: "", columns: [], hasMore: false };
238
+ if (!isValidDatabase(input?.database) || !isValidDatabase(input?.table))
239
+ return newQueryBranch(
240
+ "defect",
241
+ empty,
242
+ {},
243
+ failure("listColumns", "VALIDATION", "Invalid ClickHouse metadata identifier")
244
+ );
245
+ const exchange = await this.client.getColumns(call, input.database, input.table);
246
+ return metadataAttempt(exchange, "listColumns", empty, (rows) => {
247
+ const columns = [];
248
+ for (const row of rows) {
249
+ if (typeof row.type !== "string" || !row.type) return void 0;
250
+ if (columns.length < 100) columns.push({ name: row.name, type: row.type });
251
+ }
252
+ return { database: input.database, table: input.table, columns, hasMore: rows.length > 100 };
253
+ });
254
+ }
255
+ };
256
+ function isValidDatabase(value) {
257
+ return typeof value === "string" && value.length > 0 && value.trim() === value && new TextEncoder().encode(value).length <= 128 && [...value].every(
258
+ (character) => character.codePointAt(0) >= 32 && character.codePointAt(0) !== 127
259
+ ) && !/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF])/.test(value);
260
+ }
261
+ function emptyExchange(error) {
262
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
263
+ }
264
+ function failure(operation, kind, message) {
265
+ return { provider: "clickhouse", operation, kind, message };
266
+ }
267
+ function metadataAttempt(exchange, operation, empty, project) {
268
+ const terminal = (branch, kind, message) => newQueryBranch(branch, empty, {}, failure(operation, kind, message));
269
+ const retry = (kind, message, delay = 0) => newQueryRetry(failure(operation, kind, message), delay);
270
+ if (exchange.error === "credential")
271
+ return terminal("defect", "AUTHENTICATION", "ClickHouse credentials are unavailable or invalid");
272
+ if (exchange.error === "request") return retry("TRANSPORT", "ClickHouse request failed");
273
+ if (exchange.status === 429)
274
+ return retry("RATE_LIMIT", "ClickHouse rate limited the request", exchange.retryAfterMs);
275
+ if (exchange.status === 408 || exchange.status >= 500)
276
+ return retry("AVAILABILITY", "ClickHouse is temporarily unavailable", exchange.retryAfterMs);
277
+ if (exchange.status !== 200)
278
+ return terminal("providerRejected", "PROVIDER_REJECTION", `ClickHouse rejected HTTP ${exchange.status}`);
279
+ if (exchange.error === "tooLarge")
280
+ return terminal(
281
+ "invalidResponse",
282
+ "RESPONSE_TOO_LARGE",
283
+ "ClickHouse response exceeded the configured limit"
284
+ );
285
+ const rows = decodeRows(exchange.body);
286
+ const page = rows && project(rows);
287
+ if (!page) return terminal("invalidResponse", "PROTOCOL", "ClickHouse returned invalid metadata JSON");
288
+ return newQueryBranch("listed", page);
289
+ }
290
+ function header(headers, name) {
291
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
292
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
293
+ }
294
+ function isObject(value) {
295
+ return typeof value === "object" && value !== null && !Array.isArray(value);
296
+ }
297
+ function metadataFields(key, value, context) {
298
+ if (key.toLowerCase() === "rows" && typeof value === "number" && context?.source && !/^-?\d+$/.test(context.source))
299
+ return NaN;
300
+ if (!isObject(value)) return value;
301
+ return Object.fromEntries(Object.entries(value).map(([name, field]) => [name.toLowerCase(), field]));
302
+ }
303
+ function decodeRows(body) {
304
+ let raw;
305
+ try {
306
+ raw = JSON.parse(new TextDecoder().decode(body), metadataFields);
307
+ } catch {
308
+ return void 0;
309
+ }
310
+ if (!isObject(raw) || !Array.isArray(raw.data) || raw.data.length > 101 || (raw.rows ?? 0) !== raw.data.length)
311
+ return void 0;
312
+ const data = raw.data;
313
+ if (!data.every(
314
+ (row) => isObject(row) && typeof row.name === "string" && row.name.length > 0
315
+ ))
316
+ return void 0;
317
+ return data;
318
+ }
319
+
320
+ // src/project.ts
321
+ function newProjectConnection2(project, connectionName) {
322
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
323
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "clickhouse" && entry.connectionName === name);
324
+ if (!selected) throw new TypeError("ClickHouse project connection is not configured");
325
+ const fields = z.strictObject({ baseUrl: z.string(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
326
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
327
+ const config = {
328
+ baseUrl: fields.baseUrl,
329
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
330
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
331
+ };
332
+ const credentials = {
333
+ async resolve(_call, signal) {
334
+ const privateFields = await loadedProject.resolveCredential("clickhouse", name, signal);
335
+ if (typeof privateFields.username !== "string" || typeof privateFields.password !== "string") throw new TypeError("ClickHouse credentials are unavailable");
336
+ return { username: privateFields.username, password: new SecretString2(privateFields.password) };
337
+ }
338
+ };
339
+ return new ClickHouseClient(config, credentials);
340
+ });
341
+ }
342
+ function parseDurationMilliseconds(value) {
343
+ let remaining = value;
344
+ let milliseconds = 0;
345
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
346
+ while (remaining) {
347
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
348
+ if (!part) throw new TypeError("ClickHouse timeout must be a positive Go duration");
349
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
350
+ remaining = remaining.slice(part[0].length);
351
+ }
352
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("ClickHouse timeout must resolve to positive whole milliseconds");
353
+ return milliseconds;
354
+ }
355
+
356
+ // src/index.ts
357
+ var Connection2 = Connection;
358
+ function newConnection(client, reference) {
359
+ return new Connection2(reference, client);
360
+ }
361
+ function newConnectionWithOperations(operations, reference) {
362
+ return newConnection(operations, reference);
363
+ }
364
+ export {
365
+ ClickHouseClient,
366
+ ColumnSchema,
367
+ ColumnsPageSchema,
368
+ ConfigSchema,
369
+ Connection2 as Connection,
370
+ ConnectorID,
371
+ CredentialMaterialError,
372
+ DatabasesPageSchema,
373
+ ListColumnsBranch,
374
+ ListColumnsBranchDefect,
375
+ ListColumnsBranchInvalidResponse,
376
+ ListColumnsBranchListed,
377
+ ListColumnsBranchProviderRejected,
378
+ ListColumnsDefinition,
379
+ ListColumnsInputSchema,
380
+ ListColumnsMetadata,
381
+ ListColumnsOperation,
382
+ ListDatabasesBranch,
383
+ ListDatabasesBranchDefect,
384
+ ListDatabasesBranchInvalidResponse,
385
+ ListDatabasesBranchListed,
386
+ ListDatabasesBranchProviderRejected,
387
+ ListDatabasesDefinition,
388
+ ListDatabasesInputSchema,
389
+ ListDatabasesMetadata,
390
+ ListDatabasesOperation,
391
+ ListTablesBranch,
392
+ ListTablesBranchDefect,
393
+ ListTablesBranchInvalidResponse,
394
+ ListTablesBranchListed,
395
+ ListTablesBranchProviderRejected,
396
+ ListTablesDefinition,
397
+ ListTablesInputSchema,
398
+ ListTablesMetadata,
399
+ ListTablesOperation,
400
+ ProviderID,
401
+ TablesPageSchema,
402
+ decodeCredentials,
403
+ isCredentialMaterialError,
404
+ newConnection,
405
+ newConnectionWithOperations,
406
+ newListColumnsStep,
407
+ newListDatabasesStep,
408
+ newListTablesStep,
409
+ newProjectConnection2 as newProjectConnection
410
+ };