@autoai-ui/autoui 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,74 @@
1
+ import { existsSync as p, writeFileSync as f } from "node:fs";
2
+ import { resolve as a } from "node:path";
3
+ import { Project as d } from "ts-morph";
4
+ import { l as S, a as w } from "./standalone-qbUKaa9E.js";
5
+ function N(s = {}) {
6
+ return (e = {}) => {
7
+ const i = s.runtimeSchemaFile || ".autoui-runtime-schema.json";
8
+ return {
9
+ ...e,
10
+ webpack: (o, { isServer: t, dev: r }) => (typeof e.webpack == "function" && (o = e.webpack(o, { isServer: t, dev: r })), !t && r && (o.plugins = o.plugins || [], o.plugins.push(
11
+ new I({
12
+ appId: s.appId,
13
+ version: s.version,
14
+ runtimeSchemaFile: i
15
+ })
16
+ )), o)
17
+ };
18
+ };
19
+ }
20
+ class I {
21
+ options;
22
+ constructor(e) {
23
+ this.options = {
24
+ appId: e.appId || "unknown",
25
+ version: e.version || "1.0.0",
26
+ runtimeSchemaFile: e.runtimeSchemaFile || ".autoui-runtime-schema.json"
27
+ };
28
+ }
29
+ apply(e) {
30
+ e.hooks.beforeCompile.tapAsync(
31
+ "AutoUISchemaWebpackPlugin",
32
+ async (i, o) => {
33
+ await this.generateSchema(), o();
34
+ }
35
+ );
36
+ }
37
+ async generateSchema() {
38
+ if (process.env.NODE_ENV === "production") {
39
+ console.log("[AutoUI Next.js Plugin] Skipping schema generation in production build. Using existing schema file.");
40
+ return;
41
+ }
42
+ const i = process.env.NODE_ENV || "development", t = { ...S(i), ...process.env }, r = this.options.appId === "unknown" ? t.AUTOUI_APP_ID || "unknown" : this.options.appId, g = this.options.version === "1.0.0" ? t.AUTOUI_VERSION || "1.0.0" : this.options.version;
43
+ try {
44
+ let n = a(process.cwd(), "tsconfig.json");
45
+ if (p(n) || (n = a(process.cwd(), "tsconfig.app.json")), !p(n)) {
46
+ console.warn("[AutoUI Next.js Plugin] No tsconfig.json or tsconfig.app.json found, skipping schema extraction");
47
+ return;
48
+ }
49
+ const l = new d({
50
+ tsConfigFilePath: n
51
+ });
52
+ if (l.getSourceFiles().filter(
53
+ (c) => !c.isDeclarationFile() && !c.getFilePath().includes("node_modules")
54
+ ).length === 0) {
55
+ console.warn("[AutoUI Next.js Plugin] No source files found after filtering!");
56
+ return;
57
+ }
58
+ const u = w(l, r, g);
59
+ if (u.components.length === 0 && u.functions.length === 0)
60
+ return;
61
+ const m = a(process.cwd(), this.options.runtimeSchemaFile), h = a(m, "..");
62
+ if (!p(h)) {
63
+ const { mkdirSync: c } = await import("node:fs");
64
+ c(h, { recursive: !0 });
65
+ }
66
+ f(m, JSON.stringify(u, null, 2), "utf-8"), console.log(`[AutoUI Next.js Plugin] Schema written to ${this.options.runtimeSchemaFile}`);
67
+ } catch (n) {
68
+ console.error("❌ [AutoUI Next.js Plugin] Error in plugin:", n), n instanceof Error && (console.error(` Error message: ${n.message}`), n.stack && console.error(` Stack trace: ${n.stack}`));
69
+ }
70
+ }
71
+ }
72
+ export {
73
+ N as w
74
+ };
@@ -0,0 +1 @@
1
+ "use strict";var S=Object.create;var g=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var v=Object.getPrototypeOf,P=Object.prototype.hasOwnProperty;var k=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of w(e))!P.call(n,o)&&o!==t&&g(n,o,{get:()=>e[o],enumerable:!(s=I(e,o))||s.enumerable});return n};var U=(n,e,t)=>(t=n!=null?S(v(n)):{},k(e||!n||!n.__esModule?g(t,"default",{value:n,enumerable:!0}):t,n));const a=require("node:fs"),u=require("node:path"),j=require("ts-morph"),d=require("./standalone-Xrc3J06Y.cjs");function A(n={}){return(e={})=>{const t=n.runtimeSchemaFile||".autoui-runtime-schema.json";return{...e,webpack:(s,{isServer:o,dev:r})=>(typeof e.webpack=="function"&&(s=e.webpack(s,{isServer:o,dev:r})),!o&&r&&(s.plugins=s.plugins||[],s.plugins.push(new F({appId:n.appId,version:n.version,runtimeSchemaFile:t}))),s)}}}class F{options;constructor(e){this.options={appId:e.appId||"unknown",version:e.version||"1.0.0",runtimeSchemaFile:e.runtimeSchemaFile||".autoui-runtime-schema.json"}}apply(e){e.hooks.beforeCompile.tapAsync("AutoUISchemaWebpackPlugin",async(t,s)=>{await this.generateSchema(),s()})}async generateSchema(){if(process.env.NODE_ENV==="production"){console.log("[AutoUI Next.js Plugin] Skipping schema generation in production build. Using existing schema file.");return}const t=process.env.NODE_ENV||"development",o={...d.loadEnvVars(t),...process.env},r=this.options.appId==="unknown"?o.AUTOUI_APP_ID||"unknown":this.options.appId,f=this.options.version==="1.0.0"?o.AUTOUI_VERSION||"1.0.0":this.options.version;try{let i=u.resolve(process.cwd(),"tsconfig.json");if(a.existsSync(i)||(i=u.resolve(process.cwd(),"tsconfig.app.json")),!a.existsSync(i)){console.warn("[AutoUI Next.js Plugin] No tsconfig.json or tsconfig.app.json found, skipping schema extraction");return}const p=new j.Project({tsConfigFilePath:i});if(p.getSourceFiles().filter(c=>!c.isDeclarationFile()&&!c.getFilePath().includes("node_modules")).length===0){console.warn("[AutoUI Next.js Plugin] No source files found after filtering!");return}const l=d.generateSchema(p,r,f);if(l.components.length===0&&l.functions.length===0)return;const h=u.resolve(process.cwd(),this.options.runtimeSchemaFile),m=u.resolve(h,"..");if(!a.existsSync(m)){const{mkdirSync:c}=await import("node:fs");c(m,{recursive:!0})}a.writeFileSync(h,JSON.stringify(l,null,2),"utf-8"),console.log(`[AutoUI Next.js Plugin] Schema written to ${this.options.runtimeSchemaFile}`)}catch(i){console.error("❌ [AutoUI Next.js Plugin] Error in plugin:",i),i instanceof Error&&(console.error(` Error message: ${i.message}`),i.stack&&console.error(` Stack trace: ${i.stack}`))}}}exports.withAutoUI=A;
package/dist/index.cjs CHANGED
@@ -206,7 +206,7 @@ CRITICAL RULES FOR newInstructionPlan:
206
206
  - Example: If TaskStats requires "tasks" prop, use: { "tasks": "{{tasks}}" } NOT { "filter": "food" }
207
207
  - Example: If ProductCard has "addToCart" callback, use: { "callbacks": { "onAction": "addToCart" } } or props: { "onAddToCart": "addToCart" }
208
208
 
