@aivue/tabular-intelligence 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,15 +8,44 @@
8
8
  ## đŸŽ¯ Features
9
9
 
10
10
  - 🔌 **Generic TFM Client** - Connect to any HTTP-based Tabular Foundation Model API
11
+ - đŸ’Ŧ **Natural Language Q&A** - Ask questions about your data in plain English
12
+ - 📮 **Postman Collection Integration** - Import Postman collections and query API data with AI
11
13
  - 📊 **Descriptive Statistics** - Mean, median, mode, std dev, percentiles, distributions
12
14
  - 🚨 **Anomaly Detection** - Statistical and ML-based outlier detection
13
15
  - đŸŽ¯ **Segmentation & Clustering** - K-means, DBSCAN, hierarchical clustering
14
16
  - 🔮 **Predictions** - Time series forecasting and predictive modeling
15
17
  - 📈 **Correlation Analysis** - Pearson correlation matrices and significance testing
18
+ - 🤖 **AI Summaries** - Generate intelligent summaries of your data
19
+ - 🌐 **Table Extraction** - Extract data from HTML tables or Vue data grids
16
20
  - 🔄 **Local Fallback** - Built-in statistical analysis when API is unavailable
17
21
  - 🎨 **Vue Integration** - Reactive composables for seamless Vue.js integration
18
22
  - đŸ“Ļ **Smart DataTable Ready** - Designed to work with @aivue/smart-datatable
19
23
 
24
+ ### đŸ’Ŧ Q&A Capabilities
25
+
26
+ **Ask any question about your Vue tables – AI answers directly from your data.**
27
+
28
+ - "Which region had the highest revenue last quarter?"
29
+ - "How many customers churned with tenure < 6 months?"
30
+ - "What is the average order value for India vs US?"
31
+ - "Show me products with price > $100 and quantity < 10"
32
+
33
+ The AI analyzes your table data and provides natural language answers with supporting statistics and data.
34
+
35
+ ### 📮 Postman Collection Integration
36
+
37
+ **Import Postman collections and query API data with natural language.**
38
+
39
+ - Import Postman Collection v2.1 JSON files
40
+ - Automatically discover all API endpoints
41
+ - Execute API requests with variable substitution
42
+ - Convert API responses to tabular format
43
+ - Ask questions about API data using AI
44
+
45
+ Perfect for MarketStack, financial APIs, and any REST API with tabular data!
46
+
47
+ See [POSTMAN-INTEGRATION.md](./POSTMAN-INTEGRATION.md) for detailed documentation.
48
+
20
49
  ## đŸ“Ļ Installation
21
50
 
22
51
  ```bash
@@ -96,6 +125,111 @@ async function analyzeData() {
96
125
  </script>
97
126
  ```
98
127
 
128
+ ## đŸ’Ŧ Q&A Usage
129
+
130
+ ### Setup Q&A
131
+
132
+ ```typescript
133
+ import { useTabularIntelligence, QuestionInput, AnswerDisplay, QuestionHistory } from '@aivue/tabular-intelligence';
134
+
135
+ const {
136
+ askQuestion,
137
+ generateSummary,
138
+ questionHistory,
139
+ lastAnswer,
140
+ clearHistory,
141
+ } = useTabularIntelligence({
142
+ config: {
143
+ provider: 'local',
144
+ baseUrl: 'https://api.example.com/tfm',
145
+ },
146
+ data: tableData,
147
+ qaConfig: {
148
+ provider: 'openai',
149
+ apiKey: 'sk-...',
150
+ model: 'gpt-4-turbo-preview',
151
+ },
152
+ });
153
+
154
+ // Ask a question
155
+ const answer = await askQuestion('What is the average price by category?');
156
+
157
+ // Generate AI summary
158
+ const summary = await generateSummary();
159
+ ```
160
+
161
+ ### Q&A Components
162
+
163
+ ```vue
164
+ <template>
165
+ <div>
166
+ <!-- Question Input -->
167
+ <QuestionInput
168
+ :loading="loading"
169
+ @submit="handleQuestion"
170
+ />
171
+
172
+ <!-- Latest Answer -->
173
+ <AnswerDisplay
174
+ v-if="lastAnswer"
175
+ :answer="lastAnswer"
176
+ />
177
+
178
+ <!-- Question History -->
179
+ <QuestionHistory
180
+ :questions="questionHistory"
181
+ @clear="clearHistory"
182
+ @select="handleSelectQuestion"
183
+ />
184
+ </div>
185
+ </template>
186
+
187
+ <script setup>
188
+ import { QuestionInput, AnswerDisplay, QuestionHistory, useTabularIntelligence } from '@aivue/tabular-intelligence';
189
+
190
+ const { askQuestion, questionHistory, lastAnswer, clearHistory } = useTabularIntelligence({
191
+ config: { provider: 'local' },
192
+ data: tableData,
193
+ qaConfig: {
194
+ provider: 'openai',
195
+ apiKey: import.meta.env.VITE_OPENAI_API_KEY,
196
+ },
197
+ });
198
+
199
+ async function handleQuestion(question) {
200
+ await askQuestion(question);
201
+ }
202
+
203
+ function handleSelectQuestion(question) {
204
+ console.log('Selected:', question);
205
+ }
206
+ </script>
207
+ ```
208
+
209
+ ### Table Extraction
210
+
211
+ Extract data from HTML tables or Vue data grids:
212
+
213
+ ```typescript
214
+ // Extract from DOM
215
+ const extracted = intelligence.extractFromDOM({
216
+ selector: 'table.my-table',
217
+ includeHeaders: true,
218
+ maxRows: 1000,
219
+ inferTypes: true,
220
+ });
221
+
222
+ // Load from Vue data grid
223
+ intelligence.loadFromVueGrid(
224
+ gridData,
225
+ [
226
+ { field: 'name', header: 'Product Name' },
227
+ { field: 'price', header: 'Price' },
228
+ ],
229
+ { inferTypes: true }
230
+ );
231
+ ```
232
+
99
233
  ## 📖 API Reference
100
234
 
101
235
  ### `useTabularIntelligence(options)`
@@ -107,6 +241,8 @@ Main composable for tabular intelligence.
107
241
  - `data?: Ref<any[]>` - Reactive data array
108
242
  - `schema?: Ref<TableSchema>` - Optional table schema
109
243
  - `useLocalFallback?: boolean` - Enable local analysis fallback (default: true)
244
+ - `qaConfig?: QAEngineConfig` - Q&A engine configuration (optional)
245
+ - `maxQuestionHistory?: number` - Maximum questions to keep in history (default: 50)
110
246
 
