@boltic/sdk 0.1.4 → 0.1.5
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/dist/databases/index.d.ts +82 -0
- package/dist/databases/index.js +1 -1
- package/dist/databases/index.mjs +1 -1
- package/dist/databases/test-client-DzMli6cH.js +2 -0
- package/dist/databases/test-client-DzMli6cH.js.map +1 -0
- package/dist/databases/test-client-rR_4EBUe.mjs +2 -0
- package/dist/databases/test-client-rR_4EBUe.mjs.map +1 -0
- package/dist/databases/testing.d.ts +82 -0
- package/dist/databases/testing.js +1 -1
- package/dist/databases/testing.mjs +1 -1
- package/dist/sdk.js +559 -22
- package/dist/sdk.js.map +1 -1
- package/dist/sdk.mjs +559 -22
- package/dist/sdk.mjs.map +1 -1
- package/dist/types/index.d.ts +271 -0
- package/package.json +1 -1
- package/dist/databases/test-client-BEAX5vfC.mjs +0 -2
- package/dist/databases/test-client-BEAX5vfC.mjs.map +0 -1
- package/dist/databases/test-client-BgkvBtst.js +0 -2
- package/dist/databases/test-client-BgkvBtst.js.map +0 -1
package/dist/types/index.d.ts
CHANGED
|
@@ -173,6 +173,7 @@ export declare class BolticClient {
|
|
|
173
173
|
private databaseResource;
|
|
174
174
|
private workflowResource;
|
|
175
175
|
private serverlessResource;
|
|
176
|
+
private storageResource;
|
|
176
177
|
private currentDatabase;
|
|
177
178
|
private clientOptions;
|
|
178
179
|
constructor(apiKey: string, options?: ClientOptions);
|
|
@@ -354,6 +355,17 @@ export declare class BolticClient {
|
|
|
354
355
|
maxAttempts?: number;
|
|
355
356
|
}) => Promise<BolticErrorResponse | BolticSuccessResponse<ServerlessData>>;
|
|
356
357
|
};
|
|
358
|
+
get storage(): {
|
|
359
|
+
list: (params?: ListStorageParams) => Promise<BolticErrorResponse | ListStorageData>;
|
|
360
|
+
upload: (params: UploadParams) => Promise<BolticErrorResponse | UploadData>;
|
|
361
|
+
createFolder: (params: CreateFolderParams) => Promise<BolticErrorResponse | CreateFolderData>;
|
|
362
|
+
deleteFile: (params: DeleteFileParams) => Promise<BolticErrorResponse | {
|
|
363
|
+
message: unknown;
|
|
364
|
+
}>;
|
|
365
|
+
makePublic: (filePath: string) => Promise<BolticErrorResponse | ObjectAccessSummary>;
|
|
366
|
+
makePrivate: (filePath: string) => Promise<BolticErrorResponse | ObjectAccessSummary>;
|
|
367
|
+
downloadFile: (params: DownloadFileParams) => Promise<BolticErrorResponse | DownloadFileData>;
|
|
368
|
+
};
|
|
357
369
|
getSqlResource(): SqlResource;
|
|
358
370
|
updateApiKey(newApiKey: string): void;
|
|
359
371
|
updateConfig(updates: Partial<ClientConfig>): void;
|
|
@@ -414,6 +426,15 @@ export declare interface BolticSuccessResponse<T> {
|
|
|
414
426
|
};
|
|
415
427
|
}
|
|
416
428
|
|
|
429
|
+
export declare function buildStorageEndpointPath(endpoint: StorageApiEndpoint): string;
|
|
430
|
+
|
|
431
|
+
export declare interface ChangeObjectAccessParams {
|
|
432
|
+
/** Full file path in bucket */
|
|
433
|
+
file_path: string;
|
|
434
|
+
/** `true` = public, `false` = private */
|
|
435
|
+
public: boolean;
|
|
436
|
+
}
|
|
437
|
+
|
|
417
438
|
export declare interface ClientConfig extends EnvironmentConfig {
|
|
418
439
|
apiKey: string;
|
|
419
440
|
environment: Environment;
|
|
@@ -525,6 +546,16 @@ export declare function createClient(apiKey: string, options?: ClientOptions): B
|
|
|
525
546
|
*/
|
|
526
547
|
export declare function createErrorWithContext(message: string, context?: Record<string, unknown>): Error;
|
|
527
548
|
|
|
549
|
+
export declare interface CreateFolderData {
|
|
550
|
+
message: string;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
export declare interface CreateFolderParams {
|
|
554
|
+
storageType?: string;
|
|
555
|
+
/** Target folder path (`folder_path` body field). */
|
|
556
|
+
folder_path: string;
|
|
557
|
+
}
|
|
558
|
+
|
|
528
559
|
export declare type CreateServerlessData = ServerlessData;
|
|
529
560
|
|
|
530
561
|
export declare interface CreateServerlessParams {
|
|
@@ -697,10 +728,45 @@ export declare const DEFAULT_SCALING: {
|
|
|
697
728
|
readonly MaxIdleTime: 0;
|
|
698
729
|
};
|
|
699
730
|
|
|
731
|
+
/** Default backend storage driver (GCS). */
|
|
732
|
+
export declare const DEFAULT_STORAGE_TYPE: "gcs";
|
|
733
|
+
|
|
734
|
+
export declare interface DeleteFileData {
|
|
735
|
+
message: unknown;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
export declare interface DeleteFileParams {
|
|
739
|
+
storageType?: string;
|
|
740
|
+
/** Full object path in bucket */
|
|
741
|
+
filename: string;
|
|
742
|
+
/** Optional metering payload (Zenith sends `totalsize`). */
|
|
743
|
+
filepath?: string;
|
|
744
|
+
totalsize?: number;
|
|
745
|
+
}
|
|
746
|
+
|
|
700
747
|
declare interface DeleteIndexResponse {
|
|
701
748
|
message?: string;
|
|
702
749
|
}
|
|
703
750
|
|
|
751
|
+
export declare interface DownloadFileData {
|
|
752
|
+
bytes: ArrayBuffer;
|
|
753
|
+
/** Usually 206 Partial Content for range responses. */
|
|
754
|
+
status: number;
|
|
755
|
+
contentType?: string;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/** `POST /file-export` — byte range download; SDK requests full file by default. */
|
|
759
|
+
export declare interface DownloadFileParams {
|
|
760
|
+
storageType?: string;
|
|
761
|
+
/** Full object path in bucket (same as list `fullPath` / delete `filename`). */
|
|
762
|
+
file_name: string;
|
|
763
|
+
/**
|
|
764
|
+
* Size in bytes from `list()` item `size`. If omitted, the SDK lists the parent folder
|
|
765
|
+
* and matches by `fullPath` / `name`.
|
|
766
|
+
*/
|
|
767
|
+
sizeBytes?: number | string;
|
|
768
|
+
}
|
|
769
|
+
|
|
704
770
|
export declare type Environment = 'local' | 'sit' | 'uat' | 'prod';
|
|
705
771
|
|
|
706
772
|
export declare interface EnvironmentConfig {
|
|
@@ -953,6 +1019,11 @@ declare interface HttpRequestConfig {
|
|
|
953
1019
|
data?: unknown;
|
|
954
1020
|
timeout?: number;
|
|
955
1021
|
signal?: AbortSignal;
|
|
1022
|
+
/**
|
|
1023
|
+
* Opt-in only. When unset (default), JSON/text parsing is unchanged for all services.
|
|
1024
|
+
* Storage `downloadFile` sets `arraybuffer` for binary bodies.
|
|
1025
|
+
*/
|
|
1026
|
+
responseType?: 'arraybuffer';
|
|
956
1027
|
}
|
|
957
1028
|
|
|
958
1029
|
declare interface HttpResponse<T = unknown> {
|
|
@@ -1080,9 +1151,39 @@ export declare interface ListServerlessParams {
|
|
|
1080
1151
|
query?: string;
|
|
1081
1152
|
}
|
|
1082
1153
|
|
|
1154
|
+
export declare interface ListStorageData {
|
|
1155
|
+
files: StorageListFilesPayload;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** List query — forwarded to backend object listing. */
|
|
1159
|
+
export declare interface ListStorageParams {
|
|
1160
|
+
storageType?: string;
|
|
1161
|
+
/** Folder prefix to list under */
|
|
1162
|
+
basePath?: string;
|
|
1163
|
+
pageSize?: number | string;
|
|
1164
|
+
nextPageToken?: string;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/**
|
|
1168
|
+
* `expire_in` for upload temporary read URLs is **minutes**.
|
|
1169
|
+
* Backend caps TTL to 7 days.
|
|
1170
|
+
*/
|
|
1171
|
+
export declare const MAX_SIGNED_URL_EXPIRE_MINUTES: number;
|
|
1172
|
+
|
|
1083
1173
|
/** Maximum number of status polling attempts before timeout */
|
|
1084
1174
|
export declare const MAX_STATUS_POLLING_ATTEMPTS = 60;
|
|
1085
1175
|
|
|
1176
|
+
/** Returned by `makePublic` / `makePrivate` — matches `POST /change-object-access` success body. */
|
|
1177
|
+
export declare interface ObjectAccessSummary {
|
|
1178
|
+
/** Human-readable status from the API. */
|
|
1179
|
+
message: string;
|
|
1180
|
+
/** Full object path in the bucket. */
|
|
1181
|
+
name: string;
|
|
1182
|
+
size: string | null;
|
|
1183
|
+
updated: string | null;
|
|
1184
|
+
public: boolean;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1086
1187
|
export declare interface PaginationInfo {
|
|
1087
1188
|
total_count: number;
|
|
1088
1189
|
total_pages: number;
|
|
@@ -1666,6 +1767,7 @@ export declare const SERVICE_PATHS: {
|
|
|
1666
1767
|
readonly WORKFLOW_TEMPORAL: "/service/panel/temporal/v1.0";
|
|
1667
1768
|
readonly INTEGRATION: "/service/panel/integration/v1";
|
|
1668
1769
|
readonly SERVERLESS: "/service/panel/serverless/v1.0";
|
|
1770
|
+
readonly STORAGE: "/service/panel/storage/v1.0";
|
|
1669
1771
|
};
|
|
1670
1772
|
|
|
1671
1773
|
export declare interface ServiceAuthConfig extends AuthConfig_2 {
|
|
@@ -1707,6 +1809,123 @@ declare class SqlResource {
|
|
|
1707
1809
|
/** Polling interval in milliseconds between status checks */
|
|
1708
1810
|
export declare const STATUS_POLLING_INTERVAL_MS = 5000;
|
|
1709
1811
|
|
|
1812
|
+
export declare const STORAGE_ENDPOINTS: StorageEndpoints;
|
|
1813
|
+
|
|
1814
|
+
export declare class StorageApiClient extends BaseApiClient {
|
|
1815
|
+
constructor(apiKey: string, config?: Omit<BaseApiClientConfig, 'apiKey'>);
|
|
1816
|
+
/** Shared try/catch + http — same idea as inlined blocks in serverless/workflow clients, but DRY for storage. */
|
|
1817
|
+
private requestStorage;
|
|
1818
|
+
private url;
|
|
1819
|
+
private storageTypeQuery;
|
|
1820
|
+
private listQuery;
|
|
1821
|
+
/** `expire_in` is minutes; clamp to max temporary URL lifetime (7 days). */
|
|
1822
|
+
private normalizeExpireInMinutes;
|
|
1823
|
+
private isTruthyFormFlag;
|
|
1824
|
+
/**
|
|
1825
|
+
* `public` shortcut: true + no expire_in → permanent; true + expire_in → temporary signed URL; false → private.
|
|
1826
|
+
* Legacy: omit `public` and pass `is_public` / `is_public_permanent` / `expire_in` as before.
|
|
1827
|
+
*/
|
|
1828
|
+
private appendUploadVisibility;
|
|
1829
|
+
private buildUploadForm;
|
|
1830
|
+
private isErrorResult;
|
|
1831
|
+
private isAclErrorResult;
|
|
1832
|
+
private buildObjectAccessSummary;
|
|
1833
|
+
/**
|
|
1834
|
+
* Parses Hawkeye `POST /change-object-access` success JSON
|
|
1835
|
+
* `{ message, name, size, updated, public }`.
|
|
1836
|
+
*/
|
|
1837
|
+
private parseChangeObjectAccessResponse;
|
|
1838
|
+
/** Resolves the list row for a full object path (same folder semantics as download size resolution). */
|
|
1839
|
+
private findFileListItem;
|
|
1840
|
+
/** Keep only SDK list fields; flatten metadata to `size` / `updatedAt`. */
|
|
1841
|
+
private normalizeListItem;
|
|
1842
|
+
/** Map wire `shareable_link` to `temporary_sharable_link`. */
|
|
1843
|
+
private normalizeUploadData;
|
|
1844
|
+
private normalizeListResponse;
|
|
1845
|
+
list(params?: ListStorageParams): Promise<StorageResult_2<ListStorageData>>;
|
|
1846
|
+
createFolder(body: CreateFolderParams): Promise<StorageResult_2<CreateFolderData>>;
|
|
1847
|
+
deleteFile(params: DeleteFileParams): Promise<StorageResult_2<{
|
|
1848
|
+
message: unknown;
|
|
1849
|
+
}>>;
|
|
1850
|
+
/**
|
|
1851
|
+
* `POST /change-object-access` — used by `makePublic` / `makePrivate`.
|
|
1852
|
+
* Preferring API body `{ message, name, size, updated, public }`; otherwise falls back to a parent list.
|
|
1853
|
+
*/
|
|
1854
|
+
setObjectAccess(body: ChangeObjectAccessParams): Promise<StorageResult_2<ObjectAccessSummary>>;
|
|
1855
|
+
upload(params: UploadParams): Promise<StorageResult_2<UploadData>>;
|
|
1856
|
+
private resolveFileSizeBytes;
|
|
1857
|
+
/**
|
|
1858
|
+
* Download file bytes via `POST /file-export` (range 0..size-1).
|
|
1859
|
+
*/
|
|
1860
|
+
downloadFile(params: DownloadFileParams): Promise<StorageResult_2<DownloadFileData>>;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
export declare type StorageApiEndpoint = {
|
|
1864
|
+
path: string;
|
|
1865
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
1866
|
+
authenticated: boolean;
|
|
1867
|
+
};
|
|
1868
|
+
|
|
1869
|
+
declare interface StorageEndpoints {
|
|
1870
|
+
list: StorageApiEndpoint;
|
|
1871
|
+
upload: StorageApiEndpoint;
|
|
1872
|
+
directory: StorageApiEndpoint;
|
|
1873
|
+
deleteFile: StorageApiEndpoint;
|
|
1874
|
+
objectAccess: StorageApiEndpoint;
|
|
1875
|
+
/** Range download (`POST /file-export`). */
|
|
1876
|
+
fileExport: StorageApiEndpoint;
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
/** Response shape from `GET .../list` — `{ files: listResult }`. */
|
|
1880
|
+
export declare interface StorageListFilesPayload {
|
|
1881
|
+
data?: StorageListItem[];
|
|
1882
|
+
next_page_token?: string;
|
|
1883
|
+
totalCount?: number;
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* List row — only these fields are returned (size / `updatedAt` flattened from object metadata).
|
|
1888
|
+
*/
|
|
1889
|
+
export declare interface StorageListItem {
|
|
1890
|
+
name?: string;
|
|
1891
|
+
path?: string;
|
|
1892
|
+
folderName?: string;
|
|
1893
|
+
parentPath?: string;
|
|
1894
|
+
isDirectory?: boolean;
|
|
1895
|
+
isPublic?: boolean;
|
|
1896
|
+
cdnUrl?: string | null;
|
|
1897
|
+
/** Full object path in the bucket: `parentPath/name` for files, when derivable. */
|
|
1898
|
+
fullPath?: string;
|
|
1899
|
+
/** Byte size as string (from object metadata). */
|
|
1900
|
+
size?: string;
|
|
1901
|
+
/** Last update time (from `updated` / `timeUpdated` in raw metadata). */
|
|
1902
|
+
updatedAt?: string;
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
export declare class StorageResource extends BaseResource {
|
|
1906
|
+
private apiClient;
|
|
1907
|
+
constructor(client: BaseClient);
|
|
1908
|
+
list(params?: ListStorageParams): Promise<StorageResult<ListStorageData>>;
|
|
1909
|
+
/** Direct upload — `POST /upload` (multipart); server persists the object. */
|
|
1910
|
+
upload(params: UploadParams): Promise<StorageResult<UploadData>>;
|
|
1911
|
+
createFolder(params: CreateFolderParams): Promise<StorageResult<CreateFolderData>>;
|
|
1912
|
+
deleteFile(params: DeleteFileParams): Promise<StorageResult<{
|
|
1913
|
+
message: unknown;
|
|
1914
|
+
}>>;
|
|
1915
|
+
makePublic(filePath: string): Promise<StorageResult<ObjectAccessSummary>>;
|
|
1916
|
+
makePrivate(filePath: string): Promise<StorageResult<ObjectAccessSummary>>;
|
|
1917
|
+
/** Download file bytes via `POST /file-export` (full file). */
|
|
1918
|
+
downloadFile(params: DownloadFileParams): Promise<StorageResult<DownloadFileData>>;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
export declare type StorageResponse<T> = StorageSuccess<T> | BolticErrorResponse;
|
|
1922
|
+
|
|
1923
|
+
declare type StorageResult<T> = StorageResponse<T>;
|
|
1924
|
+
|
|
1925
|
+
declare type StorageResult_2<T> = T | BolticErrorResponse;
|
|
1926
|
+
|
|
1927
|
+
declare type StorageSuccess<T> = T;
|
|
1928
|
+
|
|
1710
1929
|
/**
|
|
1711
1930
|
* Table Builder - provides a fluent interface for creating tables
|
|
1712
1931
|
*/
|
|
@@ -2037,6 +2256,58 @@ export declare interface UpdateServerlessParams {
|
|
|
2037
2256
|
payload: Partial<CreateServerlessParams>;
|
|
2038
2257
|
}
|
|
2039
2258
|
|
|
2259
|
+
export declare interface UploadData {
|
|
2260
|
+
message: string;
|
|
2261
|
+
path: string;
|
|
2262
|
+
/** Temporary signed read URL (mapped from API `shareable_link` when present). */
|
|
2263
|
+
temporary_sharable_link?: string;
|
|
2264
|
+
public_url?: string;
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
/**
|
|
2268
|
+
* Shared multipart fields for `POST /upload` (direct upload handler).
|
|
2269
|
+
*
|
|
2270
|
+
* **Preferred — `public` (mapped by the SDK):**
|
|
2271
|
+
* - Omitted or `false` → private upload.
|
|
2272
|
+
* - `true` **without** `expire_in` → permanent public (CDN-style `public_url`); sends `is_public_permanent`, not time-limited signed upload.
|
|
2273
|
+
* - `true` **with** `expire_in` → temporary signed read URL (`temporary_sharable_link` on upload response). `expire_in` is **minutes**, max 7 days (SDK clamps to `MAX_SIGNED_URL_EXPIRE_MINUTES`).
|
|
2274
|
+
*
|
|
2275
|
+
* If **`public` is set** (including `false`), it takes precedence over `is_public` / `is_public_permanent` for the wire shape.
|
|
2276
|
+
*
|
|
2277
|
+
* **Legacy (omit `public`):** set `is_public` / `is_public_permanent` / `expire_in` directly as the backend expects.
|
|
2278
|
+
*/
|
|
2279
|
+
export declare interface UploadMultipartFields {
|
|
2280
|
+
storageType?: string;
|
|
2281
|
+
file: Blob;
|
|
2282
|
+
filepath?: string;
|
|
2283
|
+
overwrite?: boolean | string;
|
|
2284
|
+
/**
|
|
2285
|
+
* High-level visibility. See interface JSDoc. When present, controls how `is_public` / `is_public_permanent` / `expire_in` are sent.
|
|
2286
|
+
*/
|
|
2287
|
+
public?: boolean | string;
|
|
2288
|
+
/** @deprecated Prefer `public` unless you need raw backend fields. */
|
|
2289
|
+
is_public?: boolean | string;
|
|
2290
|
+
/**
|
|
2291
|
+
* Signed URL lifetime in **minutes** when using `public: true` (temporary) or legacy `is_public: true`.
|
|
2292
|
+
* Capped at 7 days; the SDK clamps to `MAX_SIGNED_URL_EXPIRE_MINUTES`.
|
|
2293
|
+
*/
|
|
2294
|
+
expire_in?: number | string;
|
|
2295
|
+
/** @deprecated Prefer `public: true` without `expire_in` unless you need raw backend fields. */
|
|
2296
|
+
is_public_permanent?: boolean | string;
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
/**
|
|
2300
|
+
* Direct upload — `POST /upload` (multipart). The handler reads `req.body.filename` (not `file_name`).
|
|
2301
|
+
* Multer: `file` field. Path: `filepath` + `filename`.
|
|
2302
|
+
*/
|
|
2303
|
+
export declare type UploadParams = UploadMultipartFields & ({
|
|
2304
|
+
filename: string;
|
|
2305
|
+
file_name?: string;
|
|
2306
|
+
} | {
|
|
2307
|
+
file_name: string;
|
|
2308
|
+
filename?: string;
|
|
2309
|
+
});
|
|
2310
|
+
|
|
2040
2311
|
export declare const VERSION = "1.0.0";
|
|
2041
2312
|
|
|
2042
2313
|
export declare interface WhereCondition {
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e={"asia-south1":{local:{baseURL:"http://localhost:8000",timeout:3e4,debug:!0},sit:{baseURL:"https://asia-south1.api.fcz0.de/service/sdk/boltic-tables",timeout:15e3},uat:{baseURL:"https://asia-south1.api.uat.fcz0.de/service/sdk/boltic-tables",timeout:15e3},prod:{baseURL:"https://asia-south1.api.boltic.io/service/sdk/boltic-tables",timeout:1e4}},"us-central1":{local:{baseURL:"http://localhost:8000",timeout:3e4,debug:!0},sit:{baseURL:"https://us-central1.api.fcz0.de/service/sdk/boltic-tables",timeout:15e3},uat:{baseURL:"https://us-central1.api.uat.fcz0.de/service/sdk/boltic-tables",timeout:15e3},prod:{baseURL:"https://us-central1.api.boltic.io/service/sdk/boltic-tables",timeout:1e4}}},t=e["asia-south1"],r={"asia-south1":{local:{host:"http://localhost:8000",timeout:3e4,debug:!0},sit:{host:"https://asia-south1.api.fcz0.de",timeout:15e3},uat:{host:"https://asia-south1.api.uat.fcz0.de",timeout:15e3},prod:{host:"https://asia-south1.api.boltic.io",timeout:1e4}},"us-central1":{local:{host:"http://localhost:8000",timeout:3e4,debug:!0},sit:{host:"https://us-central1.api.fcz0.de",timeout:15e3},uat:{host:"https://us-central1.api.uat.fcz0.de",timeout:15e3},prod:{host:"https://us-central1.api.boltic.io",timeout:1e4}}};function s(e,t,s){const a=r[e];if(!a)throw new Error(`Unsupported region: ${e}`);const i=a[t];if(!i)throw new Error(`Unsupported environment: ${t} for region: ${e}`);return`${i.host}${s}`}function a(e){return"error"in e&&void 0!==e.error}function i(e){return"pagination"in e}class n extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.failures=t}}class o extends Error{constructor(e,t,r){super(e),this.name="ApiError",this.statusCode=t,this.response=r}}function d(e,t){const r=new Error(e);return t&&(r.context=t),r}function l(e){return e instanceof Error&&(e.message.includes("network")||e.message.includes("fetch")||e.message.includes("timeout")||"AbortError"===e.name)}function u(e){if(e&&"object"==typeof e){if("response"in e&&e.response&&"object"==typeof e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}if("status"in e&&"number"==typeof e.status)return e.status}return null}function c(e){if(e instanceof Error){const t=e.context,r=u(e);let s=`${e.name}: ${e.message}`;return r&&(s+=` (HTTP ${r})`),t&&(s+=`\nContext: ${JSON.stringify(t,null,2)}`),s}return String(e)}class h{constructor(){try{this.axios=require("axios")}catch(e){throw d("Axios is required for Node.js < 18. Please install axios: npm install axios",{error:e})}}async request(e){try{const t={url:e.url,method:e.method.toLowerCase(),headers:e.headers,params:e.params,data:e.data,timeout:e.timeout,signal:e.signal,validateStatus:()=>!0},r=await this.axios(t);if(r.status<200||r.status>=300){if("string"==typeof r.data&&r.data.trim().startsWith("<!DOCTYPE")||"string"==typeof r.data&&r.data.includes("<html")){const t=r.data.match(/<pre>(.*?)<\/pre>/s);throw d(t?t[1].trim():`HTTP ${r.status}: ${r.statusText}`,{url:e.url,method:e.method,status:r.status,statusText:r.statusText,isHtmlError:!0})}if(r.data&&"object"==typeof r.data&&"error"in r.data)return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}};throw d(`HTTP ${r.status}: ${r.statusText}`,{url:e.url,method:e.method,status:r.status,statusText:r.statusText,responseData:r.data})}return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}}}catch(t){const r=t;if("ECONNABORTED"===r.code||r.message?.includes("timeout"))throw d("Request timeout",{url:e.url,method:e.method,timeout:e.timeout});if("ERR_NETWORK"===r.code||"ENOTFOUND"===r.code||"ECONNREFUSED"===r.code||"EHOSTUNREACH"===r.code||"ETIMEDOUT"===r.code||"ERR_INTERNET_DISCONNECTED"===r.code||r.message?.includes("network")||r.message?.includes("internet")||r.message?.includes("connection")||r.message?.includes("resolve"))throw d("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,errorCode:r.code,originalMessage:r.message});if("AbortError"===r.name||"ERR_CANCELED"===r.code)throw d("Request was aborted",{url:e.url,method:e.method});throw d(`HTTP request failed: ${r.message||"Unknown error"}`,{url:e.url,method:e.method,originalError:t})}}}class m{async request(e){const t=new URL(e.url);e.params&&Object.entries(e.params).forEach(([e,r])=>{null!=r&&t.searchParams.append(e,String(r))});const r={method:e.method,headers:{"Content-Type":"application/json",...e.headers},signal:e.signal};e.data&&["POST","PUT","PATCH","DELETE"].includes(e.method)&&(r.body=JSON.stringify(e.data));try{const s=new AbortController;let a;e.timeout&&(a=setTimeout(()=>s.abort(),e.timeout),r.signal=e.signal?(()=>{const t=new AbortController;return e.signal.addEventListener("abort",()=>t.abort()),s.signal.addEventListener("abort",()=>t.abort()),t.signal})():s.signal);const i=await fetch(t.toString(),r);a&&clearTimeout(a);const n=i.headers.get("content-type");let o;o=n?.includes("application/json")?await i.json():await i.text();const l={};if(i.headers.forEach((e,t)=>{l[t]=e}),i.status<200||i.status>=300){if("string"==typeof o&&(o.trim().startsWith("<!DOCTYPE")||o.includes("<html"))){const t=o.match(/<pre>(.*?)<\/pre>/s);throw d(t?t[1].trim():`HTTP ${i.status}: ${i.statusText}`,{url:e.url,method:e.method,status:i.status,statusText:i.statusText,isHtmlError:!0})}if(o&&"object"==typeof o&&"error"in o)return{data:o,status:i.status,statusText:i.statusText,headers:l};throw d(`HTTP ${i.status}: ${i.statusText}`,{url:e.url,method:e.method,status:i.status,statusText:i.statusText,responseData:o})}return{data:o,status:i.status,statusText:i.statusText,headers:l}}catch(s){if(s instanceof Error&&"AbortError"===s.name)throw d("Request was aborted",{type:"AbortError",url:e.url,method:e.method});if(s instanceof Error){const t=s.message.toLowerCase();if("TypeError"===s.name&&(t.includes("network")||t.includes("fetch")||t.includes("failed to fetch")||t.includes("internet")||t.includes("connection")||t.includes("resolve")||t.includes("unreachable")))throw d("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,originalMessage:s.message})}throw d(`HTTP request failed: ${s instanceof Error?s.message:"Unknown error"}`,{url:e.url,method:e.method,originalError:s})}}}function p(){if("undefined"!=typeof fetch)return new m;try{return new h}catch(e){throw d("No suitable HTTP adapter found. Please use Node.js >= 18 or install axios: npm install axios",{error:e})}}class f{constructor(e){this.tokenInfo=null,this.config={maxRetries:3,...e},this.validateApiKey(e.apiKey)}validateApiKey(e){if(!e||"string"!=typeof e||0===e.trim().length)throw d("API key is required and must be a non-empty string",{name:"AuthenticationError",code:"INVALID_API_KEY"});if(e.length<10)throw d("API key appears to be invalid (too short)",{name:"AuthenticationError",code:"INVALID_API_KEY_FORMAT"})}getAuthHeaders(){return{"x-boltic-token":this.config.apiKey}}updateApiKey(e){this.validateApiKey(e),this.config.apiKey=e,this.tokenInfo=null}isAuthenticated(){return!!this.config.apiKey}async validateApiKeyAsync(){try{return this.validateApiKey(this.config.apiKey),!0}catch{return!1}}getTokenInfo(){return this.tokenInfo?{...this.tokenInfo}:null}getMaxRetries(){return this.config.maxRetries||3}toString(){return`AuthManager { authenticated: ${this.isAuthenticated()}, maxRetries: ${this.getMaxRetries()} }`}toJSON(){return{authenticated:this.isAuthenticated(),maxRetries:this.getMaxRetries()}}[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}const g="/service/sdk/boltic-tables/v1",_="/service/panel/temporal/v1.0",b="/service/panel/integration/v1";class y{constructor(e,t={},r=g){this.config={apiKey:e,...t},this.httpAdapter=p(),this.environment=t.environment||"prod",this.region=t.region||"asia-south1",this.baseURL=s(this.region,this.environment,r)}resolveAdditionalServiceURL(e){return s(this.region,this.environment,e)}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey,...this.config.headers}}formatErrorResponse(e,t="API"){if(this.config.debug&&console.error(`[${this.constructor.name}] ${t} Error:`,e),e&&"object"==typeof e&&"response"in e){const r=e;return r.response?.data?.error?r.response.data:{error:{code:`${t}_ERROR`,message:e instanceof Error?e.message:`Unknown ${t} error`,meta:[`Status: ${r.response?.status||"unknown"}`]}}}return e instanceof Error?{error:{code:`${t}_CLIENT_ERROR`,message:e.message,meta:[]}}:{error:{code:`${t}_UNKNOWN_ERROR`,message:`An unexpected ${t} error occurred`,meta:[]}}}toString(){return`${this.constructor.name} { environment: "${this.config.environment||"prod"}", debug: ${this.config.debug||!1} }`}toJSON(){const e={...this.config};return delete e.apiKey,{client:this.constructor.name,config:e}}[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class w{constructor(){this.requestInterceptors=/* @__PURE__ */new Map,this.responseInterceptors=/* @__PURE__ */new Map,this.nextId=0,this.request={use:e=>{const t=this.nextId++;return this.requestInterceptors.set(t,e),t},eject:e=>{this.requestInterceptors.delete(e)}},this.response={use:(e,t)=>{const r=this.nextId++;return this.responseInterceptors.set(r,{fulfilled:e,rejected:t}),r},eject:e=>{this.responseInterceptors.delete(e)}}}async executeRequestInterceptors(e){let t=e;for(const r of Array.from(this.requestInterceptors.values()))t=await r(t);return t}async executeResponseInterceptors(e){let t=e;for(const{fulfilled:r}of Array.from(this.responseInterceptors.values()))r&&(t=await r(t));return t}async executeErrorInterceptors(e){let t=e;for(const{rejected:r}of Array.from(this.responseInterceptors.values()))r&&(t=await r(t));return t}}class R{constructor(e,t){this.config=e,this.authManager=t,this.httpAdapter=p(),this.interceptors=new w,this.setupDefaultInterceptors()}setupDefaultInterceptors(){this.interceptors.request.use(e=>{const t=this.authManager.getAuthHeaders();return e.headers={...e.headers,...t,...this.config.headers},e}),this.interceptors.response.use(e=>(this.config.debug&&console.log("HTTP Response:",e),e),e=>this.handleError(e))}handleError(e){if(this.config.debug&&console.error("HTTP Error:",e),e instanceof Error&&e.context)throw e;const t=u(e);if(!t)throw d("Network request failed",{name:"NetworkError",originalError:e});const r=e.response?.data||e.data;throw d(r?.message||r?.error||`HTTP ${t} error`,{name:"ApiError",statusCode:t,response:r,isClientError:t>=400&&t<500,isServerError:t>=500,isAuthError:401===t||403===t,isNotFoundError:404===t,isRateLimitError:429===t})}async request(e){let t;const r=this.config.maxRetries;for(let a=0;a<=r;a++)try{e.url.startsWith("http")||(e.url=`${this.config.baseURL}${e.url}`),e.timeout||(e.timeout=this.config.timeout);const t=await this.interceptors.executeRequestInterceptors(e),r=await this.httpAdapter.request(t);if(r.status>=400){const e=d(`HTTP ${r.status} error`,{name:"ApiError",statusCode:r.status,response:r.data,statusText:r.statusText});throw await this.interceptors.executeErrorInterceptors(e)}return await this.interceptors.executeResponseInterceptors(r)}catch(s){if(t=s,a===r)break;const e=u(s);if(e&&e>=400&&e<500)break;if(a<r){const e=this.config.retryDelay*Math.pow(2,a);await new Promise(t=>setTimeout(t,e))}}throw await this.interceptors.executeErrorInterceptors(t)}get(e,t){return this.request({...t,method:"GET",url:e})}post(e,t,r){return this.request({...r,method:"POST",url:e,data:t})}put(e,t,r){return this.request({...r,method:"PUT",url:e,data:t})}patch(e,t,r){return this.request({...r,method:"PATCH",url:e,data:t})}delete(e,t){return this.request({...t,method:"DELETE",url:e})}getInterceptors(){return this.interceptors}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}}class E{constructor(e,t){this.client=e,this.basePath=t}getBasePath(){return this.basePath}async makeRequest(e,t,r,s){const a=`${this.basePath}${t}`;try{let t;switch(e){case"GET":t=await this.client.get(a,{params:s?.params});break;case"POST":t=await this.client.post(a,r,{params:s?.params});break;case"PUT":t=await this.client.put(a,r,{params:s?.params});break;case"PATCH":t=await this.client.patch(a,r,{params:s?.params});break;case"DELETE":t=await this.client.delete(a,{params:s?.params})}return t.data}catch(i){return{error:{code:"CLIENT_ERROR",message:c(i),meta:["Request failed"]}}}}buildQueryParams(e={}){const t={};return e.fields?.length&&(t.fields=e.fields.join(",")),e.sort?.length&&(t.sort=e.sort.map(e=>`${e.field}:${e.order}`).join(",")),void 0!==e.limit&&(t.limit=e.limit),void 0!==e.offset&&(t.offset=e.offset),e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&(t[`where[${e}]`]="object"==typeof r?JSON.stringify(r):r)}),t}handleResponse(e){return"error"in e&&this.client.getConfig().debug&&console.error("API Error:",e.error),e}}class T{constructor(t,r="prod",s="asia-south1",a){const i=e[s][r];this.config={apiKey:t,environment:r,region:s,retryAttempts:3,retryDelay:1e3,maxRetries:3,debug:!1,headers:{},...i,...a}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}toString(){return`ConfigManager { environment: "${this.config.environment}", region: "${this.config.region}", debug: ${this.config.debug} }`}toJSON(){const e={...this.config};return delete e.apiKey,e}[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function v(e,t){if(!t||0===t.length)return e;const r={};for(const s of t)s in e&&(r[s]=e[s]);return r}function A(e,t){return t&&0!==t.length?e.map(e=>v(e,t)):e}function I(e,t){if(!t||""===t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}db_id=${encodeURIComponent(t)}`}const C={path:"/tables/{table_id}/fields/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},O={path:"/tables/{table_id}/fields",method:"POST",authenticated:!0},N={path:"/tables/{table_id}/fields/{field_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},x={path:"/tables/{table_id}/fields/{field_id}",method:"PATCH",authenticated:!0},$={path:"/tables/{table_id}/fields/{field_id}",method:"DELETE",authenticated:!0},S=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r},L=Object.freeze({MMDDYY:"%m/%d/%y",MMDDYYYY:"%m/%d/%Y",MM_DD_YYYY:"%m-%d-%Y",DD_MM_YYYY:"%d-%m-%Y",DDMMYYYY:"%d/%m/%Y",DDMMYY:"%d/%m/%y",YYYY_MM_DD:"%Y-%m-%d",MMMM__DD__YYYY:"%B %d %Y",MMM__DD__YYYY:"%b %d %Y",ddd__MMM__DD__YYYY:"%a %b %d %Y"}),q=Object.freeze({HH_mm_ss:"%H:%M:%S",HH_mm_ssZ:"%H:%M:%SZ",HH_mm_ss_SSS:"%H:%M:%S.%f",HH_mm_ss__Z:"%H:%M:%S %Z",HH_mm__AMPM:"%I:%M %p",HH_mm_ss__AMPM:"%I:%M:%S %p"});var k=/* @__PURE__ */(e=>(e.TEXT="text",e.EMAIL="email",e.LONG_TEXT="long-text",e.DATE_TIME="date-time",e.NUMBER="number",e.CURRENCY="currency",e.CHECKBOX="checkbox",e.DROPDOWN="dropdown",e.PHONE_NUMBER="phone-number",e.LINK="link",e.JSON="json",e.VECTOR="vector",e.SPARSEVECTOR="sparsevec",e.HALFVECTOR="halfvec",e.ENCRYPTED="encrypted",e))(k||{});const D={text:["email","long-text","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec","encrypted"],email:["text","long-text","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec"],"long-text":["text","email","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec"],"date-time":["text","email","long-text","phone-number","link"],number:["text","email","long-text","currency","phone-number","link"],currency:["text","email","long-text","number","phone-number","link"],checkbox:["text","email","long-text","phone-number","link"],dropdown:[],"phone-number":["text","email","long-text","date-time","number","currency","checkbox","link","json","vector","sparsevec","halfvec"],link:["text","email","long-text","number","currency","checkbox","phone-number","json","vector","sparsevec","halfvec"],json:["text","email","long-text","phone-number","link"],vector:["text","email","long-text","phone-number","link","halfvec","sparsevec","vector"],sparsevec:["text","email","long-text","phone-number","link","vector","halfvec","sparsevec"],halfvec:["text","email","long-text","phone-number","link","vector","sparsevec","halfvec"],encrypted:[]},U={text:[],email:[],"long-text":[],number:["decimals"],currency:["decimals","currency_format"],checkbox:[],dropdown:["selection_source","selectable_items","multiple_selections"],"date-time":["timezone","date_format","time_format"],"phone-number":["phone_format"],link:[],json:[],vector:["vector_dimension"],sparsevec:["vector_dimension"],halfvec:["vector_dimension"],encrypted:["show_decrypted","is_deterministic"]};function M(e){if(!e||"object"!=typeof e)throw new Error("Invalid request: single column data is required");if(!e.name||!e.type)throw new Error("Column name and type are required");return{name:(t=e).name,type:t.type,is_nullable:t.is_nullable??!0,is_primary_key:t.is_primary_key??!1,is_unique:t.is_unique??!1,is_visible:t.is_visible??!0,is_readonly:t.is_readonly??!1,is_indexed:t.is_indexed??!1,field_order:t.field_order??1,alignment:t.alignment??"left",timezone:t.timezone??void 0,date_format:t.date_format?H(t.date_format):void 0,time_format:t.time_format?P(t.time_format):void 0,decimals:t.decimals??void 0,currency_format:t.currency_format??void 0,selection_source:"dropdown"!==t.type||t.selection_source?t.selection_source??void 0:"provide-static-list",selectable_items:t.selectable_items??void 0,multiple_selections:t.multiple_selections??void 0,phone_format:t.phone_format??void 0,vector_dimension:t.vector_dimension??void 0,description:t.description??void 0,default_value:t.default_value??void 0,show_decrypted:t.show_decrypted??void 0,is_deterministic:t.is_deterministic??void 0};var t}function H(e){return L[e]||e}function P(e){return q[e]||e}class B extends y{constructor(e,t={}){super(e,t)}async createColumn(e,t){try{const r=O,s=`${this.baseURL}${S(r,{table_id:e})}`,a=M(t),i=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout});return this.config.debug&&console.log("Column API Response:",JSON.stringify(i.data,null,2)),i.data}catch(r){return this.formatErrorResponse(r)}}async createColumns(e,t){try{const r=t.columns,s=[];for(const t of r){const r=await this.createColumn(e,t);if(a(r))return r;s.push(r.data)}if(t.fields&&s.length>0){const e=A(s,t.fields);s.splice(0,s.length,...e)}return{data:s,message:"Columns created successfully"}}catch(r){return this.formatErrorResponse(r)}}async listColumns(e,t={}){try{const r=C;let s=`${this.baseURL}${S(r,{table_id:e})}?no_cache=true`;s=I(s,t.db_id);const a=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data;return t.fields&&a.data&&(a.data=A(a.data,t.fields)),a}catch(r){return this.formatErrorResponse(r)}}async getColumn(e,t,r={}){try{const s=N,a=`${this.baseURL}${S(s,{table_id:e,field_id:t})}`,i=await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),timeout:this.config.timeout});this.config.debug&&console.log("Column API Response:",JSON.stringify(i.data,null,2));const n=i.data;return r.fields&&n.data&&(n.data=v(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async updateColumn(e,t,r){try{const s=x,a=`${this.baseURL}${S(s,{table_id:e,field_id:t})}`,i=function(e){const t={};return void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=e.type),void 0!==e.description&&(t.description=e.description),void 0!==e.is_nullable&&(t.is_nullable=e.is_nullable),void 0!==e.is_unique&&(t.is_unique=e.is_unique),void 0!==e.is_primary_key&&(t.is_primary_key=e.is_primary_key),void 0!==e.is_indexed&&(t.is_indexed=e.is_indexed),void 0!==e.is_visible&&(t.is_visible=e.is_visible),void 0!==e.is_readonly&&(t.is_readonly=e.is_readonly),void 0!==e.default_value&&(t.default_value=e.default_value),void 0!==e.field_order&&(t.field_order=e.field_order),void 0!==e.show_decrypted&&(t.show_decrypted=e.show_decrypted),void 0!==e.is_deterministic&&(t.is_deterministic=e.is_deterministic),void 0!==e.alignment&&(t.alignment=e.alignment),void 0!==e.decimals&&(t.decimals=e.decimals),void 0!==e.currency_format&&(t.currency_format=e.currency_format),"dropdown"===e.type||void 0!==e.selectable_items?t.selection_source="provide-static-list":void 0!==e.selection_source&&(t.selection_source=e.selection_source),void 0!==e.selectable_items&&(t.selectable_items=e.selectable_items),void 0!==e.multiple_selections&&(t.multiple_selections=e.multiple_selections),void 0!==e.phone_format&&(t.phone_format=e.phone_format),void 0!==e.timezone&&(t.timezone=e.timezone),void 0!==e.vector_dimension&&(t.vector_dimension=e.vector_dimension),void 0!==e.date_format&&(t.date_format=H(e.date_format)),void 0!==e.time_format&&(t.time_format=P(e.time_format)),t}(r),n=(await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=v(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async deleteColumn(e,t){try{const r=$,s=`${this.baseURL}${S(r,{table_id:e,field_id:t})}`;return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async findColumnByName(e,t){try{const r={page:{page_no:1,page_size:1},filters:[{field:"name",operator:"=",values:[t]}],sort:[]},s=await this.listColumns(e,r);if(a(s))return s;const i=s.data[0]||null;return{data:i,message:i?"Column found":"Column not found"}}catch(r){return this.formatErrorResponse(r)}}convertColumnDetailsToUpdateRequest(e){return{name:e.name,type:e.type,description:e.description,is_nullable:e.is_nullable,is_unique:e.is_unique,is_indexed:e.is_indexed,is_visible:e.is_visible,is_primary_key:e.is_primary_key,is_readonly:e.is_readonly,default_value:e.default_value,field_order:e.field_order,alignment:e.alignment,decimals:e.decimals,currency_format:e.currency_format,selection_source:e.selection_source,selectable_items:e.selectable_items,multiple_selections:e.multiple_selections,phone_format:e.phone_format,date_format:e.date_format,time_format:e.time_format,timezone:e.timezone,vector_dimension:e.vector_dimension}}async updateColumnByName(e,t,r){try{const s=await this.findColumnByName(e,t);if(a(s))return s;if(!s.data)return{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["404"]}};const i={...this.convertColumnDetailsToUpdateRequest(s.data),...r};return await this.updateColumn(e,s.data.id,i)}catch(s){return this.formatErrorResponse(s)}}async deleteColumnByName(e,t){try{const r=await this.findColumnByName(e,t);return a(r)?r:r.data?await this.deleteColumn(e,r.data.id):{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["Column not found"]}}}catch(r){return this.formatErrorResponse(r)}}}const j={path:"/tables/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},Y={path:"/tables",method:"POST",authenticated:!0},F={path:"/tables/{table_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},K={path:"/tables/{table_id}",method:"PATCH",authenticated:!0},W={path:"/tables/{table_id}",method:"DELETE",authenticated:!0},z=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r},Q={EQUALS:"=",NOT_EQUALS:"!=",GREATER_THAN:">",GREATER_THAN_EQUAL:">=",LESS_THAN:"<",LESS_THAN_EQUAL:"<=",LIKE:"LIKE",ILIKE:"ILIKE",STARTS_WITH:"STARTS WITH",IN:"IN",NOT_IN:"NOT IN",IS_EMPTY:"IS EMPTY",IS_NULL:"IS NULL",IS_NOT_NULL:"IS NOT NULL",BETWEEN:"BETWEEN",ARRAY_CONTAINS:"@>",ARRAY_NOT_CONTAINS:"NOT @>",ANY:"ANY",IS_ONE_OF_ARRAY:"IS ONE OF",DROPDOWN_ITEM_STARTS_WITH:"DROPDOWN ITEM STARTS WITH",WITHIN:"WITHIN"},G={$eq:Q.EQUALS,$ne:Q.NOT_EQUALS,$gt:Q.GREATER_THAN,$gte:Q.GREATER_THAN_EQUAL,$lt:Q.LESS_THAN,$lte:Q.LESS_THAN_EQUAL,$like:Q.LIKE,$ilike:Q.ILIKE,$startsWith:Q.STARTS_WITH,$in:Q.IN,$notIn:Q.NOT_IN,$between:Q.BETWEEN,$isEmpty:Q.IS_EMPTY,$isNull:Q.IS_NULL,$isNotNull:Q.IS_NOT_NULL,$arrayContains:Q.ARRAY_CONTAINS,$arrayNotContains:Q.ARRAY_NOT_CONTAINS,$any:Q.ANY,$isOneOfArray:Q.IS_ONE_OF_ARRAY,$dropdownItemStartsWith:Q.DROPDOWN_ITEM_STARTS_WITH,$within:Q.WITHIN};function J(e){return Array.isArray(e)?e.length>0&&"object"==typeof e[0]&&"field"in e[0]&&"operator"in e[0]&&"values"in e[0]?e:(console.warn("Legacy Record<string, unknown>[] filter format detected. Please migrate to the new filter format."),[]):V(e)}function V(e){const t=[];return Object.entries(e).forEach(([e,r])=>{"object"!=typeof r||Array.isArray(r)||null===r?t.push({field:e,operator:Q.EQUALS,values:[r]}):Object.entries(r).forEach(([r,s])=>{const a=G[r];if(!a)throw new Error(`Unsupported operator: ${r}`);let i;i=a===Q.BETWEEN&&Array.isArray(s)&&2===s.length?s:a!==Q.IN&&a!==Q.NOT_IN&&a!==Q.IS_ONE_OF_ARRAY||!Array.isArray(s)?a===Q.IS_NULL||a===Q.IS_NOT_NULL||a===Q.IS_EMPTY?[]:[s]:s,t.push({field:e,operator:a,values:i})})}),t}function X(e,t="AND"){const r=J(e);return r.forEach((e,t)=>{if(!e.field)throw new Error(`Filter at index ${t} missing required field`);if(!e.operator)throw new Error(`Filter at index ${t} missing required operator`);if(!Array.isArray(e.values))throw new Error(`Filter at index ${t} values must be an array`)}),{filters:r,whereOperator:t}}function Z(e){const t={};return e.forEach(e=>{const r={};Object.entries(G).forEach(([e,t])=>{r[t]=e});const s=r[e.operator];if(!s)throw new Error(`Unsupported API operator: ${e.operator}`);t[e.field]||(t[e.field]={});const a=t[e.field];"$between"===s&&2===e.values.length?a[s]=e.values:a[s]="$in"===s||"$notIn"===s||"$isOneOfArray"===s?e.values:"$isNull"===s||"$isNotNull"===s||"$isEmpty"===s||e.values[0]}),t}class ee{constructor(){this.filters=[]}equals(e,t){return this.filters.push({field:e,operator:Q.EQUALS,values:[t]}),this}notEquals(e,t){return this.filters.push({field:e,operator:Q.NOT_EQUALS,values:[t]}),this}greaterThan(e,t){return this.filters.push({field:e,operator:Q.GREATER_THAN,values:[t]}),this}lessThan(e,t){return this.filters.push({field:e,operator:Q.LESS_THAN,values:[t]}),this}between(e,t,r){return this.filters.push({field:e,operator:Q.BETWEEN,values:[t,r]}),this}in(e,t){return this.filters.push({field:e,operator:Q.IN,values:t}),this}like(e,t){return this.filters.push({field:e,operator:Q.LIKE,values:[t]}),this}startsWith(e,t){return this.filters.push({field:e,operator:Q.STARTS_WITH,values:[t]}),this}isEmpty(e){return this.filters.push({field:e,operator:Q.IS_EMPTY,values:[]}),this}isNull(e){return this.filters.push({field:e,operator:Q.IS_NULL,values:[]}),this}arrayContains(e,t){return this.filters.push({field:e,operator:Q.ARRAY_CONTAINS,values:[t]}),this}build(){return[...this.filters]}clear(){return this.filters=[],this}}function te(){return new ee}function re(e){return{name:e.name,type:e.type,is_nullable:e.is_nullable??!0,is_primary_key:e.is_primary_key??!1,is_unique:e.is_unique??!1,is_indexed:e.is_indexed??!1,is_visible:e.is_visible??!0,is_readonly:e.is_readonly??!1,field_order:e.field_order??1,alignment:e.alignment??"left",timezone:e.timezone??void 0,date_format:e.date_format??void 0,time_format:e.time_format??void 0,decimals:e.decimals??void 0,currency_format:e.currency_format??void 0,selection_source:"dropdown"!==e.type||e.selection_source?e.selection_source??void 0:"provide-static-list",selectable_items:e.selectable_items??void 0,multiple_selections:e.multiple_selections??!1,phone_format:e.phone_format??void 0,vector_dimension:e.vector_dimension??void 0,description:e.description,default_value:e.default_value}}class se extends y{constructor(e,t={}){super(e,t)}async createTable(e,t={}){try{const r=Y;let s=`${this.baseURL}${r.path}`;s=I(s,t.db_id);const a=function(e,t={}){return{name:e.name,description:e.description,fields:e.fields.map(re),is_ai_generated_schema:t.is_ai_generated_schema||!1,is_template:t.is_template||!1}}(e,t);return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async listTables(e={}){try{const t=j;let r=`${this.baseURL}${t.path}`;r=I(r,e.db_id);const s=(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return e.fields&&s.data&&(s.data=A(s.data,e.fields)),s}catch(t){return this.formatErrorResponse(t)}}async getTable(e,t={}){try{const r=F;let s=`${this.baseURL}${z(r,{table_id:e})}`;s=I(s,t.db_id);const a=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return t.fields&&a.data&&(a.data=v(a.data,t.fields)),a}catch(r){return this.formatErrorResponse(r)}}async updateTable(e,t){try{const{fields:r,db_id:s,...a}=t,i=K;let n=`${this.baseURL}${z(i,{table_id:e})}`;n=I(n,s);const o=(await this.httpAdapter.request({url:n,method:i.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout})).data;return r&&o.data&&(o.data=v(o.data,r)),o}catch(r){return this.formatErrorResponse(r)}}async deleteTable(e,t={}){try{const r=W;let s=`${this.baseURL}${z(r,{table_id:e})}`;s=I(s,t.db_id);return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}}class ae extends E{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.tablesApiClient=new se(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async create(e,t){try{const r={...e};e.fields&&e.fields.length>0&&(r.fields=await this.processFieldsDefaults(e.fields));const s=await this.tablesApiClient.createTable(r,t?{db_id:t}:{});if(a(s))throw new o(s.error.message||"Create table failed",400,s.error);return s}catch(r){throw r instanceof o?r:new o(this.formatError(r),500)}}async processFieldsDefaults(e){const t=[];for(let r=0;r<e.length;r++){const s={...e[r]};if(void 0===s.is_primary_key&&(s.is_primary_key=!1),void 0===s.is_unique&&(s.is_unique=!1),void 0===s.is_nullable&&(s.is_nullable=!0),void 0===s.is_indexed&&(s.is_indexed=!1),"encrypted"===s.type&&(void 0===s.show_decrypted&&(s.show_decrypted=!1),void 0===s.is_deterministic&&(s.is_deterministic=!1),void 0!==s.default_value&&null!==s.default_value))throw new Error("Encrypted columns do not accept a default value");if(void 0===s.field_order&&(s.field_order=r+1),s.field_order<=0||s.field_order>=2147483647)throw new Error("Field order must be a number greater than 0 and less than 2147483647");t.push(s)}return t}transformTableQueryToApiRequest(e){const t={page:{page_no:1,page_size:e.limit||100},filters:[],sort:[]};if(e.offset&&e.limit){const r=Math.floor(e.offset/e.limit)+1;t.page.page_no=r}return e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&t.filters.push({field:e,operator:"=",values:[r]})}),e.sort&&(t.sort=e.sort.map(e=>({field:e.field,direction:e.order}))),t}async findAll(e={},t){try{const r=this.transformTableQueryToApiRequest(e),s=[...r.filters];t&&s.push({field:"db_id",operator:"=",values:[t]});const i=e.where?.resource_id||"boltic";s.push({field:"resource_id",operator:"=",values:[i]});const n={page:r.page,filters:s,sort:r.sort,...e.fields&&{fields:e.fields}},d=await this.tablesApiClient.listTables(n);if(a(d))throw new o(d.error.message||"List tables failed",400,d.error);return d}catch(r){throw r instanceof o?r:new o(this.formatError(r),500)}}async findOne(e,t){try{if(!e.where?.id&&!e.where?.name)throw new n("Either id or name must be provided in where clause");if(e.where?.id){const r=await this.tablesApiClient.getTable(e.where.id,t?{db_id:t}:{});if(a(r)){if("TABLE_NOT_FOUND"===r.error.code)return{data:null,message:"Table not found"};throw new o(r.error.message||"Get table failed",400,r.error)}return r}{const r=[{field:"name",operator:"=",values:[e.where.name]}];t&&r.push({field:"db_id",operator:"=",values:[t]});const s=e.where?.resource_id||"boltic";r.push({field:"resource_id",operator:"=",values:[s]});const n={page:{page_no:1,page_size:1},filters:r,sort:[]},d=await this.tablesApiClient.listTables(n);if(a(d))throw new o(d.error.message||"Find table by name failed",400,d.error);const l=i(d)?d.data[0]:null;return{data:l||null,message:l?"Table found":"Table not found"}}}catch(r){throw r instanceof o||r instanceof n?r:new o(this.formatError(r),500)}}async findByName(e,t){return this.findOne({where:{name:e}},t)}async findById(e,t){return this.findOne({where:{id:e}},t)}async update(e,t,r){try{const s=await this.findByName(e,r);if(!s.data)throw new o(`Table '${e}' not found`,404);if(s.data.snapshot_url)throw new o(`Cannot update snapshot table '${e}'. Snapshots are read-only and cannot be modified.`,400);const i=await this.tablesApiClient.updateTable(s.data.id,r?{...t,db_id:r}:t);if(a(i))throw new o(i.error.message||"Update table failed",400,i.error);return i}catch(s){throw s instanceof o?s:new o(this.formatError(s),500)}}async delete(e,t){try{const r=await this.findByName(e,t);if(!r.data)throw new o(`Table '${e}' not found`,404);if(r.data.snapshot_url)throw new o(`Cannot delete snapshot table '${e}'. Snapshots are read-only and cannot be deleted.`,400);const s=await this.tablesApiClient.deleteTable(r.data.id,t?{db_id:t}:{});if(a(s))throw new o(s.error.message||"Delete table failed",400,s.error);return s}catch(r){throw r instanceof o?r:new o(this.formatError(r),500)}}async rename(e,t,r){try{return await this.update(e,{name:t},r)}catch(s){throw s instanceof o?s:new o(this.formatError(s),500)}}formatError(e){return e instanceof Error?e.message:"string"==typeof e?e:"An unexpected error occurred"}}class ie extends E{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.columnsApiClient=new B(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers}),this.tablesApiClient=new se(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async create(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.processColumnDefaults(r.id,t),i=await this.columnsApiClient.createColumn(r.id,s);return a(i),i}catch(r){return{error:{code:"CREATE_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async processColumnDefaults(e,t){const r={...t};if(void 0===r.is_primary_key&&(r.is_primary_key=!1),void 0===r.is_unique&&(r.is_unique=!1),void 0===r.is_nullable&&(r.is_nullable=!0),void 0===r.is_indexed&&(r.is_indexed=!1),"encrypted"===r.type&&(void 0===r.show_decrypted&&(r.show_decrypted=!1),void 0===r.is_deterministic&&(r.is_deterministic=!1),void 0!==r.default_value&&null!==r.default_value))throw new Error("Encrypted columns do not accept a default value");if(void 0===r.field_order&&(r.field_order=await this.generateFieldOrder(e)),r.field_order<=0||r.field_order>=2147483647)throw new Error("Field order must be a number greater than 0 and less than 2147483647");return r}async generateFieldOrder(e){try{const t=await this.columnsApiClient.listColumns(e);let r=0;if(!a(t)&&t.data&&Array.isArray(t.data))for(const e of t.data)e.field_order&&e.field_order>r&&(r=e.field_order);return r+1}catch(t){return Math.floor(Date.now()/1e3)%2147483647}}transformColumnQueryToApiRequest(e){const t={page:{page_no:1,page_size:e.limit||100},filters:[],sort:[]};if(e.offset&&e.limit){const r=Math.floor(e.offset/e.limit)+1;t.page.page_no=r}return e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&t.filters.push({field:e,operator:"=",values:[r]})}),e.sort&&(t.sort=e.sort.map(e=>({field:e.field,direction:e.order}))),t}async createMany(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=[];for(const e of t){const t=await this.processColumnDefaults(r.id,e);s.push(t)}const i=await this.columnsApiClient.createColumns(r.id,{columns:s});return a(i),i}catch(r){return{error:{code:"CREATE_COLUMNS_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async findAll(e,t={}){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=this.transformColumnQueryToApiRequest(t),i=await this.columnsApiClient.listColumns(r.id,s);return a(i),i}catch(r){return{error:{code:"LIST_COLUMNS_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async get(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.findColumnByName(r.id,t);return a(s)?s:s.data?{data:s.data,message:"Column found successfully"}:{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table '${e}'`}}}catch(r){return{error:{code:"GET_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async findById(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.getColumn(r.id,t);return a(s),s}catch(r){return{error:{code:"FIND_COLUMN_BY_ID_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async update(e,t,r){try{const s=await this.getTableInfo(e);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i=await this.columnsApiClient.updateColumnByName(s.id,t,r);return a(i),i}catch(s){return{error:{code:"UPDATE_COLUMN_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async delete(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.deleteColumnByName(r.id,t);return a(s)?s:{data:{success:!0,message:"Column deleted successfully"}}}catch(r){return{error:{code:"DELETE_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async getTableInfo(e){try{const t=new ae(this.client),r=await t.findByName(e);return r.data?{id:r.data.id,snapshot_url:r.data.snapshot_url}:null}catch(t){return console.error("Error getting table info:",t),null}}async getTableId(e){const t=await this.getTableInfo(e);return t?.id||null}}const ne={path:"/tables/databases",method:"POST",authenticated:!0},oe={path:"/tables/databases/list",method:"POST",authenticated:!0},de={path:"/tables/databases/{db_id}",method:"PATCH",authenticated:!0},le={path:"/tables/databases/{db_id}",method:"DELETE",authenticated:!0},ue={path:"/tables/databases/jobs/list",method:"POST",authenticated:!0},ce={path:"/tables/databases/delete-status/{job_id}",method:"GET",authenticated:!0},he=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,t)}),r};class me extends y{constructor(e,t={}){super(e,t)}async createDatabase(e){try{const t=ne,r=`${this.baseURL}${t.path}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async listDatabases(e={},t,r){try{const s=oe;let a=`${this.baseURL}${s.path}`;const i=new URLSearchParams;t?.connector_id&&i.append("connector_id",t.connector_id),t?.add_default_if_missing&&i.append("add_default_if_missing",t.add_default_if_missing),i.toString()&&(a+=`?${i.toString()}`);const n=(await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return r?.fields&&!("error"in n)?{...n,data:A(n.data,r.fields)}:n}catch(s){return this.formatErrorResponse(s)}}async updateDatabase(e,t){try{const r=de,s=he(r,{db_id:e}),a=`${this.baseURL}${s}`;return(await this.httpAdapter.request({url:a,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async deleteDatabase(e){try{const t=le,r=he(t,{db_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async listDatabaseJobs(e={},t){try{const r=ue,s=`${this.baseURL}${r.path}`,a=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return t?.fields&&!("error"in a)?{...a,data:A(a.data,t.fields)}:a}catch(r){return this.formatErrorResponse(r)}}async pollDeleteStatus(e){try{const t=ce,r=he(t,{job_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}}class pe extends E{constructor(e){super(e,"/v1/tables/databases"),this.apiClient=new me(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async create(e){const t=await this.apiClient.createDatabase(e);return a(t)?{error:{code:"number"==typeof t.error.code?String(t.error.code):t.error.code,message:t.error.message,meta:t.error.meta}}:t}async findAll(e){const t={};if(e?.page&&(t.page=e.page),e?.sort&&(t.sort=e.sort),e?.filters){const r=e.filters.filter(e=>"status"!==e.field);t.filters=[...r,{field:"status",operator:"=",values:["ACTIVE"]}]}else t.filters=[{field:"status",operator:"=",values:["ACTIVE"]}];const r={};e?.connector_id&&(r.connector_id=e.connector_id),void 0!==e?.add_default_if_missing&&(r.add_default_if_missing=e.add_default_if_missing?"true":"false");const s=await this.apiClient.listDatabases(t,r,e);if(a(s))return{error:{code:"number"==typeof s.error.code?String(s.error.code):s.error.code,message:s.error.message,meta:s.error.meta}};if("pagination"in s&&s.pagination){const e=s.pagination;return{...s,pagination:{total_count:e.total_count,total_pages:e.total_pages??Math.ceil(e.total_count/e.per_page),current_page:e.current_page,per_page:e.per_page,type:"page"}}}return s}async findOne(e,t){const r=await this.findAll({filters:[{field:"db_internal_name",operator:"=",values:[e]}],fields:t?.fields,page:{page_no:1,page_size:1}});return a(r)?r:0===r.data.length?{error:{code:"NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}}:{data:r.data[0],message:"Database found"}}async getDefault(){const e=await this.findAll({filters:[{field:"is_default",operator:"=",values:[!0]}],page:{page_no:1,page_size:1}});return a(e)?e:0===e.data.length?{error:{code:"NOT_FOUND",message:"Default database not found",meta:[]}}:{data:e.data[0],message:"Default database found"}}async update(e,t){const r=await this.findOne(e);if(a(r))return{error:{code:"DATABASE_NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}};const s=r.data.id,i={db_name:t.db_name},n=await this.apiClient.updateDatabase(s,i);return a(n)?{error:{code:"number"==typeof n.error.code?String(n.error.code):n.error.code,message:n.error.message,meta:n.error.meta}}:n}async delete(e){const t=await this.findOne(e);if(a(t))return{error:{code:"DATABASE_NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}};if(t.data.is_default)return{error:{code:"CANNOT_DELETE_DEFAULT",message:"Cannot delete the default database",meta:[]}};const r=t.data.id,s=await this.apiClient.deleteDatabase(r);return a(s)?{error:{code:"number"==typeof s.error.code?String(s.error.code):s.error.code,message:s.error.message,meta:s.error.meta}}:s}async listJobs(e){const t={};void 0!==e?.deleted_by_me&&(t.deleted_by_me=e.deleted_by_me),e?.page&&(t.page=e.page),e?.sort&&(t.sort=e.sort),e?.filters&&(t.filters=e.filters);const r=await this.apiClient.listDatabaseJobs(t,e);if(a(r))return{error:{code:"number"==typeof r.error.code?String(r.error.code):r.error.code,message:r.error.message,meta:r.error.meta}};if("pagination"in r&&r.pagination){const e=r.pagination;return{...r,pagination:{total_count:e.total_count,total_pages:e.total_pages??Math.ceil(e.total_count/e.per_page),current_page:e.current_page,per_page:e.per_page,type:"page"}}}return{...r,data:r.data||[]}}async pollDeleteStatus(e){const t=await this.apiClient.pollDeleteStatus(e);return a(t)?{error:{code:"number"==typeof t.error.code?String(t.error.code):t.error.code,message:t.error.message,meta:t.error.meta}}:t}}const fe={path:"/tables/indexes/{table_id}",method:"POST",authenticated:!0},ge={path:"/tables/indexes/{table_id}/list",method:"POST",authenticated:!0},_e={path:"/tables/indexes/{table_id}",method:"DELETE",authenticated:!0},be=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r};class ye extends y{constructor(e,t={}){super(e,t)}async addIndex(e,t,r){try{const s=fe;let a=`${this.baseURL}${be(s,{table_id:e})}`;a=I(a,r);return(await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}async listIndexes(e,t,r){try{const s=ge;let a=`${this.baseURL}${be(s,{table_id:e})}`;a=I(a,r);return(await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}async deleteIndex(e,t,r){try{const s=_e;let a=`${this.baseURL}${be(s,{table_id:e})}`;a=I(a,r);return(await this.httpAdapter.request({url:a,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}}class we{constructor(e){this.client=e;const t=e.getConfig();this.apiClient=new ye(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers}),this.tableResource=new ae(e)}async resolveTableId(e,t){const r=await this.tableResource.findByName(e,t);if(!r.data)throw new Error(`Table not found: ${e}`);return r.data.id}async addIndex(e,t,r){try{const s=await this.resolveTableId(e,r);return await this.apiClient.addIndex(s,t,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to add index",meta:["IndexResource.addIndex"]}}}}async listIndexes(e,t,r){try{const s=await this.resolveTableId(e,r);return await this.apiClient.listIndexes(s,t,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to list indexes",meta:["IndexResource.listIndexes"]}}}}async deleteIndex(e,t,r){try{const s=await this.resolveTableId(e,r),a={index_name:t};return await this.apiClient.deleteIndex(s,a,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to delete index",meta:["IndexResource.deleteIndex"]}}}}}const Re={path:"/tables/{table_id}/records",method:"POST",authenticated:!0},Ee={path:"/tables/{table_id}/records/bulk-insert",method:"POST",authenticated:!0},Te={path:"/tables/{table_id}/records/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},ve={path:"/tables/{table_id}/records/{record_id}",method:"GET",authenticated:!0,rateLimit:{requests:200,window:6e4}},Ae={path:"/tables/{table_id}/records/bulk-update",method:"PUT",authenticated:!0},Ie={path:"/tables/{table_id}/records/{record_id}",method:"PATCH",authenticated:!0},Ce={path:"/tables/{table_id}/records/list",method:"DELETE",authenticated:!0},Oe=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r};class Ne extends y{constructor(e,t={}){super(e,t)}async insertRecord(e,t){try{const{table_id:r,fields:s,...a}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for insert operation"));const i=Re;let n=`${this.baseURL}${Oe(i,{table_id:r})}`;n=I(n,t);const o=(await this.httpAdapter.request({url:n,method:i.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout})).data;return s&&o.data&&(o.data=v(o.data,s)),o}catch(r){return this.formatErrorResponse(r)}}async insertManyRecords(e,t,r={validation:!0},s){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for bulk insert operation"));if(!e||!Array.isArray(e)||0===e.length)return this.formatErrorResponse(new Error("records array is required and cannot be empty"));const a=Ee;let i=`${this.baseURL}${Oe(a,{table_id:t})}`;const n=new URLSearchParams;void 0!==r.validation&&n.append("validation",r.validation.toString()),n.toString()&&(i+=`?${n.toString()}`),i=I(i,s);return(await this.httpAdapter.request({url:i,method:a.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(a){return this.formatErrorResponse(a)}}async getRecord(e,t,r={},s){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for get operation"));const a=ve;let i=`${this.baseURL}${Oe(a,{table_id:t,record_id:e})}`;const n=new URLSearchParams;r.show_decrypted&&n.append("show_decrypted","true"),n.toString()&&(i+=`?${n.toString()}`),i=I(i,s);const o=(await this.httpAdapter.request({url:i,method:a.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return r.fields&&o.data&&(o.data=v(o.data,r.fields)),o}catch(a){return this.formatErrorResponse(a)}}async listRecords(e={},t){try{const{table_id:r,...s}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for list operation"));const a=Te;let i=`${this.baseURL}${Oe(a,{table_id:r})}`;i=I(i,t);const n=(await this.httpAdapter.request({url:i,method:a.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return s.fields&&n.data&&(n.data=A(n.data,s.fields)),n}catch(r){return this.formatErrorResponse(r)}}async updateRecords(e,t){try{const{table_id:r,set:s,filters:a,fields:i,show_decrypted:n,...o}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for update operation"));const d={updates:s,filters:a,...o};i&&(d.fields=i);const l=Ae;let u=`${this.baseURL}${Oe(l,{table_id:r})}`;const c=new URLSearchParams;n&&c.append("show_decrypted","true"),c.toString()&&(u+=`?${c.toString()}`),u=I(u,t);const h=(await this.httpAdapter.request({url:u,method:l.method,headers:this.buildHeaders(),data:d,timeout:this.config.timeout})).data;return i&&h.data&&(h.data=A(h.data,i)),h}catch(r){return this.formatErrorResponse(r)}}async updateRecordById(e,t,r){try{const{table_id:s,show_decrypted:a,...i}=t;if(!s)return this.formatErrorResponse(new Error("table_id is required for updateById operation"));const n=Ie;let o=`${this.baseURL}${Oe(n,{record_id:e,table_id:s})}`;const d=new URLSearchParams;a&&d.append("show_decrypted","true"),d.toString()&&(o+=`?${d.toString()}`),o=I(o,r);const l=(await this.httpAdapter.request({url:o,method:n.method,headers:this.buildHeaders(),data:i.set,timeout:this.config.timeout})).data;return i.fields&&l.data&&(l.data=v(l.data,i.fields)),l}catch(s){return this.formatErrorResponse(s)}}async deleteRecords(e,t){try{const{table_id:r}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for delete operation"));const s=function(e){const t={};return e.record_ids&&e.record_ids.length>0&&(t.record_ids=e.record_ids),e.filters&&(Array.isArray(e.filters)?(e.filters.length>0&&"object"==typeof e.filters[0]&&"field"in e.filters[0]&&"operator"in e.filters[0]&&"values"in e.filters[0]||console.warn("Legacy Record<string, unknown>[] filter format detected. Please migrate to the new filter format."),t.filters=e.filters):t.filters=V(e.filters)),t}(e),a=Ce;let i=`${this.baseURL}${Oe(a,{table_id:r})}`;i=I(i,t);return(await this.httpAdapter.request({url:i,method:a.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async deleteRecordById(e,t,r){return this.deleteRecords({record_ids:[e],table_id:t.table_id},r)}}class xe{constructor(e){this.client=e,this.apiClient=new Ne(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug}),this.tablesApiClient=new se(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async insert(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i=await this.ensureCompleteRecordData(e,t);if("error"in i&&i.error)return i;const n={...i,table_id:s.id},o=await this.apiClient.insertRecord(n,r);return a(o),o}catch(s){return{error:{code:"INSERT_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async insertMany(e,t,r={validation:!0},s){try{if(!t||!Array.isArray(t)||0===t.length)return{error:{code:"INVALID_INPUT",message:"Records array is required and cannot be empty"}};const i=await this.getTableInfo(e,s);if(!i)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const n=await this.apiClient.insertManyRecords(t,i.id,r,s);return a(n),n}catch(i){return{error:{code:"INSERT_MANY_ERROR",message:i instanceof Error?i.message:"Unknown error occurred"}}}}async get(e,t,r,s){try{let i=!1,n=s;"string"==typeof r?n=r:"object"==typeof r&&(i=r.show_decrypted||!1,n=r.dbId||s);const o=await this.getTableInfo(e,n);if(!o)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const d=await this.apiClient.getRecord(t,o.id,{fields:void 0,show_decrypted:i},n);return a(d),d}catch(i){return{error:{code:"GET_ERROR",message:i instanceof Error?i.message:"Unknown error occurred"}}}}async list(e,t={},r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i={...t,table_id:s.id},n=await this.apiClient.listRecords(i,r);return a(n),n}catch(s){return{error:{code:"LIST_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async update(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i={...t,table_id:s.id},n=await this.apiClient.updateRecords(i,r);return a(n),n}catch(s){return{error:{code:"UPDATE_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async updateById(e,t,r,s,i){try{let n=!1,o=i;"string"==typeof s?o=s:"object"==typeof s&&(n=s.show_decrypted||!1,o=s.dbId||i);const d=await this.getTableInfo(e,o);if(!d)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const l={id:t,set:r,table_id:d.id,show_decrypted:n},u=await this.apiClient.updateRecordById(t,l,o);return a(u),u}catch(n){return{error:{code:"UPDATE_BY_ID_ERROR",message:n instanceof Error?n.message:"Unknown error occurred"}}}}async delete(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i={...t,table_id:s.id},n=await this.apiClient.deleteRecords(i,r);return a(n),n}catch(s){return{error:{code:"DELETE_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async deleteById(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i=await this.apiClient.deleteRecordById(t,{table_id:s.id},r);return a(i),i}catch(s){return{error:{code:"DELETE_BY_ID_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async getTableInfo(e,t){try{const r=new ae(this.client),s=await r.findByName(e,t);return s.data?{id:s.data.id,snapshot_url:s.data.snapshot_url}:null}catch(r){return console.error("Error getting table info:",r),null}}async ensureCompleteRecordData(e,t){try{const r=new ie(this.client),s=await r.findAll(e);if(a(s))return s;const i=Array.isArray(s.data)?s.data:[],n={...t};for(const e of i)"id"!==e.name&&"created_at"!==e.name&&"updated_at"!==e.name&&(e.name in t||(n[e.name]=null));return n}catch(r){return{error:{code:"COMPLETE_DATA_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}}class $e{constructor(e){this.queryOptions={},this.updateData={},this.tableName=e.tableName,this.recordResource=e.recordResource}where(e){return this.queryOptions.filters||(this.queryOptions.filters=[]),Object.entries(e).forEach(([e,t])=>{this.queryOptions.filters.push({field:e,operator:"equals",values:[t]})}),this}orderBy(e,t="asc"){return this.queryOptions.sort||(this.queryOptions.sort=[]),this.queryOptions.sort.push({field:e,order:t}),this}limit(e){return this.queryOptions.page?this.queryOptions.page.page_size=e:this.queryOptions.page={page_no:1,page_size:e},this}offset(e){if(this.queryOptions.page){const t=this.queryOptions.page.page_size||50;this.queryOptions.page.page_no=Math.floor(e/t)+1}else this.queryOptions.page={page_no:Math.floor(e/50)+1,page_size:50};return this}select(e){return this.queryOptions.fields=e,this}set(e){return this.updateData={...this.updateData,...e},this}page(e,t=50){return this.queryOptions.page={page_no:e,page_size:t},this}async list(){return this.recordResource.list(this.tableName,this.queryOptions)}async findAll(){return this.recordResource.list(this.tableName,this.queryOptions)}async findOne(){const e={...this.queryOptions,limit:1},t=await this.recordResource.list(this.tableName,e);if("error"in t)return t;const r=t.data.length>0?t.data[0]:null;return{data:r,message:r?"Record found":"No record found"}}buildWhereConditions(){const e={};return this.queryOptions.filters&&this.queryOptions.filters.forEach(t=>{if("field"in t&&"values"in t){const r=t,s=String(r.field);"equals"===r.operator?e[s]=r.values[0]:"contains"===r.operator?e[s]={$like:`%${String(r.values[0])}%`}:e[s]=r.values[0]}else Object.assign(e,t)}),e}async update(){if(!this.updateData)return{error:{code:"MISSING_UPDATE_DATA",message:"Update data is required for update operation"}};const e={set:this.updateData,filters:this.queryOptions.filters||[]};return this.recordResource.update(this.tableName,e)}async updateById(e){return this.recordResource.updateById(this.tableName,e,this.updateData)}async deleteById(e){return this.recordResource.deleteById(this.tableName,e)}async deleteByIds(e){return this.recordResource.delete(this.tableName,{record_ids:e})}async delete(){if(!this.queryOptions.filters||0===this.queryOptions.filters.length)return{error:{code:"MISSING_DELETE_CONDITIONS",message:"Filter conditions are required for delete operation. Use where() to specify conditions."}};const e={filters:this.buildWhereConditions()};return this.recordResource.delete(this.tableName,e)}getQueryOptions(){return{...this.queryOptions}}getUpdateData(){return{...this.updateData}}async insert(e){return this.recordResource.insert(this.tableName,e)}}function Se(e){return new $e(e)}const Le={path:"/tables/query/text-to-sql",method:"POST",authenticated:!0,rateLimit:{requests:100,window:6e4}},qe={path:"/tables/query/execute",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},ke=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))}),r};class De extends y{constructor(e,t={}){super(e,t)}async textToSQL(e,t){try{const r=Le;let s=`${this.baseURL}${ke(r)}`;t&&(s+=`?db_id=${encodeURIComponent(t)}`);const a=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});if(a.status>=400)return this.formatErrorResponse({response:{data:a.data,status:a.status}},"SQL");const i=a.data;return this.createAsyncIterable(i.data)}catch(r){return this.formatErrorResponse(r,"SQL")}}async executeSQL(e,t){try{const r=qe;let s=`${this.baseURL}${ke(r)}`;t&&(s+=`?db_id=${encodeURIComponent(t)}`);const a=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});return a.status>=400?this.formatErrorResponse({response:{data:a.data,status:a.status}},"SQL"):a.data}catch(r){return this.formatErrorResponse(r,"SQL")}}async*createAsyncIterable(e){yield e}}class Ue{constructor(e){const t=e.getConfig();this.sqlApiClient=new De(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async textToSQL(e,t={},r){const s=function(e,t={}){return{prompt:e,current_query:t.currentQuery}}(e,t),a=await this.sqlApiClient.textToSQL(s,r);if("error"in a&&void 0!==a.error)throw a;return a}async executeSQL(e,t){const r=await this.sqlApiClient.executeSQL({query:e},t);return a(r),r}}class Me{constructor(e,t){this.fields=[],this.tableName=e.name,this.description=e.description,this.tablesApiClient=t}name(e){return this.tableName=e,this}describe(e){return this.description=e,this}text(e,t={}){return this.fields.push({name:e,type:"text",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,alignment:t.alignment||"left",field_order:this.fields.length+1}),this}longText(e,t={}){return this.fields.push({name:e,type:"long-text",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:t.alignment||"left",field_order:this.fields.length+1}),this}number(e,t={}){return this.fields.push({name:e,type:"number",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,decimals:t.decimals,alignment:t.alignment||"right",field_order:this.fields.length+1}),this}currency(e,t={}){return this.fields.push({name:e,type:"currency",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,currency_format:t.currencyFormat,decimals:t.decimals,alignment:"right",field_order:this.fields.length+1}),this}checkbox(e,t={}){return this.fields.push({name:e,type:"checkbox",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,alignment:"center",field_order:this.fields.length+1}),this}dropdown(e,t,r={}){return this.fields.push({name:e,type:"dropdown",is_nullable:r.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:r.defaultValue,description:r.description,selection_source:"provide-static-list",selectable_items:t,multiple_selections:r.multiple??!1,alignment:"left",field_order:this.fields.length+1}),this}email(e,t={}){return this.fields.push({name:e,type:"email",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}phone(e,t={}){return this.fields.push({name:e,type:"phone-number",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,phone_format:t.format,alignment:"left",field_order:this.fields.length+1}),this}link(e,t={}){return this.fields.push({name:e,type:"link",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}json(e,t={}){return this.fields.push({name:e,type:"json",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}dateTime(e,t={}){return this.fields.push({name:e,type:"date-time",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,date_format:t.dateFormat,time_format:t.timeFormat,timezone:t.timezone,alignment:"left",field_order:this.fields.length+1}),this}vector(e,t,r={}){return this.fields.push({name:e,type:"vector",is_nullable:r.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:r.description,vector_dimension:t,alignment:"left",field_order:this.fields.length+1}),this}addField(e){return this.fields.push({...e,field_order:e.field_order||this.fields.length+1}),this}removeField(e){return this.fields=this.fields.filter(t=>t.name!==e),this.fields.forEach((e,t)=>{e.field_order=t+1}),this}getFields(){return[...this.fields]}getName(){return this.tableName}getDescription(){return this.description}build(){if(!this.tableName)throw new n("Table name is required",[{field:"name",message:"Table name cannot be empty"}]);if(0===this.fields.length)throw new n("At least one field is required",[{field:"fields",message:"Table must have at least one field"}]);return{name:this.tableName,description:this.description,fields:this.fields}}async create(e={}){if(!this.tablesApiClient)throw new Error("TablesApiClient is required for table creation");const t=this.build();return this.tablesApiClient.createTable(t,e)}}function He(e,t){return new Me(e,t)}const Pe={string:{type:"string",fallback_value:""},number:{type:"number",fallback_value:""},boolean:{type:"boolean",secondary_type:"string",fallback_value:""},int:{type:"number",fallback_value:""},integer:{type:"number",fallback_value:""},"date-time":{type:"date-time",secondary_type:"string",fallback_value:""},date:{type:"date",secondary_type:"string",fallback_value:""},json:{type:"object",fallback_value:{}},text:{type:"string",fallback_value:""},email:{type:"string",fallback_value:""},password:{type:"string",fallback_value:""},url:{type:"string",fallback_value:""},textarea:{type:"string",fallback_value:""},select:{type:"string",fallback_value:""},multiselect:{type:"string",fallback_value:""},autocomplete:{type:"array",fallback_value:[]},radio:{type:"string",fallback_value:""},radiobuttons:{type:"string",fallback_value:""},checkbox:{type:"array",fallback_value:[]},toggle:{type:"boolean",fallback_value:""},hidden:{type:"string",fallback_value:""},slider:{type:"number",fallback_value:""},datepicker:{type:"string",fallback_value:""},phoneinput:{type:"string",fallback_value:""},time:{type:"string",fallback_value:""},datetime:{type:"string",fallback_value:""},code:{type:"string",fallback_value:""},multitext:{type:"array",fallback_value:[]},array:{type:"array",fallback_value:[]},keyvalue:{type:"object",fallback_value:{}},object:{type:"object",fallback_value:{}},phone:{type:"string",fallback_value:""},"number[]":{type:"string",fallback_value:""},"number []":{type:"string",fallback_value:""},"object | any":{type:"string",fallback_value:""}},Be={path:"/workflows/execute/activity",method:"POST",authenticated:!0},je={path:"/workflows/run/{run_id}",method:"GET",authenticated:!0},Ye={path:"/integrations",method:"GET",authenticated:!0},Fe={path:"/integrations/entity/{entity}",method:"GET",authenticated:!0},Ke={path:"/integrations/{integration_slug}/schema",method:"GET",authenticated:!0},We={path:"/integrations/{integration_slug}/fields",method:"GET",authenticated:!0};function ze(e,t={}){let r=e.path;for(const[s,a]of Object.entries(t))r=r.replace(`{${s}}`,a);return r}class Qe extends y{constructor(e,t={}){super(e,t,_),this.integrationBaseURL=this.resolveAdditionalServiceURL(b)}async executeActivity(e){try{const t=Be,r=`${this.baseURL}${t.path}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getExecutionById(e){try{const t=je,r=ze(t,{run_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getIntegrations(e={}){try{const t=Ye,r=new URLSearchParams({page:String(e.page??1),per_page:String(e.per_page??999)}),s=`${this.baseURL}${t.path}?${r.toString()}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getCredentials(e){try{const t=Fe,r=ze(t,{entity:e.entity.toUpperCase()}),s=new URLSearchParams({current_page:String(e.current_page??1),page_size:String(e.page_size??999)}),a=`${this.integrationBaseURL}${r}?${s.toString()}`;return(await this.httpAdapter.request({url:a,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"INTEGRATION")}}async getIntegrationResource(e){try{const t=Ke,r=ze(t,{integration_slug:e.integration_slug}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getIntegrationForm(e){try{const t=We,r=ze(t,{integration_slug:e.integration_slug}),s=new URLSearchParams({resource:e.resource,operation:e.operation,secret:e.secret}),a=`${this.baseURL}${r}?${s.toString()}`;return(await this.httpAdapter.request({url:a,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}}const Ge=/* @__PURE__ */new Set(["resource","operation"]);function Je(e){return Pe[e]??{type:"string",fallback_value:""}}function Ve(e){return new Promise(t=>setTimeout(t,e))}class Xe extends E{constructor(e){super(e,"/workflows");const t=e.getConfig();this.apiClient=new Qe(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug})}async executeIntegration(e){const t=function(e){return{nodes:[{data:{type:e.data.type,name:e.data.name,properties:e.data.properties}}],result:e.result??{payload:{},global_variables:{}}}}(e),r=await this.apiClient.executeActivity(t);if(a(r))return r;if(e.executeOnly)return r;const s=r.data?.execution_id;return s?this.pollExecution(s):{error:{code:"MISSING_EXECUTION_ID",message:"Execute API response did not contain an execution_id",meta:[]}}}async getIntegrationExecuteById(e){return this.apiClient.getExecutionById(e)}async getIntegrations(e={}){return this.apiClient.getIntegrations(e)}async getCredentials(e){return this.apiClient.getCredentials(e)}async getIntegrationResource(e){return this.apiClient.getIntegrationResource(e)}async getIntegrationForm(e){const t=await this.apiClient.getIntegrationForm(e);if(console.log("rawResult",JSON.stringify(t,null,2)),a(t))return t;const r=(t.data?.parameters||t.data)??[],s=e.asJsonSchema?function(e,t=Ge){const r={};for(const s of e){if(t.has(s.name))continue;const e=Je(s.meta?.displayType||"text"),a=s.meta?.validation?.required??!1,i=void 0!==s.meta?.value?s.meta.value:e.fallback_value,n={type:e.type,required:a,default:i};s.meta?.description&&(n.description=s.meta.description),s.meta?.options&&Array.isArray(s.meta.options)&&s.meta.options.length>0&&(n.enum=s.meta.options.map(e=>e.value)),r[s.name]=n}return{type:"object",properties:r}}(r):function(e,t=Ge){const r={};for(const s of e){if(t.has(s.name))continue;const e=Je(s.meta?.displayType||"text");r[s.name]=void 0!==s.meta?.value?s.meta.value:e.fallback_value}return r}(r);if(e.asJsonSchema){const t=s;t.properties.secret&&(t.properties.secret.default=e.secret)}else{"secret"in s&&(s.secret=e.secret)}return{data:s,message:t.message}}async pollExecution(e){const t=this.client.getConfig().debug;for(let r=0;r<30;r++){const s=await this.apiClient.getExecutionById(e);if(a(s))return s;if(s.data&&Object.keys(s.data).length>0)return t&&console.log(`[WorkflowResource] Execution ${e} completed after ${r+1} poll(s)`),s;await Ve(1e3)}return{error:{code:"EXECUTION_TIMEOUT",message:`Execution ${e} did not complete within 30 polling attempts`,meta:[`execution_id: ${e}`,"max_attempts: 30"]}}}}class Ze{constructor(e,t={}){this.currentDatabase=null,this.clientOptions=t,this.configManager=new T(e,t.environment||"prod",t.region||"asia-south1",t);const r=this.configManager.getConfig();this.authManager=new f({apiKey:r.apiKey,maxRetries:r.maxRetries}),this.baseClient=new R(r,this.authManager),this.tableResource=new ae(this.baseClient),this.columnResource=new ie(this.baseClient),this.recordResource=new xe(this.baseClient),this.sqlResource=new Ue(this.baseClient),this.indexResource=new we(this.baseClient),this.databaseResource=new pe(this.baseClient),this.workflowResource=new Xe(this.baseClient),this.currentDatabase=null}getCurrentDatabase(){return this.currentDatabase}async useDatabase(e){if(console.log(`Database internal name:${e}`),!e||""===e)return void(this.currentDatabase=null);const t=await this.databaseResource.findOne(e);if(console.log(`Result:${JSON.stringify(t,null,2)}`),a(t))throw console.log(`Error:${t.error.message}`),new Error(t.error.message||`Failed to switch database to internal name '${e}'`);const r=t.data;this.currentDatabase={databaseId:r.id,dbInternalName:r.db_internal_name||e}}get databases(){return{create:e=>this.databaseResource.create(e),findAll:e=>this.databaseResource.findAll(e),findOne:(e,t)=>this.databaseResource.findOne(e,t),getDefault:()=>this.databaseResource.getDefault(),update:(e,t)=>this.databaseResource.update(e,t),delete:e=>this.databaseResource.delete(e),listJobs:e=>this.databaseResource.listJobs(e),pollDeleteStatus:e=>this.databaseResource.pollDeleteStatus(e)}}get tables(){const e=this.currentDatabase?.databaseId;return{create:t=>this.tableResource.create(t,e),findAll:t=>this.tableResource.findAll(t,e),findById:t=>this.tableResource.findById(t,e),findByName:t=>this.tableResource.findByName(t,e),findOne:t=>this.tableResource.findOne(t,e),update:(t,r)=>this.tableResource.update(t,r,e),delete:t=>this.tableResource.delete(t,e),rename:(t,r)=>this.tableResource.rename(t,r,e)}}get columns(){return{create:(e,t)=>this.columnResource.create(e,t),createMany:(e,t)=>this.columnResource.createMany(e,t),findAll:(e,t)=>this.columnResource.findAll(e,t),findOne:(e,t)=>this.columnResource.get(e,t),findById:(e,t)=>this.columnResource.findById(e,t),update:(e,t,r)=>this.columnResource.update(e,t,r),delete:(e,t)=>this.columnResource.delete(e,t)}}get indexes(){return{addIndex:(e,t)=>this.indexResource.addIndex(e,t),listIndexes:(e,t)=>this.indexResource.listIndexes(e,t),deleteIndex:(e,t)=>this.indexResource.deleteIndex(e,t)}}table(e){return He({name:e})}from(e){const t=this.currentDatabase?.databaseId;return{indexes:()=>({addIndex:r=>this.indexResource.addIndex(e,r,t),listIndexes:r=>this.indexResource.listIndexes(e,r,t),deleteIndex:r=>this.indexResource.deleteIndex(e,r,t)}),records:()=>({insert:r=>this.recordResource.insert(e,r,t),insertMany:(r,s)=>this.recordResource.insertMany(e,r,s,t),findOne:r=>this.recordResource.get(e,r,t),update:r=>this.recordResource.update(e,r,t),updateById:(r,s)=>this.recordResource.updateById(e,r,s,t),delete:r=>this.recordResource.delete(e,r,t),deleteById:r=>this.recordResource.deleteById(e,r,t)})}}get records(){const e=this.currentDatabase?.databaseId;return{insert:(t,r)=>this.recordResource.insert(t,r,e),insertMany:(t,r,s)=>this.recordResource.insertMany(t,r,s,e),findAll:(t,r)=>this.recordResource.list(t,r,e),findOne:(t,r,s)=>this.recordResource.get(t,r,s,e),update:(t,r)=>this.recordResource.update(t,r,e),updateById:(t,r,s,a)=>this.recordResource.updateById(t,r,s,a,e),delete:(t,r)=>this.recordResource.delete(t,r,e),deleteById:(t,r)=>this.recordResource.deleteById(t,r,e)}}record(e){return Se({tableName:e,recordResource:this.recordResource})}get sql(){const e=this.currentDatabase?.databaseId;return{textToSQL:(t,r)=>this.sqlResource.textToSQL(t,r,e),executeSQL:t=>this.sqlResource.executeSQL(t,e)}}get workflow(){return{executeIntegration:e=>this.workflowResource.executeIntegration(e),getIntegrationExecuteById:e=>this.workflowResource.getIntegrationExecuteById(e),getIntegrations:e=>this.workflowResource.getIntegrations(e),getCredentials:e=>this.workflowResource.getCredentials(e),getIntegrationResource:e=>this.workflowResource.getIntegrationResource(e),getIntegrationForm:e=>this.workflowResource.getIntegrationForm(e)}}getSqlResource(){return this.sqlResource}updateApiKey(e){this.configManager.updateConfig({apiKey:e}),this.authManager.updateApiKey(e)}updateConfig(e){this.configManager.updateConfig(e),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}getConfig(){return this.configManager.getConfig()}async validateApiKey(){return this.authManager.validateApiKeyAsync()}isAuthenticated(){return this.authManager.isAuthenticated()}getHttpClient(){return this.baseClient}addRequestInterceptor(e){return this.baseClient.getInterceptors().request.use(e)}addResponseInterceptor(e,t){return this.baseClient.getInterceptors().response.use(e,t)}ejectRequestInterceptor(e){this.baseClient.getInterceptors().request.eject(e)}ejectResponseInterceptor(e){this.baseClient.getInterceptors().response.eject(e)}async testConnection(){try{return await this.authManager.validateApiKeyAsync()}catch(e){return!1}}getVersion(){return"1.0.0"}getEnvironment(){return this.configManager.getConfig().environment}getRegion(){return this.configManager.getConfig().region}enableDebug(){this.configManager.updateConfig({debug:!0}),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}disableDebug(){this.configManager.updateConfig({debug:!1}),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}isDebugEnabled(){return this.configManager.getConfig().debug||!1}updateAllResourcesConfig(){this.tableResource=new ae(this.baseClient),this.columnResource=new ie(this.baseClient),this.recordResource=new xe(this.baseClient),this.sqlResource=new Ue(this.baseClient),this.indexResource=new we(this.baseClient),this.databaseResource=new pe(this.baseClient),this.workflowResource=new Xe(this.baseClient)}toString(){const e=this.getConfig();return`BolticClient { environment: "${e.environment}", region: "${e.region}", debug: ${e.debug} }`}toJSON(){const e=this.getConfig();return{environment:e.environment,region:e.region,debug:e.debug,timeout:e.timeout,version:this.getVersion()}}[/* @__PURE__ */Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function et(e={}){return new Ze(e.apiKey||"test-api-key-12345",{environment:"local",region:"asia-south1",debug:e.debug??!0,timeout:3e4,...e})}function tt(e,t){return{data:e,pagination:t}}function rt(e,t){return{error:e,details:t}}export{o as A,Ze as B,L as D,t as E,Q as F,e as R,Ue as S,q as T,n as V,i as a,ee as b,X as c,te as d,V as e,Se as f,He as g,d as h,a as i,c as j,u as k,l,Z as m,J as n,rt as o,tt as p,et as q,r,s,k as t,D as u,U as v};
|
|
2
|
-
//# sourceMappingURL=test-client-BEAX5vfC.mjs.map
|