209
- Return JSON only.`.trim()};function qs(e){if(e==null)throw new Error("Invalid LLM response: null or undefined");if(typeof e=="string"){let r=e;const a=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);a&&(r=a[1].trim());try{e=JSON.parse(r)}catch{throw new Error(`Invalid LLM response: content is a string but not valid JSON: ${e.substring(0,100)}`)}}if(typeof e!="object"||Array.isArray(e))throw new Error(`Invalid LLM response: expected object but got ${typeof e}${Array.isArray(e)?" (array)":""}`);const{parseTo:t,data:o,newInstructionPlan:n}=e;if(o===void 0)throw new Error("Invalid LLM response: missing data field");let s;if(t==="array")if(Array.isArray(o))s=o;else if(typeof o=="object"&&o!==null&&!Array.isArray(o)){const r=Object.values(o);if(r.length!==1)throw new Error(`LLM data object must contain exactly one value when parseTo is 'array', got ${r.length}`);if(s=r[0],!Array.isArray(s))throw new Error(`Expected array but got ${typeof s}`)}else throw new Error(`Expected array or object containing array, got ${typeof o}`);else if(t==="object"){if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`Expected object but got ${Array.isArray(o)?"array":typeof o}`);const r=Object.values(o);if(r.length!==1)throw new Error(`LLM data object must contain exactly one value when parseTo is 'object', got ${r.length}`);s=r[0]}else s=o;return{parseTo:t??"primitive",data:s,newInstructionPlan:n??null}}const Gs=async(e,t,o,n,s,r,a,i)=>{try{const l=await Js(e,t,o,n,s,r,a,i);console.log(`📤 [ExtraAnalysis] Sending request to LLM (prompt length: ${l.length} chars)`);const c=t.llm.proxyUrl??"https://autoui-proxy.onrender.com",u=await fetch(`${c}/chat/extraAnalysis`,{method:"POST",headers:{"Content-Type":"application/json","X-AUTOUI-APP-ID":t.appId,...t.llm.sharedSecret&&{"X-AUTOUI-SECRET":t.llm.sharedSecret}},body:JSON.stringify({messages:[{role:"user",content:l}],temperature:t.llm.temperature??.2,appId:t.appId})});if(!u.ok){const b=await u.text();throw console.error(`❌ [ExtraAnalysis] API error ${u.status}:`,b),new Error(`AutoUI proxy error: ${u.status} - ${b}`)}let f=await u.text();console.log("✅ [ExtraAnalysis] Raw response received (text):",f.substring(0,200));const d=f.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);d&&(f=d[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks"));let m;try{m=JSON.parse(f),console.log("✅ [ExtraAnalysis] Parsed JSON response")}catch(b){throw console.error("❌ [ExtraAnalysis] Response is not valid JSON:",b),console.error("❌ [ExtraAnalysis] Response text:",f),new Error(`Invalid JSON response from LLM: ${f.substring(0,200)}`)}if(m&&typeof m=="object"){if("content"in m&&typeof m.content=="string")try{let b=m.content;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);x&&(b=x[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks from nested content")),m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed content from wrapper")}catch{console.warn("⚠️ [ExtraAnalysis] content.content is not JSON, using original")}else if("response"in m)if(typeof m.response=="string"){let b=m.response;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);if(x){b=x[1].trim();try{m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed response from wrapper (stripped markdown)")}catch{m=b,console.log("✅ [ExtraAnalysis] Extracted response from wrapper (as string)")}}else m=m.response,console.log("✅ [ExtraAnalysis] Extracted response from wrapper")}else m=m.response,console.log("✅ [ExtraAnalysis] Extracted response from wrapper");else if("message"in m&&typeof m.message=="string")try{let b=m.message;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);x&&(b=x[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks from message")),m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed message from wrapper")}catch{console.warn("⚠️ [ExtraAnalysis] message is not JSON, using original")}}console.log("✅ [ExtraAnalysis] Final content to parse:",typeof m,m);const S=qs(m);return console.log("✅ [ExtraAnalysis] Parsed response:",{hasData:!!S.data,hasNewPlan:!!S.newInstructionPlan,parseTo:S.parseTo}),S}catch(l){return console.error("❌ [ExtraAnalysis] Error during analysis:",l),{parseTo:i?.parseTo??"primitive",data:e,newInstructionPlan:null}}},Ys=async(e,t,o,n,s,r,a,i,l,c,u,f,d)=>{console.log(`🔍 [AnalyzeDataStep] Starting analysis for step "${n.name}" at index ${s}`),console.log("🔍 [AnalyzeDataStep] Output data type:",typeof t,Array.isArray(t)?"array":"object"),console.log("🔍 [AnalyzeDataStep] Assign key:",o),console.log("🔍 [AnalyzeDataStep] Next step:",r?.type,r?.type==="component"||r?.type==="function"?r.name:"");const m=c.steps.slice(s+1);let S=null;if(o&&m.length>0){const{getExpectedSchemaForAssignKey:b}=await Promise.resolve().then(()=>Ds);S=await b(o,m,e),S?console.log(`📋 [AnalyzeDataStep] Expected schema found for assign key "${o}":`,S):console.log(`ℹ️ [AnalyzeDataStep] No expected schema - no remaining steps consume assign key "${o}"`)}else console.log("ℹ️ [AnalyzeDataStep] No expected schema - no assign key or no remaining steps");try{console.log("🚀 [AnalyzeDataStep] Calling extraAnalysisWithLLM...");const b=await Gs(t,e,a,i,c,n,s,S);console.log("✅ [AnalyzeDataStep] Received analysis result:",{hasData:!!b.data,hasNewPlan:!!b.newInstructionPlan,parseTo:b.parseTo});const x=En(r,o),g=kn(b.data,x);if(console.log("Extra analysis data received from LLM:",b),console.log("Normalized ctx value:",g),o&&(l[o]=g),b.newInstructionPlan!=null&&b.newInstructionPlan!=""){if(console.log("analyzed.newInstructionPlan: ",b.newInstructionPlan),o){const h=JSON.parse(JSON.stringify(b.newInstructionPlan));h.steps&&h.steps.forEach(y=>{y.type==="component"&&y.props&&Object.keys(y.props).forEach(I=>{typeof y.props[I]=="string"&&y.props[I]==="{{data}}"&&(y.props[I]=`{{${o}}}`)})}),Rt(h,e,u,f,d,a,i,l)}else Rt(b.newInstructionPlan,e,u,f,d,a,i,l);return!0}return!1}catch(b){return console.error(b),!0}},Tt=new Map,Vo=new Set;async function Xs(e){const t=e;if(Vo.has(t))return Tt.get(t)||null;Vo.add(t);try{let o;if(t.startsWith("http://")||t.startsWith("https://")){console.log(`📥 [Runtime Validation] Fetching schema from URL: ${t}`);const n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch schema: ${n.status} ${n.statusText}`);o=await n.json()}else{const n=[t.startsWith("/")?t:`/${t}`,`/public/${t}`,t];let s=null;for(const r of n)try{console.log(`📥 [Runtime Validation] Trying to fetch schema from: ${r}`);const a=await fetch(r);if(a.ok){o=await a.json(),console.log(`✅ [Runtime Validation] Successfully loaded schema from: ${r}`);break}else s=new Error(`HTTP ${a.status}: ${a.statusText}`)}catch(a){s=a instanceof Error?a:new Error(String(a));continue}if(!o)throw s||new Error(`Failed to load schema from any path: ${n.join(", ")}`)}return o&&o.types&&o.components&&o.functions?(console.log("✅ [Runtime Validation] Runtime schema loaded successfully",{path:t,types:Object.keys(o.types).length,components:o.components.length,functions:o.functions.length}),Tt.set(t,o),o):(console.warn("⚠️ [Runtime Validation] Runtime schema has invalid structure"),Tt.set(t,null),null)}catch(o){return console.warn(`⚠️ [Runtime Validation] Runtime schema file not found at "${t}":`,o),Tt.set(t,null),null}}async function so(e){const t=e?.runtime?.runtimeSchemaPath||".autoui-runtime-schema.json";return await Xs(t)}function Je(e,t){return t.types[e]||null}function at(e,t,o,n,s=""){const r=[],a=s||"value",i=" ".repeat((s.match(/\./g)||[]).length+1);if(console.log(`${i}🔎 [Type Validation] Validating "${a}" against type "${o}"`),console.log(`${i} 📦 Value:`,e),console.log(`${i} 🔍 Value type: ${typeof e}, isArray: ${Array.isArray(e)}, isNull: ${e===null}`),console.log(`${i} 📋 Type definition:`,JSON.stringify(t,null,2)),e==null)return console.log(`${i} ℹ️ Value is ${e===void 0?"undefined":"null"} - skipping (optionality checked at prop/param level)`),r;switch(t.type){case"primitive":if(console.log(`${i} 🔍 Checking primitive type: "${o}"`),o==="string"&&typeof e!="string"){const l=`${a} must be a string, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else if(o==="number"&&(typeof e!="number"||isNaN(e))){const l=`${a} must be a number, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else if(o==="boolean"&&typeof e!="boolean"){const l=`${a} must be a boolean, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else console.log(`${i} ✅ Primitive type check passed`);break;case"enum":if(console.log(`${i} 🔍 Checking enum type with values:`,t.values),t.values&&Array.isArray(t.values))if(t.values.includes(e))console.log(`${i} ✅ Enum value check passed`);else{const l=`${a} must be one of: ${t.values.join(", ")}, got: ${e}`;console.log(`${i} ❌ ${l}`),r.push(l)}break;case"array":if(console.log(`${i} 🔍 Checking array type`),Array.isArray(e)){if(console.log(`${i} ✅ Array type check passed (length: ${e.length})`),t.items){const l=t.items.type;console.log(`${i} 🔍 Validating array items against type: "${l}"`);const c=Je(l,n);c?e.forEach((u,f)=>{console.log(`${i} 📦 Validating item [${f}]:`,u);const d=at(u,c,l,n,`${s}[${f}]`);r.push(...d)}):console.log(`${i} ⚠️ Item type "${l}" not found in schema`)}}else{const l=`${a} must be an array, got ${typeof e}`;if(console.log(`${i} ❌ ${l}`),console.log(`${i} 💡 Value is:`,e),console.log(`${i} 💡 Value constructor:`,e?.constructor?.name),typeof e=="string"){console.log(`${i} 💡 String value might be JSON - attempting to parse...`);try{const c=JSON.parse(e);console.log(`${i} 💡 Parsed successfully! Type: ${typeof c}, isArray: ${Array.isArray(c)}`),Array.isArray(c)&&console.log(`${i} ⚠️ WARNING: Value is a JSON string that should be parsed before validation!`)}catch{console.log(`${i} 💡 String is not valid JSON`)}}r.push(l)}break;case"object":if(console.log(`${i} 🔍 Checking object type`),typeof e!="object"||e===null||Array.isArray(e)){const l=`${a} must be an object, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else t.properties&&(console.log(`${i} ✅ Object type check passed`),console.log(`${i} 🔍 Validating object properties:`,Object.keys(t.properties)),Object.entries(t.properties).forEach(([l,c])=>{const u=e[l],f=s?`${s}.${l}`:l;if(console.log(`${i} 📦 Property "${l}":`,u),c.required&&u==null){const d=`${f} is required but was ${u===void 0?"undefined":"null"}`;console.log(`${i} ❌ ${d}`),r.push(d)}if(u!=null){const d=Je(c.type,n);if(d){const m=at(u,d,c.type,n,f);r.push(...m)}}}));break;case"union":if(console.log(`${i} 🔍 Checking union type with members:`,t.refs),t.refs&&t.refs.length>0){const l=[];for(const u of t.refs){console.log(`${i} 🔍 Trying union member: "${u}"`);const f=Je(u,n);if(f){const d=at(e,f,u,n,s);if(d.length===0)return console.log(`${i} ✅ Union member "${u}" validated successfully`),[];console.log(`${i} ❌ Union member "${u}" failed:`,d),l.push(...d)}}const c=`${a} does not match any union member. Errors: ${l.join("; ")}`;console.log(`${i} ❌ ${c}`),r.push(c)}break}return r.length===0?console.log(`${i} ✅ Type validation passed for "${a}"`):console.log(`${i} ❌ Type validation failed for "${a}" with ${r.length} error(s)`),r}function Zs(e,t,o){const n=[];console.log(`
209
+ Return JSON only.`.trim()};function qs(e){if(e==null)throw new Error("Invalid LLM response: null or undefined");if(typeof e=="string"){let r=e;const a=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);a&&(r=a[1].trim());try{e=JSON.parse(r)}catch{throw new Error(`Invalid LLM response: content is a string but not valid JSON: ${e.substring(0,100)}`)}}if(typeof e!="object"||Array.isArray(e))throw new Error(`Invalid LLM response: expected object but got ${typeof e}${Array.isArray(e)?" (array)":""}`);const{parseTo:t,data:o,newInstructionPlan:n}=e;if(o===void 0)throw new Error("Invalid LLM response: missing data field");let s;if(t==="array")if(Array.isArray(o))s=o;else if(typeof o=="object"&&o!==null&&!Array.isArray(o)){const r=Object.values(o);if(r.length!==1)throw new Error(`LLM data object must contain exactly one value when parseTo is 'array', got ${r.length}`);if(s=r[0],!Array.isArray(s))throw new Error(`Expected array but got ${typeof s}`)}else throw new Error(`Expected array or object containing array, got ${typeof o}`);else if(t==="object"){if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`Expected object but got ${Array.isArray(o)?"array":typeof o}`);const r=Object.values(o);if(r.length!==1)throw new Error(`LLM data object must contain exactly one value when parseTo is 'object', got ${r.length}`);s=r[0]}else s=o;return{parseTo:t??"primitive",data:s,newInstructionPlan:n??null}}const Gs=async(e,t,o,n,s,r,a,i)=>{try{const l=await Js(e,t,o,n,s,r,a,i);console.log(`📤 [ExtraAnalysis] Sending request to LLM (prompt length: ${l.length} chars)`);const c=t.llm.proxyUrl??"https://autoui-proxy.onrender.com",u=await fetch(`${c}/chat/extraAnalysis`,{method:"POST",headers:{"Content-Type":"application/json","X-AUTOUI-APP-ID":t.appId,...t.llm.sharedSecret&&{"X-AUTOUI-SECRET":t.llm.sharedSecret}},body:JSON.stringify({messages:[{role:"user",content:l}],temperature:t.llm.temperature??.2,appId:t.appId})});if(!u.ok){const b=await u.text();throw console.error(`❌ [ExtraAnalysis] API error ${u.status}:`,b),new Error(`AutoUI proxy error: ${u.status} - ${b}`)}let f=await u.text();console.log("✅ [ExtraAnalysis] Raw response received (text):",f.substring(0,200));const d=f.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);d&&(f=d[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks"));let m;try{m=JSON.parse(f),console.log("✅ [ExtraAnalysis] Parsed JSON response")}catch(b){throw console.error("❌ [ExtraAnalysis] Response is not valid JSON:",b),console.error("❌ [ExtraAnalysis] Response text:",f),new Error(`Invalid JSON response from LLM: ${f.substring(0,200)}`)}if(m&&typeof m=="object"){if("content"in m&&typeof m.content=="string")try{let b=m.content;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);x&&(b=x[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks from nested content")),m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed content from wrapper")}catch{console.warn("⚠️ [ExtraAnalysis] content.content is not JSON, using original")}else if("response"in m)if(typeof m.response=="string"){let b=m.response;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);if(x){b=x[1].trim();try{m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed response from wrapper (stripped markdown)")}catch{m=b,console.log("✅ [ExtraAnalysis] Extracted response from wrapper (as string)")}}else m=m.response,console.log("✅ [ExtraAnalysis] Extracted response from wrapper")}else m=m.response,console.log("✅ [ExtraAnalysis] Extracted response from wrapper");else if("message"in m&&typeof m.message=="string")try{let b=m.message;const x=b.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);x&&(b=x[1].trim(),console.log("✅ [ExtraAnalysis] Stripped markdown code blocks from message")),m=JSON.parse(b),console.log("✅ [ExtraAnalysis] Extracted and parsed message from wrapper")}catch{console.warn("⚠️ [ExtraAnalysis] message is not JSON, using original")}}console.log("✅ [ExtraAnalysis] Final content to parse:",typeof m,m);const S=qs(m);return console.log("✅ [ExtraAnalysis] Parsed response:",{hasData:!!S.data,hasNewPlan:!!S.newInstructionPlan,parseTo:S.parseTo}),S}catch(l){return console.error("❌ [ExtraAnalysis] Error during analysis:",l),{parseTo:i?.parseTo??"primitive",data:e,newInstructionPlan:null}}},Ys=async(e,t,o,n,s,r,a,i,l,c,u,f,d)=>{console.log(`🔍 [AnalyzeDataStep] Starting analysis for step "${n.name}" at index ${s}`),console.log("🔍 [AnalyzeDataStep] Output data type:",typeof t,Array.isArray(t)?"array":"object"),console.log("🔍 [AnalyzeDataStep] Assign key:",o),console.log("🔍 [AnalyzeDataStep] Next step:",r?.type,r?.type==="component"||r?.type==="function"?r.name:"");const m=c.steps.slice(s+1);let S=null;if(o&&m.length>0){const{getExpectedSchemaForAssignKey:b}=await Promise.resolve().then(()=>Ds);S=await b(o,m,e),S?console.log(`📋 [AnalyzeDataStep] Expected schema found for assign key "${o}":`,S):console.log(`ℹ️ [AnalyzeDataStep] No expected schema - no remaining steps consume assign key "${o}"`)}else console.log("ℹ️ [AnalyzeDataStep] No expected schema - no assign key or no remaining steps");try{console.log("🚀 [AnalyzeDataStep] Calling extraAnalysisWithLLM...");const b=await Gs(t,e,a,i,c,n,s,S);console.log("✅ [AnalyzeDataStep] Received analysis result:",{hasData:!!b.data,hasNewPlan:!!b.newInstructionPlan,parseTo:b.parseTo});const x=En(r,o),g=kn(b.data,x);if(console.log("Extra analysis data received from LLM:",b),console.log("Normalized ctx value:",g),o&&(l[o]=g),b.newInstructionPlan!=null&&b.newInstructionPlan!=""){if(console.log("analyzed.newInstructionPlan: ",b.newInstructionPlan),o){const h=JSON.parse(JSON.stringify(b.newInstructionPlan));h.steps&&h.steps.forEach(y=>{y.type==="component"&&y.props&&Object.keys(y.props).forEach(I=>{typeof y.props[I]=="string"&&y.props[I]==="{{data}}"&&(y.props[I]=`{{${o}}}`)})}),Rt(h,e,u,f,d,a,i,l)}else Rt(b.newInstructionPlan,e,u,f,d,a,i,l);return!0}return!1}catch(b){return console.error(b),!0}},Tt=new Map,Vo=new Set;async function Xs(e){const t=e;if(Vo.has(t))return Tt.get(t)||null;Vo.add(t);try{let o;if(t.startsWith("http://")||t.startsWith("https://")){console.log(`📥 [Runtime Validation] Fetching schema from URL: ${t}`);const n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch schema: ${n.status} ${n.statusText}`);o=await n.json()}else{const n=[t.startsWith("/")?t:`/${t}`,t,`/public/${t}`];let s=null;for(const r of n)try{console.log(`📥 [Runtime Validation] Trying to fetch schema from: ${r}`);const a=await fetch(r);if(a.ok){o=await a.json(),console.log(`✅ [Runtime Validation] Successfully loaded schema from: ${r}`);break}else s=new Error(`HTTP ${a.status}: ${a.statusText}`)}catch(a){s=a instanceof Error?a:new Error(String(a));continue}if(!o)throw s||new Error(`Failed to load schema from any path: ${n.join(", ")}`)}return o&&o.types&&o.components&&o.functions?(console.log("✅ [Runtime Validation] Runtime schema loaded successfully",{path:t,types:Object.keys(o.types).length,components:o.components.length,functions:o.functions.length}),Tt.set(t,o),o):(console.warn("⚠️ [Runtime Validation] Runtime schema has invalid structure"),Tt.set(t,null),null)}catch(o){return console.warn(`⚠️ [Runtime Validation] Runtime schema file not found at "${t}":`,o),Tt.set(t,null),null}}async function so(e){const t=e?.runtime?.runtimeSchemaPath||".autoui-runtime-schema.json";return await Xs(t)}function Je(e,t){return t.types[e]||null}function at(e,t,o,n,s=""){const r=[],a=s||"value",i=" ".repeat((s.match(/\./g)||[]).length+1);if(console.log(`${i}🔎 [Type Validation] Validating "${a}" against type "${o}"`),console.log(`${i} 📦 Value:`,e),console.log(`${i} 🔍 Value type: ${typeof e}, isArray: ${Array.isArray(e)}, isNull: ${e===null}`),console.log(`${i} 📋 Type definition:`,JSON.stringify(t,null,2)),e==null)return console.log(`${i} ℹ️ Value is ${e===void 0?"undefined":"null"} - skipping (optionality checked at prop/param level)`),r;switch(t.type){case"primitive":if(console.log(`${i} 🔍 Checking primitive type: "${o}"`),o==="string"&&typeof e!="string"){const l=`${a} must be a string, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else if(o==="number"&&(typeof e!="number"||isNaN(e))){const l=`${a} must be a number, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else if(o==="boolean"&&typeof e!="boolean"){const l=`${a} must be a boolean, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else console.log(`${i} ✅ Primitive type check passed`);break;case"enum":if(console.log(`${i} 🔍 Checking enum type with values:`,t.values),t.values&&Array.isArray(t.values))if(t.values.includes(e))console.log(`${i} ✅ Enum value check passed`);else{const l=`${a} must be one of: ${t.values.join(", ")}, got: ${e}`;console.log(`${i} ❌ ${l}`),r.push(l)}break;case"array":if(console.log(`${i} 🔍 Checking array type`),Array.isArray(e)){if(console.log(`${i} ✅ Array type check passed (length: ${e.length})`),t.items){const l=t.items.type;console.log(`${i} 🔍 Validating array items against type: "${l}"`);const c=Je(l,n);c?e.forEach((u,f)=>{console.log(`${i} 📦 Validating item [${f}]:`,u);const d=at(u,c,l,n,`${s}[${f}]`);r.push(...d)}):console.log(`${i} ⚠️ Item type "${l}" not found in schema`)}}else{const l=`${a} must be an array, got ${typeof e}`;if(console.log(`${i} ❌ ${l}`),console.log(`${i} 💡 Value is:`,e),console.log(`${i} 💡 Value constructor:`,e?.constructor?.name),typeof e=="string"){console.log(`${i} 💡 String value might be JSON - attempting to parse...`);try{const c=JSON.parse(e);console.log(`${i} 💡 Parsed successfully! Type: ${typeof c}, isArray: ${Array.isArray(c)}`),Array.isArray(c)&&console.log(`${i} ⚠️ WARNING: Value is a JSON string that should be parsed before validation!`)}catch{console.log(`${i} 💡 String is not valid JSON`)}}r.push(l)}break;case"object":if(console.log(`${i} 🔍 Checking object type`),typeof e!="object"||e===null||Array.isArray(e)){const l=`${a} must be an object, got ${typeof e}`;console.log(`${i} ❌ ${l}`),r.push(l)}else t.properties&&(console.log(`${i} ✅ Object type check passed`),console.log(`${i} 🔍 Validating object properties:`,Object.keys(t.properties)),Object.entries(t.properties).forEach(([l,c])=>{const u=e[l],f=s?`${s}.${l}`:l;if(console.log(`${i} 📦 Property "${l}":`,u),c.required&&u==null){const d=`${f} is required but was ${u===void 0?"undefined":"null"}`;console.log(`${i} ❌ ${d}`),r.push(d)}if(u!=null){const d=Je(c.type,n);if(d){const m=at(u,d,c.type,n,f);r.push(...m)}}}));break;case"union":if(console.log(`${i} 🔍 Checking union type with members:`,t.refs),t.refs&&t.refs.length>0){const l=[];for(const u of t.refs){console.log(`${i} 🔍 Trying union member: "${u}"`);const f=Je(u,n);if(f){const d=at(e,f,u,n,s);if(d.length===0)return console.log(`${i} ✅ Union member "${u}" validated successfully`),[];console.log(`${i} ❌ Union member "${u}" failed:`,d),l.push(...d)}}const c=`${a} does not match any union member. Errors: ${l.join("; ")}`;console.log(`${i} ❌ ${c}`),r.push(c)}break}return r.length===0?console.log(`${i} ✅ Type validation passed for "${a}"`):console.log(`${i} ❌ Type validation failed for "${a}" with ${r.length} error(s)`),r}function Zs(e,t,o){const n=[];console.log(`
210
210
  🔍 [Runtime Validation] ==========================================`),console.log(`🔍 [Runtime Validation] Starting validation for component: "${e}"`),console.log("🔍 [Runtime Validation] Raw props received:",JSON.stringify(t,null,2)),console.log("🔍 [Runtime Validation] Props type check:",Object.entries(t).map(([r,a])=>`${r}: ${typeof a} (${Array.isArray(a)?"array":typeof a})`));const s=o.components.find(r=>r.name===e);return s?(console.log(`✅ [Runtime Validation] Found component schema for "${e}"`),console.log("📋 [Runtime Validation] Component schema:",JSON.stringify(s.props,null,2)),Object.entries(s.props).forEach(([r,a])=>{console.log(`
211
211
  📌 [Runtime Validation] Validating prop: "${r}"`),console.log(" 📥 [Runtime Validation] Prop reference:",JSON.stringify(a,null,2));const i=t[r];if(console.log(" 📦 [Runtime Validation] Prop value received:",i),console.log(` 🔎 [Runtime Validation] Prop value type: ${typeof i}`),console.log(` 🔎 [Runtime Validation] Prop value isArray: ${Array.isArray(i)}`),console.log(` 🔎 [Runtime Validation] Prop value isNull: ${i===null}`),console.log(` 🔎 [Runtime Validation] Prop value isUndefined: ${i===void 0}`),typeof i=="string"){console.log(` 📝 [Runtime Validation] String value length: ${i.length}`),console.log(` 📝 [Runtime Validation] String preview: ${i.substring(0,100)}${i.length>100?"...":""}`);try{const l=JSON.parse(i);console.log(" 🔄 [Runtime Validation] String appears to be JSON! Parsed as:",typeof l),Array.isArray(l)&&console.log(` 🔄 [Runtime Validation] Parsed JSON is an array with ${l.length} items`)}catch{console.log(" ℹ️ [Runtime Validation] String is not valid JSON")}}if(a.required&&i==null){const l=`Prop "${r}" is required but was ${i===void 0?"undefined":"null"}`;console.log(` ❌ [Runtime Validation] ${l}`),n.push(l);return}if(i!=null){console.log(` 🔍 [Runtime Validation] Resolving type: "${a.type}"`);const l=Je(a.type,o);if(l){console.log(" ✅ [Runtime Validation] Type definition found:",JSON.stringify(l,null,2)),console.log(" 🔄 [Runtime Validation] Starting type validation...");const c=at(i,l,a.type,o,r);c.length>0?console.log(` ❌ [Runtime Validation] Validation failed with ${c.length} error(s):`,c):console.log(` ✅ [Runtime Validation] Prop "${r}" passed validation`),n.push(...c)}else console.warn(` ⚠️ [Runtime Validation] Type "${a.type}" not found in schema for prop "${r}"`),console.log(" 📋 [Runtime Validation] Available types:",Object.keys(o.types).slice(0,10))}else console.log(` ℹ️ [Runtime Validation] Prop "${r}" is ${i===void 0?"undefined":"null"} - skipping validation`)}),console.log(`
212
212
  📊 [Runtime Validation] Validation summary for "${e}":`),n.length===0?console.log(" ✅ All props validated successfully"):console.log(` ❌ Found ${n.length} validation error(s):`,n),console.log(`🔍 [Runtime Validation] ==========================================
package/dist/index.mjs CHANGED
@@ -4771,8 +4771,11 @@ async function ai(e) {
4771
4771
  } else {
4772
4772
  const n = [
4773
4773
  t.startsWith("/") ? t : `/${t}`,
4774
- `/public/${t}`,
4775
- t
4774
+ // Root path (works for Next.js public/ and Vite public/)
4775
+ t,
4776
+ // Original path as-is
4777
+ `/public/${t}`
4778
+ // Explicit public path (may work in some setups)
4776
4779
  ];
4777
4780
  let s = null;
4778
4781
  for (const r of n)
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Next.js plugin entry point
3
+ *
4
+ * This file provides a cleaner import path for Next.js users:
5
+ * import { withAutoUI } from '@autoai-ui/autoui/nextjs';
6
+ */
7
+ export { withAutoUI } from './build-time/nextjsPlugin';
8
+ export type { AutoUINextJSPluginOptions } from './build-time/nextjsPlugin';
9
+ export { generateSchemaStandalone } from './build-time/nextjsPlugin/standalone';
@@ -1,2 +1,5 @@
1
1
  export { autouiTypeSchemaPlugin } from './build-time/typeSchemaPlugin';
2
2
  export type * from './build-time/typeSchemaPlugin/types';
3
+ export { withAutoUI } from './build-time/nextjsPlugin';
4
+ export type { AutoUINextJSPluginOptions } from './build-time/nextjsPlugin';
5
+ export { generateSchemaStandalone } from './build-time/nextjsPlugin/standalone';
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ "use strict";const s=require("./standalone-Xrc3J06Y.cjs"),o=process.argv.slice(2),n={};for(let e=0;e<o.length;e++){const t=o[e];t==="--app-id"&&o[e+1]?(n.appId=o[e+1],e++):t==="--version"&&o[e+1]?(n.version=o[e+1],e++):t==="--output"&&o[e+1]?(n.runtimeSchemaFile=o[e+1],e++):t==="--tsconfig"&&o[e+1]?(n.tsconfigPath=o[e+1],e++):(t==="--help"||t==="-h")&&(console.log(`
3
+ AutoUI Next.js Schema Generator
4
+
5
+ Usage:
6
+ autoui-nextjs-generate-schema [options]
7
+
8
+ Options:
9
+ --app-id <id> Application ID (default: from AUTOUI_APP_ID env var or 'unknown')
10
+ --version <version> Application version (default: from AUTOUI_VERSION env var or '1.0.0')
11
+ --output <path> Output file path (default: '.autoui-runtime-schema.json')
12
+ --tsconfig <path> Path to tsconfig.json (default: 'tsconfig.json' or 'tsconfig.app.json')
13
+ --help, -h Show this help message
14
+
15
+ Environment Variables:
16
+ AUTOUI_APP_ID Application ID (overridden by --app-id)
17
+ AUTOUI_VERSION Application version (overridden by --version)
18
+ NODE_ENV Environment mode (default: 'development')
19
+
20
+ Examples:
21
+ autoui-nextjs-generate-schema
22
+ autoui-nextjs-generate-schema --app-id my-app --version 1.0.0
23
+ autoui-nextjs-generate-schema --output ./schema.json --tsconfig ./tsconfig.json
24
+ `),process.exit(0))}s.generateSchemaStandalone(n).catch(e=>{console.error("Fatal error:",e),process.exit(1)});
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ import { g as s } from "./standalone-qbUKaa9E.js";
3
+ const o = process.argv.slice(2), n = {};
4
+ for (let e = 0; e < o.length; e++) {
5
+ const t = o[e];
6
+ t === "--app-id" && o[e + 1] ? (n.appId = o[e + 1], e++) : t === "--version" && o[e + 1] ? (n.version = o[e + 1], e++) : t === "--output" && o[e + 1] ? (n.runtimeSchemaFile = o[e + 1], e++) : t === "--tsconfig" && o[e + 1] ? (n.tsconfigPath = o[e + 1], e++) : (t === "--help" || t === "-h") && (console.log(`
7
+ AutoUI Next.js Schema Generator
8
+
9
+ Usage:
10
+ autoui-nextjs-generate-schema [options]
11
+
12
+ Options:
13
+ --app-id <id> Application ID (default: from AUTOUI_APP_ID env var or 'unknown')
14
+ --version <version> Application version (default: from AUTOUI_VERSION env var or '1.0.0')
15
+ --output <path> Output file path (default: '.autoui-runtime-schema.json')
16
+ --tsconfig <path> Path to tsconfig.json (default: 'tsconfig.json' or 'tsconfig.app.json')
17
+ --help, -h Show this help message
18
+
19
+ Environment Variables:
20
+ AUTOUI_APP_ID Application ID (overridden by --app-id)
21
+ AUTOUI_VERSION Application version (overridden by --version)
22
+ NODE_ENV Environment mode (default: 'development')
23
+
24
+ Examples:
25
+ autoui-nextjs-generate-schema
26
+ autoui-nextjs-generate-schema --app-id my-app --version 1.0.0
27
+ autoui-nextjs-generate-schema --output ./schema.json --tsconfig ./tsconfig.json
28
+ `), process.exit(0));
29
+ }
30
+ s(n).catch((e) => {
31
+ console.error("Fatal error:", e), process.exit(1);
32
+ });
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-CRVe9SlW.cjs"),t=require("./standalone-Xrc3J06Y.cjs");exports.withAutoUI=e.withAutoUI;exports.generateSchemaStandalone=t.generateSchemaStandalone;
@@ -0,0 +1,2 @@
1
+ export * from './lib/nextjs'
2
+ export {}
@@ -0,0 +1,6 @@
1
+ import { w as o } from "./index-C7NbIxYi.js";
2
+ import { g as r } from "./standalone-qbUKaa9E.js";
3
+ export {
4
+ r as generateSchemaStandalone,
5
+ o as withAutoUI
6
+ };
package/dist/plugin.cjs CHANGED
@@ -1,4 +1 @@
1
- "use strict";var x=Object.create;var I=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,O=Object.prototype.hasOwnProperty;var _=(t,e,n,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of F(e))!O.call(t,o)&&o!==n&&I(t,o,{get:()=>e[o],enumerable:!(l=w(e,o))||l.enumerable});return t};var q=(t,e,n)=>(n=t!=null?x(k(t)):{},_(e||!t||!t.__esModule?I(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("node:fs"),h=require("node:path"),y=require("ts-morph"),j=require("node:crypto");function L(t){const e=[],n=[],l=t.getSourceFiles(),o=t.getTypeChecker();for(const g of l)g.isDeclarationFile()||g.getFilePath().includes("node_modules")||g.forEachDescendant(u=>{if(y.Node.isCallExpression(u)){const i=u.getExpression();if(y.Node.isIdentifier(i)){const s=i.getText();if(s==="autouiRegisterComponentPropsSchema"){const m=u.getArguments();if(m.length>0){const p=m[0],c=o.getTypeAtLocation(p),r=o.getSymbolAtLocation(p);let a="Unknown";if(r)a=r.getName();else{const f=c.getSymbol();f&&(a=f.getName())}console.log(`[AutoUI Type Schema] Found component registration: "${a}"`),e.push({name:a,type:c})}}if(s==="autouiRegisterFunctionParamsSchema"){const m=u.getArguments();if(m.length>0){const p=m[0],c=o.getTypeAtLocation(p),r=o.getSymbolAtLocation(p);let a="Unknown";if(r)a=r.getName();else{const f=c.getSymbol();f&&(a=f.getName())}console.log(`[AutoUI Type Schema] Found function registration: "${a}"`),n.push({name:a,type:c})}}}}});return{components:e,functions:n}}function v(t,e){const n=t.getDeclarations();for(const o of n)if(y.Node.isPropertySignature(o)&&o.hasQuestionToken()||y.Node.isParameterDeclaration(o)&&(o.hasQuestionToken()||o.hasInitializer())||y.Node.isBindingElement(o)&&o.hasInitializer())return!0;if(e.isUnion()){const o=e.getUnionTypes(),g=o.some(i=>{if(i.isUndefined())return!0;const s=i.getText();if(s==="undefined"||s==="void")return!0;try{if((i.getFlags()&256)!==0)return!0}catch{}return!1}),u=o.some(i=>!!(i.isNull()||i.getText()==="null"));if(g||u)return!0}if(e.isUndefined())return!0;const l=e.getText();return l==="undefined"||l==="void"}function A(t){if(t.isUnion()){const n=t.getUnionTypes().find(l=>{if(l.isUndefined()||l.isNull())return!1;const o=l.getText();if(o==="undefined"||o==="null"||o==="void")return!1;try{if((l.getFlags()&256)!==0)return!1}catch{}return!0});if(n)return n}return t}function P(t,e){if(e.typeNames.has(t))return e.typeNames.get(t);const n=t.getSymbol();if(n){const o=n.getName();if(o&&o!=="__type"&&o!=="__function"){const g=n.getDeclarations();if(g&&g.length>0){const u=g[0],i=u.getSourceFile();if(!i.isDeclarationFile()&&!i.getFilePath().includes("node_modules")&&(y.Node.isTypeAliasDeclaration(u)||y.Node.isInterfaceDeclaration(u)||y.Node.isEnumDeclaration(u)))return e.typeNames.set(t,o),o}}}if(t.isArray()){const o=t.getArrayElementType();if(o)return`${P(o,e)}[]`}const l=t.getText();return l==="string"||l==="number"||l==="boolean"?l:C(t,e)}function C(t,e){const n=t.getText(),l=j.createHash("md5").update(n).digest("hex").substring(0,8);let o="Anonymous";n.includes("{")?o="Object":n.includes("[")?o="Array":n.includes("|")&&(o="Union");const g=e.anonymousTypeCounter.get(o)||0;e.anonymousTypeCounter.set(o,g+1);const u=`${o}_${l}`;return e.typeNames.set(t,u),u}function T(t,e){const n=P(t,e);if(e.types.has(n)||e.visitedTypes.has(t))return n;if(e.visitedTypes.add(t),t.isString()||t.isStringLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": string`),e.types.set(n,{type:"primitive"}),n;if(t.isNumber()||t.isNumberLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": number`),e.types.set(n,{type:"primitive"}),n;if(t.isBoolean()||t.isBooleanLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": boolean`),e.types.set(n,{type:"primitive"}),n;if(t.isArray()){const i=t.getArrayElementType();if(i){console.log(`[AutoUI Type Schema] Extracting array type "${n}"`);const s=T(i,e);return e.types.set(n,{type:"array",items:{type:s},refs:[s]}),console.log(` → Array element type: "${s}"`),n}}if(t.isEnum()){const i=t.getSymbol();if(i){const s=i.getValueDeclaration();if(s&&y.Node.isEnumDeclaration(s)){const m=s.getMembers().map(p=>p.getName());return console.log(`[AutoUI Type Schema] Extracting enum type "${n}" with values: [${m.join(", ")}]`),e.types.set(n,{type:"enum",values:m}),n}}}if(t.isUnion()){const i=t.getUnionTypes();console.log(`[AutoUI Type Schema] Extracting union type "${n}" with ${i.length} union members`);const s=[];let m=!0,p=!1;for(const r of i){if(r.isUndefined()||r.isNull()){p=!0;continue}if(r.isStringLiteral()){const a=r.getLiteralValue();typeof a=="string"?s.push(a):m=!1}else m=!1}if(m&&s.length>0&&!p){const r=t.getSymbol();if(r){const a=r.getDeclarations();if(a&&a.length>0){const f=a[0];if(y.Node.isTypeAliasDeclaration(f)){const d=r.getName();return console.log(` → Converting string literal union to enum "${d}" with values: [${s.join(", ")}]`),e.types.set(d,{type:"enum",values:s}),e.typeNames.set(t,d),d}}}}const c=[];for(const r of i)if(!r.isUndefined()&&!r.isNull()){const a=T(r,e);c.includes(a)||c.push(a)}if(console.log(` → Union members: [${c.join(", ")}]`),c.length>1)return e.types.set(n,{type:"union",refs:c}),n;if(c.length===1)return console.log(` → Single type union (with undefined) - returning "${c[0]}"`),c[0]}const l={},o=[],g=t.getProperties(),u=t.getText();console.log(`[AutoUI Type Schema] Extracting object type "${n}":`),console.log(` Type text: ${u.substring(0,100)}${u.length>100?"...":""}`),console.log(` Properties count: ${g.length}`);for(const i of g){const s=i.getName();if(s.startsWith("__")||s==="toString"||s==="valueOf")continue;const m=i.getValueDeclaration()||i.getDeclarations()[0];if(!m)continue;const p=e.checker.getTypeAtLocation(m);console.log(` [Object Property] ${s}:`),console.log(` Raw type: ${p.getText()}`);const c=v(i,p),r=!c;c&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const a=A(p);a!==p&&console.log(` Extracting non-optional type: ${a.getText()}`);const f=T(a,e);l[s]={type:f,required:r},console.log(` → Evaluated type: "${f}" (required: ${r})`),o.includes(f)||o.push(f)}return e.types.set(n,{type:"object",properties:l,refs:o}),n}function R(t,e){const n={};let l=null;const o=t.getTypeArguments();if(o.length>0)l=o[0],console.log(`[AutoUI Type Schema] Extracting component props from generic type argument: ${l.getText()}`);else{const u=t.getCallSignatures();if(u.length>0){const s=u[0].getParameters();if(s.length>0){const p=s[0].getValueDeclaration();p&&(l=e.checker.getTypeAtLocation(p),console.log(`[AutoUI Type Schema] Extracting component props from call signature parameter: ${l.getText()}`))}}}if(!l)return console.log("[AutoUI Type Schema] Could not extract props type from component"),n;const g=l.getProperties();console.log(`[AutoUI Type Schema] Extracting component props from type: ${l.getText()}`),console.log(`[AutoUI Type Schema] Properties count: ${g.length}`);for(const u of g){const i=u.getName();if(i.startsWith("__")||i==="toString"||i==="valueOf")continue;const s=u.getValueDeclaration()||u.getDeclarations()[0];if(!s)continue;const m=e.checker.getTypeAtLocation(s);console.log(` [Component Prop] ${i}:`),console.log(` Raw type: ${m.getText()}`);const p=v(u,m),c=!p;p&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const r=A(m);r!==m&&console.log(` Extracting non-optional type: ${r.getText()}`);const a=T(r,e);n[i]={type:a,required:c},console.log(` → Evaluated type: "${a}" (required: ${c})`)}return n}function V(t,e){const n={},l=t.getCallSignatures();if(l.length>0){const o=l[0],g=o.getParameters();console.log(`[AutoUI Type Schema] Extracting function parameters (count: ${g.length})`);for(const s of g){const m=s.getName();if(m&&!m.startsWith("__")){const p=s.getValueDeclaration();if(!p)continue;const c=e.checker.getTypeAtLocation(p);console.log(` [Function Param] ${m}:`),console.log(` Raw type: ${c.getText()}`);const r=v(s,c),a=!r;r&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const f=A(c);f!==c&&console.log(` Extracting non-optional type: ${f.getText()}`);const d=T(f,e);n[m]={type:d,required:a},console.log(` → Evaluated type: "${d}" (required: ${a})`)}else{const p=s.getValueDeclaration();if(!p)continue;const c=e.checker.getTypeAtLocation(p);if(console.log(" [Function Param] (destructured):"),console.log(` Raw type: ${c.getText()}`),c.isObject()){const r=c.getProperties();console.log(` Extracting destructured object properties (count: ${r.length})`);for(const a of r){const f=a.getName();if(f.startsWith("__"))continue;console.log(` [Destructured Prop] ${f}:`);const d=a.getValueDeclaration()||a.getDeclarations()[0];if(!d)continue;const N=e.checker.getTypeAtLocation(d);console.log(` Raw type: ${N.getText()}`);const E=v(a,N),b=!E;E&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const U=A(N);U!==N&&console.log(` Extracting non-optional type: ${U.getText()}`);const D=T(U,e);n[f]={type:D,required:b},console.log(` → Evaluated type: "${D}" (required: ${b})`)}}else{const r=T(c,e);n.param={type:r,required:!0},console.log(` → Evaluated type: "${r}" (required: true)`)}}}const u=o.getReturnType(),i=T(u,e);return console.log(` [Function Return] → Evaluated type: "${i}"`),{params:n,returns:{type:i}}}return{params:n,returns:{type:"void"}}}function W(t,e,n){const o={checker:t.getTypeChecker(),types:new Map,typeNames:new Map,visitedTypes:new Set,anonymousTypeCounter:new Map};console.log(`[AutoUI Type Schema] Starting schema generation for appId: ${e}, version: ${n}`);const{components:g,functions:u}=L(t);console.log(`[AutoUI Type Schema] Found ${g.length} component(s) and ${u.length} function(s)`);const i=[];for(const{name:p,type:c}of g){console.log(`
2
- [AutoUI Type Schema] ========================================`),console.log(`[AutoUI Type Schema] Processing Component: "${p}"`),console.log("[AutoUI Type Schema] ========================================");const r=R(c,o);i.push({name:p,props:r}),console.log(`[AutoUI Type Schema] ✓ Component "${p}" processed with ${Object.keys(r).length} prop(s)`)}const s=[];for(const{name:p,type:c}of u){console.log(`
3
- [AutoUI Type Schema] ========================================`),console.log(`[AutoUI Type Schema] Processing Function: "${p}"`),console.log("[AutoUI Type Schema] ========================================");const{params:r,returns:a}=V(c,o);s.push({name:p,params:r,returns:a}),console.log(`[AutoUI Type Schema] ✓ Function "${p}" processed with ${Object.keys(r).length} param(s), return type: "${a.type}"`)}const m={};for(const[p,c]of o.types.entries())m[p]=c;return{appId:e,version:n,generatedAt:new Date().toISOString(),types:m,components:i,functions:s}}function $(t){const e={};if(!S.existsSync(t))return e;try{const l=S.readFileSync(t,"utf-8").split(`
4
- `);for(const o of l){const g=o.trim();if(!g||g.startsWith("#"))continue;const u=g.match(/^([^=:#]+)=(.*)$/);if(u){const i=u[1].trim();let s=u[2].trim();(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),e[i]=s}}}catch{}return e}function M(t="development"){const e=process.cwd(),n={},l=$(h.resolve(e,".env"));Object.assign(n,l);const o=$(h.resolve(e,`.env.${t}`));Object.assign(n,o);const g=$(h.resolve(e,".env.local"));Object.assign(n,g);const u=process.env.NODE_ENV||t;if(u!==t){const i=$(h.resolve(e,`.env.${u}`));Object.assign(n,i)}return n}function B(t={}){const e=t.runtimeSchemaFile||".autoui-runtime-schema.json";return{name:"autoui-type-schema",enforce:"pre",async buildStart(){if(process.env.NODE_ENV==="production"||process.env.MODE==="production"){console.log("[AutoUI Type Schema Plugin] Skipping schema generation in production build. Using existing schema file.");return}const g={...M("development"),...process.env},u=t.appId||g.AUTOUI_APP_ID||"unknown",i=t.version||g.AUTOUI_VERSION||"1.0.0";try{let s=h.resolve(process.cwd(),"tsconfig.app.json");if(S.existsSync(s)||(s=h.resolve(process.cwd(),"tsconfig.json")),!S.existsSync(s)){console.warn("[AutoUI Type Schema Plugin] No tsconfig.json or tsconfig.app.json found, skipping schema extraction");return}const m=new y.Project({tsConfigFilePath:s});if(m.getSourceFiles().filter(f=>!f.isDeclarationFile()&&!f.getFilePath().includes("node_modules")).length===0){console.warn("[AutoUI Type Schema Plugin] No source files found after filtering!");return}const c=W(m,u,i);if(c.components.length===0&&c.functions.length===0)return;const r=h.resolve(process.cwd(),e),a=h.resolve(r,"..");if(!S.existsSync(a)){const{mkdirSync:f}=await import("node:fs");f(a,{recursive:!0})}S.writeFileSync(r,JSON.stringify(c,null,2),"utf-8"),console.log(`[AutoUI Type Schema Plugin] Schema written to ${e}`)}catch(s){console.error("❌ [AutoUI Type Schema Plugin] Error in plugin:",s),s instanceof Error&&(console.error(` Error message: ${s.message}`),s.stack&&console.error(` Stack trace: ${s.stack}`))}}}}exports.autouiTypeSchemaPlugin=B;
1
+ "use strict";var y=Object.create;var d=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var U=(e,n,t,a)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of v(n))!w.call(e,r)&&r!==t&&d(e,r,{get:()=>n[r],enumerable:!(a=P(n,r))||a.enumerable});return e};var A=(e,n,t)=>(t=e!=null?y(I(e)):{},U(n||!e||!e.__esModule?d(t,"default",{value:e,enumerable:!0}):t,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("node:fs"),c=require("node:path"),T=require("ts-morph"),l=require("./standalone-Xrc3J06Y.cjs"),E=require("./index-CRVe9SlW.cjs");function F(e={}){const n=e.runtimeSchemaFile||".autoui-runtime-schema.json";return{name:"autoui-type-schema",enforce:"pre",async buildStart(){if(process.env.NODE_ENV==="production"||process.env.MODE==="production"){console.log("[AutoUI Type Schema Plugin] Skipping schema generation in production build. Using existing schema file.");return}const m={...l.loadEnvVars("development"),...process.env},S=e.appId||m.AUTOUI_APP_ID||"unknown",f=e.version||m.AUTOUI_VERSION||"1.0.0";try{let o=c.resolve(process.cwd(),"tsconfig.app.json");if(i.existsSync(o)||(o=c.resolve(process.cwd(),"tsconfig.json")),!i.existsSync(o)){console.warn("[AutoUI Type Schema Plugin] No tsconfig.json or tsconfig.app.json found, skipping schema extraction");return}const p=new T.Project({tsConfigFilePath:o});if(p.getSourceFiles().filter(s=>!s.isDeclarationFile()&&!s.getFilePath().includes("node_modules")).length===0){console.warn("[AutoUI Type Schema Plugin] No source files found after filtering!");return}const u=l.generateSchema(p,S,f);if(u.components.length===0&&u.functions.length===0)return;const g=c.resolve(process.cwd(),n),h=c.resolve(g,"..");if(!i.existsSync(h)){const{mkdirSync:s}=await import("node:fs");s(h,{recursive:!0})}i.writeFileSync(g,JSON.stringify(u,null,2),"utf-8"),console.log(`[AutoUI Type Schema Plugin] Schema written to ${n}`)}catch(o){console.error("❌ [AutoUI Type Schema Plugin] Error in plugin:",o),o instanceof Error&&(console.error(` Error message: ${o.message}`),o.stack&&console.error(` Stack trace: ${o.stack}`))}}}}exports.generateSchemaStandalone=l.generateSchemaStandalone;exports.withAutoUI=E.withAutoUI;exports.autouiTypeSchemaPlugin=F;
package/dist/plugin.mjs CHANGED
@@ -1,389 +1,11 @@
1
- import { existsSync as N, readFileSync as P, writeFileSync as w } from "node:fs";
2
- import { resolve as h } from "node:path";
3
- import { Node as d, Project as x } from "ts-morph";
4
- import { createHash as F } from "node:crypto";
5
- function k(n) {
6
- const e = [], t = [], p = n.getSourceFiles(), o = n.getTypeChecker();
7
- for (const g of p)
8
- g.isDeclarationFile() || g.getFilePath().includes("node_modules") || g.forEachDescendant((l) => {
9
- if (d.isCallExpression(l)) {
10
- const i = l.getExpression();
11
- if (d.isIdentifier(i)) {
12
- const s = i.getText();
13
- if (s === "autouiRegisterComponentPropsSchema") {
14
- const m = l.getArguments();
15
- if (m.length > 0) {
16
- const u = m[0], c = o.getTypeAtLocation(u), r = o.getSymbolAtLocation(u);
17
- let a = "Unknown";
18
- if (r)
19
- a = r.getName();
20
- else {
21
- const f = c.getSymbol();
22
- f && (a = f.getName());
23
- }
24
- console.log(`[AutoUI Type Schema] Found component registration: "${a}"`), e.push({ name: a, type: c });
25
- }
26
- }
27
- if (s === "autouiRegisterFunctionParamsSchema") {
28
- const m = l.getArguments();
29
- if (m.length > 0) {
30
- const u = m[0], c = o.getTypeAtLocation(u), r = o.getSymbolAtLocation(u);
31
- let a = "Unknown";
32
- if (r)
33
- a = r.getName();
34
- else {
35
- const f = c.getSymbol();
36
- f && (a = f.getName());
37
- }
38
- console.log(`[AutoUI Type Schema] Found function registration: "${a}"`), t.push({ name: a, type: c });
39
- }
40
- }
41
- }
42
- }
43
- });
44
- return { components: e, functions: t };
45
- }
46
- function v(n, e) {
47
- const t = n.getDeclarations();
48
- for (const o of t)
49
- if (d.isPropertySignature(o) && o.hasQuestionToken() || d.isParameterDeclaration(o) && (o.hasQuestionToken() || o.hasInitializer()) || d.isBindingElement(o) && o.hasInitializer())
50
- return !0;
51
- if (e.isUnion()) {
52
- const o = e.getUnionTypes(), g = o.some((i) => {
53
- if (i.isUndefined()) return !0;
54
- const s = i.getText();
55
- if (s === "undefined" || s === "void") return !0;
56
- try {
57
- if ((i.getFlags() & 256) !== 0) return !0;
58
- } catch {
59
- }
60
- return !1;
61
- }), l = o.some((i) => !!(i.isNull() || i.getText() === "null"));
62
- if (g || l)
63
- return !0;
64
- }
65
- if (e.isUndefined())
66
- return !0;
67
- const p = e.getText();
68
- return p === "undefined" || p === "void";
69
- }
70
- function A(n) {
71
- if (n.isUnion()) {
72
- const t = n.getUnionTypes().find((p) => {
73
- if (p.isUndefined() || p.isNull()) return !1;
74
- const o = p.getText();
75
- if (o === "undefined" || o === "null" || o === "void")
76
- return !1;
77
- try {
78
- if ((p.getFlags() & 256) !== 0) return !1;
79
- } catch {
80
- }
81
- return !0;
82
- });
83
- if (t)
84
- return t;
85
- }
86
- return n;
87
- }
88
- function I(n, e) {
89
- if (e.typeNames.has(n))
90
- return e.typeNames.get(n);
91
- const t = n.getSymbol();
92
- if (t) {
93
- const o = t.getName();
94
- if (o && o !== "__type" && o !== "__function") {
95
- const g = t.getDeclarations();
96
- if (g && g.length > 0) {
97
- const l = g[0], i = l.getSourceFile();
98
- if (!i.isDeclarationFile() && !i.getFilePath().includes("node_modules") && (d.isTypeAliasDeclaration(l) || d.isInterfaceDeclaration(l) || d.isEnumDeclaration(l)))
99
- return e.typeNames.set(n, o), o;
100
- }
101
- }
102
- }
103
- if (n.isArray()) {
104
- const o = n.getArrayElementType();
105
- if (o)
106
- return `${I(o, e)}[]`;
107
- }
108
- const p = n.getText();
109
- return p === "string" || p === "number" || p === "boolean" ? p : O(n, e);
110
- }
111
- function O(n, e) {
112
- const t = n.getText(), p = F("md5").update(t).digest("hex").substring(0, 8);
113
- let o = "Anonymous";
114
- t.includes("{") ? o = "Object" : t.includes("[") ? o = "Array" : t.includes("|") && (o = "Union");
115
- const g = e.anonymousTypeCounter.get(o) || 0;
116
- e.anonymousTypeCounter.set(o, g + 1);
117
- const l = `${o}_${p}`;
118
- return e.typeNames.set(n, l), l;
119
- }
120
- function T(n, e) {
121
- const t = I(n, e);
122
- if (e.types.has(t) || e.visitedTypes.has(n))
123
- return t;
124
- if (e.visitedTypes.add(n), n.isString() || n.isStringLiteral())
125
- return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": string`), e.types.set(t, { type: "primitive" }), t;
126
- if (n.isNumber() || n.isNumberLiteral())
127
- return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": number`), e.types.set(t, { type: "primitive" }), t;
128
- if (n.isBoolean() || n.isBooleanLiteral())
129
- return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": boolean`), e.types.set(t, { type: "primitive" }), t;
130
- if (n.isArray()) {
131
- const i = n.getArrayElementType();
132
- if (i) {
133
- console.log(`[AutoUI Type Schema] Extracting array type "${t}"`);
134
- const s = T(i, e);
135
- return e.types.set(t, {
136
- type: "array",
137
- items: { type: s },
138
- refs: [s]
139
- }), console.log(` → Array element type: "${s}"`), t;
140
- }
141
- }
142
- if (n.isEnum()) {
143
- const i = n.getSymbol();
144
- if (i) {
145
- const s = i.getValueDeclaration();
146
- if (s && d.isEnumDeclaration(s)) {
147
- const m = s.getMembers().map((u) => u.getName());
148
- return console.log(`[AutoUI Type Schema] Extracting enum type "${t}" with values: [${m.join(", ")}]`), e.types.set(t, {
149
- type: "enum",
150
- values: m
151
- }), t;
152
- }
153
- }
154
- }
155
- if (n.isUnion()) {
156
- const i = n.getUnionTypes();
157
- console.log(`[AutoUI Type Schema] Extracting union type "${t}" with ${i.length} union members`);
158
- const s = [];
159
- let m = !0, u = !1;
160
- for (const r of i) {
161
- if (r.isUndefined() || r.isNull()) {
162
- u = !0;
163
- continue;
164
- }
165
- if (r.isStringLiteral()) {
166
- const a = r.getLiteralValue();
167
- typeof a == "string" ? s.push(a) : m = !1;
168
- } else
169
- m = !1;
170
- }
171
- if (m && s.length > 0 && !u) {
172
- const r = n.getSymbol();
173
- if (r) {
174
- const a = r.getDeclarations();
175
- if (a && a.length > 0) {
176
- const f = a[0];
177
- if (d.isTypeAliasDeclaration(f)) {
178
- const y = r.getName();
179
- return console.log(` → Converting string literal union to enum "${y}" with values: [${s.join(", ")}]`), e.types.set(y, {
180
- type: "enum",
181
- values: s
182
- }), e.typeNames.set(n, y), y;
183
- }
184
- }
185
- }
186
- }
187
- const c = [];
188
- for (const r of i)
189
- if (!r.isUndefined() && !r.isNull()) {
190
- const a = T(r, e);
191
- c.includes(a) || c.push(a);
192
- }
193
- if (console.log(` → Union members: [${c.join(", ")}]`), c.length > 1)
194
- return e.types.set(t, {
195
- type: "union",
196
- refs: c
197
- }), t;
198
- if (c.length === 1)
199
- return console.log(` → Single type union (with undefined) - returning "${c[0]}"`), c[0];
200
- }
201
- const p = {}, o = [], g = n.getProperties(), l = n.getText();
202
- console.log(`[AutoUI Type Schema] Extracting object type "${t}":`), console.log(` Type text: ${l.substring(0, 100)}${l.length > 100 ? "..." : ""}`), console.log(` Properties count: ${g.length}`);
203
- for (const i of g) {
204
- const s = i.getName();
205
- if (s.startsWith("__") || s === "toString" || s === "valueOf")
206
- continue;
207
- const m = i.getValueDeclaration() || i.getDeclarations()[0];
208
- if (!m) continue;
209
- const u = e.checker.getTypeAtLocation(m);
210
- console.log(` [Object Property] ${s}:`), console.log(` Raw type: ${u.getText()}`);
211
- const c = v(i, u), r = !c;
212
- c && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
213
- const a = A(u);
214
- a !== u && console.log(` Extracting non-optional type: ${a.getText()}`);
215
- const f = T(a, e);
216
- p[s] = { type: f, required: r }, console.log(` → Evaluated type: "${f}" (required: ${r})`), o.includes(f) || o.push(f);
217
- }
218
- return e.types.set(t, {
219
- type: "object",
220
- properties: p,
221
- refs: o
222
- }), t;
223
- }
224
- function _(n, e) {
225
- const t = {};
226
- let p = null;
227
- const o = n.getTypeArguments();
228
- if (o.length > 0)
229
- p = o[0], console.log(`[AutoUI Type Schema] Extracting component props from generic type argument: ${p.getText()}`);
230
- else {
231
- const l = n.getCallSignatures();
232
- if (l.length > 0) {
233
- const s = l[0].getParameters();
234
- if (s.length > 0) {
235
- const u = s[0].getValueDeclaration();
236
- u && (p = e.checker.getTypeAtLocation(u), console.log(`[AutoUI Type Schema] Extracting component props from call signature parameter: ${p.getText()}`));
237
- }
238
- }
239
- }
240
- if (!p)
241
- return console.log("[AutoUI Type Schema] Could not extract props type from component"), t;
242
- const g = p.getProperties();
243
- console.log(`[AutoUI Type Schema] Extracting component props from type: ${p.getText()}`), console.log(`[AutoUI Type Schema] Properties count: ${g.length}`);
244
- for (const l of g) {
245
- const i = l.getName();
246
- if (i.startsWith("__") || i === "toString" || i === "valueOf")
247
- continue;
248
- const s = l.getValueDeclaration() || l.getDeclarations()[0];
249
- if (!s) continue;
250
- const m = e.checker.getTypeAtLocation(s);
251
- console.log(` [Component Prop] ${i}:`), console.log(` Raw type: ${m.getText()}`);
252
- const u = v(l, m), c = !u;
253
- u && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
254
- const r = A(m);
255
- r !== m && console.log(` Extracting non-optional type: ${r.getText()}`);
256
- const a = T(r, e);
257
- t[i] = { type: a, required: c }, console.log(` → Evaluated type: "${a}" (required: ${c})`);
258
- }
259
- return t;
260
- }
261
- function j(n, e) {
262
- const t = {}, p = n.getCallSignatures();
263
- if (p.length > 0) {
264
- const o = p[0], g = o.getParameters();
265
- console.log(`[AutoUI Type Schema] Extracting function parameters (count: ${g.length})`);
266
- for (const s of g) {
267
- const m = s.getName();
268
- if (m && !m.startsWith("__")) {
269
- const u = s.getValueDeclaration();
270
- if (!u) continue;
271
- const c = e.checker.getTypeAtLocation(u);
272
- console.log(` [Function Param] ${m}:`), console.log(` Raw type: ${c.getText()}`);
273
- const r = v(s, c), a = !r;
274
- r && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
275
- const f = A(c);
276
- f !== c && console.log(` Extracting non-optional type: ${f.getText()}`);
277
- const y = T(f, e);
278
- t[m] = { type: y, required: a }, console.log(` → Evaluated type: "${y}" (required: ${a})`);
279
- } else {
280
- const u = s.getValueDeclaration();
281
- if (!u) continue;
282
- const c = e.checker.getTypeAtLocation(u);
283
- if (console.log(" [Function Param] (destructured):"), console.log(` Raw type: ${c.getText()}`), c.isObject()) {
284
- const r = c.getProperties();
285
- console.log(` Extracting destructured object properties (count: ${r.length})`);
286
- for (const a of r) {
287
- const f = a.getName();
288
- if (f.startsWith("__")) continue;
289
- console.log(` [Destructured Prop] ${f}:`);
290
- const y = a.getValueDeclaration() || a.getDeclarations()[0];
291
- if (!y) continue;
292
- const S = e.checker.getTypeAtLocation(y);
293
- console.log(` Raw type: ${S.getText()}`);
294
- const E = v(a, S), b = !E;
295
- E && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
296
- const U = A(S);
297
- U !== S && console.log(` Extracting non-optional type: ${U.getText()}`);
298
- const D = T(U, e);
299
- t[f] = { type: D, required: b }, console.log(` → Evaluated type: "${D}" (required: ${b})`);
300
- }
301
- } else {
302
- const r = T(c, e);
303
- t.param = { type: r, required: !0 }, console.log(` → Evaluated type: "${r}" (required: true)`);
304
- }
305
- }
306
- }
307
- const l = o.getReturnType(), i = T(l, e);
308
- return console.log(` [Function Return] → Evaluated type: "${i}"`), { params: t, returns: { type: i } };
309
- }
310
- return { params: t, returns: { type: "void" } };
311
- }
312
- function q(n, e, t) {
313
- const o = {
314
- checker: n.getTypeChecker(),
315
- types: /* @__PURE__ */ new Map(),
316
- typeNames: /* @__PURE__ */ new Map(),
317
- visitedTypes: /* @__PURE__ */ new Set(),
318
- anonymousTypeCounter: /* @__PURE__ */ new Map()
319
- };
320
- console.log(`[AutoUI Type Schema] Starting schema generation for appId: ${e}, version: ${t}`);
321
- const { components: g, functions: l } = k(n);
322
- console.log(`[AutoUI Type Schema] Found ${g.length} component(s) and ${l.length} function(s)`);
323
- const i = [];
324
- for (const { name: u, type: c } of g) {
325
- console.log(`
326
- [AutoUI Type Schema] ========================================`), console.log(`[AutoUI Type Schema] Processing Component: "${u}"`), console.log("[AutoUI Type Schema] ========================================");
327
- const r = _(c, o);
328
- i.push({ name: u, props: r }), console.log(`[AutoUI Type Schema] ✓ Component "${u}" processed with ${Object.keys(r).length} prop(s)`);
329
- }
330
- const s = [];
331
- for (const { name: u, type: c } of l) {
332
- console.log(`
333
- [AutoUI Type Schema] ========================================`), console.log(`[AutoUI Type Schema] Processing Function: "${u}"`), console.log("[AutoUI Type Schema] ========================================");
334
- const { params: r, returns: a } = j(c, o);
335
- s.push({ name: u, params: r, returns: a }), console.log(`[AutoUI Type Schema] ✓ Function "${u}" processed with ${Object.keys(r).length} param(s), return type: "${a.type}"`);
336
- }
337
- const m = {};
338
- for (const [u, c] of o.types.entries())
339
- m[u] = c;
340
- return {
341
- appId: e,
342
- version: t,
343
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
344
- types: m,
345
- components: i,
346
- functions: s
347
- };
348
- }
349
- function $(n) {
350
- const e = {};
351
- if (!N(n))
352
- return e;
353
- try {
354
- const p = P(n, "utf-8").split(`
355
- `);
356
- for (const o of p) {
357
- const g = o.trim();
358
- if (!g || g.startsWith("#"))
359
- continue;
360
- const l = g.match(/^([^=:#]+)=(.*)$/);
361
- if (l) {
362
- const i = l[1].trim();
363
- let s = l[2].trim();
364
- (s.startsWith('"') && s.endsWith('"') || s.startsWith("'") && s.endsWith("'")) && (s = s.slice(1, -1)), e[i] = s;
365
- }
366
- }
367
- } catch {
368
- }
369
- return e;
370
- }
371
- function L(n = "development") {
372
- const e = process.cwd(), t = {}, p = $(h(e, ".env"));
373
- Object.assign(t, p);
374
- const o = $(h(e, `.env.${n}`));
375
- Object.assign(t, o);
376
- const g = $(h(e, ".env.local"));
377
- Object.assign(t, g);
378
- const l = process.env.NODE_ENV || n;
379
- if (l !== n) {
380
- const i = $(h(e, `.env.${l}`));
381
- Object.assign(t, i);
382
- }
383
- return t;
384
- }
385
- function M(n = {}) {
386
- const e = n.runtimeSchemaFile || ".autoui-runtime-schema.json";
1
+ import { existsSync as s, writeFileSync as f } from "node:fs";
2
+ import { resolve as n } from "node:path";
3
+ import { Project as g } from "ts-morph";
4
+ import { l as h, a as d } from "./standalone-qbUKaa9E.js";
5
+ import { g as j } from "./standalone-qbUKaa9E.js";
6
+ import { w as x } from "./index-C7NbIxYi.js";
7
+ function E(r = {}) {
8
+ const i = r.runtimeSchemaFile || ".autoui-runtime-schema.json";
387
9
  return {
388
10
  name: "autoui-type-schema",
389
11
  enforce: "pre",
@@ -392,37 +14,39 @@ function M(n = {}) {
392
14
  console.log("[AutoUI Type Schema Plugin] Skipping schema generation in production build. Using existing schema file.");
393
15
  return;
394
16
  }
395
- const g = { ...L("development"), ...process.env }, l = n.appId || g.AUTOUI_APP_ID || "unknown", i = n.version || g.AUTOUI_VERSION || "1.0.0";
17
+ const c = { ...h("development"), ...process.env }, m = r.appId || c.AUTOUI_APP_ID || "unknown", p = r.version || c.AUTOUI_VERSION || "1.0.0";
396
18
  try {
397
- let s = h(process.cwd(), "tsconfig.app.json");
398
- if (N(s) || (s = h(process.cwd(), "tsconfig.json")), !N(s)) {
19
+ let e = n(process.cwd(), "tsconfig.app.json");
20
+ if (s(e) || (e = n(process.cwd(), "tsconfig.json")), !s(e)) {
399
21
  console.warn("[AutoUI Type Schema Plugin] No tsconfig.json or tsconfig.app.json found, skipping schema extraction");
400
22
  return;
401
23
  }
402
- const m = new x({
403
- tsConfigFilePath: s
24
+ const a = new g({
25
+ tsConfigFilePath: e
404
26
  });
405
- if (m.getSourceFiles().filter(
406
- (f) => !f.isDeclarationFile() && !f.getFilePath().includes("node_modules")
27
+ if (a.getSourceFiles().filter(
28
+ (o) => !o.isDeclarationFile() && !o.getFilePath().includes("node_modules")
407
29
  ).length === 0) {
408
30
  console.warn("[AutoUI Type Schema Plugin] No source files found after filtering!");
409
31
  return;
410
32
  }
411
- const c = q(m, l, i);
412
- if (c.components.length === 0 && c.functions.length === 0)
33
+ const t = d(a, m, p);
34
+ if (t.components.length === 0 && t.functions.length === 0)
413
35
  return;
414
- const r = h(process.cwd(), e), a = h(r, "..");
415
- if (!N(a)) {
416
- const { mkdirSync: f } = await import("node:fs");
417
- f(a, { recursive: !0 });
36
+ const u = n(process.cwd(), i), l = n(u, "..");
37
+ if (!s(l)) {
38
+ const { mkdirSync: o } = await import("node:fs");
39
+ o(l, { recursive: !0 });
418
40
  }
419
- w(r, JSON.stringify(c, null, 2), "utf-8"), console.log(`[AutoUI Type Schema Plugin] Schema written to ${e}`);
420
- } catch (s) {
421
- console.error("❌ [AutoUI Type Schema Plugin] Error in plugin:", s), s instanceof Error && (console.error(` Error message: ${s.message}`), s.stack && console.error(` Stack trace: ${s.stack}`));
41
+ f(u, JSON.stringify(t, null, 2), "utf-8"), console.log(`[AutoUI Type Schema Plugin] Schema written to ${i}`);
42
+ } catch (e) {
43
+ console.error("❌ [AutoUI Type Schema Plugin] Error in plugin:", e), e instanceof Error && (console.error(` Error message: ${e.message}`), e.stack && console.error(` Stack trace: ${e.stack}`));
422
44
  }
423
45
  }
424
46
  };
425
47
  }
426
48
  export {
427
- M as autouiTypeSchemaPlugin
49
+ E as autouiTypeSchemaPlugin,
50
+ j as generateSchemaStandalone,
51
+ x as withAutoUI
428
52
  };
@@ -0,0 +1,4 @@
1
+ "use strict";var P=Object.create;var b=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var O=Object.getPrototypeOf,_=Object.prototype.hasOwnProperty;var q=(e,t,n,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of j(t))!_.call(e,o)&&o!==n&&b(e,o,{get:()=>t[o],enumerable:!(u=k(t,o))||u.enumerable});return e};var C=(e,t,n)=>(n=e!=null?P(O(e)):{},q(t||!e||!e.__esModule?b(n,"default",{value:e,enumerable:!0}):n,e));const S=require("node:fs"),h=require("node:path"),y=require("ts-morph"),L=require("node:crypto");function R(e){const t=[],n=[],u=e.getSourceFiles(),o=e.getTypeChecker();for(const g of u)g.isDeclarationFile()||g.getFilePath().includes("node_modules")||g.forEachDescendant(l=>{if(y.Node.isCallExpression(l)){const s=l.getExpression();if(y.Node.isIdentifier(s)){const r=s.getText();if(r==="autouiRegisterComponentPropsSchema"){const f=l.getArguments();if(f.length>0){const i=f[0],p=o.getTypeAtLocation(i),c=o.getSymbolAtLocation(i);let a="Unknown";if(c)a=c.getName();else{const m=p.getSymbol();m&&(a=m.getName())}console.log(`[AutoUI Type Schema] Found component registration: "${a}"`),t.push({name:a,type:p})}}if(r==="autouiRegisterFunctionParamsSchema"){const f=l.getArguments();if(f.length>0){const i=f[0],p=o.getTypeAtLocation(i),c=o.getSymbolAtLocation(i);let a="Unknown";if(c)a=c.getName();else{const m=p.getSymbol();m&&(a=m.getName())}console.log(`[AutoUI Type Schema] Found function registration: "${a}"`),n.push({name:a,type:p})}}}}});return{components:t,functions:n}}function v(e,t){const n=e.getDeclarations();for(const o of n)if(y.Node.isPropertySignature(o)&&o.hasQuestionToken()||y.Node.isParameterDeclaration(o)&&(o.hasQuestionToken()||o.hasInitializer())||y.Node.isBindingElement(o)&&o.hasInitializer())return!0;if(t.isUnion()){const o=t.getUnionTypes(),g=o.some(s=>{if(s.isUndefined())return!0;const r=s.getText();if(r==="undefined"||r==="void")return!0;try{if((s.getFlags()&256)!==0)return!0}catch{}return!1}),l=o.some(s=>!!(s.isNull()||s.getText()==="null"));if(g||l)return!0}if(t.isUndefined())return!0;const u=t.getText();return u==="undefined"||u==="void"}function A(e){if(e.isUnion()){const n=e.getUnionTypes().find(u=>{if(u.isUndefined()||u.isNull())return!1;const o=u.getText();if(o==="undefined"||o==="null"||o==="void")return!1;try{if((u.getFlags()&256)!==0)return!1}catch{}return!0});if(n)return n}return e}function D(e,t){if(t.typeNames.has(e))return t.typeNames.get(e);const n=e.getSymbol();if(n){const o=n.getName();if(o&&o!=="__type"&&o!=="__function"){const g=n.getDeclarations();if(g&&g.length>0){const l=g[0],s=l.getSourceFile();if(!s.isDeclarationFile()&&!s.getFilePath().includes("node_modules")&&(y.Node.isTypeAliasDeclaration(l)||y.Node.isInterfaceDeclaration(l)||y.Node.isEnumDeclaration(l)))return t.typeNames.set(e,o),o}}}if(e.isArray()){const o=e.getArrayElementType();if(o)return`${D(o,t)}[]`}const u=e.getText();return u==="string"||u==="number"||u==="boolean"?u:V(e,t)}function V(e,t){const n=e.getText(),u=L.createHash("md5").update(n).digest("hex").substring(0,8);let o="Anonymous";n.includes("{")?o="Object":n.includes("[")?o="Array":n.includes("|")&&(o="Union");const g=t.anonymousTypeCounter.get(o)||0;t.anonymousTypeCounter.set(o,g+1);const l=`${o}_${u}`;return t.typeNames.set(e,l),l}function T(e,t){const n=D(e,t);if(t.types.has(n)||t.visitedTypes.has(e))return n;if(t.visitedTypes.add(e),e.isString()||e.isStringLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": string`),t.types.set(n,{type:"primitive"}),n;if(e.isNumber()||e.isNumberLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": number`),t.types.set(n,{type:"primitive"}),n;if(e.isBoolean()||e.isBooleanLiteral())return console.log(`[AutoUI Type Schema] Extracting primitive type "${n}": boolean`),t.types.set(n,{type:"primitive"}),n;if(e.isArray()){const s=e.getArrayElementType();if(s){console.log(`[AutoUI Type Schema] Extracting array type "${n}"`);const r=T(s,t);return t.types.set(n,{type:"array",items:{type:r},refs:[r]}),console.log(` → Array element type: "${r}"`),n}}if(e.isEnum()){const s=e.getSymbol();if(s){const r=s.getValueDeclaration();if(r&&y.Node.isEnumDeclaration(r)){const f=r.getMembers().map(i=>i.getName());return console.log(`[AutoUI Type Schema] Extracting enum type "${n}" with values: [${f.join(", ")}]`),t.types.set(n,{type:"enum",values:f}),n}}}if(e.isUnion()){const s=e.getUnionTypes();console.log(`[AutoUI Type Schema] Extracting union type "${n}" with ${s.length} union members`);const r=[];let f=!0,i=!1;for(const c of s){if(c.isUndefined()||c.isNull()){i=!0;continue}if(c.isStringLiteral()){const a=c.getLiteralValue();typeof a=="string"?r.push(a):f=!1}else f=!1}if(f&&r.length>0&&!i){const c=e.getSymbol();if(c){const a=c.getDeclarations();if(a&&a.length>0){const m=a[0];if(y.Node.isTypeAliasDeclaration(m)){const d=c.getName();return console.log(` → Converting string literal union to enum "${d}" with values: [${r.join(", ")}]`),t.types.set(d,{type:"enum",values:r}),t.typeNames.set(e,d),d}}}}const p=[];for(const c of s)if(!c.isUndefined()&&!c.isNull()){const a=T(c,t);p.includes(a)||p.push(a)}if(console.log(` → Union members: [${p.join(", ")}]`),p.length>1)return t.types.set(n,{type:"union",refs:p}),n;if(p.length===1)return console.log(` → Single type union (with undefined) - returning "${p[0]}"`),p[0]}const u={},o=[],g=e.getProperties(),l=e.getText();console.log(`[AutoUI Type Schema] Extracting object type "${n}":`),console.log(` Type text: ${l.substring(0,100)}${l.length>100?"...":""}`),console.log(` Properties count: ${g.length}`);for(const s of g){const r=s.getName();if(r.startsWith("__")||r==="toString"||r==="valueOf")continue;const f=s.getValueDeclaration()||s.getDeclarations()[0];if(!f)continue;const i=t.checker.getTypeAtLocation(f);console.log(` [Object Property] ${r}:`),console.log(` Raw type: ${i.getText()}`);const p=v(s,i),c=!p;p&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const a=A(i);a!==i&&console.log(` Extracting non-optional type: ${a.getText()}`);const m=T(a,t);u[r]={type:m,required:c},console.log(` → Evaluated type: "${m}" (required: ${c})`),o.includes(m)||o.push(m)}return t.types.set(n,{type:"object",properties:u,refs:o}),n}function W(e,t){const n={};let u=null;const o=e.getTypeArguments();if(o.length>0)u=o[0],console.log(`[AutoUI Type Schema] Extracting component props from generic type argument: ${u.getText()}`);else{const l=e.getCallSignatures();if(l.length>0){const r=l[0].getParameters();if(r.length>0){const i=r[0].getValueDeclaration();i&&(u=t.checker.getTypeAtLocation(i),console.log(`[AutoUI Type Schema] Extracting component props from call signature parameter: ${u.getText()}`))}}}if(!u)return console.log("[AutoUI Type Schema] Could not extract props type from component"),n;const g=u.getProperties();console.log(`[AutoUI Type Schema] Extracting component props from type: ${u.getText()}`),console.log(`[AutoUI Type Schema] Properties count: ${g.length}`);for(const l of g){const s=l.getName();if(s.startsWith("__")||s==="toString"||s==="valueOf")continue;const r=l.getValueDeclaration()||l.getDeclarations()[0];if(!r)continue;const f=t.checker.getTypeAtLocation(r);console.log(` [Component Prop] ${s}:`),console.log(` Raw type: ${f.getText()}`);const i=v(l,f),p=!i;i&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const c=A(f);c!==f&&console.log(` Extracting non-optional type: ${c.getText()}`);const a=T(c,t);n[s]={type:a,required:p},console.log(` → Evaluated type: "${a}" (required: ${p})`)}return n}function M(e,t){const n={},u=e.getCallSignatures();if(u.length>0){const o=u[0],g=o.getParameters();console.log(`[AutoUI Type Schema] Extracting function parameters (count: ${g.length})`);for(const r of g){const f=r.getName();if(f&&!f.startsWith("__")){const i=r.getValueDeclaration();if(!i)continue;const p=t.checker.getTypeAtLocation(i);console.log(` [Function Param] ${f}:`),console.log(` Raw type: ${p.getText()}`);const c=v(r,p),a=!c;c&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const m=A(p);m!==p&&console.log(` Extracting non-optional type: ${m.getText()}`);const d=T(m,t);n[f]={type:d,required:a},console.log(` → Evaluated type: "${d}" (required: ${a})`)}else{const i=r.getValueDeclaration();if(!i)continue;const p=t.checker.getTypeAtLocation(i);if(console.log(" [Function Param] (destructured):"),console.log(` Raw type: ${p.getText()}`),p.isObject()){const c=p.getProperties();console.log(` Extracting destructured object properties (count: ${c.length})`);for(const a of c){const m=a.getName();if(m.startsWith("__"))continue;console.log(` [Destructured Prop] ${m}:`);const d=a.getValueDeclaration()||a.getDeclarations()[0];if(!d)continue;const N=t.checker.getTypeAtLocation(d);console.log(` Raw type: ${N.getText()}`);const E=v(a,N),x=!E;E&&console.log(" Detected as optional (question token, union with undefined/null, or default value)");const U=A(N);U!==N&&console.log(` Extracting non-optional type: ${U.getText()}`);const I=T(U,t);n[m]={type:I,required:x},console.log(` → Evaluated type: "${I}" (required: ${x})`)}}else{const c=T(p,t);n.param={type:c,required:!0},console.log(` → Evaluated type: "${c}" (required: true)`)}}}const l=o.getReturnType(),s=T(l,t);return console.log(` [Function Return] → Evaluated type: "${s}"`),{params:n,returns:{type:s}}}return{params:n,returns:{type:"void"}}}function w(e,t,n){const o={checker:e.getTypeChecker(),types:new Map,typeNames:new Map,visitedTypes:new Set,anonymousTypeCounter:new Map};console.log(`[AutoUI Type Schema] Starting schema generation for appId: ${t}, version: ${n}`);const{components:g,functions:l}=R(e);console.log(`[AutoUI Type Schema] Found ${g.length} component(s) and ${l.length} function(s)`);const s=[];for(const{name:i,type:p}of g){console.log(`
2
+ [AutoUI Type Schema] ========================================`),console.log(`[AutoUI Type Schema] Processing Component: "${i}"`),console.log("[AutoUI Type Schema] ========================================");const c=W(p,o);s.push({name:i,props:c}),console.log(`[AutoUI Type Schema] ✓ Component "${i}" processed with ${Object.keys(c).length} prop(s)`)}const r=[];for(const{name:i,type:p}of l){console.log(`
3
+ [AutoUI Type Schema] ========================================`),console.log(`[AutoUI Type Schema] Processing Function: "${i}"`),console.log("[AutoUI Type Schema] ========================================");const{params:c,returns:a}=M(p,o);r.push({name:i,params:c,returns:a}),console.log(`[AutoUI Type Schema] ✓ Function "${i}" processed with ${Object.keys(c).length} param(s), return type: "${a.type}"`)}const f={};for(const[i,p]of o.types.entries())f[i]=p;return{appId:t,version:n,generatedAt:new Date().toISOString(),types:f,components:s,functions:r}}function $(e){const t={};if(!S.existsSync(e))return t;try{const u=S.readFileSync(e,"utf-8").split(`
4
+ `);for(const o of u){const g=o.trim();if(!g||g.startsWith("#"))continue;const l=g.match(/^([^=:#]+)=(.*)$/);if(l){const s=l[1].trim();let r=l[2].trim();(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))&&(r=r.slice(1,-1)),t[s]=r}}}catch{}return t}function F(e="development"){const t=process.cwd(),n={},u=$(h.resolve(t,".env"));Object.assign(n,u);const o=$(h.resolve(t,`.env.${e}`));Object.assign(n,o);const g=$(h.resolve(t,".env.local"));Object.assign(n,g);const l=process.env.NODE_ENV||e;if(l!==e){const s=$(h.resolve(t,`.env.${l}`));Object.assign(n,s)}return n}async function B(e={}){const t=e.runtimeSchemaFile||".autoui-runtime-schema.json",n=process.env.NODE_ENV||"development",o={...F(n),...process.env},g=e.appId||o.AUTOUI_APP_ID||"unknown",l=e.version||o.AUTOUI_VERSION||"1.0.0";try{let s;e.tsconfigPath?s=h.resolve(process.cwd(),e.tsconfigPath):(s=h.resolve(process.cwd(),"tsconfig.json"),S.existsSync(s)||(s=h.resolve(process.cwd(),"tsconfig.app.json"))),S.existsSync(s)||(console.warn("[AutoUI Next.js Standalone] No tsconfig.json or tsconfig.app.json found, skipping schema extraction"),process.exit(0));const r=new y.Project({tsConfigFilePath:s});r.getSourceFiles().filter(a=>!a.isDeclarationFile()&&!a.getFilePath().includes("node_modules")).length===0&&(console.warn("[AutoUI Next.js Standalone] No source files found after filtering!"),process.exit(0)),console.log(`[AutoUI Next.js Standalone] Generating schema for appId: ${g}, version: ${l}`);const i=w(r,g,l);i.components.length===0&&i.functions.length===0&&(console.log("[AutoUI Next.js Standalone] No components or functions found, skipping schema file generation"),process.exit(0));const p=h.resolve(process.cwd(),t),c=h.resolve(p,"..");if(!S.existsSync(c)){const{mkdirSync:a}=await import("node:fs");a(c,{recursive:!0})}S.writeFileSync(p,JSON.stringify(i,null,2),"utf-8"),console.log(`✅ [AutoUI Next.js Standalone] Schema written to ${t}`),console.log(` Components: ${i.components.length}`),console.log(` Functions: ${i.functions.length}`),console.log(` Types: ${Object.keys(i.types).length}`)}catch(s){console.error("❌ [AutoUI Next.js Standalone] Error generating schema:",s),s instanceof Error&&(console.error(` Error message: ${s.message}`),s.stack&&console.error(` Stack trace: ${s.stack}`)),process.exit(1)}}exports.generateSchema=w;exports.generateSchemaStandalone=B;exports.loadEnvVars=F;
@@ -0,0 +1,412 @@
1
+ import { existsSync as N, readFileSync as D, writeFileSync as w } from "node:fs";
2
+ import { resolve as h } from "node:path";
3
+ import { Node as d, Project as F } from "ts-morph";
4
+ import { createHash as P } from "node:crypto";
5
+ function k(n) {
6
+ const e = [], t = [], p = n.getSourceFiles(), o = n.getTypeChecker();
7
+ for (const g of p)
8
+ g.isDeclarationFile() || g.getFilePath().includes("node_modules") || g.forEachDescendant((l) => {
9
+ if (d.isCallExpression(l)) {
10
+ const s = l.getExpression();
11
+ if (d.isIdentifier(s)) {
12
+ const i = s.getText();
13
+ if (i === "autouiRegisterComponentPropsSchema") {
14
+ const f = l.getArguments();
15
+ if (f.length > 0) {
16
+ const r = f[0], u = o.getTypeAtLocation(r), c = o.getSymbolAtLocation(r);
17
+ let a = "Unknown";
18
+ if (c)
19
+ a = c.getName();
20
+ else {
21
+ const m = u.getSymbol();
22
+ m && (a = m.getName());
23
+ }
24
+ console.log(`[AutoUI Type Schema] Found component registration: "${a}"`), e.push({ name: a, type: u });
25
+ }
26
+ }
27
+ if (i === "autouiRegisterFunctionParamsSchema") {
28
+ const f = l.getArguments();
29
+ if (f.length > 0) {
30
+ const r = f[0], u = o.getTypeAtLocation(r), c = o.getSymbolAtLocation(r);
31
+ let a = "Unknown";
32
+ if (c)
33
+ a = c.getName();
34
+ else {
35
+ const m = u.getSymbol();
36
+ m && (a = m.getName());
37
+ }
38
+ console.log(`[AutoUI Type Schema] Found function registration: "${a}"`), t.push({ name: a, type: u });
39
+ }
40
+ }
41
+ }
42
+ }
43
+ });
44
+ return { components: e, functions: t };
45
+ }
46
+ function A(n, e) {
47
+ const t = n.getDeclarations();
48
+ for (const o of t)
49
+ if (d.isPropertySignature(o) && o.hasQuestionToken() || d.isParameterDeclaration(o) && (o.hasQuestionToken() || o.hasInitializer()) || d.isBindingElement(o) && o.hasInitializer())
50
+ return !0;
51
+ if (e.isUnion()) {
52
+ const o = e.getUnionTypes(), g = o.some((s) => {
53
+ if (s.isUndefined()) return !0;
54
+ const i = s.getText();
55
+ if (i === "undefined" || i === "void") return !0;
56
+ try {
57
+ if ((s.getFlags() & 256) !== 0) return !0;
58
+ } catch {
59
+ }
60
+ return !1;
61
+ }), l = o.some((s) => !!(s.isNull() || s.getText() === "null"));
62
+ if (g || l)
63
+ return !0;
64
+ }
65
+ if (e.isUndefined())
66
+ return !0;
67
+ const p = e.getText();
68
+ return p === "undefined" || p === "void";
69
+ }
70
+ function v(n) {
71
+ if (n.isUnion()) {
72
+ const t = n.getUnionTypes().find((p) => {
73
+ if (p.isUndefined() || p.isNull()) return !1;
74
+ const o = p.getText();
75
+ if (o === "undefined" || o === "null" || o === "void")
76
+ return !1;
77
+ try {
78
+ if ((p.getFlags() & 256) !== 0) return !1;
79
+ } catch {
80
+ }
81
+ return !0;
82
+ });
83
+ if (t)
84
+ return t;
85
+ }
86
+ return n;
87
+ }
88
+ function x(n, e) {
89
+ if (e.typeNames.has(n))
90
+ return e.typeNames.get(n);
91
+ const t = n.getSymbol();
92
+ if (t) {
93
+ const o = t.getName();
94
+ if (o && o !== "__type" && o !== "__function") {
95
+ const g = t.getDeclarations();
96
+ if (g && g.length > 0) {
97
+ const l = g[0], s = l.getSourceFile();
98
+ if (!s.isDeclarationFile() && !s.getFilePath().includes("node_modules") && (d.isTypeAliasDeclaration(l) || d.isInterfaceDeclaration(l) || d.isEnumDeclaration(l)))
99
+ return e.typeNames.set(n, o), o;
100
+ }
101
+ }
102
+ }
103
+ if (n.isArray()) {
104
+ const o = n.getArrayElementType();
105
+ if (o)
106
+ return `${x(o, e)}[]`;
107
+ }
108
+ const p = n.getText();
109
+ return p === "string" || p === "number" || p === "boolean" ? p : j(n, e);
110
+ }
111
+ function j(n, e) {
112
+ const t = n.getText(), p = P("md5").update(t).digest("hex").substring(0, 8);
113
+ let o = "Anonymous";
114
+ t.includes("{") ? o = "Object" : t.includes("[") ? o = "Array" : t.includes("|") && (o = "Union");
115
+ const g = e.anonymousTypeCounter.get(o) || 0;
116
+ e.anonymousTypeCounter.set(o, g + 1);
117
+ const l = `${o}_${p}`;
118
+ return e.typeNames.set(n, l), l;
119
+ }
120
+ function T(n, e) {
121
+ const t = x(n, e);
122
+ if (e.types.has(t) || e.visitedTypes.has(n))
123
+ return t;
124
+ if (e.visitedTypes.add(n), n.isString() || n.isStringLiteral())
125
+ return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": string`), e.types.set(t, { type: "primitive" }), t;
126
+ if (n.isNumber() || n.isNumberLiteral())
127
+ return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": number`), e.types.set(t, { type: "primitive" }), t;
128
+ if (n.isBoolean() || n.isBooleanLiteral())
129
+ return console.log(`[AutoUI Type Schema] Extracting primitive type "${t}": boolean`), e.types.set(t, { type: "primitive" }), t;
130
+ if (n.isArray()) {
131
+ const s = n.getArrayElementType();
132
+ if (s) {
133
+ console.log(`[AutoUI Type Schema] Extracting array type "${t}"`);
134
+ const i = T(s, e);
135
+ return e.types.set(t, {
136
+ type: "array",
137
+ items: { type: i },
138
+ refs: [i]
139
+ }), console.log(` → Array element type: "${i}"`), t;
140
+ }
141
+ }
142
+ if (n.isEnum()) {
143
+ const s = n.getSymbol();
144
+ if (s) {
145
+ const i = s.getValueDeclaration();
146
+ if (i && d.isEnumDeclaration(i)) {
147
+ const f = i.getMembers().map((r) => r.getName());
148
+ return console.log(`[AutoUI Type Schema] Extracting enum type "${t}" with values: [${f.join(", ")}]`), e.types.set(t, {
149
+ type: "enum",
150
+ values: f
151
+ }), t;
152
+ }
153
+ }
154
+ }
155
+ if (n.isUnion()) {
156
+ const s = n.getUnionTypes();
157
+ console.log(`[AutoUI Type Schema] Extracting union type "${t}" with ${s.length} union members`);
158
+ const i = [];
159
+ let f = !0, r = !1;
160
+ for (const c of s) {
161
+ if (c.isUndefined() || c.isNull()) {
162
+ r = !0;
163
+ continue;
164
+ }
165
+ if (c.isStringLiteral()) {
166
+ const a = c.getLiteralValue();
167
+ typeof a == "string" ? i.push(a) : f = !1;
168
+ } else
169
+ f = !1;
170
+ }
171
+ if (f && i.length > 0 && !r) {
172
+ const c = n.getSymbol();
173
+ if (c) {
174
+ const a = c.getDeclarations();
175
+ if (a && a.length > 0) {
176
+ const m = a[0];
177
+ if (d.isTypeAliasDeclaration(m)) {
178
+ const y = c.getName();
179
+ return console.log(` → Converting string literal union to enum "${y}" with values: [${i.join(", ")}]`), e.types.set(y, {
180
+ type: "enum",
181
+ values: i
182
+ }), e.typeNames.set(n, y), y;
183
+ }
184
+ }
185
+ }
186
+ }
187
+ const u = [];
188
+ for (const c of s)
189
+ if (!c.isUndefined() && !c.isNull()) {
190
+ const a = T(c, e);
191
+ u.includes(a) || u.push(a);
192
+ }
193
+ if (console.log(` → Union members: [${u.join(", ")}]`), u.length > 1)
194
+ return e.types.set(t, {
195
+ type: "union",
196
+ refs: u
197
+ }), t;
198
+ if (u.length === 1)
199
+ return console.log(` → Single type union (with undefined) - returning "${u[0]}"`), u[0];
200
+ }
201
+ const p = {}, o = [], g = n.getProperties(), l = n.getText();
202
+ console.log(`[AutoUI Type Schema] Extracting object type "${t}":`), console.log(` Type text: ${l.substring(0, 100)}${l.length > 100 ? "..." : ""}`), console.log(` Properties count: ${g.length}`);
203
+ for (const s of g) {
204
+ const i = s.getName();
205
+ if (i.startsWith("__") || i === "toString" || i === "valueOf")
206
+ continue;
207
+ const f = s.getValueDeclaration() || s.getDeclarations()[0];
208
+ if (!f) continue;
209
+ const r = e.checker.getTypeAtLocation(f);
210
+ console.log(` [Object Property] ${i}:`), console.log(` Raw type: ${r.getText()}`);
211
+ const u = A(s, r), c = !u;
212
+ u && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
213
+ const a = v(r);
214
+ a !== r && console.log(` Extracting non-optional type: ${a.getText()}`);
215
+ const m = T(a, e);
216
+ p[i] = { type: m, required: c }, console.log(` → Evaluated type: "${m}" (required: ${c})`), o.includes(m) || o.push(m);
217
+ }
218
+ return e.types.set(t, {
219
+ type: "object",
220
+ properties: p,
221
+ refs: o
222
+ }), t;
223
+ }
224
+ function O(n, e) {
225
+ const t = {};
226
+ let p = null;
227
+ const o = n.getTypeArguments();
228
+ if (o.length > 0)
229
+ p = o[0], console.log(`[AutoUI Type Schema] Extracting component props from generic type argument: ${p.getText()}`);
230
+ else {
231
+ const l = n.getCallSignatures();
232
+ if (l.length > 0) {
233
+ const i = l[0].getParameters();
234
+ if (i.length > 0) {
235
+ const r = i[0].getValueDeclaration();
236
+ r && (p = e.checker.getTypeAtLocation(r), console.log(`[AutoUI Type Schema] Extracting component props from call signature parameter: ${p.getText()}`));
237
+ }
238
+ }
239
+ }
240
+ if (!p)
241
+ return console.log("[AutoUI Type Schema] Could not extract props type from component"), t;
242
+ const g = p.getProperties();
243
+ console.log(`[AutoUI Type Schema] Extracting component props from type: ${p.getText()}`), console.log(`[AutoUI Type Schema] Properties count: ${g.length}`);
244
+ for (const l of g) {
245
+ const s = l.getName();
246
+ if (s.startsWith("__") || s === "toString" || s === "valueOf")
247
+ continue;
248
+ const i = l.getValueDeclaration() || l.getDeclarations()[0];
249
+ if (!i) continue;
250
+ const f = e.checker.getTypeAtLocation(i);
251
+ console.log(` [Component Prop] ${s}:`), console.log(` Raw type: ${f.getText()}`);
252
+ const r = A(l, f), u = !r;
253
+ r && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
254
+ const c = v(f);
255
+ c !== f && console.log(` Extracting non-optional type: ${c.getText()}`);
256
+ const a = T(c, e);
257
+ t[s] = { type: a, required: u }, console.log(` → Evaluated type: "${a}" (required: ${u})`);
258
+ }
259
+ return t;
260
+ }
261
+ function _(n, e) {
262
+ const t = {}, p = n.getCallSignatures();
263
+ if (p.length > 0) {
264
+ const o = p[0], g = o.getParameters();
265
+ console.log(`[AutoUI Type Schema] Extracting function parameters (count: ${g.length})`);
266
+ for (const i of g) {
267
+ const f = i.getName();
268
+ if (f && !f.startsWith("__")) {
269
+ const r = i.getValueDeclaration();
270
+ if (!r) continue;
271
+ const u = e.checker.getTypeAtLocation(r);
272
+ console.log(` [Function Param] ${f}:`), console.log(` Raw type: ${u.getText()}`);
273
+ const c = A(i, u), a = !c;
274
+ c && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
275
+ const m = v(u);
276
+ m !== u && console.log(` Extracting non-optional type: ${m.getText()}`);
277
+ const y = T(m, e);
278
+ t[f] = { type: y, required: a }, console.log(` → Evaluated type: "${y}" (required: ${a})`);
279
+ } else {
280
+ const r = i.getValueDeclaration();
281
+ if (!r) continue;
282
+ const u = e.checker.getTypeAtLocation(r);
283
+ if (console.log(" [Function Param] (destructured):"), console.log(` Raw type: ${u.getText()}`), u.isObject()) {
284
+ const c = u.getProperties();
285
+ console.log(` Extracting destructured object properties (count: ${c.length})`);
286
+ for (const a of c) {
287
+ const m = a.getName();
288
+ if (m.startsWith("__")) continue;
289
+ console.log(` [Destructured Prop] ${m}:`);
290
+ const y = a.getValueDeclaration() || a.getDeclarations()[0];
291
+ if (!y) continue;
292
+ const S = e.checker.getTypeAtLocation(y);
293
+ console.log(` Raw type: ${S.getText()}`);
294
+ const E = A(a, S), I = !E;
295
+ E && console.log(" Detected as optional (question token, union with undefined/null, or default value)");
296
+ const U = v(S);
297
+ U !== S && console.log(` Extracting non-optional type: ${U.getText()}`);
298
+ const b = T(U, e);
299
+ t[m] = { type: b, required: I }, console.log(` → Evaluated type: "${b}" (required: ${I})`);
300
+ }
301
+ } else {
302
+ const c = T(u, e);
303
+ t.param = { type: c, required: !0 }, console.log(` → Evaluated type: "${c}" (required: true)`);
304
+ }
305
+ }
306
+ }
307
+ const l = o.getReturnType(), s = T(l, e);
308
+ return console.log(` [Function Return] → Evaluated type: "${s}"`), { params: t, returns: { type: s } };
309
+ }
310
+ return { params: t, returns: { type: "void" } };
311
+ }
312
+ function q(n, e, t) {
313
+ const o = {
314
+ checker: n.getTypeChecker(),
315
+ types: /* @__PURE__ */ new Map(),
316
+ typeNames: /* @__PURE__ */ new Map(),
317
+ visitedTypes: /* @__PURE__ */ new Set(),
318
+ anonymousTypeCounter: /* @__PURE__ */ new Map()
319
+ };
320
+ console.log(`[AutoUI Type Schema] Starting schema generation for appId: ${e}, version: ${t}`);
321
+ const { components: g, functions: l } = k(n);
322
+ console.log(`[AutoUI Type Schema] Found ${g.length} component(s) and ${l.length} function(s)`);
323
+ const s = [];
324
+ for (const { name: r, type: u } of g) {
325
+ console.log(`
326
+ [AutoUI Type Schema] ========================================`), console.log(`[AutoUI Type Schema] Processing Component: "${r}"`), console.log("[AutoUI Type Schema] ========================================");
327
+ const c = O(u, o);
328
+ s.push({ name: r, props: c }), console.log(`[AutoUI Type Schema] ✓ Component "${r}" processed with ${Object.keys(c).length} prop(s)`);
329
+ }
330
+ const i = [];
331
+ for (const { name: r, type: u } of l) {
332
+ console.log(`
333
+ [AutoUI Type Schema] ========================================`), console.log(`[AutoUI Type Schema] Processing Function: "${r}"`), console.log("[AutoUI Type Schema] ========================================");
334
+ const { params: c, returns: a } = _(u, o);
335
+ i.push({ name: r, params: c, returns: a }), console.log(`[AutoUI Type Schema] ✓ Function "${r}" processed with ${Object.keys(c).length} param(s), return type: "${a.type}"`);
336
+ }
337
+ const f = {};
338
+ for (const [r, u] of o.types.entries())
339
+ f[r] = u;
340
+ return {
341
+ appId: e,
342
+ version: t,
343
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
344
+ types: f,
345
+ components: s,
346
+ functions: i
347
+ };
348
+ }
349
+ function $(n) {
350
+ const e = {};
351
+ if (!N(n))
352
+ return e;
353
+ try {
354
+ const p = D(n, "utf-8").split(`
355
+ `);
356
+ for (const o of p) {
357
+ const g = o.trim();
358
+ if (!g || g.startsWith("#"))
359
+ continue;
360
+ const l = g.match(/^([^=:#]+)=(.*)$/);
361
+ if (l) {
362
+ const s = l[1].trim();
363
+ let i = l[2].trim();
364
+ (i.startsWith('"') && i.endsWith('"') || i.startsWith("'") && i.endsWith("'")) && (i = i.slice(1, -1)), e[s] = i;
365
+ }
366
+ }
367
+ } catch {
368
+ }
369
+ return e;
370
+ }
371
+ function C(n = "development") {
372
+ const e = process.cwd(), t = {}, p = $(h(e, ".env"));
373
+ Object.assign(t, p);
374
+ const o = $(h(e, `.env.${n}`));
375
+ Object.assign(t, o);
376
+ const g = $(h(e, ".env.local"));
377
+ Object.assign(t, g);
378
+ const l = process.env.NODE_ENV || n;
379
+ if (l !== n) {
380
+ const s = $(h(e, `.env.${l}`));
381
+ Object.assign(t, s);
382
+ }
383
+ return t;
384
+ }
385
+ async function M(n = {}) {
386
+ const e = n.runtimeSchemaFile || ".autoui-runtime-schema.json", t = process.env.NODE_ENV || "development", o = { ...C(t), ...process.env }, g = n.appId || o.AUTOUI_APP_ID || "unknown", l = n.version || o.AUTOUI_VERSION || "1.0.0";
387
+ try {
388
+ let s;
389
+ n.tsconfigPath ? s = h(process.cwd(), n.tsconfigPath) : (s = h(process.cwd(), "tsconfig.json"), N(s) || (s = h(process.cwd(), "tsconfig.app.json"))), N(s) || (console.warn("[AutoUI Next.js Standalone] No tsconfig.json or tsconfig.app.json found, skipping schema extraction"), process.exit(0));
390
+ const i = new F({
391
+ tsConfigFilePath: s
392
+ });
393
+ i.getSourceFiles().filter(
394
+ (a) => !a.isDeclarationFile() && !a.getFilePath().includes("node_modules")
395
+ ).length === 0 && (console.warn("[AutoUI Next.js Standalone] No source files found after filtering!"), process.exit(0)), console.log(`[AutoUI Next.js Standalone] Generating schema for appId: ${g}, version: ${l}`);
396
+ const r = q(i, g, l);
397
+ r.components.length === 0 && r.functions.length === 0 && (console.log("[AutoUI Next.js Standalone] No components or functions found, skipping schema file generation"), process.exit(0));
398
+ const u = h(process.cwd(), e), c = h(u, "..");
399
+ if (!N(c)) {
400
+ const { mkdirSync: a } = await import("node:fs");
401
+ a(c, { recursive: !0 });
402
+ }
403
+ w(u, JSON.stringify(r, null, 2), "utf-8"), console.log(`✅ [AutoUI Next.js Standalone] Schema written to ${e}`), console.log(` Components: ${r.components.length}`), console.log(` Functions: ${r.functions.length}`), console.log(` Types: ${Object.keys(r.types).length}`);
404
+ } catch (s) {
405
+ console.error("❌ [AutoUI Next.js Standalone] Error generating schema:", s), s instanceof Error && (console.error(` Error message: ${s.message}`), s.stack && console.error(` Stack trace: ${s.stack}`)), process.exit(1);
406
+ }
407
+ }
408
+ export {
409
+ q as a,
410
+ M as g,
411
+ C as l
412
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autoai-ui/autoui",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "scripts": {
@@ -96,6 +96,17 @@
96
96
  "react": ">=19.0.0 < 20.0.0",
97
97
  "react-dom": ">=19.0.0 <20.0.0"
98
98
  },
99
+ "peerDependenciesMeta": {
100
+ "next": {
101
+ "optional": true
102
+ },
103
+ "webpack": {
104
+ "optional": true
105
+ }
106
+ },
107
+ "bin": {
108
+ "autoui-nextjs-generate-schema": "./dist/nextjs-standalone.mjs"
109
+ },
99
110
  "exports": {
100
111
  ".": {
101
112
  "types": "./dist/index.d.ts",
@@ -106,6 +117,11 @@
106
117
  "types": "./dist/plugin.d.ts",
107
118
  "import": "./dist/plugin.mjs",
108
119
  "require": "./dist/plugin.cjs"
120
+ },
121
+ "./nextjs": {
122
+ "types": "./dist/nextjs.d.ts",
123
+ "import": "./dist/nextjs.mjs",
124
+ "require": "./dist/nextjs.cjs"
109
125
  }
110
126
  },
111
127
  "types": "dist/index.d.ts",