@aivue/tabular-intelligence 1.1.0 → 1.3.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
@@ -9,6 +9,7 @@
9
9
 
10
10
  - 🔌 **Generic TFM Client** - Connect to any HTTP-based Tabular Foundation Model API
11
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
12
13
  - 📊 **Descriptive Statistics** - Mean, median, mode, std dev, percentiles, distributions
13
14
  - 🚨 **Anomaly Detection** - Statistical and ML-based outlier detection
14
15
  - đŸŽ¯ **Segmentation & Clustering** - K-means, DBSCAN, hierarchical clustering
@@ -31,6 +32,20 @@
31
32
 
32
33
  The AI analyzes your table data and provides natural language answers with supporting statistics and data.
33
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
+
34
49
  ## đŸ“Ļ Installation
35
50
 
36
51
  ```bash
@@ -1,8 +1,10 @@
1
- import { TFMConfig, AnalysisRequest, AnalysisResult, TableSchema, QARequest, QAResponse, AISummary, TableExtractionOptions, ExtractedTable } from '../types';
1
+ import { TFMConfig, AnalysisRequest, AnalysisResult, TableSchema, QARequest, QAResponse, AISummary, TableExtractionOptions, ExtractedTable, APIQueryRequest, APIQueryResponse } from '../types';
2
2
  import { QAEngineConfig } from '../utils/qaEngine';
3
+ import { ParsedCollection, ParsedEndpoint } from '../utils/postmanParser';
3
4
  export declare class TabularIntelligence {
4
5
  private config;
5
6
  private qaEngine?;
7
+ private parsedCollection?;
6
8
  constructor(config: TFMConfig, qaConfig?: QAEngineConfig);
7
9
  /**
8
10
  * Initialize or update Q&A engine
@@ -48,5 +50,36 @@ export declare class TabularIntelligence {
48
50
  * Get current configuration (without sensitive data)
49
51
  */
50
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
+ }>;
51
84
  }
52
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,EAEd,WAAW,EAMX,SAAS,EACT,UAAU,EACV,SAAS,EACT,sBAAsB,EACtB,cAAc,EACf,MAAM,UAAU,CAAC;AAClB,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGlE,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,QAAQ,CAAC,CAAW;gBAEhB,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,cAAc;IAYxD;;OAEG;IACH,YAAY,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI5C;;OAEG;YACW,OAAO;IA+CrB;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAkBhE;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAgE3B;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC;IAQ1D;;OAEG;IACG,eAAe,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC;IAgB3E;;OAEG;IACH,cAAc,CAAC,OAAO,CAAC,EAAE,sBAAsB,GAAG,cAAc,GAAG,IAAI;IAIvE;;OAEG;IACH,gBAAgB,CACd,IAAI,EAAE,GAAG,EAAE,EACX,OAAO,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EACnE,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc;IAIjB;;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,UAAU,CAAC;AAClB,OAAO,EAAY,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAA0B,KAAK,gBAAgB,EAAE,KAAK,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI5G,qBAAa,mBAAmB;IAC9B,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,QAAQ,CAAC,CAAW;IAC5B,OAAO,CAAC,gBAAgB,CAAC,CAAmB;gBAEhC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,cAAc;IAYxD;;OAEG;IACH,YAAY,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI;IAI5C;;OAEG;YACW,OAAO;IA+CrB;;OAEG;IACG,OAAO,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;IAkBhE;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAgE3B;;OAEG;IACG,WAAW,CAAC,OAAO,EAAE,SAAS,GAAG,OAAO,CAAC,UAAU,CAAC;IAQ1D;;OAEG;IACG,eAAe,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC;IAgB3E;;OAEG;IACH,cAAc,CAAC,OAAO,CAAC,EAAE,sBAAsB,GAAG,cAAc,GAAG,IAAI;IAIvE;;OAEG;IACH,gBAAgB,CACd,IAAI,EAAE,GAAG,EAAE,EACX,OAAO,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EACnE,OAAO,CAAC,EAAE,sBAAsB,GAC/B,cAAc;IAIjB;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI;IAI9C;;OAEG;IACH,SAAS,IAAI,IAAI,CAAC,SAAS,EAAE,QAAQ,CAAC;IAStC;;OAEG;IACH,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
@@ -11,5 +11,7 @@ export { default as QuestionHistory } from './components/QuestionHistory.vue';
11
11
  export { inferSchema, inferColumnType, calculateStats, detectAnomalies } from './utils/helpers';
12
12
  export { QAEngine, type QAEngineConfig } from './utils/qaEngine';
13
13
  export { extractFromDOM, normalizeVueData } from './utils/tableExtractor';
14
- 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, } from './types';
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';
15
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,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;AAG1E,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,GACV,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,17 +1,17 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("vue");function _(c,o){if(c.length===0)return{columns:[],rowCount:0,name:o};const a=c[0];return{columns:Object.keys(a).map(n=>{const s=T(c,n);return{name:n,type:s,nullable:c.some(i=>i[n]==null)}}),rowCount:c.length,name:o}}function T(c,o){const a=c.map(n=>n[o]).filter(n=>n!=null);if(a.length===0)return"string";if(a.every(n=>typeof n=="number"||!isNaN(Number(n))))return"number";if(a.every(n=>typeof n=="boolean"||n==="true"||n==="false"))return"boolean";if(a.every(n=>!isNaN(Date.parse(n))))return"date";const t=new Set(a);return t.size<a.length*.5&&t.size<20?"categorical":"string"}function x(c,o,a){const t=c.map(r=>r[o]).filter(r=>r!=null),n=t.length,s=c.length-n,i={column:o,count:n,nullCount:s};if(a==="number"){const r=t.map(Number).filter(l=>!isNaN(l));if(r.length>0){const l=[...r].sort((d,f)=>d-f),m=r.reduce((d,f)=>d+f,0);i.mean=m/r.length,i.median=l[Math.floor(l.length/2)],i.min=l[0],i.max=l[l.length-1];const h=r.reduce((d,f)=>d+Math.pow(f-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(t);i.uniqueValues=r.size;const l={};t.forEach(h=>{const d=String(h);l[d]=(l[d]||0)+1});const m=Math.max(...Object.values(l));i.mode=Object.keys(l).find(h=>l[h]===m)}return i}function I(c,o,a=.5){const t=[],n=1.5+(1-a)*1.5;return o.forEach(s=>{const i=c.map((y,w)=>({value:Number(y[s]),idx:w})).filter(y=>!isNaN(y.value));if(i.length===0)return;const r=[...i].sort((y,w)=>y.value-w.value),l=r[Math.floor(r.length*.25)].value,m=r[Math.floor(r.length*.75)].value,h=m-l,d=l-n*h,f=m+n*h;i.forEach(({value:y,idx:w})=>{if(y<d||y>f){const v=t.find(A=>A.rowIndex===w),b=y<d?`${s}: ${y.toFixed(2)} < ${d.toFixed(2)}`:`${s}: ${y.toFixed(2)} > ${f.toFixed(2)}`;v?(v.reasons.push(b),v.affectedColumns.push(s),v.score=Math.min(1,v.score+.2)):t.push({rowIndex:w,row:c[w],score:.7,reasons:[b],affectedColumns:[s]})}})}),t.sort((s,i)=>i.score-s.score)}class V{constructor(o){this.config={maxTokens:1e3,temperature:.3,...o}}async answerQuestion(o){const a=Date.now();try{const{question:t,schema:n,data:s=[],sampleSize:i=100,includeAggregates:r=!0}=o,l=s.length>i?this.sampleData(s,i):s,m=r?this.calculateAggregates(s,n):void 0,h=this.buildPrompt(t,n,l,m,s.length),d=await this.callLLM(h);return{answer:this.parseResponse(d,t,s.length>i),processingTime:Date.now()-a}}catch(t){return console.error("Q&A error:",t),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:t instanceof Error?t.message:"Unknown error"},processingTime:Date.now()-a}}}sampleData(o,a){if(o.length<=a)return o;const t=Math.floor(o.length/a),n=[];for(let s=0;s<o.length&&n.length<a;s+=t)n.push(o[s]);return n}calculateAggregates(o,a){const t={};for(const n of a.columns)if(n.type==="number"&&o.length>0)try{const s=x(o,n.name,"number");t[n.name]={mean:s.mean,median:s.median,min:s.min,max:s.max,count:s.count}}catch{}else if(n.type==="categorical"||n.type==="string"){const s=o.map(r=>r[n.name]).filter(r=>r!=null),i=new Set(s);t[n.name]={uniqueCount:i.size,totalCount:s.length,topValues:this.getTopValues(s,5)}}return t}getTopValues(o,a){const t=new Map;for(const n of o)t.set(n,(t.get(n)||0)+1);return Array.from(t.entries()).map(([n,s])=>({value:n,count:s})).sort((n,s)=>s.count-n.count).slice(0,a)}buildPrompt(o,a,t,n,s){const i=s&&s>t.length;let r=`You are a data analyst assistant. Answer the following question about a table dataset.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("vue");function $(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,d)=>p-d),u=r.reduce((p,d)=>p+d,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,d)=>p+Math.pow(d-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,d=u+a*h;i.forEach(({value:g,idx:y})=>{if(g<p||g>d){const v=s.find(C=>C.rowIndex===y),b=g<p?`${o}: ${g.toFixed(2)} < ${p.toFixed(2)}`:`${o}: ${g.toFixed(2)} > ${d.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
2
 
3
3
  `;r+=`**Table Schema:**
4
- `,r+=`Table: ${a.name}
4
+ `,r+=`Table: ${t.name}
5
5
  `,r+=`Columns:
6
- `;for(const l of a.columns)r+=`- ${l.name} (${l.type})
6
+ `;for(const l of t.columns)r+=`- ${l.name} (${l.type})
7
7
  `;return r+=`
8
- `,n&&Object.keys(n).length>0&&(r+=`**Summary Statistics:**
9
- `,r+=JSON.stringify(n,null,2),r+=`
8
+ `,a&&Object.keys(a).length>0&&(r+=`**Summary Statistics:**
9
+ `,r+=JSON.stringify(a,null,2),r+=`
10
10
 
11
- `),r+=`**Sample Data** (${t.length} rows${i?` out of ${s} total`:""}):
12
- `,r+=JSON.stringify(t.slice(0,10),null,2),r+=`
11
+ `),r+=`**Sample Data** (${s.length} rows${i?` out of ${o} total`:""}):
12
+ `,r+=JSON.stringify(s.slice(0,10),null,2),r+=`
13
13
 
14
- `,r+=`**Question:** ${o}
14
+ `,r+=`**Question:** ${e}
15
15
 
16
16
  `,r+=`**Instructions:**
17
17
  `,r+=`1. Answer ONLY based on the data provided above.
@@ -27,5 +27,5 @@
27
27
  `,r+=` "isApproximate": ${i},
28
28
  `,r+=` "supportingData": { "key": "value" } // optional
29
29
  `,r+=`}
30
- `,r}async callLLM(o){const{provider:a,apiKey:t,baseUrl:n,model:s,maxTokens:i,temperature:r}=this.config;if(a==="openai")return this.callOpenAI(o,t,s||"gpt-4-turbo-preview",i,r);if(a==="anthropic")return this.callAnthropic(o,t,s||"claude-3-5-sonnet-20241022",i,r);if(a==="custom"&&n)return this.callCustomAPI(o,n,t);throw new Error(`Unsupported provider: ${a}`)}async callOpenAI(o,a,t,n,s){var l,m;const i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`},body:JSON.stringify({model:t,messages:[{role:"user",content:o}],max_tokens:n,temperature:s,response_format:{type:"json_object"}})});if(!i.ok)throw new Error(`OpenAI API error: ${i.statusText}`);return((m=(l=(await i.json()).choices[0])==null?void 0:l.message)==null?void 0:m.content)||""}async callAnthropic(o,a,t,n,s){var l;const i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":a,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:t,max_tokens:n,temperature:s,messages:[{role:"user",content:o}]})});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(o,a,t){const n={"Content-Type":"application/json"};t&&(n.Authorization=`Bearer ${t}`);const s=await fetch(a,{method:"POST",headers:n,body:JSON.stringify({prompt:o})});if(!s.ok)throw new Error(`Custom API error: ${s.statusText}`);const i=await s.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(o,a,t){try{const n=JSON.parse(o);return{questionId:this.generateId(),text:n.answer||n.text||o,timestamp:new Date,confidence:n.confidence||.8,cannotAnswer:n.cannotAnswer||!1,isApproximate:n.isApproximate!==void 0?n.isApproximate:t,supportingData:n.supportingData,reason:n.reason}}catch{return{questionId:this.generateId(),text:o,timestamp:new Date,confidence:.7,isApproximate:t}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function M(c={}){const{selector:o="table",includeHeaders:a=!0,maxRows:t,inferTypes:n=!0,skipEmptyRows:s=!0}=c,i=document.querySelector(o);if(!i||i.tagName!=="TABLE")return console.warn(`No table found with selector: ${o}`),null;const l=Array.from(i.rows);if(l.length===0)return null;let m=[],h=0;if(a&&l[0]){const w=l[0];m=Array.from(w.cells).map((v,b)=>{var E;return((E=v.textContent)==null?void 0:E.trim())||""||`Column${b+1}`}),h=1}else{const w=l[0];m=Array.from(w.cells).map((v,b)=>`Column${b+1}`)}const d=[],f=t?l.slice(h,h+t):l.slice(h);for(const w of f){const v=Array.from(w.cells);if(s&&v.every(A=>{var E;return!((E=A.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((A,E)=>{var C;const $=m[E]||`Column${E+1}`;let D=((C=A.textContent)==null?void 0:C.trim())||"";if(n&&D){const B=parseFloat(D);!isNaN(B)&&D===B.toString()&&(D=B)}b[$]=D}),d.push(b)}return{schema:n&&d.length>0?_(d,"Extracted Table"):H(m,d.length),data:d,source:"dom",metadata:{selector:o,rowCount:d.length,columnCount:m.length,extractedAt:new Date}}}function O(c,o,a={}){const{maxRows:t,inferTypes:n=!0}=a,s=t?c.slice(0,t):c;let i;return o&&o.length>0?i={name:"Vue Data Grid",columns:o.map(r=>({name:r.field,type:n&&s.length>0?T(s,r.field):"string",nullable:!0})),rowCount:s.length}:s.length>0?i=_(s,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:s,source:"vue",metadata:{rowCount:s.length,columnCount:i.columns.length,extractedAt:new Date}}}function H(c,o=0){return{name:"Extracted Table",columns:c.map(a=>({name:a,type:"string",nullable:!0})),rowCount:o}}class Q{constructor(o,a){this.config={timeout:3e4,...o},a&&(this.qaEngine=new V(a))}initializeQA(o){this.qaEngine=new V(o)}async callTFM(o){const a=Date.now();try{const t=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({...o,model:this.config.model}),signal:AbortSignal.timeout(this.config.timeout||3e4)});if(!t.ok){const i=await t.text();throw new Error(`TFM API error: ${t.status} - ${i}`)}const n=await t.json(),s=Date.now()-a;return{success:!0,result:n.result||n,metadata:{processingTime:s,model:this.config.model||"unknown",version:n.version}}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error",metadata:{processingTime:Date.now()-a,model:this.config.model||"unknown"}}}}async analyze(o){const a={operation:o.type,data:o.data,schema:o.schema,parameters:o.options},t=await this.callTFM(a);if(!t.success)throw new Error(t.error||"Analysis failed");return this.parseAnalysisResult(o.type,t.result,t.metadata)}parseAnalysisResult(o,a,t){const n={type:o,timestamp:new Date,summary:a.summary||"",insights:a.insights||[],recommendations:a.recommendations,confidence:a.confidence||.8,processingTime:t==null?void 0:t.processingTime};switch(o){case"descriptive_stats":return{...n,descriptiveStats:a.stats||a.descriptiveStats};case"anomaly_detection":return{...n,anomalies:a.anomalies||[]};case"segmentation":case"clustering":return{...n,clusters:a.clusters||[]};case"prediction":return{...n,predictions:a.predictions||a};case"correlation":return{...n,correlations:a.correlations||a};case"summary":return{...n,aiSummary:a.summary||a};case"qa":return{...n,qaAnswer:a.answer||a};default:return n}}async askQuestion(o){if(!this.qaEngine)throw new Error("Q&A engine not initialized. Call initializeQA() first.");return this.qaEngine.answerQuestion(o)}async generateSummary(o,a){const t={type:"summary",data:o,schema:a},n=await this.analyze(t);if(!n.aiSummary)throw new Error("Failed to generate summary");return n.aiSummary}extractFromDOM(o){return M(o)}normalizeVueData(o,a,t){return O(o,a,t)}updateConfig(o){this.config={...this.config,...o}}getConfig(){const{apiKey:o,...a}=this.config;return a}}function R(c){const o=new Q(c.config,c.qaConfig),a=e.ref(!1),t=e.ref(null),n=e.ref(null),s=c.data||e.ref([]),i=c.schema||e.ref(null),r=e.ref([]),l=e.ref([]),m=e.ref(null),h=c.maxQuestionHistory||50,d=c.useLocalFallback!==!1;async function f(u,p){a.value=!0,t.value=null;try{const g={type:u,data:s.value,schema:i.value||void 0,options:p},k=await o.analyze(g);return n.value=k,k}catch(g){if(t.value=g instanceof Error?g:new Error("Analysis failed"),d)return y(u,p);throw t.value}finally{a.value=!1}}function y(u,p){const g=i.value||_(s.value);switch(u){case"descriptive_stats":{const k=g.columns.map(N=>x(s.value,N.name,N.type));return{type:u,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=g.columns.filter(S=>S.type==="number").map(S=>S.name),N=I(s.value,k,p==null?void 0:p.sensitivity);return{type:u,timestamp:new Date,anomalies:N,summary:`Found ${N.length} anomalies`,insights:N.slice(0,3).map(S=>S.reasons[0]),confidence:.8}}default:throw new Error(`Local analysis not supported for type: ${u}`)}}async function w(){return(await f("descriptive_stats")).descriptiveStats||[]}async function v(u,p){return(await f("anomaly_detection",{sensitivity:p,features:u})).anomalies||[]}async function b(u,p=3){return f("clustering",{features:u,numClusters:p})}async function A(u,p){return f("prediction",{targetColumn:u,...p})}function E(u){o.updateConfig(u)}function $(u,p=!0){s.value=u,p&&(i.value=_(u))}function D(){a.value=!1,t.value=null,n.value=null,r.value=[],l.value=[],m.value=null}async function C(u,p){a.value=!0,t.value=null;try{const g=i.value||_(s.value),k={question:u,schema:g,data:s.value,sampleSize:100,includeAggregates:!0,...p},S=(await o.askQuestion(k)).answer,P={id:S.questionId,text:u,timestamp:new Date,context:{tableSchema:g,rowCount:s.value.length}};return r.value.push(P),l.value.push(S),m.value=S,r.value.length>h&&(r.value.shift(),l.value.shift()),S}catch(g){throw t.value=g instanceof Error?g:new Error("Q&A failed"),t.value}finally{a.value=!1}}async function B(){a.value=!0,t.value=null;try{const u=i.value||_(s.value);return await o.generateSummary(s.value,u)}catch(u){throw t.value=u instanceof Error?u:new Error("Summary generation failed"),t.value}finally{a.value=!1}}function F(){r.value=[],l.value=[],m.value=null}function z(u){const p=o.extractFromDOM(u);return p&&(s.value=p.data,i.value=p.schema),p}function L(u,p,g){const k=o.normalizeVueData(u,p,g);s.value=k.data,i.value=k.schema}function j(u){o.initializeQA(u)}return{client:o,loading:a,error:t,lastResult:n,data:s,schema:i,questionHistory:r,answerHistory:l,lastAnswer:m,analyze:f,getDescriptiveStats:w,detectAnomalies:v,performClustering:b,predict:A,askQuestion:C,generateSummary:B,clearHistory:F,extractFromDOM:z,loadFromVueGrid:L,updateConfig:E,initializeQA:j,setData:$,reset:D}}const J={class:"ti-question-input"},K={class:"ti-input-wrapper"},U=["placeholder","disabled","onKeydown"],G=["disabled"],Y={key:0},W={key:1,class:"ti-loading"},X={key:0,class:"ti-hint"},Z=e.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:o}){const a=c,t=o,n=e.ref("");function s(){n.value.trim()&&!a.disabled&&!a.loading&&(t("submit",n.value.trim()),n.value="")}function i(r){}return(r,l)=>(e.openBlock(),e.createElementBlock("div",J,[e.createElementVNode("div",K,[e.withDirectives(e.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=m=>n.value=m),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[e.withKeys(e.withModifiers(s,["exact","prevent"]),["enter"]),e.withKeys(e.withModifiers(i,["shift"]),["enter"])]},null,40,U),[[e.vModelText,n.value]]),e.createElementVNode("button",{disabled:r.disabled||!n.value.trim(),class:"ti-submit-btn",onClick:s},[r.loading?(e.openBlock(),e.createElementBlock("span",W,e.toDisplayString(r.loadingLabel),1)):(e.openBlock(),e.createElementBlock("span",Y,e.toDisplayString(r.submitLabel),1))],8,G)]),r.showHint?(e.openBlock(),e.createElementBlock("div",X,e.toDisplayString(r.hint),1)):e.createCommentVNode("",!0)]))}}),q=(c,o)=>{const a=c.__vccOpts||c;for(const[t,n]of o)a[t]=n;return a},ee=q(Z,[["__scopeId","data-v-90db5921"]]),te={class:"ti-answer-header"},ne={class:"ti-answer-icon"},oe={key:0},se={key:1},ae={class:"ti-answer-meta"},re={class:"ti-confidence"},ie={class:"ti-timestamp"},le={class:"ti-answer-text"},ce={key:0,class:"ti-approximate-notice"},ue={key:1,class:"ti-reason"},me={key:2,class:"ti-supporting-data"},de={key:0,class:"ti-supporting-content"},pe={key:0,class:"ti-aggregates"},he={key:1,class:"ti-rows"},fe={class:"ti-table-wrapper"},ge={class:"ti-table"},we=e.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const o=e.ref(!1);function a(t){return new Date(t).toLocaleTimeString()}return(t,n)=>(e.openBlock(),e.createElementBlock("div",{class:e.normalizeClass(["ti-answer-display",{"ti-cannot-answer":t.answer.cannotAnswer}])},[e.createElementVNode("div",te,[e.createElementVNode("div",ne,[t.answer.cannotAnswer?(e.openBlock(),e.createElementBlock("span",se,"âš ī¸")):(e.openBlock(),e.createElementBlock("span",oe,"💡"))]),e.createElementVNode("div",ae,[e.createElementVNode("div",re," Confidence: "+e.toDisplayString(Math.round(t.answer.confidence*100))+"% ",1),e.createElementVNode("div",ie,e.toDisplayString(a(t.answer.timestamp)),1)])]),e.createElementVNode("div",le,e.toDisplayString(t.answer.text),1),t.answer.isApproximate?(e.openBlock(),e.createElementBlock("div",ce," â„šī¸ This answer is based on sampled data and may be approximate. ")):e.createCommentVNode("",!0),t.answer.reason&&t.answer.cannotAnswer?(e.openBlock(),e.createElementBlock("div",ue,[n[1]||(n[1]=e.createElementVNode("strong",null,"Reason:",-1)),e.createTextVNode(" "+e.toDisplayString(t.answer.reason),1)])):e.createCommentVNode("",!0),t.answer.supportingData?(e.openBlock(),e.createElementBlock("div",me,[e.createElementVNode("button",{class:"ti-toggle-btn",onClick:n[0]||(n[0]=s=>o.value=!o.value)},e.toDisplayString(o.value?"â–ŧ":"â–ļ")+" Supporting Data ",1),o.value?(e.openBlock(),e.createElementBlock("div",de,[t.answer.supportingData.aggregates?(e.openBlock(),e.createElementBlock("div",pe,[n[2]||(n[2]=e.createElementVNode("h4",null,"Aggregates:",-1)),e.createElementVNode("pre",null,e.toDisplayString(JSON.stringify(t.answer.supportingData.aggregates,null,2)),1)])):e.createCommentVNode("",!0),t.answer.supportingData.rows&&t.answer.supportingData.rows.length>0?(e.openBlock(),e.createElementBlock("div",he,[e.createElementVNode("h4",null,"Sample Rows ("+e.toDisplayString(t.answer.supportingData.rows.length)+"):",1),e.createElementVNode("div",fe,[e.createElementVNode("table",ge,[e.createElementVNode("thead",null,[e.createElementVNode("tr",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Object.keys(t.answer.supportingData.rows[0]),(s,i)=>(e.openBlock(),e.createElementBlock("th",{key:i},e.toDisplayString(s),1))),128))])]),e.createElementVNode("tbody",null,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.answer.supportingData.rows.slice(0,5),(s,i)=>(e.openBlock(),e.createElementBlock("tr",{key:i},[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(Object.keys(s),(r,l)=>(e.openBlock(),e.createElementBlock("td",{key:l},e.toDisplayString(s[r]),1))),128))]))),128))])])])])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)])):e.createCommentVNode("",!0)],2))}}),ye=q(we,[["__scopeId","data-v-d1aaae1d"]]),ve={class:"ti-question-history"},ke={class:"ti-history-header"},be={key:0,class:"ti-empty-state"},Ee={key:1,class:"ti-history-list"},Se=["onClick"],Ae={class:"ti-question-header"},De={class:"ti-question-number"},Ne={class:"ti-question-time"},_e={class:"ti-question-text"},Be={key:0,class:"ti-question-context"},Ce=e.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:o}){const a=c,t=e.computed(()=>[...a.questions].reverse());function n(s){const i=new Date(s),l=new Date().getTime()-i.getTime(),m=Math.floor(l/6e4),h=Math.floor(l/36e5),d=Math.floor(l/864e5);return m<1?"Just now":m<60?`${m}m ago`:h<24?`${h}h ago`:`${d}d ago`}return(s,i)=>(e.openBlock(),e.createElementBlock("div",ve,[e.createElementVNode("div",ke,[i[1]||(i[1]=e.createElementVNode("h3",null,"Question History",-1)),s.questions.length>0?(e.openBlock(),e.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>s.$emit("clear"))}," Clear History ")):e.createCommentVNode("",!0)]),s.questions.length===0?(e.openBlock(),e.createElementBlock("div",be,i[2]||(i[2]=[e.createElementVNode("div",{class:"ti-empty-icon"},"đŸ’Ŧ",-1),e.createElementVNode("p",null,"No questions asked yet",-1),e.createElementVNode("p",{class:"ti-empty-hint"},"Ask a question about your data to get started",-1)]))):(e.openBlock(),e.createElementBlock("div",Ee,[(e.openBlock(!0),e.createElementBlock(e.Fragment,null,e.renderList(t.value,(r,l)=>(e.openBlock(),e.createElementBlock("div",{key:r.id,class:"ti-history-item",onClick:m=>s.$emit("select",r)},[e.createElementVNode("div",Ae,[e.createElementVNode("span",De,"#"+e.toDisplayString(s.questions.length-l),1),e.createElementVNode("span",Ne,e.toDisplayString(n(r.timestamp)),1)]),e.createElementVNode("div",_e,e.toDisplayString(r.text),1),r.context?(e.openBlock(),e.createElementBlock("div",Be,e.toDisplayString(r.context.rowCount)+" rows ",1)):e.createCommentVNode("",!0)],8,Se))),128))]))]))}}),$e=q(Ce,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=ye;exports.QAEngine=V;exports.QuestionHistory=$e;exports.QuestionInput=ee;exports.TabularIntelligence=Q;exports.calculateStats=x;exports.detectAnomalies=I;exports.extractFromDOM=M;exports.inferColumnType=T;exports.inferSchema=_;exports.normalizeVueData=O;exports.useTabularIntelligence=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=[],d=s?l.slice(h,h+s):l.slice(h);for(const y of d){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?$(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=$(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 S(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=S(e.url,t);const i={...e.queryParams,...t,...a},r=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(S(String(i[d]),t))}`).join("&");r&&(o=o.includes("?")?`${o}&${r}`:`${o}?${r}`);const l={"Content-Type":"application/json",...e.headers,...s};if(Object.keys(l).forEach(d=>{l[d]=S(l[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",g=S(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(l[d]=g)}else if(e.auth.type==="bearer"){const d=S(e.auth.credentials.token||"",t);l.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=S(e.auth.credentials.username||"",t),g=S(e.auth.credentials.password||"",t),y=btoa(`${d}:${g}`);l.Authorization=`Basic ${y}`}}const u=await fetch(o,{method:e.method,headers:l}),h={};return u.headers.forEach((d,g)=>{h[g]=d}),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=$(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 d(m,f){t.value=!0,s.value=null;try{const w={type:m,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(m,f);throw s.value}finally{t.value=!1}}function g(m,f){const w=i.value||$(o.value);switch(m){case"descriptive_stats":{const k=w.columns.map(N=>x(o.value,N.name,N.type));return{type:m,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:m,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: ${m}`)}}async function y(){return(await d("descriptive_stats")).descriptiveStats||[]}async function v(m,f){return(await d("anomaly_detection",{sensitivity:f,features:m})).anomalies||[]}async function b(m,f=3){return d("clustering",{features:m,numClusters:f})}async function C(m,f){return d("prediction",{targetColumn:m,...f})}function E(m){e.updateConfig(m)}function q(m,f=!0){o.value=m,f&&(i.value=$(m))}function D(){t.value=!1,s.value=null,a.value=null,r.value=[],l.value=[],u.value=null}async function B(m,f){t.value=!0,s.value=null;try{const w=i.value||$(o.value),k={question:m,schema:w,data:o.value,sampleSize:100,includeAggregates:!0,...f},A=(await e.askQuestion(k)).answer,K={id:A.questionId,text:m,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 m=i.value||$(o.value);return await e.generateSummary(o.value,m)}catch(m){throw s.value=m instanceof Error?m:new Error("Summary generation failed"),s.value}finally{t.value=!1}}function L(){r.value=[],l.value=[],u.value=null}function H(m){const f=e.extractFromDOM(m);return f&&(o.value=f.data,i.value=f.schema),f}function J(m,f,w){const k=e.normalizeVueData(m,f,w);o.value=k.data,i.value=k.schema}function U(m){e.initializeQA(m)}return{client:e,loading:t,error:s,lastResult:a,data:o,schema:i,questionHistory:r,answerHistory:l,lastAnswer:u,analyze:d,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))}}),Se=M(Ce,[["__scopeId","data-v-d1aaae1d"]]),$e={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",$e,[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=Se;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=$;exports.normalizeVueData=Q;exports.parsePostmanCollection=F;exports.replaceVariables=S;exports.useTabularIntelligence=X;
31
31
  //# sourceMappingURL=index.js.map