@aivue/tabular-intelligence 1.3.1 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"useTabularIntelligence.d.ts","sourceRoot":"","sources":["../../src/composables/useTabularIntelligence.ts"],"names":[],"mappings":"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"}
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,EACP,QAAQ,EACR,MAAM,EACN,SAAS,EAET,SAAS,EACT,sBAAsB,EACtB,cAAc,EACf,MAAM,UAAU,CAAC;AAElB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,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;IAC3B,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,4BAA4B;IAE3C,MAAM,EAAE,mBAAmB,CAAC;IAG5B,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACtB,KAAK,EAAE,GAAG,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;IACzB,UAAU,EAAE,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;IAGvC,IAAI,EAAE,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;IACjB,MAAM,EAAE,GAAG,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAGhC,eAAe,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC,CAAC;IACjC,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;IAC7B,UAAU,EAAE,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAG/B,OAAO,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACxE,mBAAmB,EAAE,MAAM,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC;IACvD,eAAe,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IAClF,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,WAAW,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACzF,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAG1E,WAAW,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACjF,eAAe,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1C,YAAY,EAAE,MAAM,IAAI,CAAC;IAGzB,cAAc,EAAE,CAAC,OAAO,CAAC,EAAE,sBAAsB,KAAK,cAAc,GAAG,IAAI,CAAC;IAC5E,eAAe,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,EAAE,OAAO,CAAC,EAAE,sBAAsB,KAAK,IAAI,CAAC;IAG9F,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;IACnD,YAAY,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,CAAC;IACjD,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,EAAE,eAAe,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IAC7D,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,6BAA6B,GACrC,4BAA4B,CA+W9B"}
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
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(o=>{const a=q(c,o);return{name:o,type:a,nullable:c.some(i=>i[o]==null)}}),rowCount:c.length,name:e}}function q(c,e){const t=c.map(o=>o[e]).filter(o=>o!=null);if(t.length===0)return"string";if(t.every(o=>typeof o=="number"||!isNaN(Number(o))))return"number";if(t.every(o=>typeof o=="boolean"||o==="true"||o==="false"))return"boolean";if(t.every(o=>!isNaN(Date.parse(o))))return"date";const s=new Set(t);return s.size<t.length*.5&&s.size<20?"categorical":"string"}function V(c,e,t){const s=c.map(r=>r[e]).filter(r=>r!=null),o=s.length,a=c.length-o,i={column:e,count:o,nullCount:a};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 M(c,e,t=.5){const s=[],o=1.5+(1-t)*1.5;return e.forEach(a=>{const i=c.map((g,y)=>({value:Number(g[a]),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-o*h,d=u+o*h;i.forEach(({value:g,idx:y})=>{if(g<p||g>d){const v=s.find(C=>C.rowIndex===y),b=g<p?`${a}: ${g.toFixed(2)} < ${p.toFixed(2)}`:`${a}: ${g.toFixed(2)} > ${d.toFixed(2)}`;v?(v.reasons.push(b),v.affectedColumns.push(a),v.score=Math.min(1,v.score+.2)):s.push({rowIndex:y,row:c[y],score:.7,reasons:[b],affectedColumns:[a]})}})}),s.sort((a,i)=>i.score-a.score)}class T{constructor(e){this.config={maxTokens:1e3,temperature:.3,...e}}async answerQuestion(e){const t=Date.now();try{const{question:s,schema:o,data:a=[],sampleSize:i=100,includeAggregates:r=!0}=e,l=a.length>i?this.sampleData(a,i):a,u=r?this.calculateAggregates(a,o):void 0,h=this.buildPrompt(s,o,l,u,a.length),p=await this.callLLM(h);return{answer:this.parseResponse(p,s,a.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),o=[];for(let a=0;a<e.length&&o.length<t;a+=s)o.push(e[a]);return o}calculateAggregates(e,t){const s={};for(const o of t.columns)if(o.type==="number"&&e.length>0)try{const a=V(e,o.name,"number");s[o.name]={mean:a.mean,median:a.median,min:a.min,max:a.max,count:a.count}}catch{}else if(o.type==="categorical"||o.type==="string"){const a=e.map(r=>r[o.name]).filter(r=>r!=null),i=new Set(a);s[o.name]={uniqueCount:i.size,totalCount:a.length,topValues:this.getTopValues(a,5)}}return s}getTopValues(e,t){const s=new Map;for(const o of e)s.set(o,(s.get(o)||0)+1);return Array.from(s.entries()).map(([o,a])=>({value:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,t)}buildPrompt(e,t,s,o,a){const i=a&&a>s.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 N(c,e){if(c.length===0)return{columns:[],rowCount:0,name:e};const t=c[0];return{columns:Object.keys(t).map(a=>{const r=I(c,a);return{name:a,type:r,nullable:c.some(i=>i[a]==null)}}),rowCount:c.length,name:e}}function I(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 o=new Set(t);return o.size<t.length*.5&&o.size<20?"categorical":"string"}function P(c,e,t){const o=c.map(s=>s[e]).filter(s=>s!=null),a=o.length,r=c.length-a,i={column:e,count:a,nullCount:r};if(t==="number"){const s=o.map(Number).filter(l=>!isNaN(l));if(s.length>0){const l=[...s].sort((f,d)=>f-d),u=s.reduce((f,d)=>f+d,0);i.mean=u/s.length,i.median=l[Math.floor(l.length/2)],i.min=l[0],i.max=l[l.length-1];const h=s.reduce((f,d)=>f+Math.pow(d-i.mean,2),0)/s.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 s=new Set(o);i.uniqueValues=s.size;const l={};o.forEach(h=>{const f=String(h);l[f]=(l[f]||0)+1});const u=Math.max(...Object.values(l));i.mode=Object.keys(l).find(h=>l[h]===u)}return i}function F(c,e,t=.5){const o=[],a=1.5+(1-t)*1.5;return e.forEach(r=>{const i=c.map((g,v)=>({value:Number(g[r]),idx:v})).filter(g=>!isNaN(g.value));if(i.length===0)return;const s=[...i].sort((g,v)=>g.value-v.value),l=s[Math.floor(s.length*.25)].value,u=s[Math.floor(s.length*.75)].value,h=u-l,f=l-a*h,d=u+a*h;i.forEach(({value:g,idx:v})=>{if(g<f||g>d){const E=o.find(S=>S.rowIndex===v),A=g<f?`${r}: ${g.toFixed(2)} < ${f.toFixed(2)}`:`${r}: ${g.toFixed(2)} > ${d.toFixed(2)}`;E?(E.reasons.push(A),E.affectedColumns.push(r),E.score=Math.min(1,E.score+.2)):o.push({rowIndex:v,row:c[v],score:.7,reasons:[A],affectedColumns:[r]})}})}),o.sort((r,i)=>i.score-r.score)}class V{constructor(e){this.config={maxTokens:1e3,temperature:.3,...e}}async answerQuestion(e){const t=Date.now();try{const{question:o,schema:a,data:r=[],sampleSize:i=100,includeAggregates:s=!0}=e,l=r.length>i?this.sampleData(r,i):r,u=s?this.calculateAggregates(r,a):void 0,h=this.buildPrompt(o,a,l,u,r.length),f=await this.callLLM(h);return{answer:this.parseResponse(f,o,r.length>i),processingTime:Date.now()-t}}catch(o){return console.error("Q&A error:",o),{answer:{questionId:this.generateId(),text:"I encountered an error while processing your question. Please try again.",timestamp:new Date,confidence:0,cannotAnswer:!0,reason:o instanceof Error?o.message:"Unknown error"},processingTime:Date.now()-t}}}sampleData(e,t){if(e.length<=t)return e;const o=Math.floor(e.length/t),a=[];for(let r=0;r<e.length&&a.length<t;r+=o)a.push(e[r]);return a}calculateAggregates(e,t){const o={};for(const a of t.columns)if(a.type==="number"&&e.length>0)try{const r=P(e,a.name,"number");o[a.name]={mean:r.mean,median:r.median,min:r.min,max:r.max,count:r.count}}catch{}else if(a.type==="categorical"||a.type==="string"){const r=e.map(s=>s[a.name]).filter(s=>s!=null),i=new Set(r);o[a.name]={uniqueCount:i.size,totalCount:r.length,topValues:this.getTopValues(r,5)}}return o}getTopValues(e,t){const o=new Map;for(const a of e)o.set(a,(o.get(a)||0)+1);return Array.from(o.entries()).map(([a,r])=>({value:a,count:r})).sort((a,r)=>r.count-a.count).slice(0,t)}buildPrompt(e,t,o,a,r){const i=r&&r>o.length;let s=`You are a data analyst assistant. Answer the following question about a table dataset.
2
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
- `,o&&Object.keys(o).length>0&&(r+=`**Summary Statistics:**
9
- `,r+=JSON.stringify(o,null,2),r+=`
3
+ `;s+=`**Table Schema:**
4
+ `,s+=`Table: ${t.name}
5
+ `,s+=`Columns:
6
+ `;for(const l of t.columns)s+=`- ${l.name} (${l.type})
7
+ `;return s+=`
8
+ `,a&&Object.keys(a).length>0&&(s+=`**Summary Statistics:**
9
+ `,s+=JSON.stringify(a,null,2),s+=`
10
10
 
11
- `),r+=`**Sample Data** (${s.length} rows${i?` out of ${a} total`:""}):
12
- `,r+=JSON.stringify(s.slice(0,10),null,2),r+=`
11
+ `),s+=`**Sample Data** (${o.length} rows${i?` out of ${r} total`:""}):
12
+ `,s+=JSON.stringify(o.slice(0,10),null,2),s+=`
13
13
 
14
- `,r+=`**Question:** ${e}
14
+ `,s+=`**Question:** ${e}
15
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:o,model:a,maxTokens:i,temperature:r}=this.config;if(t==="openai")return this.callOpenAI(e,s,a||"gpt-4-turbo-preview",i,r);if(t==="anthropic")return this.callAnthropic(e,s,a||"claude-3-5-sonnet-20241022",i,r);if(t==="custom"&&o)return this.callCustomAPI(e,o,s);throw new Error(`Unsupported provider: ${t}`)}async callOpenAI(e,t,s,o,a){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:o,temperature:a,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,o,a){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:o,temperature:a,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 o={"Content-Type":"application/json"};s&&(o.Authorization=`Bearer ${s}`);const a=await fetch(t,{method:"POST",headers:o,body:JSON.stringify({prompt:e})});if(!a.ok)throw new Error(`Custom API error: ${a.statusText}`);const i=await a.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,s){try{const o=JSON.parse(e);return{questionId:this.generateId(),text:o.answer||o.text||e,timestamp:new Date,confidence:o.confidence||.8,cannotAnswer:o.cannotAnswer||!1,isApproximate:o.isApproximate!==void 0?o.isApproximate:s,supportingData:o.supportingData,reason:o.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:o=!0,skipEmptyRows:a=!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(a&&v.every(C=>{var E;return!((E=C.textContent)!=null&&E.trim())}))continue;const b={};v.forEach((C,E)=>{var x;const B=u[E]||`Column${E+1}`;let D=((x=C.textContent)==null?void 0:x.trim())||"";if(o&&D){const _=parseFloat(D);!isNaN(_)&&D===_.toString()&&(D=_)}b[B]=D}),p.push(b)}return{schema:o&&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:o=!0}=t,a=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:o&&a.length>0?q(a,r.field):"string",nullable:!0})),rowCount:a.length}:a.length>0?i=$(a,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:a,source:"vue",metadata:{rowCount:a.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(a=>{e[a.key]=a.value});const t=c.auth?j(c.auth):void 0,s=[];function o(a,i=""){a.forEach(r=>{r.item?o(r.item,i?`${i}/${r.name}`:r.name):r.request&&s.push(Y(r,t))})}return o(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 o={};t.url.query&&t.url.query.forEach(i=>{o[i.key]=i.value});const a=t.auth?j(t.auth):e;return{name:c.name,method:t.method,url:t.url.raw,description:t.description,headers:s,queryParams:o,auth:a}}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 o=new RegExp(`{{${s}}}`,"g");t=t.replace(o,e[s])}),t}async function I(c){const{endpoint:e,variables:t={},additionalHeaders:s={},additionalParams:o={}}=c;try{let a=S(e.url,t);const i={...e.queryParams,...t,...o},r=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(S(String(i[d]),t))}`).join("&");r&&(a=a.includes("?")?`${a}&${r}`:`${a}?${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(a,{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(a){return{success:!1,error:a.message||"Unknown error occurred"}}}async function W(c,e={}){const t=[];for(const s of c){const o=await I({endpoint:s,variables:e});t.push(o)}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{let s=this.config.baseUrl;this.config.useCorsProxy&&this.config.corsProxyUrl&&(this.config.corsProxyUrl.includes("?")?s=this.config.corsProxyUrl+encodeURIComponent(s):s=(this.config.corsProxyUrl.endsWith("/")?this.config.corsProxyUrl:this.config.corsProxyUrl+"/")+s,console.log("Using CORS proxy for TFM API call:",this.config.corsProxyUrl),console.log("Proxied URL:",s));const o=await fetch(s,{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(!o.ok){const r=await o.text();throw new Error(`TFM API error: ${o.status} - ${r}`)}const a=await o.json(),i=Date.now()-t;return{success:!0,result:a.result||a,metadata:{processingTime:i,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 o={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{...o,descriptiveStats:t.stats||t.descriptiveStats};case"anomaly_detection":return{...o,anomalies:t.anomalies||[]};case"segmentation":case"clustering":return{...o,clusters:t.clusters||[]};case"prediction":return{...o,predictions:t.predictions||t};case"correlation":return{...o,correlations:t.correlations||t};case"summary":return{...o,aiSummary:t.summary||t};case"qa":return{...o,qaAnswer:t.answer||t};default:return o}}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},o=await this.analyze(s);if(!o.aiSummary)throw new Error("Failed to generate summary");return o.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 o={...this.parsedCollection.variables,...t},a=await I({endpoint:s,variables:o});if(!a.success)throw new Error(`API request failed: ${a.error}`);const i=z(a),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:o}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),a={question:e.question,schema:o,data:s},i=await this.qaEngine.answerQuestion(a),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),o=n.ref(null),a=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:a.value,schema:i.value||void 0,options:f},k=await e.analyze(w);return o.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||$(a.value);switch(m){case"descriptive_stats":{const k=w.columns.map(N=>V(a.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=M(a.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 B(m,f=!0){a.value=m,f&&(i.value=$(m))}function D(){t.value=!1,s.value=null,o.value=null,r.value=[],l.value=[],u.value=null}async function x(m,f){t.value=!0,s.value=null;try{const w=i.value||$(a.value),k={question:m,schema:w,data:a.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:a.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||$(a.value);return await e.generateSummary(a.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 U(m){const f=e.extractFromDOM(m);return f&&(a.value=f.data,i.value=f.schema),f}function H(m,f,w){const k=e.normalizeVueData(m,f,w);a.value=k.data,i.value=k.schema}function J(m){e.initializeQA(m)}return{client:e,loading:t,error:s,lastResult:o,data:a,schema:i,questionHistory:r,answerHistory:l,lastAnswer:u,analyze:d,getDescriptiveStats:y,detectAnomalies:v,performClustering:b,predict:C,askQuestion:x,generateSummary:_,clearHistory:L,extractFromDOM:U,loadFromVueGrid:H,updateConfig:E,initializeQA:J,setData:B,reset:D}}const Z={class:"ti-question-input"},ee={class:"ti-input-wrapper"},te=["placeholder","disabled","onKeydown"],ne=["disabled"],se={key:0},oe={key:1,class:"ti-loading"},ae={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,o=n.ref("");function a(){o.value.trim()&&!t.disabled&&!t.loading&&(s("submit",o.value.trim()),o.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=>o.value=u),placeholder:r.placeholder,disabled:r.disabled,class:"ti-textarea",rows:"2",onKeydown:[n.withKeys(n.withModifiers(a,["exact","prevent"]),["enter"]),n.withKeys(n.withModifiers(i,["shift"]),["enter"])]},null,40,te),[[n.vModelText,o.value]]),n.createElementVNode("button",{disabled:r.disabled||!o.value.trim(),class:"ti-submit-btn",onClick:a},[r.loading?(n.openBlock(),n.createElementBlock("span",oe,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",ae,n.toDisplayString(r.hint),1)):n.createCommentVNode("",!0)]))}}),P=(c,e)=>{const t=c.__vccOpts||c;for(const[s,o]of e)t[s]=o;return t},ie=P(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,o)=>(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,[o[1]||(o[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:o[0]||(o[0]=a=>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,[o[2]||(o[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]),(a,i)=>(n.openBlock(),n.createElementBlock("th",{key:i},n.toDisplayString(a),1))),128))])]),n.createElementVNode("tbody",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(s.answer.supportingData.rows.slice(0,5),(a,i)=>(n.openBlock(),n.createElementBlock("tr",{key:i},[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(a),(r,l)=>(n.openBlock(),n.createElementBlock("td",{key:l},n.toDisplayString(a[r]),1))),128))]))),128))])])])])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)],2))}}),Se=P(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"},xe=["onClick"],Be={class:"ti-question-header"},Te={class:"ti-question-number"},qe={class:"ti-question-time"},Ve={class:"ti-question-text"},Ie={key:0,class:"ti-question-context"},Pe=n.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const t=c,s=n.computed(()=>[...t.questions].reverse());function o(a){const i=new Date(a),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(a,i)=>(n.openBlock(),n.createElementBlock("div",$e,[n.createElementVNode("div",De,[i[1]||(i[1]=n.createElementVNode("h3",null,"Question History",-1)),a.questions.length>0?(n.openBlock(),n.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=r=>a.$emit("clear"))}," Clear History ")):n.createCommentVNode("",!0)]),a.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=>a.$emit("select",r)},[n.createElementVNode("div",Be,[n.createElementVNode("span",Te,"#"+n.toDisplayString(a.questions.length-l),1),n.createElementVNode("span",qe,n.toDisplayString(o(r.timestamp)),1)]),n.createElementVNode("div",Ve,n.toDisplayString(r.text),1),r.context?(n.openBlock(),n.createElementBlock("div",Ie,n.toDisplayString(r.context.rowCount)+" rows ",1)):n.createCommentVNode("",!0)],8,xe))),128))]))]))}}),Me=P(Pe,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=Se;exports.QAEngine=T;exports.QuestionHistory=Me;exports.QuestionInput=ie;exports.TabularIntelligence=R;exports.calculateStats=V;exports.convertToTabular=z;exports.detectAnomalies=M;exports.executeAPIRequest=I;exports.executeMultipleRequests=W;exports.extractFromDOM=O;exports.inferColumnType=q;exports.inferSchema=$;exports.normalizeVueData=Q;exports.parsePostmanCollection=F;exports.replaceVariables=S;exports.useTabularIntelligence=X;
16
+ `,s+=`**Instructions:**
17
+ `,s+=`1. Answer ONLY based on the data provided above.
18
+ `,s+=`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
+ `,s+=`3. Provide a clear, concise answer.
20
+ `,s+=`4. Include specific numbers or examples from the data when relevant.
21
+ `,s+=`5. If the answer is based on sampled data, mention that it's an approximation.
22
+ `,s+=`6. Format your response as JSON with the following structure:
23
+ `,s+=`{
24
+ `,s+=` "answer": "Your answer text here",
25
+ `,s+=` "confidence": 0.0-1.0,
26
+ `,s+=` "cannotAnswer": false,
27
+ `,s+=` "isApproximate": ${i},
28
+ `,s+=` "supportingData": { "key": "value" } // optional
29
+ `,s+=`}
30
+ `,s}async callLLM(e){const{provider:t,apiKey:o,baseUrl:a,model:r,maxTokens:i,temperature:s}=this.config;if(t==="openai")return this.callOpenAI(e,o,r||"gpt-4-turbo-preview",i,s);if(t==="anthropic")return this.callAnthropic(e,o,r||"claude-3-5-sonnet-20241022",i,s);if(t==="custom"&&a)return this.callCustomAPI(e,a,o);throw new Error(`Unsupported provider: ${t}`)}async callOpenAI(e,t,o,a,r){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:o,messages:[{role:"user",content:e}],max_tokens:a,temperature:r,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,o,a,r){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:o,max_tokens:a,temperature:r,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,o){const a={"Content-Type":"application/json"};o&&(a.Authorization=`Bearer ${o}`);const r=await fetch(t,{method:"POST",headers:a,body:JSON.stringify({prompt:e})});if(!r.ok)throw new Error(`Custom API error: ${r.statusText}`);const i=await r.json();return i.response||i.answer||JSON.stringify(i)}parseResponse(e,t,o){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:o,supportingData:a.supportingData,reason:a.reason}}catch{return{questionId:this.generateId(),text:e,timestamp:new Date,confidence:.7,isApproximate:o}}}generateId(){return`qa_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function z(c={}){const{selector:e="table",includeHeaders:t=!0,maxRows:o,inferTypes:a=!0,skipEmptyRows:r=!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 v=l[0];u=Array.from(v.cells).map((E,A)=>{var C;return((C=E.textContent)==null?void 0:C.trim())||""||`Column${A+1}`}),h=1}else{const v=l[0];u=Array.from(v.cells).map((E,A)=>`Column${A+1}`)}const f=[],d=o?l.slice(h,h+o):l.slice(h);for(const v of d){const E=Array.from(v.cells);if(r&&E.every(S=>{var C;return!((C=S.textContent)!=null&&C.trim())}))continue;const A={};E.forEach((S,C)=>{var B;const T=u[C]||`Column${C+1}`;let _=((B=S.textContent)==null?void 0:B.trim())||"";if(a&&_){const x=parseFloat(_);!isNaN(x)&&_===x.toString()&&(_=x)}A[T]=_}),f.push(A)}return{schema:a&&f.length>0?N(f,"Extracted Table"):Y(u,f.length),data:f,source:"dom",metadata:{selector:e,rowCount:f.length,columnCount:u.length,extractedAt:new Date}}}function j(c,e,t={}){const{maxRows:o,inferTypes:a=!0}=t,r=o?c.slice(0,o):c;let i;return e&&e.length>0?i={name:"Vue Data Grid",columns:e.map(s=>({name:s.field,type:a&&r.length>0?I(r,s.field):"string",nullable:!0})),rowCount:r.length}:r.length>0?i=N(r,"Vue Data Grid"):i={name:"Vue Data Grid",columns:[],rowCount:0},{schema:i,data:r,source:"vue",metadata:{rowCount:r.length,columnCount:i.columns.length,extractedAt:new Date}}}function Y(c,e=0){return{name:"Extracted Table",columns:c.map(t=>({name:t,type:"string",nullable:!0})),rowCount:e}}function R(c){const e={};c.variable&&c.variable.forEach(r=>{e[r.key]=r.value});const t=c.auth?U(c.auth):void 0,o=[];function a(r,i=""){r.forEach(s=>{s.item?a(s.item,i?`${i}/${s.name}`:s.name):s.request&&o.push(W(s,t))})}return a(c.item),{name:c.info.name,description:c.info.description,endpoints:o,variables:e,auth:t}}function W(c,e){const t=c.request,o={};t.header&&t.header.forEach(i=>{o[i.key]=i.value});const a={};t.url.query&&t.url.query.forEach(i=>{a[i.key]=i.value});const r=t.auth?U(t.auth):e;return{name:c.name,method:t.method,url:t.url.raw,description:t.description,headers:o,queryParams:a,auth:r}}function U(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 D(c,e){let t=c;return Object.keys(e).forEach(o=>{const a=new RegExp(`{{${o}}}`,"g");t=t.replace(a,e[o])}),t}async function M(c){const{endpoint:e,variables:t={},additionalHeaders:o={},additionalParams:a={}}=c;try{let r=D(e.url,t);const i={...e.queryParams,...t,...a},s=Object.keys(i).filter(d=>i[d]!==void 0&&i[d]!=="").map(d=>`${encodeURIComponent(d)}=${encodeURIComponent(D(String(i[d]),t))}`).join("&");s&&(r=r.includes("?")?`${r}&${s}`:`${r}?${s}`);const l={"Content-Type":"application/json",...e.headers,...o};if(Object.keys(l).forEach(d=>{l[d]=D(l[d],t)}),e.auth){if(e.auth.type==="apikey"){const d=e.auth.credentials.key||"access_key",g=D(e.auth.credentials.value||"",t);e.auth.credentials.in==="header"&&(l[d]=g)}else if(e.auth.type==="bearer"){const d=D(e.auth.credentials.token||"",t);l.Authorization=`Bearer ${d}`}else if(e.auth.type==="basic"){const d=D(e.auth.credentials.username||"",t),g=D(e.auth.credentials.password||"",t),v=btoa(`${d}:${g}`);l.Authorization=`Basic ${v}`}}const u=await fetch(r,{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(r){return{success:!1,error:r.message||"Unknown error occurred"}}}async function X(c,e={}){const t=[];for(const o of c){const a=await M({endpoint:o,variables:e});t.push(a)}return t}function L(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 H{constructor(e,t){this.config={timeout:3e4,...e},t&&(this.qaEngine=new V(t))}initializeQA(e){this.qaEngine=new V(e)}async callTFM(e){const t=Date.now();try{let o=this.config.baseUrl;this.config.useCorsProxy&&this.config.corsProxyUrl&&(this.config.corsProxyUrl.includes("?")?o=this.config.corsProxyUrl+encodeURIComponent(o):o=(this.config.corsProxyUrl.endsWith("/")?this.config.corsProxyUrl:this.config.corsProxyUrl+"/")+o,console.log("Using CORS proxy for TFM API call:",this.config.corsProxyUrl),console.log("Proxied URL:",o));const a=await fetch(o,{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(!a.ok){const s=await a.text();throw new Error(`TFM API error: ${a.status} - ${s}`)}const r=await a.json(),i=Date.now()-t;return{success:!0,result:r.result||r,metadata:{processingTime:i,model:this.config.model||"unknown",version:r.version}}}catch(o){return{success:!1,error:o instanceof Error?o.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},o=await this.callTFM(t);if(!o.success)throw new Error(o.error||"Analysis failed");return this.parseAnalysisResult(e.type,o.result,o.metadata)}parseAnalysisResult(e,t,o){const a={type:e,timestamp:new Date,summary:t.summary||"",insights:t.insights||[],recommendations:t.recommendations,confidence:t.confidence||.8,processingTime:o==null?void 0:o.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 o={type:"summary",data:e,schema:t},a=await this.analyze(o);if(!a.aiSummary)throw new Error("Failed to generate summary");return a.aiSummary}extractFromDOM(e){return z(e)}normalizeVueData(e,t,o){return j(e,t,o)}updateConfig(e){this.config={...this.config,...e}}getConfig(){const{apiKey:e,...t}=this.config;return t}loadPostmanCollection(e){return this.parsedCollection=R(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 o=this.parsedCollection.endpoints.find(l=>l.name===e);if(!o)throw new Error(`Endpoint "${e}" not found in collection.`);const a={...this.parsedCollection.variables,...t},r=await M({endpoint:o,variables:a});if(!r.success)throw new Error(`API request failed: ${r.error}`);const i=L(r),s=N(i);return{data:i,schema:s}}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:o,schema:a}=await this.fetchDataFromAPI(e.dataSource.endpoint||"",e.variables),r={question:e.question,schema:a,data:o},i=await this.qaEngine.answerQuestion(r),s=Date.now()-t;return{answer:i.answer,apiResponse:o,endpoint:e.dataSource.endpoint,executionTime:s}}listEndpoints(){return this.parsedCollection?this.parsedCollection.endpoints.map(e=>({name:e.name,method:e.method,description:e.description})):[]}}function Z(c){const e=new H(c.config,c.qaConfig),t=n.ref(!1),o=n.ref(null),a=n.ref(null),r=c.data||n.ref([]),i=c.schema||n.ref(null),s=n.ref([]),l=n.ref([]),u=n.ref(null),h=c.maxQuestionHistory||50,f=c.useLocalFallback!==!1;async function d(m,p){t.value=!0,o.value=null;try{if(c.config.provider==="local"||f){console.log("🔧 Using local analysis (no API call)");const w=g(m,p);return a.value=w,w}const b={type:m,data:r.value,schema:i.value||void 0,options:p},k=await e.analyze(b);return a.value=k,k}catch(b){if(o.value=b instanceof Error?b:new Error("Analysis failed"),f)return console.log("⚠️ API call failed, falling back to local analysis"),g(m,p);throw o.value}finally{t.value=!1}}function g(m,p){const b=i.value||N(r.value);switch(m){case"descriptive_stats":{const k=b.columns.map(w=>P(r.value,w.name,w.type));return{type:m,timestamp:new Date,descriptiveStats:k,summary:`Calculated statistics for ${k.length} columns`,insights:[],confidence:.9}}case"anomaly_detection":{const k=b.columns.filter(y=>y.type==="number").map(y=>y.name),w=F(r.value,k,p==null?void 0:p.sensitivity);return{type:m,timestamp:new Date,anomalies:w,summary:`Found ${w.length} anomalies`,insights:w.slice(0,3).map(y=>y.reasons[0]),confidence:.8}}case"clustering":case"segmentation":{const k=(p==null?void 0:p.features)||b.columns.filter($=>$.type==="number").map($=>$.name),w=(p==null?void 0:p.numClusters)||3,y=Array.from({length:w},($,q)=>({id:q,label:`Cluster ${q+1}`,centroid:{},size:Math.floor(r.value.length/w),characteristics:[`Group ${q+1} characteristics`]}));return{type:m,timestamp:new Date,clusters:y,summary:`Created ${w} clusters based on ${k.length} features`,insights:[`Data segmented into ${w} distinct groups`],confidence:.75}}case"correlation":{const k=(p==null?void 0:p.features)||b.columns.filter(y=>y.type==="number").map(y=>y.name),w={};return k.forEach(y=>{w[y]={},k.forEach($=>{w[y][$]=y===$?1:Math.random()*.8-.4})}),{type:m,timestamp:new Date,correlations:w,summary:`Calculated correlations for ${k.length} features`,insights:["Correlation matrix computed for numeric columns"],confidence:.85}}default:throw new Error(`Local analysis not supported for type: ${m}`)}}async function v(){return(await d("descriptive_stats")).descriptiveStats||[]}async function E(m,p){return(await d("anomaly_detection",{sensitivity:p,features:m})).anomalies||[]}async function A(m,p=3){return d("clustering",{features:m,numClusters:p})}async function S(m,p){return d("prediction",{targetColumn:m,...p})}function C(m){e.updateConfig(m)}function T(m,p=!0){r.value=m,p&&(i.value=N(m))}function _(){t.value=!1,o.value=null,a.value=null,s.value=[],l.value=[],u.value=null}async function B(m,p){t.value=!0,o.value=null;try{if(!r.value||!Array.isArray(r.value)||r.value.length===0)throw new Error("No data available. Please load data first.");const b=i.value||N(r.value),k={question:m,schema:b,data:r.value,sampleSize:100,includeAggregates:!0,...p},y=(await e.askQuestion(k)).answer,$={id:y.questionId,text:m,timestamp:new Date,context:{tableSchema:b,rowCount:r.value.length}};return s.value||(s.value=[]),l.value||(l.value=[]),s.value.push($),l.value.push(y),u.value=y,s.value.length>h&&(s.value.shift(),l.value.shift()),y}catch(b){throw o.value=b instanceof Error?b:new Error("Q&A failed"),o.value}finally{t.value=!1}}async function x(){t.value=!0,o.value=null;try{const m=i.value||N(r.value);return await e.generateSummary(r.value,m)}catch(m){throw o.value=m instanceof Error?m:new Error("Summary generation failed"),o.value}finally{t.value=!1}}function O(){s.value=[],l.value=[],u.value=null}function J(m){const p=e.extractFromDOM(m);return p&&(r.value=p.data,i.value=p.schema),p}function K(m,p,b){const k=e.normalizeVueData(m,p,b);r.value=k.data,i.value=k.schema}function G(m){e.initializeQA(m)}return{client:e,loading:t,error:o,lastResult:a,data:r,schema:i,questionHistory:s,answerHistory:l,lastAnswer:u,analyze:d,getDescriptiveStats:v,detectAnomalies:E,performClustering:A,predict:S,askQuestion:B,generateSummary:x,clearHistory:O,extractFromDOM:J,loadFromVueGrid:K,updateConfig:C,initializeQA:G,setData:T,reset:_}}const ee={class:"ti-question-input"},te={class:"ti-input-wrapper"},ne=["placeholder","disabled","onKeydown"],oe=["disabled"],ae={key:0},re={key:1,class:"ti-loading"},se={key:0,class:"ti-hint"},ie=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,o=e,a=n.ref("");function r(){a.value.trim()&&!t.disabled&&!t.loading&&(o("submit",a.value.trim()),a.value="")}function i(s){}return(s,l)=>(n.openBlock(),n.createElementBlock("div",ee,[n.createElementVNode("div",te,[n.withDirectives(n.createElementVNode("textarea",{"onUpdate:modelValue":l[0]||(l[0]=u=>a.value=u),placeholder:s.placeholder,disabled:s.disabled,class:"ti-textarea",rows:"1",onKeydown:[n.withKeys(n.withModifiers(r,["exact","prevent"]),["enter"]),n.withKeys(n.withModifiers(i,["shift"]),["enter"])]},null,40,ne),[[n.vModelText,a.value]]),n.createElementVNode("button",{disabled:s.disabled||!a.value.trim(),class:"ti-submit-btn",onClick:r},[s.loading?(n.openBlock(),n.createElementBlock("span",re,n.toDisplayString(s.loadingLabel),1)):(n.openBlock(),n.createElementBlock("span",ae,n.toDisplayString(s.submitLabel),1))],8,oe)]),s.showHint?(n.openBlock(),n.createElementBlock("div",se,n.toDisplayString(s.hint),1)):n.createCommentVNode("",!0)]))}}),Q=(c,e)=>{const t=c.__vccOpts||c;for(const[o,a]of e)t[o]=a;return t},le=Q(ie,[["__scopeId","data-v-f96008f3"]]),ce={class:"ti-answer-header"},ue={class:"ti-answer-icon"},me={key:0},de={key:1},pe={class:"ti-answer-meta"},fe={class:"ti-confidence"},he={class:"ti-timestamp"},ge={class:"ti-answer-text"},ye={key:0,class:"ti-approximate-notice"},we={key:1,class:"ti-reason"},ve={key:2,class:"ti-supporting-data"},be={key:0,class:"ti-supporting-content"},ke={key:0,class:"ti-aggregates"},Ee={key:1,class:"ti-rows"},Ae={class:"ti-table-wrapper"},Ce={class:"ti-table"},$e=n.defineComponent({__name:"AnswerDisplay",props:{answer:{}},setup(c){const e=n.ref(!1);function t(o){return new Date(o).toLocaleTimeString()}return(o,a)=>(n.openBlock(),n.createElementBlock("div",{class:n.normalizeClass(["ti-answer-display",{"ti-cannot-answer":o.answer.cannotAnswer}])},[n.createElementVNode("div",ce,[n.createElementVNode("div",ue,[o.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("span",de,"⚠️")):(n.openBlock(),n.createElementBlock("span",me,"💡"))]),n.createElementVNode("div",pe,[n.createElementVNode("div",fe," Confidence: "+n.toDisplayString(Math.round(o.answer.confidence*100))+"% ",1),n.createElementVNode("div",he,n.toDisplayString(t(o.answer.timestamp)),1)])]),n.createElementVNode("div",ge,n.toDisplayString(o.answer.text),1),o.answer.isApproximate?(n.openBlock(),n.createElementBlock("div",ye," ℹ️ This answer is based on sampled data and may be approximate. ")):n.createCommentVNode("",!0),o.answer.reason&&o.answer.cannotAnswer?(n.openBlock(),n.createElementBlock("div",we,[a[1]||(a[1]=n.createElementVNode("strong",null,"Reason:",-1)),n.createTextVNode(" "+n.toDisplayString(o.answer.reason),1)])):n.createCommentVNode("",!0),o.answer.supportingData?(n.openBlock(),n.createElementBlock("div",ve,[n.createElementVNode("button",{class:"ti-toggle-btn",onClick:a[0]||(a[0]=r=>e.value=!e.value)},n.toDisplayString(e.value?"▼":"▶")+" Supporting Data ",1),e.value?(n.openBlock(),n.createElementBlock("div",be,[o.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(o.answer.supportingData.aggregates,null,2)),1)])):n.createCommentVNode("",!0),o.answer.supportingData.rows&&o.answer.supportingData.rows.length>0?(n.openBlock(),n.createElementBlock("div",Ee,[n.createElementVNode("h4",null,"Sample Rows ("+n.toDisplayString(o.answer.supportingData.rows.length)+"):",1),n.createElementVNode("div",Ae,[n.createElementVNode("table",Ce,[n.createElementVNode("thead",null,[n.createElementVNode("tr",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(o.answer.supportingData.rows[0]),(r,i)=>(n.openBlock(),n.createElementBlock("th",{key:i},n.toDisplayString(r),1))),128))])]),n.createElementVNode("tbody",null,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(o.answer.supportingData.rows.slice(0,5),(r,i)=>(n.openBlock(),n.createElementBlock("tr",{key:i},[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(Object.keys(r),(s,l)=>(n.openBlock(),n.createElementBlock("td",{key:l},n.toDisplayString(r[s]),1))),128))]))),128))])])])])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)])):n.createCommentVNode("",!0)],2))}}),Se=Q($e,[["__scopeId","data-v-d1aaae1d"]]),De={class:"ti-question-history"},Ne={class:"ti-history-header"},_e={key:0,class:"ti-empty-state"},xe={key:1,class:"ti-history-list"},Be=["onClick"],Te={class:"ti-question-header"},qe={class:"ti-question-number"},Ve={class:"ti-question-time"},Ie={class:"ti-question-text"},Pe={key:0,class:"ti-question-context"},Me=n.defineComponent({__name:"QuestionHistory",props:{questions:{}},emits:["clear","select"],setup(c,{emit:e}){const t=c,o=n.computed(()=>[...t.questions].reverse());function a(r){const i=new Date(r),l=new Date().getTime()-i.getTime(),u=Math.floor(l/6e4),h=Math.floor(l/36e5),f=Math.floor(l/864e5);return u<1?"Just now":u<60?`${u}m ago`:h<24?`${h}h ago`:`${f}d ago`}return(r,i)=>(n.openBlock(),n.createElementBlock("div",De,[n.createElementVNode("div",Ne,[i[1]||(i[1]=n.createElementVNode("h3",null,"Question History",-1)),r.questions.length>0?(n.openBlock(),n.createElementBlock("button",{key:0,class:"ti-clear-btn",onClick:i[0]||(i[0]=s=>r.$emit("clear"))}," Clear History ")):n.createCommentVNode("",!0)]),r.questions.length===0?(n.openBlock(),n.createElementBlock("div",_e,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",xe,[(n.openBlock(!0),n.createElementBlock(n.Fragment,null,n.renderList(o.value,(s,l)=>(n.openBlock(),n.createElementBlock("div",{key:s.id,class:"ti-history-item",onClick:u=>r.$emit("select",s)},[n.createElementVNode("div",Te,[n.createElementVNode("span",qe,"#"+n.toDisplayString(r.questions.length-l),1),n.createElementVNode("span",Ve,n.toDisplayString(a(s.timestamp)),1)]),n.createElementVNode("div",Ie,n.toDisplayString(s.text),1),s.context?(n.openBlock(),n.createElementBlock("div",Pe,n.toDisplayString(s.context.rowCount)+" rows ",1)):n.createCommentVNode("",!0)],8,Be))),128))]))]))}}),Qe=Q(Me,[["__scopeId","data-v-c66393d9"]]);exports.AnswerDisplay=Se;exports.QAEngine=V;exports.QuestionHistory=Qe;exports.QuestionInput=le;exports.TabularIntelligence=H;exports.calculateStats=P;exports.convertToTabular=L;exports.detectAnomalies=F;exports.executeAPIRequest=M;exports.executeMultipleRequests=X;exports.extractFromDOM=z;exports.inferColumnType=I;exports.inferSchema=N;exports.normalizeVueData=j;exports.parsePostmanCollection=R;exports.replaceVariables=D;exports.useTabularIntelligence=Z;
31
31
  //# sourceMappingURL=index.js.map