111
247
  **Returns:**
112
248
  - `client: TabularIntelligence` - Core TFM client instance
@@ -115,12 +251,21 @@ Main composable for tabular intelligence.
115
251
  - `lastResult: Ref<AnalysisResult | null>` - Last analysis result
116
252
  - `data: Ref<any[]>` - Data array
117
253
  - `schema: Ref<TableSchema | null>` - Inferred or provided schema
254
+ - `questionHistory: Ref<Question[]>` - Q&A question history
255
+ - `answerHistory: Ref<Answer[]>` - Q&A answer history
256
+ - `lastAnswer: Ref<Answer | null>` - Last Q&A answer
118
257
  - `analyze(type, options)` - Generic analysis method
119
258
  - `getDescriptiveStats()` - Get descriptive statistics
120
259
  - `detectAnomalies(columns?, sensitivity?)` - Detect anomalies
121
260
  - `performClustering(features, numClusters?)` - Perform clustering
122
261
  - `predict(targetColumn, options?)` - Make predictions
262
+ - `askQuestion(question, options?)` - Ask a question about the data
263
+ - `generateSummary()` - Generate AI summary of the data
264
+ - `clearHistory()` - Clear Q&A history
265
+ - `extractFromDOM(options?)` - Extract table from DOM
266
+ - `loadFromVueGrid(data, columns?, options?)` - Load data from Vue grid
123
267
  - `updateConfig(config)` - Update TFM configuration
268
+ - `initializeQA(qaConfig)` - Initialize Q&A engine
124
269
  - `setData(data, autoInferSchema?)` - Set new data
125
270
  - `reset()` - Reset state
126
271
 
@@ -134,6 +279,8 @@ type AnalysisType =
134
279
  | 'clustering' // K-means, DBSCAN, etc.
135
280
  | 'prediction' // Forecasting
136
281
  | 'correlation' // Correlation analysis
282
+ | 'summary' // AI-generated summary
283
+ | 'qa' // Question answering
137
284
  | 'trend_analysis' // Trend detection
138
285
  | 'outlier_detection'; // Statistical outliers
