@xaendar/compiler 0.9.3 → 0.9.4

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.
Files changed (2) hide show
  1. package/dist/compiler.js +17 -17
  2. package/package.json +3 -3
package/dist/compiler.js CHANGED
@@ -1,19 +1,19 @@
1
- import{indent as $,slice as $t}from"@xaendar/common";var E=(f=>(f[f.Element=0]="Element",f[f.Attribute=1]="Attribute",f[f.Event=2]="Event",f[f.Text=3]="Text",f[f.Interpolation=4]="Interpolation",f[f.If=5]="If",f[f.Else=6]="Else",f[f.ElseIf=7]="ElseIf",f[f.For=8]="For",f[f.Switch=9]="Switch",f[f.Case=10]="Case",f[f.Import=11]="Import",f))(E||{});var C=class{constructor(r=[],t){this.parent=t;for(let n of r)typeof n=="string"?this._identifiers.set(n,"value"):this._identifiers.set(n[0],n[1])}parent;_identifiers=new Map;_unresolvableIdentifiers=new Array;addIdentifier(r,t="value"){if(this.hasIdentifier(r))throw new Error(`Identifier "${r}" is already declared in this scope.`);this._identifiers.set(r,t)}addUnresolvableIdentifier(r){if(this.hasIdentifier(r))throw new Error(`Identifier "${r}" is already declared in this scope.`);this._unresolvableIdentifiers.push(r)}removeIdentifier(r){this._identifiers.delete(r)}removeUnresolvabledIdentifier(r){this._unresolvableIdentifiers=this._unresolvableIdentifiers.filter(t=>t!==r)}hasIdentifier(r){return this._identifiers.has(r)||(this.parent?.hasIdentifier(r)??!1)}getIdentifierKind(r){return this._identifiers.get(r)??this.parent?.getIdentifierKind(r)}hasUnresolvableIdentifier(r){return this._unresolvableIdentifiers.includes(r)||(this.parent?.hasUnresolvableIdentifier(r)??!1)}};import{indent as F}from"@xaendar/common";import{forEachChild as ge,isIdentifier as Ie,isPropertyAccessExpression as vt,isPropertyAssignment as _t}from"typescript";var St=new Set(["undefined","NaN","Infinity","globalThis","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape","Object","Function","Boolean","Symbol","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","SuppressedError","InternalError","Number","BigInt","Math","Date","Temporal","String","RegExp","Array","TypedArray","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","BigInt64Array","BigUint64Array","Float16Array","Float32Array","Float64Array","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Atomics","JSON","WeakRef","FinalizationRegistry","Iterator","AsyncIterator","Promise","GeneratorFunction","AsyncGeneratorFunction","Generator","AsyncGenerator","AsyncFunction","DisposableStack","AsyncDisposableStack","Reflect","Proxy","Intl","WebAssembly","window","document","navigator","location","history","screen","console","performance","crypto","fetch","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","queueMicrotask","structuredClone","URL","URLSearchParams","FormData","Headers","Request","Response","AbortController","AbortSignal","CustomEvent","Event","EventTarget","MutationObserver","IntersectionObserver","ResizeObserver","PerformanceObserver","Worker","SharedWorker","ServiceWorker","Blob","File","FileReader","ReadableStream","WritableStream","TransformStream","TextEncoder","TextDecoder","ImageData","Canvas","Storage","localStorage","sessionStorage","indexedDB","WebSocket","XMLHttpRequest","HTMLElement","HTMLInputElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLSelectElement","HTMLTextAreaElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLHeadingElement","HTMLTableElement","HTMLTableRowElement","HTMLTableCellElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLLabelElement","HTMLDialogElement","HTMLDetailsElement","HTMLSlotElement","HTMLTemplateElement","SVGElement","SVGSVGElement","Element","Node","NodeList","DocumentFragment","ShadowRoot","Document","Window"]),V="root";function T(e,r,t){return Le(e,e,r,Ot(t))}function Le(e,r,t,n){if(Ie(e)&&ve(e,r)){let a=e.text;if(t?.hasUnresolvableIdentifier(a)||n.skipResolution)return a;if(t){let c=wt(a,t);if(c)return c}return n.resolver?`${n.resolver}.${a}`:a}if(!ye(e,r))return e.getText();let o=e.getSourceFile().text,i="",s=e.getStart();return ge(e,a=>{i=`${i}${o.slice(s,a.getStart())}${Le(a,e,t,n)}`,s=a.getEnd()}),`${i}${o.slice(s,e.getEnd())}`}function wt(e,r){if(r.hasIdentifier(e)){let t=r.getIdentifierKind(e),n=`context.get('${e}')`;return t==="signal"?`${n}()`:n}}function ye(e,r){if(Ie(e)&&ve(e,r))return!0;let t=!1;return ge(e,n=>{t||(t=ye(n,e))}),t}function ve(e,r){return!(vt(r)&&r.name===e||_t(r)&&r.name===e||St.has(e.text)||!e.text)}function _e(e,r,t){return ae(e.tagName,r,t)}function se(e="text",r,t){return ae(e,r,t)}function w(e,r,t){return ae(e,r,t)}function ae(e,r,t){return(r!==V?`${r}__${e}${t}`:`${e}${t}`).replace(/-/g,"_")}function Ot(e){return{skipResolution:e?.skipResolution??!1,resolver:e?.resolver??"this"}}function Se(e,r,t,n,o){let i=Rt(e.attributes,n),s=bt(e.events,n),a=_e(e,r,t),c=e.tagName,m={code:[],functionsToProcess:new Map};switch(c){case"svg":m.code.push("context.createElement = createSVGElement");break;case"math":m.code.push("context.createElement = createMATHMLElement")}switch(m.code.push(`const ${a} = _renderElement(${r}, context, ${o}, '${c}',`),i.length?m.code.push(...F(["[",...F(i),"],"])):m.code[m.code.length-1]=`${m.code[m.code.length-1]} [],`,s.length?m.code.push(...F(["[",...F(s),"]"]),");"):m.code[m.code.length-1]=`${m.code[m.code.length-1]} []);`,c){case"svg":case"math":m.code.push("context.createElement = createElement")}return e.children.length&&(m.functionsToProcess.set(`${a}Children`,{fn:{node:e,parentNode:a,context:n,precode:Ft(c)},args:[a,"parentContext"]}),m.code.push(`this.${a}Children(${a}, context);`)),m}function Rt(e,r){return e?.map(({name:t,value:n})=>{let o=typeof n=="string";return`{ name: '${t}', value: () => ${o?`'${n}'`:T(n.expression,r)}, literal: ${o} },`})}function bt(e,r){r.addUnresolvableIdentifier("$event");let t=e.map(n=>{let o=!1,i=n.parameters.map(a=>{let c=T(a,r);return!o&&c==="$event"?(o=!0,`($event) => ${c},`):`() => ${c},`}),s=["{",...F([`name: '${n.name}',`,`handler: '${n.handler}',`,"parameters: ["])];return i.length?s.push(...F([...F(i),"]"]),"},"):(s[s.length-1]=`${s[s.length-1]}]`,s.push("},")),s}).flat();return r.removeIdentifier("$event"),t}function Ft(e){switch(e){case"svg":return"context.createElement = createSVGElement;";case"math":return"context.createElement = createMATHMLElement;";default:return""}}function we(e,r,t,n){let o={code:[],functionsToProcess:new Map},i=e.iterableSource,s=n.hasIdentifier(i)?i:`this.${i}`,a=se("items",r,t),c=se("i",r,t),m=U(e,"$index"),d=U(e,"$first"),x=U(e,"$last"),f=U(e,"$even"),A=U(e,"$odd"),g=new C([e.itemAlias,[m,"signal"],[d,"signal"],[x,"signal"],[f,"signal"],[A,"signal"]],n),S=w("for",r,t);return o.functionsToProcess.set(S,{fn:{precode:`const { vars, update } = _iterationVariables(context, ${a}, ${c}, '${e.itemAlias}', {
2
- $index: '${m}',
3
- $first: '${d}',
4
- $last: '${x}',
1
+ import{indent as P,slice as Vt}from"@xaendar/common";var E=(f=>(f[f.Element=0]="Element",f[f.Attribute=1]="Attribute",f[f.Event=2]="Event",f[f.Text=3]="Text",f[f.Interpolation=4]="Interpolation",f[f.If=5]="If",f[f.Else=6]="Else",f[f.ElseIf=7]="ElseIf",f[f.For=8]="For",f[f.Switch=9]="Switch",f[f.Case=10]="Case",f[f.Import=11]="Import",f))(E||{});var k=class{constructor(n=[],t){this.parent=t;for(let r=0;r<n.length;r++){let o=n[r];typeof o=="string"?this._identifiers.set(o,"value"):this._identifiers.set(o[0],o[1])}}parent;_identifiers=new Map;_unresolvableIdentifiers=new Array;addIdentifier(n,t="value"){if(this.hasIdentifier(n))throw new Error(`Identifier "${n}" is already declared in this scope.`);this._identifiers.set(n,t)}addUnresolvableIdentifier(n){if(this.hasIdentifier(n))throw new Error(`Identifier "${n}" is already declared in this scope.`);this._unresolvableIdentifiers.push(n)}removeIdentifier(n){this._identifiers.delete(n)}removeUnresolvabledIdentifier(n){this._unresolvableIdentifiers=this._unresolvableIdentifiers.filter(t=>t!==n)}hasIdentifier(n){return this._identifiers.has(n)||(this.parent?.hasIdentifier(n)??!1)}getIdentifierKind(n){return this._identifiers.get(n)??this.parent?.getIdentifierKind(n)}hasUnresolvableIdentifier(n){return this._unresolvableIdentifiers.includes(n)||(this.parent?.hasUnresolvableIdentifier(n)??!1)}};import{indent as $}from"@xaendar/common";import{slice as Se}from"@xaendar/common";import{forEachChild as Oe,isIdentifier as be,isPropertyAccessExpression as wt,isPropertyAssignment as $t}from"typescript";var Pt=new Set(["undefined","NaN","Infinity","globalThis","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape","Object","Function","Boolean","Symbol","Error","AggregateError","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","SuppressedError","InternalError","Number","BigInt","Math","Date","Temporal","String","RegExp","Array","TypedArray","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","BigInt64Array","BigUint64Array","Float16Array","Float32Array","Float64Array","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Atomics","JSON","WeakRef","FinalizationRegistry","Iterator","AsyncIterator","Promise","GeneratorFunction","AsyncGeneratorFunction","Generator","AsyncGenerator","AsyncFunction","DisposableStack","AsyncDisposableStack","Reflect","Proxy","Intl","WebAssembly","window","document","navigator","location","history","screen","console","performance","crypto","fetch","alert","confirm","prompt","setTimeout","setInterval","clearTimeout","clearInterval","requestAnimationFrame","cancelAnimationFrame","queueMicrotask","structuredClone","URL","URLSearchParams","FormData","Headers","Request","Response","AbortController","AbortSignal","CustomEvent","Event","EventTarget","MutationObserver","IntersectionObserver","ResizeObserver","PerformanceObserver","Worker","SharedWorker","ServiceWorker","Blob","File","FileReader","ReadableStream","WritableStream","TransformStream","TextEncoder","TextDecoder","ImageData","Canvas","Storage","localStorage","sessionStorage","indexedDB","WebSocket","XMLHttpRequest","HTMLElement","HTMLInputElement","HTMLButtonElement","HTMLFormElement","HTMLAnchorElement","HTMLImageElement","HTMLVideoElement","HTMLAudioElement","HTMLCanvasElement","HTMLSelectElement","HTMLTextAreaElement","HTMLDivElement","HTMLSpanElement","HTMLParagraphElement","HTMLHeadingElement","HTMLTableElement","HTMLTableRowElement","HTMLTableCellElement","HTMLUListElement","HTMLOListElement","HTMLLIElement","HTMLLabelElement","HTMLDialogElement","HTMLDetailsElement","HTMLSlotElement","HTMLTemplateElement","SVGElement","SVGSVGElement","Element","Node","NodeList","DocumentFragment","ShadowRoot","Document","Window"]),q="root";function h(e,n,t){return Re(e,e,n,Bt(t))}function Re(e,n,t,r){if(be(e)&&we(e,n)){let a=e.text;if(t?.hasUnresolvableIdentifier(a)||r.skipResolution)return a;if(t){let c=Mt(a,t);if(c)return c}return r.resolver?`${r.resolver}.${a}`:a}if(!Fe(e,n))return e.getText();let o=e.getSourceFile().text,i="",s=e.getStart();return Oe(e,a=>{i=`${i}${Se(o,s,a.getStart())}${Re(a,e,t,r)}`,s=a.getEnd()}),`${i}${Se(o,s,e.getEnd())}`}function Mt(e,n){if(n.hasIdentifier(e)){let t=n.getIdentifierKind(e),r=`context.get('${e}')`;return t==="signal"?`${r}()`:r}}function Fe(e,n){if(be(e)&&we(e,n))return!0;let t=!1;return Oe(e,r=>{t||(t=Fe(r,e))}),t}function we(e,n){return!(wt(n)&&n.name===e||$t(n)&&n.name===e||Pt.has(e.text)||!e.text)}function $e(e,n,t){return ce(e.tagName,n,t)}function pe(e="text",n,t){return ce(e,n,t)}function b(e,n,t){return ce(e,n,t)}function ce(e,n,t){return(n!==q?`${n}__${e}${t}`:`${e}${t}`).replace(/-/g,"_")}function Bt(e){return{skipResolution:e?.skipResolution??!1,resolver:e?.resolver??"this"}}function Pe(e,n,t,r,o){let i=Dt(e.attributes,r),s=Gt(e.events,r),a=$e(e,n,t),c=e.tagName,p={code:[],functionsToProcess:new Map};switch(c){case"svg":p.code.push("context.createElement = createSVGElement");break;case"math":p.code.push("context.createElement = createMATHMLElement")}switch(p.code.push(`const ${a} = _renderElement(${n}, context, ${o}, '${c}',`),i.length?p.code.push(...$(["[",...$(i),"],"])):p.code[p.code.length-1]=`${p.code[p.code.length-1]} [],`,s.length?p.code.push(...$(["[",...$(s),"]"]),");"):p.code[p.code.length-1]=`${p.code[p.code.length-1]} []);`,c){case"svg":case"math":p.code.push("context.createElement = createElement")}return e.children.length&&(p.functionsToProcess.set(`${a}Children`,{fn:{node:e,parentNode:a,context:r,precode:Ut(c)},args:[a,"parentContext"]}),p.code.push(`this.${a}Children(${a}, context);`)),p}function Dt(e,n){return e?.map(({name:t,value:r})=>{let o=typeof r=="string";return`{ name: '${t}', value: () => ${o?`'${r}'`:h(r.expression,n)}, literal: ${o} },`})}function Gt(e,n){n.addUnresolvableIdentifier("$event");let t=e.map(r=>{let o=!1,i=r.parameters.map(a=>{let c=h(a,n);return!o&&c==="$event"?(o=!0,`($event) => ${c},`):`() => ${c},`}),s=["{",...$([`name: '${r.name}',`,`handler: '${r.handler}',`,"parameters: ["])];return i.length?s.push(...$([...$(i),"]"]),"},"):(s[s.length-1]=`${s[s.length-1]}]`,s.push("},")),s}).flat();return n.removeIdentifier("$event"),t}function Ut(e){switch(e){case"svg":return"context.createElement = createSVGElement;";case"math":return"context.createElement = createMATHMLElement;";default:return""}}function Me(e,n,t,r){let o={code:[],functionsToProcess:new Map},i=e.iterableSource,s=r.hasIdentifier(i)?i:`this.${i}`,a=pe("items",n,t),c=pe("i",n,t),p=X(e,"$index"),u=X(e,"$first"),d=X(e,"$last"),f=X(e,"$even"),N=X(e,"$odd"),I=new k([e.itemAlias,[p,"signal"],[u,"signal"],[d,"signal"],[f,"signal"],[N,"signal"]],r),y=b("for",n,t);return o.functionsToProcess.set(y,{fn:{precode:`const { vars, update } = _iterationVariables(context, ${a}, ${c}, '${e.itemAlias}', {
2
+ $index: '${p}',
3
+ $first: '${u}',
4
+ $last: '${d}',
5
5
  $even: '${f}',
6
- $odd: '${A}'
6
+ $odd: '${N}'
7
7
  });
8
- const { ${e.itemAlias}, ${m}, ${d}, ${x}, ${f}, ${A} } = vars;`,node:e,parentNode:S,context:g,anchor:"anchor",isForBody:!0},args:[S,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${r}, context, () => ${s}, ${e.itemAlias} => ${T(e.trackExpression,g,{skipResolution:!0})}, this.${S}.bind(this));`),o}function U(e,r){return e.implicitAliases.get(r)??r}import{indent as M}from"@xaendar/common";function Oe(e,r,t,n){let o=new C([],n),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${r}, context, [`);let s=w("if",r,t);i.code.push(...M(["{",...M([`condition: () => ${T(e.conditionNode,n)},`,`block: this.${s}.bind(this)`]),"},"])),i.functionsToProcess.set(s,{fn:{node:e,parentNode:s,context:o,anchor:"anchor"},args:[s,"parentContext","anchor"]});let a=e.alternate,c=0;for(;a?.type===7;){let m=new C([],n),d=w("elseIf",r,`${t}_${c}`),x=a.conditionNode;i.code.push(...M(["{",...M([`condition: () => ${T(x,n)},`,`block: this.${d}.bind(this)`]),"},"])),i.functionsToProcess.set(d,{fn:{node:a,parentNode:r,context:m,anchor:"anchor"},args:[r,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let m=new C([],n),d=w("else",r,t);i.code.push(...M(["{",...M([`block: this.${d}.bind(this)`]),"},"])),i.functionsToProcess.set(d,{fn:{node:a,parentNode:r,context:m,anchor:"anchor"},args:[r,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as Re}from"@xaendar/common";function be(e,r,t,n){let o={code:[],functionsToProcess:new Map};return o.code.push(`_switch(${r}, context, () => ${T(e.expression,n)}, [`),e.children.forEach((i,s)=>{let a=new C([],n),c=i.condition?w("case",r,`${t}_${s}`):w("default",r,t);o.functionsToProcess.set(c,{fn:{node:i,parentNode:c,context:a},args:[c,"parentContext","anchor"]});let m=`this.${c}.bind(this)`;o.code.push(...Re(["{",...Re([`condition: ${i.condition?`[${i.condition.join(", ")}]`:"null"},`,`block: ${m}`]),"},"]))}),o.code.push("])"),o}function pe(e,r,t,n){return{code:[`${e.type===3?`_renderLiteralText(${r}, context, '${e.value}');`:`_renderText(${r}, context, () => ${T(e.expression,n)});`}`]}}function Fe(e,r,t,n){}var Q=class{constructor(r,t){this._input=r;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:pe,4:pe,0:Se,5:Oe,8:we,9:be,11:Fe};generate(r){try{this._nodeToProcess.clear();let t=new C,n=["_render() {",...$([`const ${V} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];r&&n.push($(`${V}.adoptedStyleSheets = [${r}];`));for(let o=0;o<this._ast.length;o++){let i=this._processNode(this._ast[o],V,o.toString(),t,null);if(i){let{code:s,functionsToProcess:a}=i;a?.forEach((c,m)=>this._nodeToProcess.set(m,c)),n.push(...$(s))}}n.push(...$(["return context;"]),"}");for(let[o,i]of this._nodeToProcess.entries()){let{node:s,parentNode:a,context:c,precode:m,anchor:d}=i.fn;n.push(`
9
- ${o}(${i.args?.join(", ")}) {`,...$(["const context = new Context(this, parentContext);"])),m&&n.push($(m)),n.push(...$([...s.children.map((x,f)=>{let A=this._processNode(x,a,f.toString(),c,d??null);if(A){let{code:g,functionsToProcess:S}=A;return S?.forEach((q,X)=>this._nodeToProcess.set(X,q)),g}return""}).flat(),i.fn.isForBody?"return { context, update };":"return context;"]),"}")}return n.join(`
10
- `)}catch(t){let n=t,{start:o,end:i}=n.cause;throw new Error(`[Generator] ${n.message}
11
- ----> ${$t(this._input,o,i)}`)}}_processNode(r,t,n,o,i){let s=this._states[r.type];if(!s)throw new Error(`No transition function for token type ${E[r.type]}`,{cause:r.span});return s(r,t,n,o,i)}};import{slice as Dt,Stack as Gt}from"@xaendar/common";var u=(l=>(l[l.TEXT=0]="TEXT",l[l.TAG_OPEN_NAME=1]="TAG_OPEN_NAME",l[l.TAG_SELF_CLOSE=2]="TAG_SELF_CLOSE",l[l.TAG_OPEN_END=3]="TAG_OPEN_END",l[l.TAG_CLOSE_NAME=4]="TAG_CLOSE_NAME",l[l.ATTRIBUTE=5]="ATTRIBUTE",l[l.ATTRIBUTE_VALUE=6]="ATTRIBUTE_VALUE",l[l.EVENT=7]="EVENT",l[l.EVENT_HANDLER=8]="EVENT_HANDLER",l[l.EVENT_PARAMETER=9]="EVENT_PARAMETER",l[l.INTERPOLATION_LITERAL=10]="INTERPOLATION_LITERAL",l[l.INTERPOLATION_EXPRESSION=11]="INTERPOLATION_EXPRESSION",l[l.IF=12]="IF",l[l.FOR=13]="FOR",l[l.ELSE=14]="ELSE",l[l.ELSE_IF=15]="ELSE_IF",l[l.SWITCH=16]="SWITCH",l[l.CASE=17]="CASE",l[l.DEFAULT=18]="DEFAULT",l[l.CONDITION=19]="CONDITION",l[l.BLOCK_OPEN=20]="BLOCK_OPEN",l[l.BLOCK_CLOSE=21]="BLOCK_CLOSE",l[l.IMPORT=22]="IMPORT",l[l.IMPORT_PATH=23]="IMPORT_PATH",l[l.EOF=24]="EOF",l))(u||{});function $e(e,r){let t=!0,n="",o;for(;t;)e.peek()===34?(e.advance(),t=!1,o={state:"tag-body",tokens:[{type:6,parts:[n]}],popState:!0}):(e.advance(),n=`${n}${e.currentChar.value}`);return o}function Pe(e,r){let t=!0,n="",o;for(;t;)switch(e.peek()){case 32:e.advance(),t=!1,o={state:"tag-body",tokens:[{type:5,parts:[n]}]};break;case 62:case 47:t=!1,o={state:"tag-body",tokens:[{type:5,parts:[n]}]};break;case 61:if(e.advance(),e.peek()!==34)throw new Error(`Attribute value must start with double quotes '"' at ${e.formattedPosition}`);e.advance(),t=!1,o={state:e.peek()===123?"interpolation":"attribute-value",pushState:!0,tokens:[{type:5,parts:[n]}]};break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function z(e,r){if(e.skipSpaces(),e.peek()!==40)throw new Error(`Expected '(' but got '${String.fromCharCode(e.peek())}' at row ${e.position.row}, col ${e.position.column}`);e.advance();let t="",n=1;for(;n>0;)switch(e.peek()){case 40:n++,t=me(e,t);break;case 41:if(n--,!n){e.advance();break}t=me(e,t);break;default:t=me(e,t)}return t}function me(e,r){return e.advance(),`${r}${e.currentChar.value}`}function Me(e,r){let t=z(e,r);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:19,parts:[t]}],popState:!0}}function Be(e,r){return{state:"flow-control-block",tokens:[{type:19,parts:[z(e,r)]}],popState:!0}}function De(e,r){let t=!0,n="",o;for(;t;)switch(e.peek()){case 32:throw new Error("No spaces are allowed in event handler name");case 40:if(!n)throw new Error(`Event handler cannot be empty at ${e.formattedPosition}`);let i="parameter";e.advance(),e.peekMatch(')"')&&(i="tag-body",e.advance(2)),o={state:i,tokens:[{type:8,parts:[n]}]},t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Ge(e,r){let t=!0,n="",o="",i=e.currentChar.index+1,s={state:"tag-body",tokens:[]};for(;t;)switch(e.peek()){case 91:case 93:case 123:case 125:case 34:case 39:case 40:n=fe(e,n),o?(o===e.currentChar.value||o==="["&&e.currentChar.value==="]"||o==="{"&&e.currentChar.value==="}")&&(o=""):o=e.currentChar.value;break;case 44:if(o)n=fe(e,n);else{let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[n],span:{start:i,end:a}}),e.advance(),e.skipSpaces(),n="",i=e.currentChar.index+1}break;case 41:if(e.advance(),e.peek()!==34)throw new Error("Event must be included in Double Quotes");if(e.advance(),!o){let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[n],span:{start:i,end:a}}),t=!1;break}n=`${n}${e.currentChar.value}`;break;default:n=fe(e,n)}return s}function fe(e,r){return e.advance(),`${r}${e.currentChar.value}`}function Ve(e,r){let t=!0,n="",o;for(e.advance();t;)switch(e.peek()){case 32:throw new Error("No spaces are allowed in event name");case 61:if(!n)throw new Error("Event name cannot be empty");if(e.advance(),e.peek()!==34)throw new Error("Event handler must be included in Double Quotes");e.advance(),o={state:"event-handler",tokens:[{type:7,parts:[n]}]},t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Ue(e,r){let t;if(e.advance(),e.peekMatch("for "))e.advance(4),t={state:"flow-control-condition",tokens:[{type:13}],pushState:!0};else if(e.peekMatch("if "))e.advance(2),t={state:"flow-control-condition",tokens:[{type:12}],pushState:!0};else if(e.peekMatch("else if "))e.advance(8),t={state:"flow-control-condition",tokens:[{type:15}],pushState:!0};else if(e.peekMatch("else "))e.advance(5),t={state:"flow-control-block",tokens:[{type:14}]};else if(e.peekMatch("switch "))e.advance(7),t={state:"flow-control-condition",tokens:[{type:16}],pushState:!0};else if(e.peekMatch("case "))e.advance(5),t={state:"case-flow-control-condition",tokens:[{type:17}],pushState:!0};else if(e.peekMatch("default "))e.advance(8),t={state:"flow-control-block",tokens:[{type:18}]};else if(e.peekMatch("import "))e.advance(7),t={state:"import"};else throw new Error(`Unknown flow-control keyword at ${e.formattedPosition}`);return t}function He(e,r){if(e.skipSpaces(),e.peek()!==123)throw new Error(`Expected '{' but got '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);return e.advance(),{state:"text",tokens:[{type:20}],pushState:!0}}function We(e,r){let t=!0,n="",o,i=!1;if(e.skipSpaces(),!e.peekMatch("from"))throw new Error(`Expected 'from' keyword after import list at ${e.formattedPosition}`);switch(e.advance(4),e.skipSpaces(),e.advance(),e.currentChar.code){case 39:i=!0;break;case 34:break;default:throw new Error(`Import statement must start with ' or ".
12
- Found character ${e.currentChar.value} at ${e.formattedPosition}`)}let s=i?39:34;for(;t;)e.peek()===s?(e.advance(),t=!1,o={state:"text",tokens:[{type:23,parts:[n]}]}):(e.advance(),n=`${n}${e.currentChar.value}`);return o}function qe(e,r){let t=!0,n="",o=e.currentChar.index+1,i={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw new Error(`Expected { after @import at ${e.formattedPosition}`);for(;t;)switch(e.peek()){case 32:e.skipSpaces(),n&&e.peek()!==44&&e.peek()!==125&&(n=`${n} `);break;case 44:Ke(i,e,n,o),n="",o=e.currentChar.index+1;break;case 125:Ke(i,e,n,o),t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return i}function Ke(e,r,t,n){let o=r.currentChar.index+1;r.advance(),e.tokens.push({type:22,parts:[t],span:{start:n,end:o}})}function Xe(e,r){let t=!0,n="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,n=ue(e,n);break;case 125:if(o--,o===0){e.advance(),n=n.trimEnd();let s=r.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw new Error(`Interpolation must end with double quotes '"', found '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);e.advance(),a="tag-body";break;case"text":a="text";break;default:throw new Error(`Unexpected state '${s}' after interpolation expression at ${e.formattedPosition}`)}i={state:a,tokens:[{type:11,parts:[n]}],popState:!0},t=!1}else n=ue(e,n);break;default:n=ue(e,n)}return i}function ue(e,r){return e.advance(1),`${r}${e.currentChar.value}`}function ze(e,r){let t=!0,n="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(n=Qe(e,n),e.peek()===125){e.advance();let i=r.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw new Error(`Attribute interpolation expression must end with double quotes '"', found '${String.fromCharCode(e.peek())}' at ${e.formattedPosition}`);e.advance(),s="tag-body";break;case"text":s="text";break;default:throw new Error(`Unexpected state '${i}' after interpolation literal at ${e.formattedPosition}`)}o={state:s,tokens:[{type:10,parts:[n]}],popState:!0},t=!1}else n=`${n}${e.currentChar.value}`;break;default:n=Qe(e,n)}return o}function Qe(e,r){return e.advance(),`${r}${e.currentChar.value}`}function je(e,r){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function Ye(e,r){let t=!0,n;for(;t;)switch(e.peek()){case 64:n={state:"event"},t=!1;break;case 32:e.skipSpaces();break;case 62:case 47:n={state:"tag-open-end"},t=!1;break;default:n={state:"attribute"},t=!1}return n}function Ze(e,r){let t=!0,n="",o;for(e.advance(2),e.skipSpaces();t;)switch(e.peek()){case 62:if(!n)throw new Error(`Tag close name cannot be empty at ${e.formattedPosition}`);e.advance(),o={state:"text",tokens:[{type:4,parts:[n]}]},t=!1;break;case 32:throw new Error(`Tag close name cannot contain spaces at ${e.formattedPosition}`);default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function Je(e,r){let t;if(e.peek()===62)e.advance(),t={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let n=e.peek();if(n===62)e.advance(),t={state:"text",tokens:[{type:2,parts:[]}]};else throw new Error(`Unexpected character '${String.fromCharCode(n)}' after '/': expected '>' to close self-closing tag at ${e.formattedPosition}`)}return t}function et(e,r){let t=!0,n="",o;for(e.advance(),e.skipSpaces();t;)switch(e.peek()){case 32:case 47:case 62:if(!n)throw new Error(`Tag name cannot be empty at ${e.formattedPosition}`);o={state:"tag-body",tokens:[{type:1,parts:[n]}]},t=!1;break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o}function tt(e){return/\S/.test(e)}function rt(e,r){let t=!0,n="",o;for(;t;)switch(e.peek()){case 60:o={state:e.peek(1,{offset:1})===47?"tag-close":"tag-open-name"},t=!1;break;case 123:o={state:"interpolation",pushState:!0},t=!1;break;case 64:o={state:"flow-control"},t=!1;break;case 125:r.history[r.history.length-1]==="flow-control-block"?(e.advance(),o={state:"text",tokens:[{type:21}],popState:!0},t=!1):(e.advance(),n=`${n}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),n=`${n}${e.currentChar.value}`}return o.tokens??=tt(n)?[{type:0,parts:[n]}]:void 0,o}var te=class{constructor(r){this.input=r}input;_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;_position={row:0,column:0};get position(){return this._position}get formattedPosition(){return`[Ln ${this._position.row}, Col ${this._position.column}]`}advance(r=1){if(r<1)throw new Error(`${r} is not a valid value. Please enter a number equal or greater than 1`);let t=this._currentChar.index+r;t>=this.input.length?(this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError()):([10,13].includes(this._currentChar.code)?(this._position.row++,this._position.column=0):this._position.column++,this._currentChar.index=t,this._currentChar.value=this.input[t],this._currentChar.code=this.input.charCodeAt(t))}peekMatch(r,t){if(typeof r=="string"){let i=this.peek(r.length);for(let s=0;s<r.length;s++)if(i[s]!==r.charCodeAt(s))return!1;return!0}let n=this._currentChar.index+1,o=this.input.slice(n,n+t);return r.test(o)}peek(r,t){let n=this._peekCache,o=typeof r=="number"?r:1,i=(typeof r=="object"?r:t)?.offset??0;return o===1?this.peekOneChar(this._currentChar.index+i+1,n):this.peekMany(o+i,n)}skipSpaces(){for(;this.peek()===32||this.peek()===10||this.peek()===13;)this.advance()}peekMany(r,t){let n=new Array,o=this._currentChar.index+1;for(let i=o;i<o+r;i++)n.push(this.peekOneChar(i,t));return n}peekOneChar(r,t){if(t.has(r))return t.get(r);r>=this.input.length&&this.throwEOFError();let n=this.input.charCodeAt(r);return t.set(r,n),n}throwEOFError(){throw new Error("",{cause:0})}};var re=class{constructor(r){this._input=r;this._cursor=new te(this._input)}_input;_cursor;_state="text";_stack=new Gt;_tokens=new Array;_states={text:rt,"tag-open-name":et,"tag-body":Ye,"tag-open-end":Je,"tag-close":Ze,attribute:Pe,"attribute-value":$e,event:Ve,"event-handler":De,parameter:Ge,"flow-control":Ue,"flow-control-condition":Be,"case-flow-control-condition":Me,"flow-control-block":He,interpolation:je,"interpolation-expression":Xe,"interpolation-literal":ze,import:qe,"import-path":We};tokenize(){let r=!1,t=this._cursor,n=-1;for(;!r;)try{n=t.currentChar.index+1;let o=this._states[this._state],{state:i,tokens:s,popState:a,pushState:c}=o(t,{history:this._stack.values,tokens:[...this._tokens]});if(s?.length){let m=t.currentChar.index+1;this._tokens.push(...this.withTokenSpans(s,{start:n,end:m}))}c&&this._stack.push(this._state),a&&this._stack.pop(),this._state=i}catch(o){let i=o;if(i.cause===0)r=!0;else throw new Error(`[Lexer] ${i.message}
13
- ----> ${Dt(this._input,n,t.currentChar.index+1)}
14
- at ${t.formattedPosition}`)}return this._tokens}throwError(r){throw new Error(`[Lexer] ${r}`)}withTokenSpans(r,t){return r.map(n=>({...n,span:n.span??t}))}};import{slice as nr}from"@xaendar/common";var ne=class{constructor(r){this._tokens=r}_tokens;_currentToken={value:{type:24},index:-1};getCurrentToken(){return this._currentToken}advance(r=1){if(r<1)throw new Error(`${r} is not a valid value. Please enter a number equal or greater than 1`);let t=this._currentToken.index+r;t>=this._tokens.length?(this._currentToken.value={type:24},this._currentToken.index=-1):(this._currentToken.index=t,this._currentToken.value=this._tokens[t])}peek(r,t){let n=typeof r=="number"?r:1,o=(typeof r=="object"?r:t)?.offset??0;return n===1?this.peekOneToken(this._currentToken.index+o+1):this.peekMany(n+o)}peekMany(r){let t=new Array,n=this._currentToken.index+1;for(let o=n;o<n+r;o++)t.push(this.peekOneToken(o));return t}peekOneToken(r){return r<this._tokens.length?this._tokens[r]:{type:24}}};import{ScriptTarget as Vt,SyntaxKind as p,createSourceFile as Ut,forEachChild as Ht}from"typescript";function y(e){let r="const x = ",o=Ut("expression.ts",`${r}${e}`,Vt.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(nt(o,r.length,i),i.length)throw new Error(i.reduce((s,a)=>`${s}${a.message}
15
- `,""));return{node:o}}function nt(e,r,t){if(!Wt(e))throw new Error(Kt(e));if(Ht(e,n=>nt(n,r,t)),t.length)throw new Error(t[0].message)}function Wt(e){switch(e.kind){case p.StringLiteral:case p.NumericLiteral:case p.BigIntLiteral:case p.TrueKeyword:case p.FalseKeyword:case p.NullKeyword:case p.UndefinedKeyword:case p.Identifier:case p.PropertyAccessExpression:case p.ElementAccessExpression:case p.CallExpression:case p.BinaryExpression:case p.EqualsEqualsToken:case p.EqualsEqualsEqualsToken:case p.ExclamationEqualsToken:case p.ExclamationEqualsEqualsToken:case p.LessThanToken:case p.LessThanEqualsToken:case p.GreaterThanToken:case p.GreaterThanEqualsToken:case p.PlusToken:case p.MinusToken:case p.AsteriskToken:case p.SlashToken:case p.PercentToken:case p.AsteriskAsteriskToken:case p.AmpersandAmpersandToken:case p.BarBarToken:case p.QuestionQuestionToken:case p.QuestionDotToken:case p.QuestionToken:case p.ColonToken:case p.AmpersandToken:case p.BarToken:case p.CaretToken:case p.LessThanLessThanToken:case p.GreaterThanGreaterThanToken:case p.GreaterThanGreaterThanGreaterThanToken:case p.InstanceOfKeyword:case p.InKeyword:case p.PrefixUnaryExpression:case p.PostfixUnaryExpression:case p.TypeOfExpression:case p.VoidExpression:case p.ConditionalExpression:case p.ParenthesizedExpression:case p.TemplateExpression:case p.NoSubstitutionTemplateLiteral:case p.TemplateHead:case p.TemplateMiddle:case p.TemplateTail:case p.TemplateSpan:case p.ArrayLiteralExpression:case p.ObjectLiteralExpression:case p.PropertyAssignment:case p.ShorthandPropertyAssignment:case p.SpreadAssignment:case p.SpreadElement:case p.TaggedTemplateExpression:case p.SyntaxList:return!0;default:return!1}}function Kt(e){switch(e.kind){case p.AwaitExpression:return"'await' is not allowed inside template expressions.";case p.YieldExpression:return"'yield' is not allowed inside template expressions.";case p.NewExpression:return"'new' is not allowed inside template expressions.";case p.ArrowFunction:case p.FunctionExpression:return"Function expressions are not allowed inside template expressions.";case p.BinaryExpression:return qt(e.operatorToken.kind)?"Assignments are not allowed inside template expressions. Use @const to declare local template variables instead.":`'${p[e.kind]}' is not allowed inside template expressions.`;default:return`'${p[e.kind]}' is not allowed inside template expressions.`}}function qt(e){return e>=p.FirstAssignment&&e<=p.LastAssignment}function H(e,r,t){let n=t.span.start;return e.advance(),{type:4,expression:y(t.parts[0]).node,span:{start:n,end:e.getCurrentToken().value.span.end}}}function ot(e,r,t){let n=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type===5||i.type===4||i.type===7)return{type:1,name:o,value:"true",span:{start:n,end:e.getCurrentToken().value.span.end}};if(i.type===11||i.type===10){let s=H(e,r,i);return{type:1,name:o,value:s,span:{start:n,end:e.getCurrentToken().value.span.end}}}if(i.type!==6)throw new Error(`Attribute value missing for ${o} in: ${o}`);return e.advance(),{type:1,name:o,value:i.parts[0],span:{start:n,end:e.getCurrentToken().value.span.end}}}function it(e,r,t){let n=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type!==8)throw new Error(`Invalid event format for ${o}`);e.advance();let s=e.getCurrentToken().value.span.end,a=new Array;for(;e.peek().type===9;)e.advance(),a.push(y(e.getCurrentToken().value.parts[0]).node),s=e.getCurrentToken().value.span.end;return{type:2,name:o,handler:i.parts[0],parameters:a,span:{start:n,end:s}}}function st(e,r,t){e.advance();let n=t.parts[0],o=new Array,i=new Array,s=!0;for(;s;){let c=e.peek();switch(c.type){case 5:o.push(ot(e,r,c));break;case 7:i.push(it(e,r,c));break;default:s=!1}}if(e.peek().type===3&&e.advance(),e.peek().type===2)return e.advance(),{type:0,tagName:n,attributes:o,events:i,children:[]};let a=new Array;for(;!Xt(e,n);){let c=r();c&&a.push(c)}return e.advance(),{type:0,tagName:n,attributes:o,events:i,children:a}}function Xt(e,r){let t=e.peek();return t.type===4&&t.parts[0]===r}import{createSourceFile as Qt,isExpressionStatement as zt,isIdentifier as jt,ScriptTarget as Yt}from"typescript";function R(e,r){let t=new Array;for(;e.peek().type!==21;){let n=r();n&&t.push(n)}return e.advance(),t}function at(e,r,t){e.advance();let n=e.peek();if(n.type!==19)throw new Error(`Expected CONDITION after FOR, got ${u[n.type]}`);let o=Zt(n.parts[0],0);e.advance(2);let i=R(e,r);return{type:8,...o,children:i}}function Zt(e,r){let t=er(e);if(t.length<2)throw new Error('@for requires at least "item of iterable; track expr".');let n=t[0].trim(),o=n.indexOf(" of ");if(o===-1)throw new Error('@for expression must be in the form "item of iterable".');let i=n.slice(0,o).trim(),s=n.slice(o+4).trim();if(!pt(i))throw new Error(`'${i}' is not a valid item alias.`);let a=y(s),c=t[1].trim();if(!c.startsWith("track "))throw new Error('Second section of @for must start with "track".');let m=c.slice(6).trim(),d=y(m),x=new Map;if(t.length>=3&&t[2]!==void 0){let f=t[2].trim(),A=r+e.indexOf(t[2]);Jt(f,A,x)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:d.node,trackSource:m,implicitAliases:x}}function Jt(e,r,t){let n=e.split(","),o=0,i=new Set(["$index","$last","$first","$even","$odd"]);for(let s of n){let a=s.trim(),c=a.indexOf("=");if(c===-1)throw new Error(`Invalid alias declaration '${a}'. Expected '$implicit = alias'.`);o+=s.length+1;let m=a.slice(0,c).trim(),d=a.slice(c+1).trim();if(!(f=>i.has(f))(d))throw new Error(`'${d}' is not a known implicit variable. Known variables: ${[...i].join(", ")}.`);if(o+=s.length+1,!pt(m))throw new Error(`'${m}' is not a valid alias identifier.`);if(o+=s.length+1,t.has(d))throw new Error(`'${d}' is already aliased in this @for expression.`);t.set(d,m),o+=s.length+1}}function er(e){let r=new Array,t="",n=0,o;for(let i=0;i<e.length;i++){let s=e[i];if(!(!t&&s===" ")){if(o){t+=s,s===o&&e[i-1]!=="\\"&&(o=null);continue}if(s==='"'||s==="'"||s==="`"){o=s,t+=s;continue}if(s==="("||s==="["||s==="{"){n++,t+=s;continue}if(s===")"||s==="]"||s==="}"){n--,t+=s;continue}if(s===";"&&n===0){r.push(t),t="";continue}t+=s}}return t.trim().length&&r.push(t),r}function pt(e){if(!e.length)return!1;let t=Qt("__id.ts",e,Yt.ESNext,!1).statements[0];return!!t&&zt(t)&&jt(t.expression)&&t.expression.text===e}function ct(e,r,t){return mt(e,r,t)}function tr(e,r,t){switch(t.type){case 15:return mt(e,r,t);case 14:let n=t.span.start;e.advance(2);let o=R(e,r);return{type:6,children:o,span:{start:n,end:e.getCurrentToken().value.span.end}}}}function mt(e,r,t){let n=t.span.start;e.advance();let o=e.peek();if(o.type!==19)throw new Error(`Expected CONDITION after ${u[t.type]}, got ${u[o.type]}`);e.advance(2);let i=o.parts[0],s=y(i),a=R(e,r),c=null,m=e.peek();return(m.type===15||m.type===14)&&(c=tr(e,r,m)),{type:t.type===12?5:7,condition:i,conditionNode:s.node,children:a,alternate:c,span:{start:n,end:e.getCurrentToken().value.span.end}}}function lt(e,r,t){let n=new Array;for(;e.peek().type===22;){e.advance();let o=e.getCurrentToken().value.parts[0],i=rr(o);n.push(i)}return e.advance(),{type:11,specifiers:n,path:e.getCurrentToken().value.parts[0]}}function rr(e){let r=e.trim(),t=r.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(t)return{imported:"*",local:t[1]};let n=r.match(/^default\s+as\s+([A-Za-z_$][\w$]*)$/);if(n)return{imported:"default",local:n[1]};let o=r.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(o)return{imported:o[1],local:o[2]??o[1]};throw new Error(`Invalid import specifier "${e}".`)}function ft(e,r,t){e.advance();let n=e.peek();if(n.type!==19)throw new Error(`Expected CONDITION after SWITCH, got ${u[n.type]}`);let o=y(n.parts[0]).node;e.advance(2);let i=new Array;for(;e.peek().type!==21;){let s=e.peek();switch(s.type){case 17:let a=s.span.start,c=new Array;do{e.advance();let f=e.peek();if(f.type!==19)throw new Error("Expected CONDITION after CASE");c.push(f.parts[0]),e.advance()}while(e.peek().type!==20);e.advance();let m=R(e,r);i.push({type:10,condition:c,children:m,span:{start:a,end:e.getCurrentToken().value.span.end}});break;case 18:let d=s.span.start;e.advance(2);let x=R(e,r);i.push({type:10,condition:null,children:x,span:{start:d,end:e.getCurrentToken().value.span.end}});break}}return e.advance(),{type:9,expression:o,children:i}}function ut(e,r,t){return e.advance(),{type:3,value:t.parts[0]}}var oe=class{constructor(r,t){this._input=r;this._cursor=new ne(t)}_input;_cursor;_states={0:ut,11:H,10:H,1:st,12:ct,13:at,16:ft,22:lt};parse(){try{let r=new Array;for(;this._cursor.peek().type!==24;){let t=this.parseNode();t&&r.push(t)}return r}catch(r){let t=r,n=this._cursor.peek();throw new Error(`[Parser] ${t.message}
16
- ----> ${nr(this._input,n.span.start,n.span.end)}`)}}parseNode(){let r=this._cursor.peek();if(r.type===24)return;let t=r.span.start,n=this._states[r.type];if(!n)throw new Error(`No transition function for token type ${u[r.type]}`);let o=n(this._cursor,this.parseNode.bind(this),r),i=this._cursor.getCurrentToken().value,s="span"in i?i.span.end:r.span.end;return{...o,span:o.span??{start:t,end:s}}}};import{indent as _r,slice as Sr}from"@xaendar/common";var D=class extends C{_imports=new Array;addImport(r){this._imports.push(r)}getImportBySelector(r){return this._imports.find(t=>t.type==="component"&&t.selectors.includes(r))}};import{indent as he}from"@xaendar/common";function dt(e,r,t){let n=new Array;if(pr(e.tagName)){let o=t.getImportBySelector(e.tagName);if(!o)throw new Error(`${e.tagName} selector is not associated to any WebComponent imported in the template`,{cause:e.span});n.push(...or(e,o,t))}else n.push(...ar(e,t));return e.children.forEach(o=>n.push(...r(o,t))),n}function or(e,r,t){let n=new Array,o=new Set(r.properties.filter(i=>i.required).map(i=>i.alias??i.name));if(e.attributes.forEach(({name:i,value:s})=>{let a=ir(r,i);a&&(o.delete(a.alias??a.name),n.push("{",...he(typeof s=="object"?[`(${T(s.expression,t,{resolver:"root"})}) satisfies ${a.type};`]:["let x!: string",`x satisfies ${a.type};`]),"}"))}),o.size)throw new Error(`${e.tagName} is missing the following required properties: ${Array.from(o.values()).join(`
17
- `)}`,{cause:e.span});return e.events.forEach(({name:i,handler:s,parameters:a})=>{let c=sr(r,i);if(!c)throw new Error(`Unknown event "${i}" on <${e.tagName}> (${r.className} has no @Event with this name).`,{cause:e.span});let m=new C([],t);m.addUnresolvableIdentifier("$event");let d=a.map(x=>T(x,m,{resolver:"root"})).join(", ");n.push("{"),c.type!=="void"&&n.push(he(`let $event!: CustomEvent<${c.type}>;`)),n.push(he(`root.${s}(${d});`),"}")}),n}function ir(e,r){return e.properties.find(t=>(t.alias??t.name)===r)}function sr(e,r){return e.events.find(t=>t.name===r)}function ar(e,r){let t=new Array;return e.attributes.forEach(({value:n})=>{typeof n!="string"&&t.push(`${T(n.expression,r,{resolver:"root"})};`)}),e.events.forEach(({handler:n,parameters:o})=>{let i=new C([],r);i.addUnresolvableIdentifier("$event");let s=o.map(a=>T(a,i,{resolver:"root"})).join(", ");t.push(`root.${n}(${s});`)}),t}function pr(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}import{indent as cr}from"@xaendar/common";function Tt(e,r,t){let n=new D([],t),o=W(e,"$index"),i=W(e,"$first"),s=W(e,"$last"),a=W(e,"$even"),c=W(e,"$odd");[o,i,s,a,c,e.itemAlias].forEach(d=>n.addUnresolvableIdentifier(d));let m=new Array;return m.push(`for (const ${e.itemAlias} of root.${e.iterableSource}) {`),m.push(...cr([`let ${o}!: number;`,`let ${i}!: boolean;`,`let ${s}!: boolean;`,`let ${a}!: boolean;`,`let ${c}!: boolean;`,`${T(e.trackExpression,t,{skipResolution:!0})};`,...e.children.flatMap(d=>r(d,n))])),m.push("}"),m}function W(e,r){return e.implicitAliases.get(r)??r}import{indent as xe}from"@xaendar/common";function ht(e,r,t){let n=new Array,o=T(e.conditionNode,t,{resolver:"root"});n.push(`if (${o}) {`),n.push(...xe(e.children.flatMap(s=>r(s,t)))),n.push("}");let i=e.alternate;for(;i?.type===7;){let s=T(i.conditionNode,t,{resolver:"root"});n.push(`else if (${s}) {`),n.push(...xe(i.children.flatMap(a=>r(a,t)))),n.push("}"),i=i.alternate}return i&&(n.push("else {"),n.push(...xe(i.children.flatMap(s=>r(s,t)))),n.push("}")),n}function Et(e,r,t){let n=e.path,o=xt(n),i=new Array;for(let s of e.specifiers){let{imported:a,local:c}=s;switch(a){case"*":i.push(`let ${c}!: typeof import('${o}');`);break;case"default":i.push(`let ${c}!: typeof import('${o}')['default'];`);break;default:let m=xt(a);i.push(`let ${c}!: typeof import('${o}')['${m}'];`);break}}return i}function xt(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{indent as Ct}from"@xaendar/common";function kt(e,r,t){let o=[`switch (${T(e.expression,t,{resolver:"root"})}) {`];return e.children.forEach(i=>{i.condition?.length?i.condition.forEach(s=>o.push(` case ${s}:`)):o.push(" default:"),o.push(...Ct(Ct([...i.children.flatMap(s=>r(s,t)),"break;"])))}),o.push("}"),o}function Ee(e,r,t){return e.type===4?[`${T(e.expression,t,{resolver:"root"})};`]:[]}import{existsSync as Ce}from"fs";import{readFile as mr}from"fs/promises";import{resolve as lr}from"path";import{createSourceFile as fr,forEachChild as ur,getNameOfDeclaration as Nt,isArrayLiteralExpression as dr,isCallExpression as K,isClassDeclaration as Tr,isDecorator as hr,isIdentifier as b,isObjectLiteralExpression as At,isPropertyAccessExpression as xr,isPropertyAssignment as gt,isPropertyDeclaration as Ne,isStringLiteral as ke,isTypeReferenceNode as Er,ScriptTarget as Cr,SyntaxKind as It}from"typescript";async function Lt(e,r,t=process.cwd()){try{let n=kr(e,t);if(!n)return;let o=await mr(n,"utf8"),i=fr(n,o,Cr.Latest,!0),s;return ur(i,a=>{if(!s&&Tr(a)){let c=a.name?.text;if(c!==r)return;let m=a.modifiers??[],d=Array.from(m).find(g=>Nr(g));if(!d)return;let x=Ir(d);if(!x?.length)return;let f=new Array,A=new Array;a.members.forEach(g=>{if(!Ne(g))return;let S=g.modifiers??[],q=!1,X=Array.from(S).find(I=>{let O=Ar(I);return q=!!O.required,O.decorator});if(X){let I=Nt(g),O=I&&b(I)?I.text:void 0;if(O){let G=yr(O,X,q);G&&f.push(G)}return}let Ae=Array.from(S).find(I=>gr(I));if(Ae){let I=Nt(g),O=I&&b(I)?I.text:void 0;if(O){let G=vr(O,Ae);G&&A.push(G)}}}),s={type:"component",className:c,selectors:x,properties:f,events:A}}}),s}catch(n){console.error(`Failed to extract component metadata from ${e}:`,n);return}}function kr(e,r){if(e.startsWith(".")){let t=lr(r,e);if(Ce(`${t}.ts`))return t+".ts";if(Ce(`${t}/index.ts`))return`${t}/index.ts`;if(Ce(t))return t}}function Nr(e){if(e.kind!==It.Decorator)return!1;let r=K(e.expression)?e.expression.expression:e.expression;return b(r)&&r.text==="WebComponent"}function Ar(e){if(!hr(e))return{decorator:!1};let r=e.expression;if(!K(r))return{decorator:!1};let t=r.expression;return b(t)&&t.text==="Property"?{decorator:!0}:xr(t)&&b(t.expression)&&t.expression.text==="Property"&&t.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function gr(e){if(e.kind!==It.Decorator)return!1;let r=K(e.expression)?e.expression.expression:e.expression;return b(r)&&r.text==="Event"}function Ir(e){try{let r=e.expression;if(!K(r))return[];let t=r.arguments;if(t.length===0)return[];let n=t[0];if(!n||!At(n))return[];let o=Array.from(n.properties).find(i=>gt(i)&&b(i.name)&&i.name.text==="selector");return Lr(o.initializer)}catch{return[]}}function Lr(e){return ke(e)?[e.text]:dr(e)?e.elements?.filter(r=>ke(r)).map(r=>r.text):[]}function yr(e,r,t){let n=r.expression,o={name:e,required:t,type:Ne(r.parent)?yt(r.parent.type):"any"};if(K(n)){let i=n.arguments,a=(i.length?i.find(c=>At(c)):void 0)?.properties?.find(c=>gt(c)&&b(c.name)&&c.name.text==="alias");a&&ke(a.initializer)&&(o.alias=a.initializer.text)}return o}function vr(e,r){let t={name:e,type:"void"};return Ne(r.parent)&&(t.type=yt(r.parent.type,!0)),t}function yt(e,r=!1){let t=r?"void":"any";if(!e||!Er(e))return t;let n=e.typeArguments;return!n||n.length===0?t:n[0].getText()}var ie=class{constructor(r,t){this._input=r;this._ast=t}_input;_ast;_context=new D;_states={3:Ee,4:Ee,0:dt,5:ht,8:Tt,9:kt,11:Et};async populateImportMetadata(r){let t=this._ast.filter(n=>n.type===11);await Promise.all(t.flatMap(n=>n.specifiers.filter(({imported:o})=>o!=="*").map(async({imported:o,local:i})=>{let s=o==="default"?i:o,a=await Lt(n.path,s,r);a&&this._context.addImport(a)})))}async generate(r){try{await this.populateImportMetadata(r);let t=this._ast.flatMap(n=>this._processNode(n,this._context));return["function typeCheck() {",..._r(t),"}"].join(`
18
- `)}catch(t){let n=t,{start:o,end:i}=n.cause;throw new Error(`[Type Checker] ${n.message}
19
- ----> ${Sr(this._input,o,i)}`)}}_processNode=(r,t)=>{let n=this._states[r.type];if(!n)throw new Error(`No transition function for token type ${E[r.type]}`,{cause:r.span});return n(r,this._processNode,t)}};async function xa(e,r,t){let n=new re(e).tokenize(),o=new oe(e,n).parse();return{javascript:new Q(e,o).generate(t),typescript:await new ie(e,o).generate(r)}}export{xa as compile};
8
+ const { ${e.itemAlias}, ${p}, ${u}, ${d}, ${f}, ${N} } = vars;`,node:e,parentNode:y,context:I,anchor:"anchor",isForBody:!0},args:[y,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${n}, context, () => ${s}, ${e.itemAlias} => ${h(e.trackExpression,I,{skipResolution:!0})}, this.${y}.bind(this));`),o}function X(e,n){return e.implicitAliases.get(n)??n}import{indent as D}from"@xaendar/common";function Be(e,n,t,r){let o=new k([],r),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${n}, context, [`);let s=b("if",n,t);i.code.push(...D(["{",...D([`condition: () => ${h(e.conditionNode,r)},`,`block: this.${s}.bind(this)`]),"},"])),i.functionsToProcess.set(s,{fn:{node:e,parentNode:s,context:o,anchor:"anchor"},args:[s,"parentContext","anchor"]});let a=e.alternate,c=0;for(;a?.type===7;){let p=new k([],r),u=b("elseIf",n,`${t}_${c}`),d=a.conditionNode;i.code.push(...D(["{",...D([`condition: () => ${h(d,r)},`,`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]}),a=a.alternate,c++}if(a){let p=new k([],r),u=b("else",n,t);i.code.push(...D(["{",...D([`block: this.${u}.bind(this)`]),"},"])),i.functionsToProcess.set(u,{fn:{node:a,parentNode:n,context:p,anchor:"anchor"},args:[n,"parentContext","anchor"]})}return i.code.push("]);"),i}import{indent as De}from"@xaendar/common";function Ge(e,n,t,r){let o={code:[],functionsToProcess:new Map};o.code.push(`_switch(${n}, context, () => ${h(e.expression,r)}, [`);let i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=new k([],r),p=a.condition?b("case",n,`${t}_${s}`):b("default",n,t);o.functionsToProcess.set(p,{fn:{node:a,parentNode:p,context:c},args:[p,"parentContext","anchor"]});let u=`this.${p}.bind(this)`;o.code.push(...De(["{",...De([`condition: ${a.condition?`[${a.condition.join(", ")}]`:"null"},`,`block: ${u}`]),"},"]))}return o.code.push("])"),o}function le(e,n,t,r){return{code:[`${e.type===3?`_renderLiteralText(${n}, context, '${e.value}');`:`_renderText(${n}, context, () => ${h(e.expression,r)});`}`]}}function Ue(e,n,t,r){}var J=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:le,4:le,0:Pe,5:Be,8:Me,9:Ge,11:Ue};generate(n){let t=r=>{if(r)for(let[o,i]of r.entries())this._nodeToProcess.set(o,i)};try{this._nodeToProcess.clear();let r=new k,o=["_render() {",...P([`const ${q} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];n&&o.push(P(`${q}.adoptedStyleSheets = [${n}];`));for(let i=0;i<this._ast.length;i++){let s=this._processNode(this._ast[i],q,i.toString(),r,null);if(s){let{code:a,functionsToProcess:c}=s;t(c),o.push(...P(a))}}o.push(...P(["return context;"]),"}");for(let[i,s]of this._nodeToProcess.entries()){let{node:a,parentNode:c,context:p,precode:u,anchor:d}=s.fn;o.push(`
9
+ ${i}(${s.args?.join(", ")}) {`,...P(["const context = new Context(this, parentContext);"])),u&&o.push(P(u)),o.push(...P([...a.children.map((f,N)=>{let I=this._processNode(f,c,N.toString(),p,d??null);if(I){let{code:y,functionsToProcess:B}=I;return t(B),y}return""}).flat(),s.fn.isForBody?"return { context, update };":"return context;"]),"}")}return o.join(`
10
+ `)}catch(r){let o=r,{start:i,end:s}=o.cause;throw new Error(`[Generator] ${o.message}
11
+ ----> ${Vt(this._input,i,s)}`)}}_processNode(n,t,r,o,i){let s=this._states[n.type];if(!s)throw new Error(`No transition function for token type ${E[n.type]}`,{cause:n.span});return s(n,t,r,o,i)}};import{slice as Ee,Stack as Xt}from"@xaendar/common";var T=(m=>(m[m.TEXT=0]="TEXT",m[m.TAG_OPEN_NAME=1]="TAG_OPEN_NAME",m[m.TAG_SELF_CLOSE=2]="TAG_SELF_CLOSE",m[m.TAG_OPEN_END=3]="TAG_OPEN_END",m[m.TAG_CLOSE_NAME=4]="TAG_CLOSE_NAME",m[m.ATTRIBUTE=5]="ATTRIBUTE",m[m.ATTRIBUTE_VALUE=6]="ATTRIBUTE_VALUE",m[m.EVENT=7]="EVENT",m[m.EVENT_HANDLER=8]="EVENT_HANDLER",m[m.EVENT_PARAMETER=9]="EVENT_PARAMETER",m[m.INTERPOLATION_LITERAL=10]="INTERPOLATION_LITERAL",m[m.INTERPOLATION_EXPRESSION=11]="INTERPOLATION_EXPRESSION",m[m.IF=12]="IF",m[m.FOR=13]="FOR",m[m.ELSE=14]="ELSE",m[m.ELSE_IF=15]="ELSE_IF",m[m.SWITCH=16]="SWITCH",m[m.CASE=17]="CASE",m[m.DEFAULT=18]="DEFAULT",m[m.CONDITION=19]="CONDITION",m[m.BLOCK_OPEN=20]="BLOCK_OPEN",m[m.BLOCK_CLOSE=21]="BLOCK_CLOSE",m[m.IMPORT=22]="IMPORT",m[m.IMPORT_PATH=23]="IMPORT_PATH",m[m.EOF=24]="EOF",m))(T||{});function Ve(e,n){let t=!0,r="",o;for(;t;)e.peek()===34?(e.advance(),t=!1,o={state:"tag-body",tokens:[{type:6,parts:[r]}],popState:!0}):(e.advance(),r=`${r}${e.currentChar.value}`);return o}function He(e,n){let t=!0,r="",o;for(;t;)switch(e.peek()){case 32:e.advance(),t=!1,o={state:"tag-body",tokens:[{type:5,parts:[r]}]};break;case 62:case 47:t=!1,o={state:"tag-body",tokens:[{type:5,parts:[r]}]};break;case 61:if(!r)throw new Error("Attribute cannot start with '='");if(e.advance(),e.peek()!==34)throw`Attribute value must start with double quotes '"'`;e.advance(),t=!1,o={state:e.peek()===123?"interpolation":"attribute-value",pushState:!0,tokens:[{type:5,parts:[r]}]};break;case 34:case 39:if(!r)throw new Error(`Attribute cannot start with ' or "`);default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function ee(e,n){if(e.skipSpaces(),e.peek()!==40)throw`Expected '(' but got '${String.fromCharCode(e.peek())}'`;e.advance();let t="",r=1;for(;r>0;)switch(e.peek()){case 40:r++,t=fe(e,t);break;case 41:if(r--,!r){e.advance();break}t=fe(e,t);break;default:t=fe(e,t)}return t}function fe(e,n){return e.advance(),`${n}${e.currentChar.value}`}function We(e,n){let t=ee(e,n);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:19,parts:[t]}],popState:!0}}function Ke(e,n){return{state:"flow-control-block",tokens:[{type:19,parts:[ee(e,n)]}],popState:!0}}function qe(e,n){let t=!0,r="",o;for(;t;)switch(e.peek()){case 32:throw"No spaces are allowed in event handler name";case 40:if(!r)throw"Event handler cannot be empty";let i="parameter";e.advance(),e.peekMatch(')"')&&(i="tag-body",e.advance(2)),o={state:i,tokens:[{type:8,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function Xe(e,n){let t=!0,r="",o="",i=e.currentChar.index+1,s={state:"tag-body",tokens:[]};for(;t;)switch(e.peek()){case 91:case 93:case 123:case 125:case 34:case 39:case 40:r=de(e,r),o?(o===e.currentChar.value||o==="["&&e.currentChar.value==="]"||o==="{"&&e.currentChar.value==="}")&&(o=""):o=e.currentChar.value;break;case 44:if(o)r=de(e,r);else{let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[r],span:{start:i,end:a}}),e.advance(),e.skipSpaces(),r="",i=e.currentChar.index+1}break;case 41:if(e.advance(),e.peek()!==34)throw"Event must be included in Double Quotes";if(e.advance(),!o){let a=e.currentChar.index+1;s.tokens.push({type:9,parts:[r],span:{start:i,end:a}}),t=!1;break}r=`${r}${e.currentChar.value}`;break;default:r=de(e,r)}return s}function de(e,n){return e.advance(),`${n}${e.currentChar.value}`}function Qe(e,n){let t=!0,r="",o;for(e.advance();t;)switch(e.peek()){case 32:throw"No spaces are allowed in event name";case 61:if(!r)throw"Event name cannot be empty";if(e.advance(),e.peek()!==34)throw"Event handler must be included in Double Quotes";e.advance(),o={state:"event-handler",tokens:[{type:7,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function je(e,n){let t;if(e.advance(),e.peekMatch("for "))e.advance(4),t={state:"flow-control-condition",tokens:[{type:13}],pushState:!0};else if(e.peekMatch("if "))e.advance(2),t={state:"flow-control-condition",tokens:[{type:12}],pushState:!0};else if(e.peekMatch("else if "))e.advance(8),t={state:"flow-control-condition",tokens:[{type:15}],pushState:!0};else if(e.peekMatch("else "))e.advance(5),t={state:"flow-control-block",tokens:[{type:14}]};else if(e.peekMatch("switch "))e.advance(7),t={state:"flow-control-condition",tokens:[{type:16}],pushState:!0};else if(e.peekMatch("case "))e.advance(5),t={state:"case-flow-control-condition",tokens:[{type:17}],pushState:!0};else if(e.peekMatch("default "))e.advance(8),t={state:"flow-control-block",tokens:[{type:18}]};else if(e.peekMatch("import "))e.advance(7),t={state:"import"};else throw"Unknown flow-control keyword";return t}function ze(e,n){if(e.skipSpaces(),e.peek()!==123)throw`Expected '{' but got '${String.fromCharCode(e.peek())}'`;return e.advance(),{state:"text",tokens:[{type:20}],pushState:!0}}function Ye(e,n){let t=!0,r="",o,i=!1;if(e.skipSpaces(),!e.peekMatch("from"))throw"Expected 'from' keyword after import list";switch(e.advance(4),e.skipSpaces(),e.advance(),e.currentChar.code){case 39:i=!0;break;case 34:break;default:throw`Import statement must start with ' or ".
12
+ Found character ${e.currentChar.value}`}let s=i?39:34;for(;t;)e.peek()===s?(e.advance(),t=!1,o={state:"text",tokens:[{type:23,parts:[r]}]}):(e.advance(),r=`${r}${e.currentChar.value}`);return o}function Je(e,n){let t=!0,r="",o=e.currentChar.index+1,i={state:"import-path",tokens:[]};if(e.skipSpaces(),e.advance(),e.currentChar.code!==123)throw"Expected { after @import";for(;t;)switch(e.peek()){case 32:e.skipSpaces(),r&&e.peek()!==44&&e.peek()!==125&&(r=`${r}`);break;case 44:Ze(i,e,r,o),r="",o=e.currentChar.index+1;break;case 125:Ze(i,e,r,o),t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return i}function Ze(e,n,t,r){let o=n.currentChar.index+1;n.advance(),e.tokens.push({type:22,parts:[t],span:{start:r,end:o}})}function et(e,n){let t=!0,r="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,r=Te(e,r);break;case 125:if(o--,o===0){e.advance(),r=r.trimEnd();let s=n.history.pop(),a;switch(s){case"attribute":if(e.peek()!==34)throw`Interpolation must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),a="tag-body";break;case"text":a="text";break;default:throw`Unexpected state '${s}' after interpolation expression`}i={state:a,tokens:[{type:11,parts:[r]}],popState:!0},t=!1}else r=Te(e,r);break;default:r=Te(e,r)}return i}function Te(e,n){return e.advance(1),`${n}${e.currentChar.value}`}function rt(e,n){let t=!0,r="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(r=tt(e,r),e.peek()===125){e.advance();let i=n.history.pop(),s;switch(i){case"attribute":if(e.peek()!==34)throw`Attribute interpolation expression must end with double quotes '"', found '${String.fromCharCode(e.peek())}'`;e.advance(),s="tag-body";break;case"text":s="text";break;default:throw`Unexpected state '${i}' after interpolation literal`}o={state:s,tokens:[{type:10,parts:[r]}],popState:!0},t=!1}else r=`${r}${e.currentChar.value}`;break;default:r=tt(e,r)}return o}function tt(e,n){return e.advance(),`${n}${e.currentChar.value}`}function nt(e,n){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function ot(e,n){let t=!0,r;for(;t;)switch(e.peek()){case 64:r={state:"event"},t=!1;break;case 32:e.skipSpaces();break;case 62:case 47:r={state:"tag-open-end"},t=!1;break;default:r={state:"attribute"},t=!1}return r}function it(e,n){let t=!0,r="",o;for(e.advance(2),e.skipSpaces();t;)switch(e.peek()){case 62:if(!r)throw"Tag close name cannot be empty";e.advance(),o={state:"text",tokens:[{type:4,parts:[r]}]},t=!1;break;case 32:throw"Tag close name cannot contain spaces";default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function st(e,n){let t;if(e.peek()===62)e.advance(),t={state:"text",tokens:[{type:3,parts:[]}]};else{e.advance();let r=e.peek();if(r===62)e.advance(),t={state:"text",tokens:[{type:2,parts:[]}]};else throw`Unexpected character '${String.fromCharCode(r)}' after '/': expected '>' to close self-closing tag`}return t}function at(e,n){let t=!0,r="",o;for(e.advance(),e.skipSpaces();t;)switch(e.peek()){case 32:case 47:case 62:if(!r)throw"Tag name cannot be empty ";o={state:"tag-body",tokens:[{type:1,parts:[r]}]},t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o}function pt(e){return/\S/.test(e)}function ct(e,n){let t=!0,r="",o;for(;t;)switch(e.peek()){case 60:o={state:e.peek(1,{offset:1})===47?"tag-close":"tag-open-name"},t=!1;break;case 123:o={state:"interpolation",pushState:!0},t=!1;break;case 64:o={state:"flow-control"},t=!1;break;case 125:n.history[n.history.length-1]==="flow-control-block"?(e.advance(),o={state:"text",tokens:[{type:21}],popState:!0},t=!1):(e.advance(),r=`${r}${e.currentChar.value}`);break;case 10:case 13:e.advance();break;default:e.advance(),r=`${r}${e.currentChar.value}`}return o.tokens??=pt(r)?[{type:0,parts:[r]}]:void 0,o}import{slice as qt}from"@xaendar/common";var W=class{constructor(n){this.input=n}input;getPositionFromCharacterIndex(n){let t=this.getLineStarts(),r=0,o=t.length-1;for(;r<o;){let a=Math.ceil((r+o)/2);t[a]<=n?r=a:o=a-1}let i=r,s=n-t[i];return`[Ln ${i}, Col ${s}]`}getLineStarts(){let n=[0],t=this.input;for(let r=0;r<t.length;r++)t[r]===`
13
+ `&&n.push(r+1);return n}};var ne=class extends W{_currentChar={code:0,index:-1,value:""};get currentChar(){return this._currentChar}_peekCache=new Map;constructor(n){super(n)}advance(n=1){if(n<1)throw`${n} is not a valid value. Please enter a number equal or greater than 1`;let t=this._currentChar.index+n;if(t>=this.input.length)this._currentChar.code=0,this._currentChar.index=-1,this._currentChar.value="",this.throwEOFError();else{for(let r=this._currentChar.index+1;r<=t;r++)this._peekCache.delete(r);this._currentChar.index=t,this._currentChar.value=this.input[t],this._currentChar.code=this.input.charCodeAt(t)}}peekMatch(n,t){if(typeof n=="string"){let i=this.peek(n.length);for(let s=0;s<n.length;s++)if(i[s]!==n.charCodeAt(s))return!1;return!0}let r=this._currentChar.index+1,o=qt(this.input,r,r+t);return n.test(o)}peek(n,t){let r=this._peekCache,o=typeof n=="number"?n:1,i=(typeof n=="object"?n:t)?.offset??0;return o===1?this.peekOneChar(this._currentChar.index+i+1,r):this.peekMany(o+i,r)}skipSpaces(){for(;this.peek()===32||this.peek()===10||this.peek()===13;)this.advance()}peekMany(n,t){let r=new Array,o=this._currentChar.index+1;for(let i=o;i<o+n;i++)r.push(this.peekOneChar(i,t));return r}peekOneChar(n,t){if(t.has(n))return t.get(n);n>=this.input.length&&this.throwEOFError();let r=this.input.charCodeAt(n);return t.set(n,r),r}throwEOFError(){throw new Error("",{cause:0})}};var oe=class{constructor(n){this._input=n;this._cursor=new ne(this._input)}_input;_cursor;_state="text";_stack=new Xt;_tokens=new Array;_states={text:ct,"tag-open-name":at,"tag-body":ot,"tag-open-end":st,"tag-close":it,attribute:He,"attribute-value":Ve,event:Qe,"event-handler":qe,parameter:Xe,"flow-control":je,"flow-control-condition":Ke,"case-flow-control-condition":We,"flow-control-block":ze,interpolation:nt,"interpolation-expression":et,"interpolation-literal":rt,import:Je,"import-path":Ye};tokenize(){let n=!1,t=this._cursor,r=-1;for(;!n;)try{r=t.currentChar.index+1;let o=this._states[this._state],{state:i,tokens:s,popState:a,pushState:c}=o(t,{history:this._stack.values,tokens:[...this._tokens]});if(s?.length){let p=t.currentChar.index+1;this._tokens.push(...this.withTokenSpans(s,{start:r,end:p}))}c&&this._stack.push(this._state),a&&this._stack.pop(),this._state=i}catch(o){let i=o instanceof Error;if(i&&o.cause===0)n=!0;else{let a=r,c=r,p=!1;for(;!p;){let A=this._input.charCodeAt(c);A===10||A===13||a-c>15&&A===32?(a=c+1,p=!0):c--}let u=t.currentChar.index,d=u<=r?u+2:u+1,f=d;for(c=f,p=!1;!p;){let A=this._input.charCodeAt(c);A===10||A===13||c-f>15&&A===32?(f=c-1,p=!0):c++}let N=Ee(this._input,a,r).replace(/^\s+/,""),I=`\x1B[4m${Ee(this._input,r,d)}\x1B[0m`,y=Ee(this._input,d+1,f).replace(/\s+$/,""),B=i?o.message:o;throw`${t.getPositionFromCharacterIndex(d+1)} ${B}
14
+ ---> ${N}${I}${y}`}}return this._tokens}withTokenSpans(n,t){return n.map(r=>({...r,span:r.span??t}))}};import{slice as lr}from"@xaendar/common";var ie=class extends W{constructor(t,r){super(t);this._tokens=r}_tokens;_currentToken={value:{type:24},index:-1};getCurrentToken(){return this._currentToken}advance(t=1){if(t<1)throw`${t} is not a valid value. Please enter a number equal or greater than 1`;let r=this._currentToken.index+t;r>=this._tokens.length?(this._currentToken.value={type:24},this._currentToken.index=-1):(this._currentToken.index=r,this._currentToken.value=this._tokens[r])}peek(t,r){let o=typeof t=="number"?t:1,i=(typeof t=="object"?t:r)?.offset??0;return o===1?this.peekOneToken(this._currentToken.index+i+1):this.peekMany(o+i)}peekMany(t){let r=new Array,o=this._currentToken.index+1;for(let i=o;i<o+t;i++)r.push(this.peekOneToken(i));return r}peekOneToken(t){return t<this._tokens.length?this._tokens[t]:{type:24}}};import{ScriptTarget as Qt,SyntaxKind as l,createSourceFile as jt,forEachChild as zt}from"typescript";function _(e){let n="const x = ",o=jt("expression.ts",`${n}${e}`,Qt.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(lt(o,n.length,i),i.length)throw i.reduce((s,a)=>`${s}${a.message}
15
+ `,"");return{node:o}}function lt(e,n,t){if(!Yt(e))throw Zt(e);if(zt(e,r=>lt(r,n,t)),t.length)throw t[0].message}function Yt(e){switch(e.kind){case l.StringLiteral:case l.NumericLiteral:case l.BigIntLiteral:case l.TrueKeyword:case l.FalseKeyword:case l.NullKeyword:case l.UndefinedKeyword:case l.Identifier:case l.PropertyAccessExpression:case l.ElementAccessExpression:case l.CallExpression:case l.BinaryExpression:case l.EqualsEqualsToken:case l.EqualsEqualsEqualsToken:case l.ExclamationEqualsToken:case l.ExclamationEqualsEqualsToken:case l.LessThanToken:case l.LessThanEqualsToken:case l.GreaterThanToken:case l.GreaterThanEqualsToken:case l.PlusToken:case l.MinusToken:case l.AsteriskToken:case l.SlashToken:case l.PercentToken:case l.AsteriskAsteriskToken:case l.AmpersandAmpersandToken:case l.BarBarToken:case l.QuestionQuestionToken:case l.QuestionDotToken:case l.QuestionToken:case l.ColonToken:case l.AmpersandToken:case l.BarToken:case l.CaretToken:case l.LessThanLessThanToken:case l.GreaterThanGreaterThanToken:case l.GreaterThanGreaterThanGreaterThanToken:case l.InstanceOfKeyword:case l.InKeyword:case l.PrefixUnaryExpression:case l.PostfixUnaryExpression:case l.TypeOfExpression:case l.VoidExpression:case l.ConditionalExpression:case l.ParenthesizedExpression:case l.TemplateExpression:case l.NoSubstitutionTemplateLiteral:case l.TemplateHead:case l.TemplateMiddle:case l.TemplateTail:case l.TemplateSpan:case l.ArrayLiteralExpression:case l.ObjectLiteralExpression:case l.PropertyAssignment:case l.ShorthandPropertyAssignment:case l.SpreadAssignment:case l.SpreadElement:case l.TaggedTemplateExpression:case l.SyntaxList:return!0;default:return!1}}function Zt(e){switch(e.kind){case l.AwaitExpression:return"'await' is not allowed inside template expressions.";case l.YieldExpression:return"'yield' is not allowed inside template expressions.";case l.NewExpression:return"'new' is not allowed inside template expressions.";case l.ArrowFunction:case l.FunctionExpression:return"Function expressions are not allowed inside template expressions.";case l.BinaryExpression:return Jt(e.operatorToken.kind)?"Assignments are not allowed inside template expressions. Use @const to declare local template variables instead.":`'${l[e.kind]}' is not allowed inside template expressions.`;default:return`'${l[e.kind]}' is not allowed inside template expressions.`}}function Jt(e){return e>=l.FirstAssignment&&e<=l.LastAssignment}function Q(e,n,t){let r=t.span.start;return e.advance(),{type:4,expression:_(t.parts[0]).node,span:{start:r,end:e.getCurrentToken().value.span.end}}}function mt(e,n,t){let r=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type===5||i.type===4||i.type===7)return{type:1,name:o,value:"true",span:{start:r,end:e.getCurrentToken().value.span.end}};if(i.type===11||i.type===10){let s=Q(e,n,i);return{type:1,name:o,value:s,span:{start:r,end:e.getCurrentToken().value.span.end}}}if(i.type!==6)throw`Attribute value missing for ${o} in: ${o}`;return e.advance(),{type:1,name:o,value:i.parts[0],span:{start:r,end:e.getCurrentToken().value.span.end}}}function ft(e,n,t){let r=t.span.start;e.advance();let o=t.parts[0],i=e.peek();if(i.type!==8)throw`Invalid event format for ${o}`;e.advance();let s=e.getCurrentToken().value.span.end,a=new Array;for(;e.peek().type===9;)e.advance(),a.push(_(e.getCurrentToken().value.parts[0]).node),s=e.getCurrentToken().value.span.end;return{type:2,name:o,handler:i.parts[0],parameters:a,span:{start:r,end:s}}}function ut(e,n,t){e.advance();let r=t.parts[0],o=new Array,i=new Array,s=!0;for(;s;){let p=e.peek();switch(p.type){case 5:o.push(mt(e,n,p));break;case 7:i.push(ft(e,n,p));break;default:s=!1}}let a=e.peek().type;switch(a){case 3:e.advance();break;case 2:return e.advance(),{type:0,tagName:r,attributes:o,events:i,children:[]};default:throw new Error(`Unexpected State ${a}`)}let c=new Array;for(;!er(e,r);){let p=n();p&&c.push(p)}return e.advance(),{type:0,tagName:r,attributes:o,events:i,children:c}}function er(e,n){let t=e.peek();switch(t.type){case 24:throw new Error(`Expected closing tag ${n}`);case 4:return t.parts[0]===n;default:return!1}}import{slice as j}from"@xaendar/common";import{createSourceFile as tr,isExpressionStatement as rr,isIdentifier as nr,ScriptTarget as or}from"typescript";function F(e,n){let t=new Array;for(;e.peek().type!==21;){let r=n();r&&t.push(r)}return e.advance(),t}function dt(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after FOR, got ${T[r.type]}`;let o=ir(r.parts[0],0);e.advance(2);let i=F(e,n);return{type:8,...o,children:i}}function ir(e,n){let t=ar(e);if(t.length<2)throw'@for requires at least "item of iterable; track expr".';let r=t[0].trim(),o=r.indexOf(" of ");if(o===-1)throw'@for expression must be in the form "item of iterable".';let i=j(r,0,o).trim(),s=j(r,o+4).trim();if(!Tt(i))throw`'${i}' is not a valid item alias.`;let a=_(s),c=t[1].trim();if(!c.startsWith("track "))throw'Second section of @for must start with "track".';let p=j(c,6).trim(),u=_(p),d=new Map;if(t.length>=3&&t[2]!==void 0){let f=t[2].trim(),N=n+e.indexOf(t[2]);sr(f,N,d)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:u.node,trackSource:p,implicitAliases:d}}function sr(e,n,t){let r=e.split(","),o=0,i=new Set(["$index","$last","$first","$even","$odd"]);for(let s=0;s<r.length;s++){let a=r[s],c=a.trim(),p=c.indexOf("=");if(p===-1)throw`Invalid alias declaration '${c}'. Expected '$implicit = alias'.`;o+=a.length+1;let u=j(c,0,p).trim(),d=j(c,p+1).trim();if(!(N=>i.has(N))(d))throw`'${d}' is not a known implicit variable. Known variables: ${[...i].join(", ")}.`;if(o+=a.length+1,!Tt(u))throw`'${u}' is not a valid alias identifier.`;if(o+=a.length+1,t.has(d))throw`'${d}' is already aliased in this @for expression.`;t.set(d,u),o+=a.length+1}}function ar(e){let n=new Array,t="",r=0,o;for(let i=0;i<e.length;i++){let s=e[i];if(!(!t&&s===" ")){if(o){t+=s,s===o&&e[i-1]!=="\\"&&(o=null);continue}if(s==='"'||s==="'"||s==="`"){o=s,t+=s;continue}if(s==="("||s==="["||s==="{"){r++,t+=s;continue}if(s===")"||s==="]"||s==="}"){r--,t+=s;continue}if(s===";"&&r===0){n.push(t),t="";continue}t+=s}}return t.trim().length&&n.push(t),n}function Tt(e){if(!e.length)return!1;let t=tr("__id.ts",e,or.ESNext,!1).statements[0];return!!t&&rr(t)&&nr(t.expression)&&t.expression.text===e}function ht(e,n,t){return xt(e,n,t)}function pr(e,n,t){switch(t.type){case 15:return xt(e,n,t);case 14:let r=t.span.start;e.advance(2);let o=F(e,n);return{type:6,children:o,span:{start:r,end:e.getCurrentToken().value.span.end}}}}function xt(e,n,t){let r=t.span.start;e.advance();let o=e.peek();if(o.type!==19)throw`Expected CONDITION after ${T[t.type]}, got ${T[o.type]}`;e.advance(2);let i=o.parts[0],s=_(i),a=F(e,n),c=null,p=e.peek();return(p.type===15||p.type===14)&&(c=pr(e,n,p)),{type:t.type===12?5:7,condition:i,conditionNode:s.node,children:a,alternate:c,span:{start:r,end:e.getCurrentToken().value.span.end}}}function Et(e,n,t){let r=new Array;for(;e.peek().type===22;){e.advance();let o=e.getCurrentToken().value.parts[0],i=cr(o);r.push(i)}return e.advance(),{type:11,specifiers:r,path:e.getCurrentToken().value.parts[0]}}function cr(e){let n=e.trim(),t=n.match(/^\*\s+as\s+([A-Za-z_$][\w$]*)$/);if(t)return{imported:"*",local:t[1]};let r=n.match(/^default\s+as\s+([A-Za-z_$][\w$]*)$/);if(r)return{imported:"default",local:r[1]};let o=n.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);if(o)return{imported:o[1],local:o[2]??o[1]};throw`Invalid import specifier "${e}".`}function Ct(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after SWITCH, got ${T[r.type]}`;let o=_(r.parts[0]).node;e.advance(2);let i=new Array;for(;e.peek().type!==21;){let s=e.peek();switch(s.type){case 17:let a=s.span.start,c=new Array;do{e.advance();let f=e.peek();if(f.type!==19)throw"Expected CONDITION after CASE";c.push(f.parts[0]),e.advance()}while(e.peek().type!==20);e.advance();let p=F(e,n);i.push({type:10,condition:c,children:p,span:{start:a,end:e.getCurrentToken().value.span.end}});break;case 18:let u=s.span.start;e.advance(2);let d=F(e,n);i.push({type:10,condition:null,children:d,span:{start:u,end:e.getCurrentToken().value.span.end}});break}}return e.advance(),{type:9,expression:o,children:i}}function kt(e,n,t){return e.advance(),{type:3,value:t.parts[0]}}var se=class{constructor(n,t){this._input=n;this._cursor=new ie(this._input,t)}_input;_cursor;_states={0:kt,11:Q,10:Q,1:ut,12:ht,13:dt,16:Ct,22:Et};parse(){let n=new Array;for(;this._cursor.peek().type!==24;){let t=this.parseNode();t&&n.push(t)}return n}parseNode(){let n=this._cursor.peek();if(n.type===24)return;let t=n.span.start;try{let r=this._states[n.type];if(!r)throw`No transition function for token type ${T[n.type]}`;let o=r(this._cursor,this.parseNode.bind(this),n),i=this._cursor.getCurrentToken().value,s="span"in i?i.span.end:n.span.end;return{...o,span:o.span??{start:t,end:s}}}catch(r){let o=r instanceof Error?r.message:r,i=this._cursor.peek(),s=i.type!==24?i.span.end:void 0;throw`${this._cursor.getPositionFromCharacterIndex(t+1)} ${o}
16
+ ---> ${lr(this._input,t,s)}`}}};import{indent as wr,slice as $r}from"@xaendar/common";var K=class extends k{_imports=new Array;addImport(n){this._imports.push(n)}getImportBySelector(n){return this._imports.find(t=>t.type==="component"&&t.selectors.includes(n))}};import{indent as Ce}from"@xaendar/common";function Nt(e,n,t){let r=new Array;if(Tr(e.tagName)){let i=t.getImportBySelector(e.tagName);if(!i)throw new Error(`${e.tagName} selector is not associated to any WebComponent imported in the template`,{cause:e.span});r.push(...mr(e,i,t))}else r.push(...dr(e,t));let o=e.children;for(let i=0;i<o.length;i++)r.push(...n(o[i],t));return r}function mr(e,n,t){let r=new Array,o=new Set(n.properties.filter(a=>a.required).map(a=>a.alias??a.name)),i=e.attributes;for(let a=0;a<i.length;a++){let{name:c,value:p}=i[a],u=fr(n,c);u&&(o.delete(u.alias??u.name),r.push("{",...Ce(typeof p=="object"?[`(${h(p.expression,t,{resolver:"root"})}) satisfies ${u.type};`]:["let x!: string",`x satisfies ${u.type};`]),"}"))}if(o.size)throw new Error(`${e.tagName} is missing the following required properties: ${Array.from(o.values()).join(`
17
+ `)}`,{cause:e.span});let s=e.events;for(let a=0;a<s.length;a++){let{name:c,handler:p,parameters:u}=s[a],d=ur(n,c);if(!d)throw new Error(`Unknown event "${c}" on <${e.tagName}> (${n.className} has no @Event with this name).`,{cause:e.span});let f=new k([],t);f.addUnresolvableIdentifier("$event");let N=u.map(I=>h(I,f,{resolver:"root"})).join(", ");r.push("{"),d.type!=="void"&&r.push(Ce(`let $event!: CustomEvent<${d.type}>;`)),r.push(Ce(`root.${p}(${N});`),"}")}return r}function fr(e,n){return e.properties.find(t=>(t.alias??t.name)===n)}function ur(e,n){return e.events.find(t=>t.name===n)}function dr(e,n){let t=new Array,r=e.attributes;for(let i=0;i<r.length;i++){let{value:s}=r[i];typeof s!="string"&&t.push(`${h(s.expression,n,{resolver:"root"})};`)}let o=e.events;for(let i=0;i<o.length;i++){let{handler:s,parameters:a}=o[i],c=new k([],n);c.addUnresolvableIdentifier("$event");let p=a.map(u=>h(u,c,{resolver:"root"})).join(", ");t.push(`root.${s}(${p});`)}return t}function Tr(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}import{indent as hr}from"@xaendar/common";function gt(e,n,t){let r=new K([],t),o=z(e,"$index"),i=z(e,"$first"),s=z(e,"$last"),a=z(e,"$even"),c=z(e,"$odd"),p=[o,i,s,a,c,e.itemAlias];for(let d=0;d<p.length;d++)r.addUnresolvableIdentifier(p[d]);let u=new Array;return u.push(`for (const ${e.itemAlias} of root.${e.iterableSource}) {`),u.push(...hr([`let ${o}!: number;`,`let ${i}!: boolean;`,`let ${s}!: boolean;`,`let ${a}!: boolean;`,`let ${c}!: boolean;`,`${h(e.trackExpression,t,{skipResolution:!0})};`,...e.children.flatMap(d=>n(d,r))])),u.push("}"),u}function z(e,n){return e.implicitAliases.get(n)??n}import{indent as ke}from"@xaendar/common";function At(e,n,t){let r=new Array,o=h(e.conditionNode,t,{resolver:"root"});r.push(`if (${o}) {`),r.push(...ke(e.children.flatMap(s=>n(s,t)))),r.push("}");let i=e.alternate;for(;i?.type===7;){let s=h(i.conditionNode,t,{resolver:"root"});r.push(`else if (${s}) {`),r.push(...ke(i.children.flatMap(a=>n(a,t)))),r.push("}"),i=i.alternate}return i&&(r.push("else {"),r.push(...ke(i.children.flatMap(s=>n(s,t)))),r.push("}")),r}function yt(e,n,t){let r=e.path,o=It(r),i=new Array;for(let s=0;s<e.specifiers.length;s++){let{imported:a,local:c}=e.specifiers[s];switch(a){case"*":i.push(`let ${c}!: typeof import('${o}');`);break;case"default":i.push(`let ${c}!: typeof import('${o}')['default'];`);break;default:let p=It(a);i.push(`let ${c}!: typeof import('${o}')['${p}'];`);break}}return i}function It(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}import{indent as Lt}from"@xaendar/common";function vt(e,n,t){let o=[`switch (${h(e.expression,t,{resolver:"root"})}) {`],i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=a.condition;if(c?.length)for(let p=0;p<c.length;p++)o.push(` case ${c[p]}:`);else o.push(" default:");o.push(...Lt(Lt([...a.children.flatMap(p=>n(p,t)),"break;"])))}return o.push("}"),o}function Ne(e,n,t){return e.type===4?[`${h(e.expression,t,{resolver:"root"})};`]:[]}import{existsSync as ge}from"fs";import{readFile as xr}from"fs/promises";import{resolve as Er}from"path";import{createSourceFile as Cr,getNameOfDeclaration as _t,isArrayLiteralExpression as kr,isCallExpression as Y,isClassDeclaration as Nr,isDecorator as gr,isIdentifier as w,isObjectLiteralExpression as St,isPropertyAccessExpression as Ar,isPropertyAssignment as Ot,isPropertyDeclaration as Ie,isStringLiteral as Ae,isTypeReferenceNode as Ir,ScriptTarget as yr,SyntaxKind as bt}from"typescript";async function Rt(e,n,t=process.cwd()){try{let r=Lr(e,t);if(!r)return;let o=await xr(r,"utf8"),i=Cr(r,o,yr.Latest,!0),s,a=i.statements;for(let c=0;c<a.length;c++){let p=a[c];if(!s&&Nr(p)){let u=p.name?.text;if(u!==n)continue;let d=p.modifiers??[],f=Array.from(d).find(A=>vr(A));if(!f)continue;let N=Or(f);if(!N?.length)continue;let I=new Array,y=new Array,B=p.members;for(let A=0;A<B.length;A++){let Z=B[A];if(!Ie(Z))continue;let ye=Z.modifiers??[],Le=!1,ve=Array.from(ye).find(L=>{let R=_r(L);return Le=!!R.required,R.decorator});if(ve){let L=_t(Z),R=L&&w(L)?L.text:void 0;if(R){let m=Rr(R,ve,Le);m&&I.push(m)}continue}let _e=Array.from(ye).find(L=>Sr(L));if(_e){let L=_t(Z),R=L&&w(L)?L.text:void 0;if(R){let m=Fr(R,_e);m&&y.push(m)}}}s={type:"component",className:u,selectors:N,properties:I,events:y}}}return s}catch(r){console.error(`Failed to extract component metadata from ${e}:`,r);return}}function Lr(e,n){if(e.startsWith(".")){let t=Er(n,e);if(ge(`${t}.ts`))return t+".ts";if(ge(`${t}/index.ts`))return`${t}/index.ts`;if(ge(t))return t}}function vr(e){if(e.kind!==bt.Decorator)return!1;let n=Y(e.expression)?e.expression.expression:e.expression;return w(n)&&n.text==="WebComponent"}function _r(e){if(!gr(e))return{decorator:!1};let n=e.expression;if(!Y(n))return{decorator:!1};let t=n.expression;return w(t)&&t.text==="Property"?{decorator:!0}:Ar(t)&&w(t.expression)&&t.expression.text==="Property"&&t.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function Sr(e){if(e.kind!==bt.Decorator)return!1;let n=Y(e.expression)?e.expression.expression:e.expression;return w(n)&&n.text==="Event"}function Or(e){try{let n=e.expression;if(!Y(n))return[];let t=n.arguments;if(t.length===0)return[];let r=t[0];if(!r||!St(r))return[];let o=Array.from(r.properties).find(i=>Ot(i)&&w(i.name)&&i.name.text==="selector");return br(o.initializer)}catch{return[]}}function br(e){return Ae(e)?[e.text]:kr(e)?e.elements?.filter(n=>Ae(n)).map(n=>n.text):[]}function Rr(e,n,t){let r=n.expression,o={name:e,required:t,type:Ie(n.parent)?Ft(n.parent.type):"any"};if(Y(r)){let i=r.arguments,a=(i.length?i.find(c=>St(c)):void 0)?.properties?.find(c=>Ot(c)&&w(c.name)&&c.name.text==="alias");a&&Ae(a.initializer)&&(o.alias=a.initializer.text)}return o}function Fr(e,n){let t={name:e,type:"void"};return Ie(n.parent)&&(t.type=Ft(n.parent.type,!0)),t}function Ft(e,n=!1){let t=n?"void":"any";if(!e||!Ir(e))return t;let r=e.typeArguments;return!r||r.length===0?t:r[0].getText()}var ae=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_context=new K;_states={3:Ne,4:Ne,0:Nt,5:At,8:gt,9:vt,11:yt};async populateImportMetadata(n){let t=this._ast.filter(r=>r.type===11);await Promise.all(t.flatMap(r=>r.specifiers.filter(({imported:o})=>o!=="*").map(async({imported:o,local:i})=>{let s=o==="default"?i:o,a=await Rt(r.path,s,n);a&&this._context.addImport(a)})))}async generate(n){try{await this.populateImportMetadata(n);let t=this._ast.flatMap(r=>this._processNode(r,this._context));return["function typeCheck() {",...wr(t),"}"].join(`
18
+ `)}catch(t){let r,o;if(t instanceof Error){let i=t.cause;o=i&&typeof i=="object"&&"start"in i&&"end"in i?i:void 0,r=t.message}else r=t;throw`${r}${o?`
19
+ ----> ${$r(this._input,o.start,o.end)}`:""}`}}_processNode=(n,t)=>{let r=this._states[n.type];if(!r)throw new Error(`No transition function for token type ${E[n.type]}`,{cause:n.span});return r(n,this._processNode,t)}};async function Sa(e,n,t){let r=new oe(e).tokenize(),o=new se(e,r).parse();return{javascript:new J(e,o).generate(t),typescript:await new ae(e,o).generate(n)}}export{Sa as compile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xaendar/compiler",
3
- "version": "0.9.3",
3
+ "version": "0.9.4",
4
4
  "description": "A library for transpiling Xaendar Templates into JavaScript code",
5
5
  "author": "Kaitenjo",
6
6
  "license": "MIT",
@@ -13,8 +13,8 @@
13
13
  },
14
14
  "main": "./dist/compiler.js",
15
15
  "dependencies": {
16
- "@xaendar/common": "0.9.3",
17
- "@xaendar/types": "0.9.3",
16
+ "@xaendar/common": "0.9.4",
17
+ "@xaendar/types": "0.9.4",
18
18
  "typescript": "^6.0.3"
19
19
  }
20
20
  }