@boltic/sdk 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ "use strict";class e extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.failures=t}}class t extends Error{constructor(e,t,r){super(e),this.name="ApiError",this.statusCode=t,this.response=r}}function r(e,t){const r=new Error(e);return t&&(r.context=t),r}function s(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 i(e){if(e instanceof Error){const t=e.context,r=s(e);let i=`${e.name}: ${e.message}`;return r&&(i+=` (HTTP ${r})`),t&&(i+=`\nContext: ${JSON.stringify(t,null,2)}`),i}return String(e)}class a{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 r("API key is required and must be a non-empty string",{name:"AuthenticationError",code:"INVALID_API_KEY"});if(e.length<10)throw r("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}}class n{constructor(){try{this.axios=require("axios")}catch(e){throw r("Axios is required for Node.js < 18. Please install axios: npm install axios",{error:e})}}async request(e){var t;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);return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}}}catch(s){const i=s;if("ECONNABORTED"===i.code||(null==(t=i.message)?void 0:t.includes("timeout")))throw r("Request timeout",{url:e.url,method:e.method,timeout:e.timeout});if("AbortError"===i.name||"ERR_CANCELED"===i.code)throw r("Request was aborted",{url:e.url,method:e.method});throw r(`HTTP request failed: ${i.message||"Unknown error"}`,{url:e.url,method:e.method,originalError:s})}}}class o{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 s={method:e.method,headers:{"Content-Type":"application/json",...e.headers},signal:e.signal};e.data&&["POST","PUT","PATCH","DELETE"].includes(e.method)&&(s.body=JSON.stringify(e.data));try{const r=new AbortController;let i;e.timeout&&(i=setTimeout(()=>r.abort(),e.timeout),s.signal=e.signal?(()=>{const t=new AbortController;return e.signal.addEventListener("abort",()=>t.abort()),r.signal.addEventListener("abort",()=>t.abort()),t.signal})():r.signal);const a=await fetch(t.toString(),s);i&&clearTimeout(i);const n=a.headers.get("content-type");let o;o=(null==n?void 0:n.includes("application/json"))?await a.json():await a.text();const d={};a.headers.forEach((e,t)=>{d[t]=e});return{data:o,status:a.status,statusText:a.statusText,headers:d}}catch(i){if(i instanceof Error&&"AbortError"===i.name)throw r("Request was aborted",{type:"AbortError",url:e.url,method:e.method});throw r(`HTTP request failed: ${i instanceof Error?i.message:"Unknown error"}`,{url:e.url,method:e.method,originalError:i})}}}function d(){if("undefined"!=typeof fetch)return new o;try{return new n}catch(e){throw r("No suitable HTTP adapter found. Please use Node.js >= 18 or install axios: npm install axios",{error:e})}}class l{constructor(){this.requestInterceptors=new Map,this.responseInterceptors=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 this.requestInterceptors.values())t=await r(t);return t}async executeResponseInterceptors(e){let t=e;for(const{fulfilled:r}of this.responseInterceptors.values())r&&(t=await r(t));return t}async executeErrorInterceptors(e){let t=e;for(const{rejected:r}of this.responseInterceptors.values())r&&(t=await r(t));return t}}class u{constructor(e,t){this.config=e,this.authManager=t,this.httpAdapter=d(),this.interceptors=new l,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){var t;if(this.config.debug&&console.error("HTTP Error:",e),e instanceof Error&&e.context)throw e;const i=s(e);if(!i)throw r("Network request failed",{name:"NetworkError",originalError:e});const a=(null==(t=e.response)?void 0:t.data)||e.data;throw r((null==a?void 0:a.message)||(null==a?void 0:a.error)||`HTTP ${i} error`,{name:"ApiError",statusCode:i,response:a,isClientError:i>=400&&i<500,isServerError:i>=500,isAuthError:401===i||403===i,isNotFoundError:404===i,isRateLimitError:429===i})}async request(e){let t;const i=this.config.maxRetries;for(let n=0;n<=i;n++)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),s=await this.httpAdapter.request(t);if(s.status>=400){const e=r(`HTTP ${s.status} error`,{name:"ApiError",statusCode:s.status,response:s.data,statusText:s.statusText});throw await this.interceptors.executeErrorInterceptors(e)}return await this.interceptors.executeResponseInterceptors(s)}catch(a){if(t=a,n===i)break;const e=s(a);if(e&&e>=400&&e<500)break;if(n<i){const e=this.config.retryDelay*Math.pow(2,n);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}}}const c={"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}}},h=c["asia-south1"];class p{constructor(e,t="prod",r="asia-south1",s){const i=c[r][t];this.config={apiKey:e,environment:t,region:r,retryAttempts:3,retryDelay:1e3,maxRetries:3,debug:!1,headers:{},...i,...s}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}}function m(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 f(e,t){return t&&0!==t.length?e.map(e=>m(e,t)):e}const _={path:"/tables/{table_id}/fields/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},g={path:"/tables/{table_id}/fields",method:"POST",authenticated:!0},b={path:"/tables/{table_id}/fields/{field_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},y={path:"/tables/{table_id}/fields/{field_id}",method:"PATCH",authenticated:!0},R={path:"/tables/{table_id}/fields/{field_id}",method:"DELETE",authenticated:!0},E=(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},w=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"}),T=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"});function A(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?v(t.date_format):void 0,time_format:t.time_format?N(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};var t}function v(e){return w[e]||e}function N(e){return T[e]||e}class O{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async createColumn(e,t){try{const r=g,s=`${this.baseURL}${E(r,{table_id:e})}`,i=A(t),a=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout});return this.config.debug&&console.log("Column API Response:",JSON.stringify(a.data,null,2)),a.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("error"in r)return r;s.push(r.data)}if(t.fields&&s.length>0){const e=f(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=_,s=`${this.baseURL}${E(r,{table_id:e})}?no_cache=true`,i=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data;return t.fields&&i.data&&(i.data=f(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async getColumn(e,t,r={}){try{const s=b,i=`${this.baseURL}${E(s,{table_id:e,field_id:t})}`,a=await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),timeout:this.config.timeout});this.config.debug&&console.log("Column API Response:",JSON.stringify(a.data,null,2));const n=a.data;return r.fields&&n.data&&(n.data=m(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async updateColumn(e,t,r){try{const s=y,i=`${this.baseURL}${E(s,{table_id:e,field_id:t})}`,a=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.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=v(e.date_format)),void 0!==e.time_format&&(t.time_format=N(e.time_format)),t}(r),n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=m(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async deleteColumn(e,t){try{const r=R,s=`${this.baseURL}${E(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("error"in 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("error"in s)return s;if(!s.data)return{data:{},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"error"in r?r:r.data?await this.deleteColumn(e,r.data.id):{data:{},error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["Column not found"]}}}catch(r){return this.formatErrorResponse(r)}}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Columns API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{data:{},error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{data:{},error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{data:{},error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}const C={path:"/tables/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},I={path:"/tables",method:"POST",authenticated:!0},L={path:"/tables/{table_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},q={path:"/tables/{table_id}",method:"PATCH",authenticated:!0},$={path:"/tables/{table_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},U={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"},x={$eq:U.EQUALS,$ne:U.NOT_EQUALS,$gt:U.GREATER_THAN,$gte:U.GREATER_THAN_EQUAL,$lt:U.LESS_THAN,$lte:U.LESS_THAN_EQUAL,$like:U.LIKE,$ilike:U.ILIKE,$startsWith:U.STARTS_WITH,$in:U.IN,$notIn:U.NOT_IN,$between:U.BETWEEN,$isEmpty:U.IS_EMPTY,$isNull:U.IS_NULL,$isNotNull:U.IS_NOT_NULL,$arrayContains:U.ARRAY_CONTAINS,$arrayNotContains:U.ARRAY_NOT_CONTAINS,$any:U.ANY,$isOneOfArray:U.IS_ONE_OF_ARRAY,$dropdownItemStartsWith:U.DROPDOWN_ITEM_STARTS_WITH,$within:U.WITHIN};function D(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."),[]):k(e)}function k(e){const t=[];return Object.entries(e).forEach(([e,r])=>{"object"!=typeof r||Array.isArray(r)||null===r?t.push({field:e,operator:U.EQUALS,values:[r]}):Object.entries(r).forEach(([r,s])=>{const i=x[r];if(!i)throw new Error(`Unsupported operator: ${r}`);let a;a=i===U.BETWEEN&&Array.isArray(s)&&2===s.length?s:i!==U.IN&&i!==U.NOT_IN&&i!==U.IS_ONE_OF_ARRAY||!Array.isArray(s)?i===U.IS_NULL||i===U.IS_NOT_NULL||i===U.IS_EMPTY?[]:[s]:s,t.push({field:e,operator:i,values:a})})}),t}class P{constructor(){this.filters=[]}equals(e,t){return this.filters.push({field:e,operator:U.EQUALS,values:[t]}),this}notEquals(e,t){return this.filters.push({field:e,operator:U.NOT_EQUALS,values:[t]}),this}greaterThan(e,t){return this.filters.push({field:e,operator:U.GREATER_THAN,values:[t]}),this}lessThan(e,t){return this.filters.push({field:e,operator:U.LESS_THAN,values:[t]}),this}between(e,t,r){return this.filters.push({field:e,operator:U.BETWEEN,values:[t,r]}),this}in(e,t){return this.filters.push({field:e,operator:U.IN,values:t}),this}like(e,t){return this.filters.push({field:e,operator:U.LIKE,values:[t]}),this}startsWith(e,t){return this.filters.push({field:e,operator:U.STARTS_WITH,values:[t]}),this}isEmpty(e){return this.filters.push({field:e,operator:U.IS_EMPTY,values:[]}),this}isNull(e){return this.filters.push({field:e,operator:U.IS_NULL,values:[]}),this}arrayContains(e,t){return this.filters.push({field:e,operator:U.ARRAY_CONTAINS,values:[t]}),this}build(){return[...this.filters]}clear(){return this.filters=[],this}}function M(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 H{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async createTable(e,t={}){try{const r=I,s=`${this.baseURL}${r.path}`,i=function(e,t={}){return{name:e.name,description:e.description,fields:e.fields.map(M),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:i,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async listTables(e={}){try{const t=C,r=`${this.baseURL}${t.path}`,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=f(s.data,e.fields)),s}catch(t){return this.formatErrorResponse(t)}}async getTable(e,t={}){try{const r=L,s=`${this.baseURL}${S(r,{table_id:e})}`,i=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return t.fields&&i.data&&(i.data=m(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async updateTable(e,t){try{const{fields:r,...s}=t,i=q,a=`${this.baseURL}${S(i,{table_id:e})}`,n=(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return r&&n.data&&(n.data=m(n.data,r)),n}catch(r){return this.formatErrorResponse(r)}}async deleteTable(e){try{const t=$,r=`${this.baseURL}${S(t,{table_id:e})}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Tables API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{data:{},error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{data:{},error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{data:{},error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}function B(e){return"error"in e&&void 0!==e.error}function Y(e){return"pagination"in e}class j{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:null==s?void 0:s.params});break;case"POST":t=await this.client.post(a,r,{params:null==s?void 0:s.params});break;case"PUT":t=await this.client.put(a,r,{params:null==s?void 0:s.params});break;case"PATCH":t=await this.client.patch(a,r,{params:null==s?void 0:s.params});break;case"DELETE":t=await this.client.delete(a,{params:null==s?void 0:s.params})}return t.data}catch(n){return{data:{},error:{code:"CLIENT_ERROR",message:i(n),meta:["Request failed"]}}}}buildQueryParams(e={}){var t,r;const s={};return(null==(t=e.fields)?void 0:t.length)&&(s.fields=e.fields.join(",")),(null==(r=e.sort)?void 0:r.length)&&(s.sort=e.sort.map(e=>`${e.field}:${e.order}`).join(",")),void 0!==e.limit&&(s.limit=e.limit),void 0!==e.offset&&(s.offset=e.offset),e.where&&Object.entries(e.where).forEach(([e,t])=>{null!=t&&(s[`where[${e}]`]="object"==typeof t?JSON.stringify(t):t)}),s}handleResponse(e){return"error"in e&&this.client.getConfig().debug&&console.error("API Error:",e.error),e}}class F extends j{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.tablesApiClient=new H(t.apiKey,{environment:t.environment,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}getTablesApiClient(){return this.tablesApiClient}async create(e){try{const r={...e};e.fields&&e.fields.length>0&&(r.fields=await this.processFieldsDefaults(e.fields));const s=await this.tablesApiClient.createTable(r);if(B(s))throw new t(s.error.message||"Create table failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(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),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={}){try{const r=this.transformTableQueryToApiRequest(e),s=await this.tablesApiClient.listTables(r);if(B(s))throw new t(s.error.message||"List tables failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}async findOne(r){var s,i,a;try{if(!(null==(s=r.where)?void 0:s.id)&&!(null==(i=r.where)?void 0:i.name))throw new e("Either id or name must be provided in where clause");if(null==(a=r.where)?void 0:a.id){const e=await this.tablesApiClient.getTable(r.where.id);if(B(e)){if("TABLE_NOT_FOUND"===e.error.code)return{data:null,message:"Table not found"};throw new t(e.error.message||"Get table failed",400,e.error)}return e}{const e={page:{page_no:1,page_size:1},filters:[{field:"name",operator:"=",values:[r.where.name]}],sort:[]},s=await this.tablesApiClient.listTables(e);if(B(s))throw new t(s.error.message||"Find table by name failed",400,s.error);const i=Y(s)?s.data[0]:null;return{data:i||null,message:i?"Table found":"Table not found"}}}catch(n){throw n instanceof t||n instanceof e?n:new t(this.formatError(n),500)}}async findByName(e){return this.findOne({where:{name:e}})}async findById(e){return this.findOne({where:{id:e}})}async update(e,r){try{const s=await this.findByName(e);if(!s.data)throw new t(`Table '${e}' not found`,404);if(s.data.snapshot_url)throw new t(`Cannot update snapshot table '${e}'. Snapshots are read-only and cannot be modified.`,400);const i=await this.tablesApiClient.updateTable(s.data.id,r);if(B(i))throw new t(i.error.message||"Update table failed",400,i.error);return i}catch(s){throw s instanceof t?s:new t(this.formatError(s),500)}}async delete(e){try{const r=await this.findByName(e);if(!r.data)throw new t(`Table '${e}' not found`,404);if(r.data.snapshot_url)throw new t(`Cannot delete snapshot table '${e}'. Snapshots are read-only and cannot be deleted.`,400);const s=await this.tablesApiClient.deleteTable(r.data.id);if(B(s))throw new t(s.error.message||"Delete table failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}async rename(e,r){try{return await this.update(e,{name:r})}catch(s){throw s instanceof t?s:new t(this.formatError(s),500)}}async setAccess(e){try{return await this.update(e.table_name,{is_shared:e.is_shared})}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}formatError(e){return e instanceof Error?e.message:"string"==typeof e?e:"An unexpected error occurred"}}class K extends j{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.columnsApiClient=new O(t.apiKey,{environment:t.environment,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers}),this.tablesApiClient=new H(t.apiKey,{environment:t.environment,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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot create column in snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s=await this.processColumnDefaults(r.id,t),i=await this.columnsApiClient.createColumn(r.id,s);return B(i),i}catch(r){return{data:{},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),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(!B(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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot create columns in snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};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 B(i),i}catch(r){return{data:{},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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=this.transformColumnQueryToApiRequest(t),i=await this.columnsApiClient.listColumns(r.id,s);return B(i),i}catch(r){return{data:{},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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.findColumnByName(r.id,t);return B(s)?s:s.data?{data:s.data,message:"Column found successfully"}:{data:{},error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table '${e}'`}}}catch(r){return{data:{},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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.getColumn(r.id,t);return B(s),s}catch(r){return{data:{},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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(s.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot update column '${t}' in snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const i=await this.columnsApiClient.updateColumnByName(s.id,t,r);return B(i),i}catch(s){return{data:{},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{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot delete column '${t}' from snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s=await this.columnsApiClient.deleteColumnByName(r.id,t);return B(s)?s:{data:{success:!0,message:"Column deleted successfully"}}}catch(r){return{data:{},error:{code:"DELETE_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async getTableInfo(e){try{const t=new F(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(null==t?void 0:t.id)||null}}const Q={path:"/tables/{table_id}/records",method:"POST",authenticated:!0},W={path:"/tables/{table_id}/records/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},z={path:"/tables/{table_id}/records/{record_id}",method:"GET",authenticated:!0,rateLimit:{requests:200,window:6e4}},G={path:"/tables/{table_id}/records",method:"PATCH",authenticated:!0},V={path:"/tables/{table_id}/records/{record_id}",method:"PATCH",authenticated:!0},J={path:"/tables/{table_id}/records/list",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};class X{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async insertRecord(e){try{const{table_id:t,fields:r,...s}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for insert operation"));const i=Q,a=`${this.baseURL}${Z(i,{table_id:t})}`,n=(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return r&&n.data&&(n.data=m(n.data,r)),n}catch(t){return this.formatErrorResponse(t)}}async getRecord(e,t,r={}){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for get operation"));const s=z,i=`${this.baseURL}${Z(s,{table_id:t,record_id:e})}`,a=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return r.fields&&a.data&&(a.data=m(a.data,r.fields)),a}catch(s){return this.formatErrorResponse(s)}}async listRecords(e={}){try{const{table_id:t,...r}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for list operation"));const s=W,i=`${this.baseURL}${Z(s,{table_id:t})}`,a=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data;return r.fields&&a.data&&(a.data=f(a.data,r.fields)),a}catch(t){return this.formatErrorResponse(t)}}async updateRecords(e){try{const{table_id:t,...r}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for update operation"));const s=G,i=`${this.baseURL}${Z(s,{table_id:t})}`,a=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data;return r.fields&&a.data&&(a.data=f(a.data,r.fields)),a}catch(t){return this.formatErrorResponse(t)}}async updateRecordById(e,t){try{const{table_id:r,...s}=t;if(!r)return this.formatErrorResponse(new Error("table_id is required for updateById operation"));const i=V,a=`${this.baseURL}${Z(i,{record_id:e,table_id:r})}`,n=(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:s.set,timeout:this.config.timeout})).data;return s.fields&&n.data&&(n.data=m(n.data,s.fields)),n}catch(r){return this.formatErrorResponse(r)}}async deleteRecords(e){try{const{table_id:t}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for delete operation"));const r=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=k(e.filters)),t}(e),s=J,i=`${this.baseURL}${Z(s,{table_id:t})}`;return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async deleteRecordById(e,t){return this.deleteRecords({record_ids:[e],table_id:t.table_id})}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Records API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{data:{},error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{data:{},error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{data:{},error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}class ee{constructor(e){this.client=e,this.apiClient=new X(e.getConfig().apiKey,{environment:e.getConfig().environment,timeout:e.getConfig().timeout,debug:e.getConfig().debug}),this.tablesApiClient=new H(e.getConfig().apiKey,{environment:e.getConfig().environment,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async insert(e,t){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot insert record into snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s=await this.ensureCompleteRecordData(e,t);if("error"in s&&s.error)return s;const i={...s,table_id:r.id},a=await this.apiClient.insertRecord(i);return B(a),a}catch(r){return{data:{},error:{code:"INSERT_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async get(e,t){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.apiClient.getRecord(t,r.id);return B(s),s}catch(r){return{data:{},error:{code:"GET_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async list(e,t={}){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s={...t,table_id:r.id},i=await this.apiClient.listRecords(s);return B(i),i}catch(r){return{data:{},error:{code:"LIST_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async update(e,t){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot update records in snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s={...t,table_id:r.id},i=await this.apiClient.updateRecords(s);return B(i),i}catch(r){return{data:{},error:{code:"UPDATE_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async updateById(e,t,r){try{const s=await this.getTableInfo(e);if(!s)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(s.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot update record in snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const i={id:t,set:r,table_id:s.id},a=await this.apiClient.updateRecordById(t,i);return B(a),a}catch(s){return{data:{},error:{code:"UPDATE_BY_ID_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async delete(e,t){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot delete records from snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s={...t,table_id:r.id},i=await this.apiClient.deleteRecords(s);return B(i),i}catch(r){return{data:{},error:{code:"DELETE_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async deleteById(e,t){try{const r=await this.getTableInfo(e);if(!r)return{data:{},error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};if(r.snapshot_url)return{data:{},error:{code:"SNAPSHOT_PROTECTION",message:`Cannot delete record from snapshot table '${e}'. Snapshots are read-only and cannot be modified.`}};const s=await this.apiClient.deleteRecordById(t,{table_id:r.id});return B(s),s}catch(r){return{data:{},error:{code:"DELETE_BY_ID_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async getTableInfo(e){try{const t=new F(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 ensureCompleteRecordData(e,t){try{const r=new K(this.client),s=await r.findAll(e);if(B(s))return s;const i=Array.isArray(s.data)?s.data:[],a={...t};for(const e of i)"id"!==e.name&&"created_at"!==e.name&&"updated_at"!==e.name&&(e.name in t||(a[e.name]=null));return a}catch(r){return{data:{},error:{code:"COMPLETE_DATA_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}}class te{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{data:[],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{data:{},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 re(e){return new te(e)}const se={path:"/tables/query/text-to-sql",method:"POST",authenticated:!0,rateLimit:{requests:100,window:6e4}},ie={path:"/tables/query/execute",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},ae=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))}),r};class ne{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey,...this.config.headers}}formatErrorResponse(e,t="API"){var r,s,i;if(this.config.debug&&console.error(`${t} Error:`,e),e&&"object"==typeof e&&"response"in e){const a=e;return(null==(s=null==(r=a.response)?void 0:r.data)?void 0:s.error)?a.response.data:{data:{},error:{code:`${t}_ERROR`,message:e.message||`Unknown ${t} error`,meta:[`Status: ${(null==(i=a.response)?void 0:i.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{data:{},error:{code:`${t}_CLIENT_ERROR`,message:e.message,meta:[`${t} client-side error occurred`]}}:{data:{},error:{code:`${t}_UNKNOWN_ERROR`,message:`An unexpected ${t} error occurred`,meta:[`Unknown ${t} error type`]}}}}class oe extends ne{constructor(e,t={}){super(e,t)}async textToSQL(e){try{const t=se,r=`${this.baseURL}${ae(t)}`,s=await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});if(s.status>=400)return this.formatErrorResponse({response:{data:s.data,status:s.status}},"SQL");const i=s.data;return this.createAsyncIterable(i.data)}catch(t){return this.formatErrorResponse(t,"SQL")}}async executeSQL(e){try{const t=ie,r=`${this.baseURL}${ae(t)}`,s=await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});return s.status>=400?this.formatErrorResponse({response:{data:s.data,status:s.status}},"SQL"):s.data}catch(t){return this.formatErrorResponse(t,"SQL")}}async*createAsyncIterable(e){yield e}}class de{constructor(e){const t=e.getConfig();this.sqlApiClient=new oe(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={}){const r=function(e,t={}){return{prompt:e,current_query:t.currentQuery}}(e,t),s=await this.sqlApiClient.textToSQL(r);if("error"in s&&void 0!==s.error)throw s;return s}async executeSQL(e){const t=await this.sqlApiClient.executeSQL({query:e});if(B(t))throw t;return t}}class le{constructor(e,t){this.isPublic=!1,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}public(e=!0){return this.isPublic=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}halfVector(e,t,r={}){return this.fields.push({name:e,type:"halfvec",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}sparseVector(e,t,r={}){return this.fields.push({name:e,type:"sparsevec",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 e("Table name is required",[{field:"name",message:"Table name cannot be empty"}]);if(0===this.fields.length)throw new e("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 ue(e,t){return new le(e,t)}class ce{constructor(e,t={}){this.currentDatabase=null,this.clientOptions=t,this.configManager=new p(e,t.environment||"prod",t.region||"asia-south1",t);const r=this.configManager.getConfig();this.authManager=new a({apiKey:r.apiKey,maxRetries:r.maxRetries}),this.baseClient=new u(r,this.authManager),this.tableResource=new F(this.baseClient),this.columnResource=new K(this.baseClient),this.recordResource=new ee(this.baseClient),this.sqlResource=new de(this.baseClient),this.currentDatabase={databaseName:"Default"}}getCurrentDatabase(){return this.currentDatabase}get tables(){return{create:e=>this.tableResource.create(e),findAll:e=>this.tableResource.findAll(e),findById:e=>this.tableResource.findById(e),findByName:e=>this.tableResource.findByName(e),findOne:e=>this.tableResource.findOne(e),update:(e,t)=>this.tableResource.update(e,t),delete:e=>this.tableResource.delete(e),rename:(e,t)=>this.tableResource.rename(e,t),setAccess:e=>this.tableResource.setAccess(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)}}table(e){return ue({name:e},this.tableResource.getTablesApiClient())}from(e){return{columns:()=>({create:t=>this.columnResource.create(e,t),findAll:t=>this.columnResource.findAll(e,t),get:t=>this.columnResource.get(e,t),update:(t,r)=>this.columnResource.update(e,t,r),delete:t=>this.columnResource.delete(e,t)}),records:()=>({insert:t=>this.recordResource.insert(e,t),findOne:t=>this.recordResource.get(e,t),update:t=>this.recordResource.update(e,t),updateById:(t,r)=>this.recordResource.updateById(e,t,r),delete:t=>this.recordResource.delete(e,t),deleteById:t=>this.recordResource.deleteById(e,t)}),record:()=>re({tableName:e,recordResource:this.recordResource})}}get records(){return{insert:(e,t)=>this.recordResource.insert(e,t),findAll:(e,t)=>this.recordResource.list(e,t),findOne:(e,t)=>this.recordResource.get(e,t),update:(e,t)=>this.recordResource.update(e,t),updateById:(e,t,r)=>this.recordResource.updateById(e,t,r),delete:(e,t)=>this.recordResource.delete(e,t),deleteById:(e,t)=>this.recordResource.deleteById(e,t)}}record(e){return re({tableName:e,recordResource:this.recordResource})}get sql(){return{textToSQL:(e,t)=>this.sqlResource.textToSQL(e,t),executeSQL:e=>this.sqlResource.executeSQL(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())}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})}disableDebug(){this.configManager.updateConfig({debug:!1})}isDebugEnabled(){return this.configManager.getConfig().debug||!1}}exports.ApiError=t,exports.BolticClient=ce,exports.ENV_CONFIGS=h,exports.FILTER_OPERATORS=U,exports.FilterBuilder=P,exports.REGION_CONFIGS=c,exports.SqlResource=de,exports.ValidationError=e,exports.buildApiFilters=function(e,t="AND"){const r=D(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}},exports.createErrorResponse=function(e,t){return{error:e,details:t}},exports.createErrorWithContext=r,exports.createFilter=function(){return new P},exports.createMockResponse=function(e,t){return{data:e,pagination:t}},exports.createRecordBuilder=re,exports.createTableBuilder=ue,exports.createTestClient=function(e={}){return new ce(e.apiKey||"test-api-key-12345",{environment:"local",region:"asia-south1",debug:e.debug??!0,timeout:3e4,...e})},exports.formatError=i,exports.getHttpStatusCode=s,exports.isErrorResponse=B,exports.isListResponse=Y,exports.isNetworkError=function(e){return e instanceof Error&&(e.message.includes("network")||e.message.includes("fetch")||e.message.includes("timeout")||"AbortError"===e.name)},exports.mapFiltersToWhere=function(e){const t={};return e.forEach(e=>{const r={};Object.entries(x).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 i=t[e.field];"$between"===s&&2===e.values.length?i[s]=e.values:i[s]="$in"===s||"$notIn"===s||"$isOneOfArray"===s?e.values:"$isNull"===s||"$isNotNull"===s||"$isEmpty"===s||e.values[0]}),t},exports.mapWhereToFilters=k,exports.normalizeFilters=D;
2
+ //# sourceMappingURL=test-client-D-SuKCUC.js.map