139
286
  ```
@@ -1,11 +1,14 @@
1
1
  import { Ref } from 'vue';
2
2
  import { TabularIntelligence } from '../core/TabularIntelligence';
3
- import { TFMConfig, AnalysisResult, AnalysisType, TableSchema, DescriptiveStats, Anomaly } from '../types';
3
+ import { TFMConfig, AnalysisResult, AnalysisType, TableSchema, DescriptiveStats, Anomaly, Question, Answer, QARequest, AISummary, TableExtractionOptions, ExtractedTable } from '../types';
4
+ import { QAEngineConfig } from '../utils/qaEngine';
4
5
  export interface UseTabularIntelligenceOptions {
5
6
  config: TFMConfig;
6
7
  data?: Ref<any[]>;
7
8
  schema?: Ref<TableSchema>;
8
9
  useLocalFallback?: boolean;
10
+ qaConfig?: QAEngineConfig;
11
+ maxQuestionHistory?: number;
9
12
  }
10
13
  export interface UseTabularIntelligenceReturn {
11
14
  client: TabularIntelligence;
@@ -14,12 +17,21 @@ export interface UseTabularIntelligenceReturn {
14
17
  lastResult: Ref<AnalysisResult | null>;
15
18
  data: Ref<any[]>;
16
19
  schema: Ref<TableSchema | null>;
20
+ questionHistory: Ref<Question[]>;
21
+ answerHistory: Ref<Answer[]>;
22
+ lastAnswer: Ref<Answer | null>;
17
23
  analyze: (type: AnalysisType, options?: any) => Promise<AnalysisResult>;
18
24
  getDescriptiveStats: () => Promise<DescriptiveStats[]>;
19
25
  detectAnomalies: (columns?: string[], sensitivity?: number) => Promise<Anomaly[]>;
20
26
  performClustering: (features: string[], numClusters?: number) => Promise<AnalysisResult>;
21
27
  predict: (targetColumn: string, options?: any) => Promise<AnalysisResult>;
28
+ askQuestion: (question: string, options?: Partial<QARequest>) => Promise<Answer>;
29
+ generateSummary: () => Promise<AISummary>;
30
+ clearHistory: () => void;
31
+ extractFromDOM: (options?: TableExtractionOptions) => ExtractedTable | null;
32
+ loadFromVueGrid: (gridData: any[], columns?: any[], options?: TableExtractionOptions) => void;
22
33
  updateConfig: (config: Partial<TFMConfig>) => void;
34
+ initializeQA: (qaConfig: QAEngineConfig) => void;
23
35
  setData: (newData: any[], autoInferSchema?: boolean) => void;
24
36
  reset: () => void;
25
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAiB,GAAG,EAAE,MAAM,KAAK,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,KAAK,EACV,SAAS,EAET,cAAc,EACd,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,OAAO,EACR,MAAM,UAAU,CAAC;AAGlB,MAAM,WAAW,6BAA6B;IAC5C,MAAM,EAAE,SAAS,CAAC;IAClB,IAAI,CAAC,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IAClB,MAAM,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC;IAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED,MAAM,WAAW,4BAA4B;IAE3C,MAAM,EA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
@@ -1,7 +1,15 @@
1
- import { TFMConfig, AnalysisRequest, AnalysisResult } from '../types';
1
+ import { TFMConfig, AnalysisRequest, AnalysisResult, TableSchema, QARequest, QAResponse, AISummary, TableExtractionOptions, ExtractedTable, APIQueryRequest, APIQueryResponse } from '../types';
2
+ import { QAEngineConfig } from '../utils/qaEngine';
3
+ import { ParsedCollection, ParsedEndpoint } from '../utils/postmanParser';
2
4
  export declare class TabularIntelligence {
3
5
  private config;
4
- constructor(config: TFMConfig);
6
+ private qaEngine?;
7
+ private parsedCollection?;
8
+ constructor(config: TFMConfig, qaConfig?: QAEngineConfig);
9
+ /**
10
+ * Initialize or update Q&A engine
11
+ */
12
+ initializeQA(qaConfig: QAEngineConfig): void;
5
13
  /**
6
14
  * Generic API call to TFM endpoint
7
15
  */
@@ -14,6 +22,26 @@ export declare class TabularIntelligence {
14
22
  * Parse TFM response into structured AnalysisResult
15
23
  */
16
24
  private parseAnalysisResult;
25
+ /**
26
+ * Ask a question about the data (Q&A)
27
+ */
28
+ askQuestion(request: QARequest): Promise<QAResponse>;
29
+ /**
30
+ * Generate AI summary of table data
31
+ */
32
+ generateSummary(data: any[], schema: TableSchema): Promise<AISummary>;
33
+ /**
34
+ * Extract table from DOM
35
+ */
36
+ extractFromDOM(options?: TableExtractionOptions): ExtractedTable | null;
37
+ /**
38
+ * Normalize Vue data grid data
39
+ */
40
+ normalizeVueData(data: any[], columns?: Array<{
41
+ field: string;
42
+ header?: string;
43
+ label?: string;
44
+ }>, options?: TableExtractionOptions): ExtractedTable;
17
45
  /**
18
46
  * Update configuration
19
47
  */
@@ -22,5 +50,36 @@ export declare class TabularIntelligence {
22
50
  * Get current configuration (without sensitive data)
23
51
  */
24
52
  getConfig(): Omit<TFMConfig, 'apiKey'>;
53
+ /**
54
+ * Load Postman collection
55
+ */
56
+ loadPostmanCollection(collection: any): ParsedCollection;
57
+ /**
58
+ * Get loaded collection
59
+ */
60
+ getCollection(): ParsedCollection | undefined;
61
+ /**
62
+ * Get endpoints from loaded collection
63
+ */
64
+ getEndpoints(): ParsedEndpoint[];
65
+ /**
66
+ * Execute API request and get data
67
+ */
68
+ fetchDataFromAPI(endpointName: string, variables?: Record<string, string>): Promise<{
69
+ data: any[];
70
+ schema?: TableSchema;
71
+ }>;
72
+ /**
73
+ * Query API data with natural language
74
+ */
75
+ queryAPI(request: APIQueryRequest): Promise<APIQueryResponse>;
76
+ /**
77
+ * List available endpoints from loaded collection
78
+ */
79
+ listEndpoints(): Array<{
80
+ name: string;
81
+ method: string;
82
+ description?: string;
83
+ }>;
25
84
  }
26
85
  //# sourceMappingURL=TabularIntelligence.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"TabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/core/TabularIntelligence.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACV,SAAS,EAGT,eAAe,EACf,cAAc,EAQf,MAAM,UAAU,CAAC;AAElB,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;gBAEd,MAAM,EAAE,SAAS;IAO7B;;OAEG;YACW,OAAO;IA+CrB;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAkBhE;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAoD3B;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI;IAI9C;;OAEG;IACH,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;CAIvC"}
1
+ {"version":3,"file":"TabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/core/TabularIntelligence.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACV,SAAS,EAGT,eAAe,EACf,cAAc,EAEd,WAAW,EAMX,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EAEd,eAAe,EACf,gBAAgB,EACjB,MAAM,UAA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ACH,qBAAqB,CAAC,UAAU,EAAE,GAAG,GAAG,gBAAgB;IAKxD;;OAEG;IACH,aAAa,IAAI,gBAAgB,GAAG,SAAS;IAI7C;;OAEG;IACH,YAAY,IAAI,cAAc,EAAE;IAIhC;;OAEG;IACG,gBAAgB,CACpB,YAAY,EAAE,MAAM,EACpB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,OAAO,CAAC;QAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,CAAC;IAgCjD;;OAEG;IACG,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAgCnE;;OAEG;IACH,aAAa,IAAI,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAW/E"}
package/dist/index.d.ts CHANGED
@@ -5,6 +5,13 @@
5
5
  export { TabularIntelligence } from './core/TabularIntelligence';
6
6
  export { useTabularIntelligence } from './composables/useTabularIntelligence';
7
7
  export type { UseTabularIntelligenceOptions, UseTabularIntelligenceReturn } from './composables/useTabularIntelligence';
8
+ export { default as QuestionInput } from './components/QuestionInput.vue';
9
+ export { default as AnswerDisplay } from './components/AnswerDisplay.vue';
10
+ export { default as QuestionHistory } from './components/QuestionHistory.vue';
8
11
  export { inferSchema, inferColumnType, calculateStats, detectAnomalies } from './utils/helpers';
9
- export type { TFMProvider, TFMConfig, TableColumn, TableSchema, AnalysisType, AnalysisRequest, AnalysisOptions, AnalysisResult, DescriptiveStats, Anomaly, Cluster, Prediction, CorrelationMatrix, TFMRequest, TFMResponse, } from './types';
12
+ export { QAEngine, type QAEngineConfig } from './utils/qaEngine';
13
+ export { extractFromDOM, normalizeVueData } from './utils/tableExtractor';
14
+ export { parsePostmanCollection, replaceVariables, type ParsedCollection, type ParsedEndpoint } from './utils/postmanParser';
15
+ export { executeAPIRequest, executeMultipleRequests, convertToTabular, type APIRequestOptions, type APIResponse } from './utils/apiClient';
16
+ export type { TFMProvider, TFMConfig, TableColumn, TableSchema, AnalysisType, AnalysisRequest, AnalysisOptions, AnalysisResult, DescriptiveStats, Anomaly, Cluster, Prediction, CorrelationMatrix, TFMRequest, TFMResponse, Question, Answer, QARequest, QAResponse, QAHistory, TableExtractionOptions, ExtractedTable, AISummary, APIDataSource, APIQueryRequest, APIQueryResponse, } from './types';
10
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGxH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGhG,YAAY,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,WAAW,GACZ,MAAM,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAGjE,OAAO,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAC9E,YAAY,EAAE,6BAA6B,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AAGxH,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAChG,OAAO,EAAE,QAAQ,EAAE,KAAK,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC7H,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAG3I,YAAY,EACV,WAAW,EACX,SAAS,EACT,WAAW,EACX,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAe,EACf,cAAc,EACd,gBAAgB,EAChB,OAAO,EACP,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,WAAW,EACX,QAAQ,EACR,MAAM,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EACd,SAAS,EACT,aAAa,EACb,eAAe,EACf,gBAAgB,GACjB,MAAM,SAAS,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,31 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("vue");class A{constructor(s){this.config={timeout:3e4,...s}}async callTFM(s){const e=Date.now();try{const n=await fetch(this.config.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...s,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!n.ok){const o=await n.text();throw new Error(`TFM API error: ${n.status} - ${o}`)}const t=await n.json(),i=Date.now()-e;return{success:!0,result:t.result||t,metadata:{processingTime:i,model:this.config.model||"unknown",version:t.version}}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error",metadata:{processingTime:Date.now()-e,model:this.config.model||"unknown"}}}}async analyze(s){const e={operation:s.type,data:s.data,schema:s.schema,parameters:s.options},n=await this.callTFM(e);if(!n.success)throw new Error(n.error||"Analysis failed");return this.parseAnalysisResult(s.type,n.result,n.metadata)}parseAnalysisResult(s,e,n){const t={type:s,timestamp:new Date,summary:e.summary||"",insights:e.insights||[],recommendations:e.recommendations,confidence:e.confidence||.8,processingTime:n==null?void 0:n.processingTime};switch(s){case"descriptive_stats":return{...t,descriptiveStats:e.stats||e.descriptiveStats};case"anomaly_detection":return{...t,anomalies:e.anomalies||[]};case"segmentation":case"clustering":return{...t,clusters:e.clusters||[]};case"prediction":return{...t,predictions:e.predictions||e};case"correlation":return{...t,correlations:e.correlations||e};default:return t}}updateConfig(s){this.config={...this.config,...s}}getConfig(){const{apiKey:s,...e}=this.config;return e}}function M(c,s){if(c.length===0)return{columns:[],rowCount:0,name:s};const e=c[0];return{columns:Object.keys(e).map(t=>{const i=N(c,t);return{name:t,type:i,nullable:c.some(o=>o[t]==null)}}),rowCount:c.length,name:s}}function N(c,s){const e=c.map(t=>t[s]).filter(t=>t!=null);if(e.length===0)return"string";if(e.every(t=>typeof t=="number"||!isNaN(Number(t))))return"number";if(e.every(t=>typeof t=="boolean"||t==="true"||t==="false"))return"boolean";if(e.every(t=>!isNaN(Date.parse(t))))return"date";const n=new Set(e);return n.size<e.length*.5&&n.size<20?"categorical":"string"}function $(c,s,e){const n=c.map(l=>l[s]).filter(l=>l!=null),t=n.length,i=c.length-t,o={column:s,count:t,nullCount:i};if(e==="number"){const l=n.map(Number).filter(r=>!isNaN(r));if(l.length>0){const r=[...l].sort((u,d)=>u-d),p=l.reduce((u,d)=>u+d,0);o.mean=p/l.length,o.median=r[Math.floor(r.length/2)],o.min=r[0],o.max=r[r.length-1];const h=l.reduce((u,d)=>u+Math.pow(d-o.mean,2),0)/l.length;o.std=Math.sqrt(h),o.percentiles={25:r[Math.floor(r.length*.25)],50:o.median,75:r[Math.floor(r.length*.75)],90:r[Math.floor(r.length*.9)]}}}else{const l=new Set(n);o.uniqueValues=l.size;const r={};n.forEach(h=>{const u=String(h);r[u]=(r[u]||0)+1});const p=Math.max(...Object.values(r));o.mode=Object.keys(r).find(h=>r[h]===p)}return o}function F(c,s,e=.5){const n=[],t=1.5+(1-e)*1.5;return s.forEach(i=>{const o=c.map((m,g)=>({value:Number(m[i]),idx:g})).filter(m=>!isNaN(m.value));if(o.length===0)return;const l=[...o].sort((m,g)=>m.value-g.value),r=l[Math.floor(l.length*.25)].value,p=l[Math.floor(l.length*.75)].value,h=p-r,u=r-t*h,d=p+t*h;o.forEach(({value:m,idx:g})=>{if(m<u||m>d){const v=n.find(a=>a.rowIndex===g),C=m<u?`${i}: ${m.toFixed(2)} < ${u.toFixed(2)}`:`${i}: ${m.toFixed(2)} > ${d.toFixed(2)}`;v?(v.reasons.push(C),v.affectedColumns.push(i),v.score=Math.min(1,v.score+.2)):n.push({rowIndex:g,row:c[g],score:.7,reasons:[C],affectedColumns:[i]})}})}),n.sort((i,o)=>o.score-i.score)}function x(c){const s=new A(c.config),e=T.ref(!1),n=T.ref(null),t=T.ref(null),i=c.data||T.ref([]),o=c.schema||T.ref(null),l=c.useLocalFallback!==!1;async function r(a,f){e.value=!0,n.value=null;try{const y={type:a,data:i.value,schema:o.value||void 0,options:f},w=await s.analyze(y);return t.value=w,w}catch(y){if(n.value=y instanceof Error?y:new Error("Analysis failed"),l)return p(a,f);throw n.value}finally{e.value=!1}}function p(a,f){const y=o.value||M(i.value);switch(a){case"descriptive_stats":{const w=y.columns.map(b=>$(i.value,b.name,b.type));return{type:a,timestamp:new Date,descriptiveStats:w,summary:`Calculated statistics for ${w.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const w=y.columns.filter(S=>S.type==="number").map(S=>S.name),b=F(i.value,w,f==null?void 0:f.sensitivity);return{type:a,timestamp:new Date,anomalies:b,summary:`Found ${b.length} anomalies`,insights:b.slice(0,3).map(S=>S.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${a}`)}}async function h(){return(await r("descriptive_stats")).descriptiveStats||[]}async function u(a,f){return(await r("anomaly_detection",{sensitivity:f,features:a})).anomalies||[]}async function d(a,f=3){return r("clustering",{features:a,numClusters:f})}async function m(a,f){return r("prediction",{targetColumn:a,...f})}function g(a){s.updateConfig(a)}function v(a,f=!0){i.value=a,f&&(o.value=M(a))}function C(){e.value=!1,n.value=null,t.value=null}return{client:s,loading:e,error:n,lastResult:t,data:i,schema:o,analyze:r,getDescriptiveStats:h,detectAnomalies:u,performClustering:d,predict:m,updateConfig:g,setData:v,reset:C}}exports.TabularIntelligence=A;exports.calculateStats=$;exports.detectAnomalies=F;exports.inferColumnType=N;exports.inferSchema=M;exports.useTabularIntelligence=x;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("vue");function S(c,e){if(c.length===0)return{columns:[],rowCount:0,name:e};const t=c[0];return{columns:Object.keys(t).map(a=>{const o=V(c,a);return{name:a,type:o,nullable:c.some(i=>i[a]==null)}}),rowCount:c.length,name:e}}function V(c,e){const t=c.map(a=>a[e]).filter(a=>a!=null);if(t.length===0)return"string";if(t.every(a=>typeof a=="number"||!isNaN(Number(a))))return"number";if(t.every(a=>typeof a=="boolean"||a==="true"||a==="false"))return"boolean";if(t.every(a=>!isNaN(Date.parse(a))))return"date";const s=new Set(t);return s.size<t.length*.5&&s.size<20?"categorical":"string"}function x(c,e,t){const s=c.map(r=>r[e]).filter(r=>r!=null),a=s.length,o=c.length-a,i={column:e,count:a,nullCount:o};if(t==="number"){const r=s.map(Number).filter(l=>!isNaN(l));if(r.length>0){const l=[...r].sort((p,m)=>p-m),u=r.reduce((p,m)=>p+m,0);i.mean=u/r.length,i.median=l[Math.floor(l.length/2)],i.min=l[0],i.max=l[l.length-1];const h=r.reduce((p,m)=>p+Math.pow(m-i.mean,2),0)/r.length;i.std=Math.sqrt(h),i.percentiles={25:l[Math.floor(l.length*.25)],50:i.median,75:l[Math.floor(l.length*.75)],90:l[Math.floor(l.length*.9)]}}}else{const r=new Set(s);i.uniqueValues=r.size;const l={};s.forEach(h=>{const p=String(h);l[p]=(l[p]||0)+1});const u=Math.max(...Object.values(l));i.mode=Object.keys(l).find(h=>l[h]===u)}return i}function P(c,e,t=.5){const s=[],a=1.5+(1-t)*1.5;return e.forEach(o=>{const i=c.map((g,y)=>({value:Number(g[o]),idx:y})).filter(g=>!isNaN(g.value));if(i.length===0)return;const r=[...i].sort((g,y)=>g.value-y.value),l=r[Math.floor(r.length*.25)].value,u=r[Math.floor(r.length*.75)].value,h=u-l,p=l-a*h,m=u+a*h;i.forEach(({value:g,idx:y})=>{if(g<p||g>m){const v=s.find(C=>C.rowIndex===y),b=g<p?`${o}: ${g.toFixed(2)} < ${p.toFixed(2)}`:`${o}: ${g.toFixed(2)} > ${m.toFixed(2)}`;v?(v.reasons.push(b),v.affectedColumns.push(o),v.score=Math.min(1,v.score+.2)):s.push({rowIndex:y,row:c[y],score:.7,reasons:[b],affectedColumns:[o]})}})}),s.sort((o,i)=>i.score-o.score)}class T{constructor(e){this.config={maxTokens:1e3,temperature:.3,...e}}async answerQuestion(e){const t=Date.now();try{const{question:s,schema:a,data:o=[],sampleSize:i=100,includeAggregates:r=!0}=e,l=o.length>i?this.sampleData(o,i):o,u=r?this.calculateAggregates(o,a):void 0,h=this.buildPrompt(s,a,l,u,o.length),p=await this.callLLM(h);return{answer:this.parseResponse(p,s,o.length>i),processingTime:Date.now()-t}}catch(s){return console.error("Q&A error:",s),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:s instanceof Error?s.message:"Unknown error"},processingTime:Date.now()-t}}}sampleData(e,t){if(e.length<=t)return e;const s=Math.floor(e.length/t),a=[];for(let o=0;o<e.length&&a.length<t;o+=s)a.push(e[o]);return a}calculateAggregates(e,t){const s={};for(const a of t.columns)if(a.type==="number"&&e.length>0)try{const o=x(e,a.name,"number");s[a.name]={mean:o.mean,median:o.median,min:o.min,max:o.max,count:o.count}}catch{}else if(a.type==="categorical"||a.type==="string"){const o=e.map(r=>r[a.name]).filter(r=>r!=null),i=new Set(o);s[a.name]={uniqueCount:i.size,totalCount:o.length,topValues:this.getTopValues(o,5)}}return s}getTopValues(e,t){const s=new Map;for(const a of e)s.set(a,(s.get(a)||0)+1);return Array.from(s.entries()).map(([a,o])=>({value:a,count:o})).sort((a,o)=>o.count-a.count).slice(0,t)}buildPrompt(e,t,s,a,o){const i=o&&o>s.length;let r=`You are a data analyst assistant. Answer the following question about a table dataset.
2
+
3
+ `;r+=`**Table Schema:**
4
+ `,r+=`Table: ${t.name}
5
+ `,r+=`Columns:
6
+ `;for(const l of t.columns)r+=`- ${l.name} (${l.type})
7
+ `;return r+=`
8
+ `,a&&Object.keys(a).length>0&&(r+=`**Summary Statistics:**
9
+ `,r+=JSON.stringify(a,null,2),r+=`
10
+
11
+ `),r+=`**Sample Data** (${s.length} rows${i?` out of ${o} total`:""}):
12
+ `,r+=JSON.stringify(s.slice(0,10),null,2),r+=`
13
+
14
+ `,r+=`**Question:** ${e}
15
+
16
+ `,r+=`**Instructions:**
17
+ `,r+=`1. Answer ONLY based on the data provided above.
18
+ `,r+=`2. If the question cannot be answered from the available data, clearly state "I cannot answer this question from the available data" and explain why.
19
+ `,r+=`3. Provide a clear, concise answer.
20
+ `,r+=`4. Include specific numbers or examples from the data when relevant.
21
+ `,r+=`5. If the answer is based on sampled data, mention that it's an approximation.
22
+ `,r+=`6. Format your response as JSON with the following structure:
23
+ `,r+=`{
24
+ `,r+=` "answer": "Your answer text here",
25
+ `,r+=` "confidence": 0.0-1.0,
26
+ `,r+=` "cannotAnswer": false,
27
+ `,r+=` "isApproximate": ${i},
28
+ `,r+=` "supportingData": { "key": "value" } // optional
29
+ `,r+=`}
30
+ `,r}async callLLM(e){const{provider:t,apiKey:s,baseUrl:a,model:o,maxTokens:i,temperature:r}=this.config;if(t==="openai")return this.callOpenAI(e,s,o||"gpt-4-turbo-preview",i,r);if(t==="anthropic")return this.callAnthropic(e,s,o||"claude-3-5-sonnet-20241022",i,r);if(t==="custom"&&a)return this.callCustomAPI(e,a,s);throw new Error(`Unsupported provider: ${t}`)}async callOpenAI(e,t,s,a,o){var l,u;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:s,messages:[{role:"user",content:e}],max_tokens:a,temperature:o,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((u=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:u.content)||""}async callAnthropic(e,t,s,a,o){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:s,max_tokens:a,temperature:o,messages:[{role:"user",content:e}]})});if(!i.ok)throw new Error(`Anthropic API error: ${i.statusText}`);return((l=(await i.json()).content[0])==null?void 0:l.text)||""}async callCustomAPI(e,t,s){const a={"Content-Type":"application/json"};s&&(a.Authorization=`Bearer ${s}`);const o=await fetch(t,{method:"POST",headers:a,body:JSON.stringify({prompt:e})});if(!o.ok)throw new Error(`Custom API error: ${o.statusText}`);const i=await o.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,s){try{const a=JSON.parse(e);return{questionId:this.generateId(),text:a.answer||a.text||e,timestamp:new Date,confidence:a.confidence||.8,cannotAnswer:a.cannotAnswer||!1,isApproximate:a.isApproximate!==void 0?a.isApproximate:s,supportingData:a.supportingData,reason:a.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:s}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function O(c={}){const{selector:e="table",includeHeaders:t=!0,maxRows:s,inferTypes:a=!0,skipEmptyRows:o=!0}=c,i=document.querySelector(e);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${e}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let u=[],h=0;if(t&&l[0]){const y=l[0];u=Array.from(y.cells).map((v,b)=>{var E;return((E=v.textContent)==null?void 0:E.trim())||""||`Column${b+1}`}),h=1}else{const y=l[0];u=Array.from(y.cells).map((v,b)=>`Column${b+1}`)}const p=[],m=s?l.slice(h,h+s):l.slice(h);for(const y of m){const v=Array.from(y.cells);if(o&&v.every(C=>{var E;return!((E=C.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((C,E)=>{var B;const q=u[E]||`Column${E+1}`;let D=((B=C.textContent)==null?void 0:B.trim())||"";if(a&&D){const _=parseFloat(D);!isNaN(_)&&D===_.toString()&&(D=_)}b[q]=D}),p.push(b)}return{schema:a&&p.length>0?S(p,"Extracted Table"):G(u,p.length),data:p,source:"dom",metadata:{selector:e,rowCount:p.length,columnCount:u.length,extractedAt:new Date}}}function Q(c,e,t={}){const{maxRows:s,inferTypes:a=!0}=t,o=s?c.slice(0,s):c;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(r=>({name:r.field,type:a&&o.length>0?V(o,r.field):"string",nullable:!0})),rowCount:o.length}:o.length>0?i=S(o,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:o,source:"vue",metadata:{rowCount:o.length,columnCount:i.columns.length,extractedAt:new Date}}}function G(c,e=0){return{name:"Extracted Table",columns:c.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function F(c){const e={};c.variable&&c.variable.forEach(o=>{e[o.key]=o.value});const t=c.auth?j(c.auth):void 0,s=[];function a(o,i=""){o.forEach(r=>{r.item?a(r.item,i?`${i}/${r.name}`:r.name):r.request&&s.push(Y(r,t))})}return a(c.item),{name:c.info.name,description:c.info.description,endpoints:s,variables:e,auth:t}}function Y(c,e){const t=c.request,s={};t.header&&t.header.forEach(i=>{s[i.key]=i.value});const a={};t.url.query&&t.url.query.forEach(i=>{a[i.key]=i.value});const o=t.auth?j(t.auth):e;return{name:c.name,method:t.method,url:t.url.raw,description:t.description,headers:s,queryParams:a,auth:o}}function j(c){const e={};return c.apikey?c.apikey.forEach(t=>{e[t.key]=t.value}):c.bearer?c.bearer.forEach(t=>{e[t.key]=t.value}):c.basic&&c.basic.forEach(t=>{e[t.key]=t.value}),{type:c.type,credentials:e}}function $(c,e){let t=c;return Object.keys(e).forEach(s=>{const a=new RegExp(`{{${s}}}`,"g");t=t.replace(a,e[s])}),t}async function I(c){const{endpoint:e,variables:t={},additionalHeaders:s={},additionalParams:a={}}=c;try{let o=$(e.url,t);const i={...e.queryParams,...a},r=Object.keys(i).map(m=>`${encodeURIComponent(m)}=${encodeURIComponent($(i[m],t))}`).join("&");r&&(o=o.includes("?")?`${o}&${r}`:`${o}?${r}`);const l={"Content-Type":"application/json",...e.headers,...s};if(Object.keys(l).forEach(m=>{l[m]=$(l[m],t)}),e.auth){if(e.auth.type==="apikey"){const m=e.auth.credentials.key||"access_key",g=$(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(l[m]=g)}else if(e.auth.type==="bearer"){const m=$(e.auth.credentials.token||"",t);l.Authorization=`Bearer ${m}`}else if(e.auth.type==="basic"){const m=$(e.auth.credentials.username||"",t),g=$(e.auth.credentials.password||"",t),y=btoa(`${m}:${g}`);l.Authorization=`Basic ${y}`}}const u=await fetch(o,{method:e.method,headers:l}),h={};return u.headers.forEach((m,g)=>{h[g]=m}),u.ok?{success:!0,data:await u.json(),statusCode:u.status,headers:h}:{success:!1,error:`HTTP ${u.status}: ${u.statusText}`,statusCode:u.status,headers:h}}catch(o){return{success:!1,error:o.message||"Unknown error occurred"}}}async function W(c,e={}){const t=[];for(const s of c){const a=await I({endpoint:s,variables:e});t.push(a)}return t}function z(c){if(!c.success||!c.data)return[];const e=c.data;return Array.isArray(e)?e:e.data&&Array.isArray(e.data)?e.data:e.results&&Array.isArray(e.results)?e.results:e.items&&Array.isArray(e.items)?e.items:typeof e=="object"?[e]:[]}class R{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new T(t))}initializeQA(e){this.qaEngine=new T(e)}async callTFM(e){const t=Date.now();try{const s=await fetch(this.config.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey&&{Authorization:`Bearer ${this.config.apiKey}`},...this.config.headers},body:JSON.stringify({...e,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!s.ok){const i=await s.text();throw new Error(`TFM API error: ${s.status} - ${i}`)}const a=await s.json(),o=Date.now()-t;return{success:!0,result:a.result||a,metadata:{processingTime:o,model:this.config.model||"unknown",version:a.version}}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error",metadata:{processingTime:Date.now()-t,model:this.config.model||"unknown"}}}}async analyze(e){const t={operation:e.type,data:e.data,schema:e.schema,parameters:e.options},s=await this.callTFM(t);if(!s.success)throw new Error(s.error||"Analysis failed");return this.parseAnalysisResult(e.type,s.result,s.metadata)}parseAnalysisResult(e,t,s){const a={type:e,timestamp:new Date,summary:t.summary||"",insights:t.insights||[],recommendations:t.recommendations,confidence:t.confidence||.8,processingTime:s==null?void 0:s.processingTime};switch(e){case"descriptive_stats":return{...a,descriptiveStats:t.stats||t.descriptiveStats};case"anomaly_detection":return{...a,anomalies:t.anomalies||[]};case"segmentation":case"clustering":return{...a,clusters:t.clusters||[]};case"prediction":return{...a,predictions:t.predictions||t};case"correlation":return{...a,correlations:t.correlations||t};case"summary":return{...a,aiSummary:t.summary||t};case"qa":return{...a,qaAnswer:t.answer||t};default:return a}}async askQuestion(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(e)}async generateSummary(e,t){const s={type:"summary",data:e,schema:t},a=await this.analyze(s);if(!a.aiSummary)throw new Error("Failed to generate summary");return a.aiSummary}extractFromDOM(e){return O(e)}normalizeVueData(e,t,s){return Q(e,t,s)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=F(e),this.parsedCollection}getCollection(){return this.parsedCollection}getEndpoints(){var e;return((e=this.parsedCollection)==null?void 0:e.endpoints)||[]}async fetchDataFromAPI(e,t){if(!this.parsedCollection)throw new Error("No Postman collection loaded. Call loadPostmanCollection() first.");const s=this.parsedCollection.endpoints.find(l=>l.name===e);if(!s)throw new Error(`Endpoint "${e}" not found in collection.`);const a={...this.parsedCollection.variables,...t},o=await I({endpoint:s,variables:a});if(!o.success)throw new Error(`API request failed: ${o.error}`);const i=z(o),r=S(i);return{data:i,schema:r}}async queryAPI(e){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Provide qaConfig in constructor or call initializeQA().");const t=Date.now(),{data:s,schema:a}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),o={question:e.question,schema:a,data:s},i=await this.qaEngine.answerQuestion(o),r=Date.now()-t;return{answer:i.answer,apiResponse:s,endpoint:e.dataSource.endpoint,executionTime:r}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function X(c){const e=new R(c.config,c.qaConfig),t=n.ref(!1),s=n.ref(null),a=n.ref(null),o=c.data||n.ref([]),i=c.schema||n.ref(null),r=n.ref([]),l=n.ref([]),u=n.ref(null),h=c.maxQuestionHistory||50,p=c.useLocalFallback!==!1;async function m(d,f){t.value=!0,s.value=null;try{const w={type:d,data:o.value,schema:i.value||void 0,options:f},k=await e.analyze(w);return a.value=k,k}catch(w){if(s.value=w instanceof Error?w:new Error("Analysis failed"),p)return g(d,f);throw s.value}finally{t.value=!1}}function g(d,f){const w=i.value||S(o.value);switch(d){case"descriptive_stats":{const k=w.columns.map(N=>x(o.value,N.name,N.type));return{type:d,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=w.columns.filter(A=>A.type==="number").map(A=>A.name),N=P(o.value,k,f==null?void 0:f.sensitivity);return{type:d,timestamp:new Date,anomalies:N,summary:`Found ${N.length} anomalies`,insights:N.slice(0,3).map(A=>A.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${d}`)}}async function y(){return(await m("descriptive_stats")).descriptiveStats||[]}async function v(d,f){return(await m("anomaly_detection",{sensitivity:f,features:d})).anomalies||[]}async function b(d,f=3){return m("clustering",{features:d,numClusters:f})}async function C(d,f){return m("prediction",{targetColumn:d,...f})}function E(d){e.updateConfig(d)}function q(d,f=!0){o.value=d,f&&(i.value=S(d))}function D(){t.value=!1,s.value=null,a.value=null,r.value=[],l.value=[],u.value=null}async function B(d,f){t.value=!0,s.value=null;try{const w=i.value||S(o.value),k={question:d,schema:w,data:o.value,sampleSize:100,includeAggregates:!0,...f},A=(await e.askQuestion(k)).answer,K={id:A.questionId,text:d,timestamp:new Date,context:{tableSchema:w,rowCount:o.value.length}};return r.value.push(K),l.value.push(A),u.value=A,r.value.length>h&&(r.value.shift(),l.value.shift()),A}catch(w){throw s.value=w instanceof Error?w:new Error("Q&A failed"),s.value}finally{t.value=!1}}async function _(){t.value=!0,s.value=null;try{const d=i.value||S(o.value);return await e.generateSummary(o.value,d)}catch(d){throw s.value=d instanceof Error?d:new Error("Summary generation failed"),s.value}finally{t.value=!1}}function L(){r.value=[],l.value=[],u.value=null}function H(d){const f=e.extractFromDOM(d);return f&&(o.value=f.data,i.value=f.schema),f}function J(d,f,w){const k=e.normalizeVueData(d,f,w);o.value=k.data,i.value=k.schema}function U(d){e.initializeQA(d)}return{client:e,loading:t,error:s,lastResult:a,data:o,schema:i,questionHistory:r,answerHistory:l,lastAnswer:u,analyze:m,getDescriptiveStats:y,detectAnomalies:v,performClustering:b,predict:C,askQuestion:B,generateSummary:_,clearHistory:L,extractFromDOM:H,loadFromVueGrid:J,updateConfig:E,initializeQA:U,setData:q,reset:D}}const Z={class:"ti-question-input"},ee={class:"ti-input-wrapper"},te=["placeholder","disabled","onKeydown"],ne=["disabled"],se={key:0},ae={key:1,class:"ti-loading"},oe={key:0,class:"ti-hint"},re=n.defineComponent({__name:"QuestionInput",props:{placeholder:{default:"Ask a question about this data..."},submitLabel:{default:"Ask"},loadingLabel:{default:"Processing..."},hint:{default:"Press Enter to submit, Shift+Enter for new line"},showHint:{type:Boolean,default:!0},disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1}},emits:["submit"],setup(c,{emit:e}){const t=c,s=e,a=n.ref("");function o(){a.value.trim()&&!t.disabled&&!t.loading&&(s("submit",a.value.trim()),a.value="")}function i(r){}return(r,l)=>(n.openBlock(),n.createElementBlock("div",Z,[n.createElementVNode("div",ee,[n.withDirectives(n.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=u=>a.value=u),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[n.withKeys(n.withModifiers(o,["exact","prevent"]),["enter"]),n.withKeys(n.withModifiers(i,["shift"]),["enter"])]},null,40,te),[[n.vModelText,a.value]]),n.createElementVNode("button",{disabled:r.disabled||!a.value.trim(),class:"ti-submit-btn",onClick:o},[r.loading?(n.openBlock(),n.createElementBlock("span",ae,n.toDisplayString(r.loadingLabel),1)):(n.openBlock(),n.createElementBlock("span",se,n.toDisplayString(r.submitLabel),1))],8,ne)]),r.showHint?(n.openBlock(),n.createElementBlock("div",oe,n.toDisplayString(r.hint),1)):n.createCommentVNode("",!0)]))}}),M=(c,e)=>{const t=c.__vccOpts||c;for(const[s,a]of e)t[s]=a;return t},ie=M(re,[["__scopeId","data-v-90db5921"]]),le={class:"ti-answer-header"},ce={class:"ti-answer-icon"},ue={key:0},de={key:1},me={class:"ti-answer-meta"},pe={class:"ti-confidence"},he={class:"ti-timestamp"},fe={class:"ti-answer-text"},ge={key:0,class:"ti-approximate-notice"},ye={key:1,class:"ti-reason"},we={key:2,class:"ti-supporting-data"},ve={key:0,class:"ti-supporting-content"},ke={key:0,class:"ti-aggregates"},be={key:1,class:"ti-rows"},Ee={class:"ti-table-wrapper"},Ae={class:"ti-table"},Ce=n.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const e=n.ref(!1);function t(s){return new Date(s).toLocaleTimeString()}return(s,a)=>(n.openBlock(),n.createElementBlock("div",{class:n.normalizeClass(["ti-answer-display",{"ti-cannot-answer":s.answer.cannotAnswer}])},[n.createElementVNode("div",le,[n.createElementVNode("div",ce,[s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("span",de,"âš ī¸")):(n.openBlock(),n.createElementBlock("span",ue,"💡"))]),n.createElementVNode("div",me,[n.createElementVNode("div",pe," Confidence: "+n.toDisplayString(Math.round(s.answer.confidence*100))+"% ",1),n.createElementVNode("div",he,n.toDisplayString(t(s.answer.timestamp)),1)])]),n.createElementVNode("div",fe,n.toDisplayString(s.answer.text),1),s.answer.isApproximate?(n.openBlock(),n.createElementBlock("div",ge," â„šī¸ This answer is based on sampled data and may be approximate. ")):n.createCommentVNode("",!0),s.answer.reason&&s.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("div",ye,[a[1]||(a[1]=n.createElementVNode("strong",null,"Reason:",-1)),n.createTextVNode(" "+n.toDisplayString(s.answer.reason),1)])):n.createCommentVNode("",!0),s.answer.supportingData?(n.openBlock(),n.createElementBlock("div",we,[n.createElementVNode("button",{class:"ti-toggle-btn",onClick:a[0]||(a[0]=o=>e.value=!e.value)},n.toDisplayString(e.value?"â–ŧ":"â–ļ")+" Supporting Data ",1),e.value?(n.openBlock(),n.createElementBlock("div",ve,[s.answer.supportingData.aggregates?(n.openBlock(),n.createElementBlock("div",ke,[a[2]||(a[2]=n.createElementVNode("h4",null,"Aggregates:",-1)),n.createElementVNode("pre",null,n.toDisplayString(JSON.stringify(s.answer.supportingData.aggregates,null,2)),1)])):n.createCommentVNode("",!0),s.answer.supportingData.rows&&s.answer.supportingData.rows.length>0?(n.openBlock(),n.createElementBlock("div",be,[n.createElementVNode("h4",null,"Sample Rows ("+n.toDisplayString(s.answer.supportingData.rows.length)+"):",1),n.createElementVNode("div",Ee,[n.createElementVNode("table",Ae,[n.createElementVNode("thead",null,[n.createElementVNode("tr",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(s.answer.supportingData.rows[0]),(o,i)=>(n.openBlock(),n.createElementBlock("th",{key:i},n.toDisplayString(o),1))),128))])]),n.createElementVNode("tbody",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.answer.supportingData.rows.slice(0,5),(o,i)=>(n.openBlock(),n.createElementBlock("tr",{key:i},[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(o),(r,l)=>(n.openBlock(),n.createElementBlock("td",{key:l},n.toDisplayString(o[r]),1))),128))]))),128))])])])])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)],2))}}),$e=M(Ce,[["__scopeId","data-v-d1aaae1d"]]),Se={class:"ti-question-history"},De={class:"ti-history-header"},Ne={key:0,class:"ti-empty-state"},_e={key:1,class:"ti-history-list"},Be=["onClick"],qe={class:"ti-question-header"},Te={class:"ti-question-number"},Ve={class:"ti-question-time"},xe={class:"ti-question-text"},Ie={key:0,class:"ti-question-context"},Me=n.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const t=c,s=n.computed(()=>[...t.questions].reverse());function a(o){const i=new Date(o),l=new Date().getTime()-i.getTime(),u=Math.floor(l/6e4),h=Math.floor(l/36e5),p=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:h<24?`${h}h ago`:`${p}d ago`}return(o,i)=>(n.openBlock(),n.createElementBlock("div",Se,[n.createElementVNode("div",De,[i[1]||(i[1]=n.createElementVNode("h3",null,"Question History",-1)),o.questions.length>0?(n.openBlock(),n.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>o.$emit("clear"))}," Clear History ")):n.createCommentVNode("",!0)]),o.questions.length===0?(n.openBlock(),n.createElementBlock("div",Ne,i[2]||(i[2]=[n.createElementVNode("div",{class:"ti-empty-icon"},"đŸ’Ŧ",-1),n.createElementVNode("p",null,"No questions asked yet",-1),n.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(n.openBlock(),n.createElementBlock("div",_e,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.value,(r,l)=>(n.openBlock(),n.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:u=>o.$emit("select",r)},[n.createElementVNode("div",qe,[n.createElementVNode("span",Te,"#"+n.toDisplayString(o.questions.length-l),1),n.createElementVNode("span",Ve,n.toDisplayString(a(r.timestamp)),1)]),n.createElementVNode("div",xe,n.toDisplayString(r.text),1),r.context?(n.openBlock(),n.createElementBlock("div",Ie,n.toDisplayString(r.context.rowCount)+" rows ",1)):n.createCommentVNode("",!0)],8,Be))),128))]))]))}}),Pe=M(Me,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=$e;exports.QAEngine=T;exports.QuestionHistory=Pe;exports.QuestionInput=ie;exports.TabularIntelligence=R;exports.calculateStats=x;exports.convertToTabular=z;exports.detectAnomalies=P;exports.executeAPIRequest=I;exports.executeMultipleRequests=W;exports.extractFromDOM=O;exports.inferColumnType=V;exports.inferSchema=S;exports.normalizeVueData=Q;exports.parsePostmanCollection=F;exports.replaceVariables=$;exports.useTabularIntelligence=X;
2
31
  //# sourceMappingURL=index.js.map