@xaendar/compiler 0.9.15 → 0.9.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compiler.js +8 -8
- package/package.json +3 -3
package/dist/compiler.js
CHANGED
|
@@ -8,15 +8,15 @@ import{indent as V,slice as zt}from"@xaendar/common";var C=(f=>(f[f.Element=0]="
|
|
|
8
8
|
const { ${e.itemAlias}, ${p}, ${u}, ${d}, ${f}, ${N} } = vars;`,node:e,parentNode:_,context:v,anchor:"anchor",isForBody:!0},args:[_,"parentContext",a,c,"anchor"]}),o.code.push(`_for(${n}, context, () => ${s}, ${e.itemAlias} => ${x(e.trackExpression,v,{skipResolution:!0})}, this.${_}.bind(this));`),o}function J(e,n){return e.implicitAliases.get(n)??n}import{indent as q}from"@xaendar/common";function Ke(e,n,t,r){let o=new g([],r),i={code:[],functionsToProcess:new Map};i.code.push(`_if(${n}, context, [`);let s=P("if",n,t);i.code.push(...q(["{",...q([`condition: () => ${x(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 g([],r),u=P("elseIf",n,`${t}_${c}`),d=a.conditionNode;i.code.push(...q(["{",...q([`condition: () => ${x(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 g([],r),u=P("else",n,t);i.code.push(...q(["{",...q([`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 qe}from"@xaendar/common";function Xe(e,n,t,r){let o={code:[],functionsToProcess:new Map};o.code.push(`_switch(${n}, context, () => ${x(e.expression,r)}, [`);let i=e.children;for(let s=0;s<i.length;s++){let a=i[s],c=new g([],r),p=a.condition?P("case",n,`${t}_${s}`):P("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(...qe(["{",...qe([`condition: ${a.condition?`[${a.condition.join(", ")}]`:"null"},`,`block: ${u}`]),"},"]))}return o.code.push("])"),o}function he(e,n,t,r){return{code:[`${e.type===3?`_renderLiteralText(${n}, context, '${e.value}');`:`_renderText(${n}, context, () => ${x(e.expression,r)});`}`]}}function Qe(e,n,t,r){}var oe=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_nodeToProcess=new Map;_states={3:he,4:he,0:He,5:Ke,8:We,9:Xe,11:Qe};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 g,o=["_render() {",...V([`const ${Z} = this._root;`,"const context = new Context(this, { createElement: document.createElement.bind(document), get: () => undefined });"])];n&&o.push(V(`${Z}.adoptedStyleSheets = [${n}];`));for(let i=0;i<this._ast.length;i++){let s=this._processNode(this._ast[i],Z,i.toString(),r,null);if(s){let{code:a,functionsToProcess:c}=s;t(c),o.push(...V(a))}}o.push(...V(["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
9
|
${i}(${s.args?.join(", ")}) {`,...V(["const context = new Context(this, parentContext);"])),u&&o.push(V(u)),o.push(...V([...a.children.map((f,N)=>{let v=this._processNode(f,c,N.toString(),p,d??null);if(v){let{code:_,functionsToProcess:W}=v;return t(W),_}return""}).flat(),s.fn.isForBody?"return { context, update };":"return context;"]),"}")}return o.join(`
|
|
10
10
|
`)}catch(r){let o=r,{start:i,end:s}=o.cause;throw new Error(`[Generator] ${o.message}
|
|
11
|
-
----> ${zt(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
|
|
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 st(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:it(i,e,r,o),r="",o=e.currentChar.index+1;break;case 125:it(i,e,r,o),t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return i}function it(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 at(e,n){let t=!0,r="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,r=ge(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=ge(e,r);break;default:r=ge(e,r)}return i}function ge(e,n){return e.advance(1),`${n}${e.currentChar.value}`}function ct(e,n){let t=!0,r="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(r=pt(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=pt(e,r)}return o}function pt(e,n){return e.advance(),`${n}${e.currentChar.value}`}function
|
|
13
|
-
`&&n.push(r+1);return n}};var pe=class extends M{_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=er(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 ce=class{constructor(n){this._input=n;this._cursor=new pe(this._input)}_input;_cursor;_state="text";_stack=new tr;_tokens=new Array;_states={text:ht,"tag-open-name":dt,"tag-body":
|
|
14
|
-
---> ${N}${v}${_}`}}return this._tokens}withTokenSpans(n,t){return n.map(r=>({...r,span:r.span??t}))}};import{slice as Er}from"@xaendar/common";var
|
|
15
|
-
`,"");return{node:o}}function xt(e,n,t){if(!ir(e))throw sr(e);if(or(e,r=>xt(r,n,t)),t.length)throw t[0].message}function ir(e){switch(e.kind){case
|
|
11
|
+
----> ${zt(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 ASTNode of type ${C[n.type]}`,{cause:n.span});return s(n,t,r,o,i)}};import{slice as Ae,Stack as tr}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 je(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 ze(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 ie(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=Ee(e,t);break;case 41:if(r--,!r){e.advance();break}t=Ee(e,t);break;default:t=Ee(e,t)}return t}function Ee(e,n){return e.advance(),`${n}${e.currentChar.value}`}function Ye(e,n){let t=ie(e,n);return e.skipSpaces(),{state:e.peekMatch("@case")?"flow-control":"flow-control-block",tokens:[{type:19,parts:[t]}],popState:!0}}function Ze(e,n){return{state:"flow-control-block",tokens:[{type:19,parts:[ie(e,n)]}],popState:!0}}function Je(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 et(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=ke(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=ke(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=ke(e,r)}return s}function ke(e,n){return e.advance(),`${n}${e.currentChar.value}`}function tt(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 rt(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 nt(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 ot(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 st(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:it(i,e,r,o),r="",o=e.currentChar.index+1;break;case 125:it(i,e,r,o),t=!1;break;default:e.advance(),r=`${r}${e.currentChar.value}`}return i}function it(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 at(e,n){let t=!0,r="",o=1,i;for(;t;)switch(e.peek()){case 123:o++,r=ge(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=ge(e,r);break;default:r=ge(e,r)}return i}function ge(e,n){return e.advance(1),`${n}${e.currentChar.value}`}function ct(e,n){let t=!0,r="`",o;for(e.advance();t;)switch(e.peek()){case 96:if(r=pt(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=pt(e,r)}return o}function pt(e,n){return e.advance(),`${n}${e.currentChar.value}`}function lt(e,n){return e.advance(),e.skipSpaces(),e.peek()===96?{state:"interpolation-literal"}:{state:"interpolation-expression"}}function mt(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 ft(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 ut(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 dt(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 Tt(e){return/\S/.test(e)}function ht(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??=Tt(r)?[{type:0,parts:[r]}]:void 0,o}import{slice as er}from"@xaendar/common";var M=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+1}, Col ${s+1}]`}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 pe=class extends M{_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=er(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 ce=class{constructor(n){this._input=n;this._cursor=new pe(this._input)}_input;_cursor;_state="text";_stack=new tr;_tokens=new Array;_states={text:ht,"tag-open-name":dt,"tag-body":mt,"tag-open-end":ut,"tag-close":ft,attribute:ze,"attribute-value":je,event:tt,"event-handler":Je,parameter:et,"flow-control":rt,"flow-control-condition":Ze,"case-flow-control-condition":Ye,"flow-control-block":nt,interpolation:lt,"interpolation-expression":at,"interpolation-literal":ct,import:st,"import-path":ot};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 R=this._input.charCodeAt(c);R===10||R===13||a-c>15&&R===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 R=this._input.charCodeAt(c);R===10||R===13||c-f>15&&R===32?(f=c-1,p=!0):c++}let N=Ae(this._input,a,r).replace(/^\s+/,""),v=`\x1B[4m${Ae(this._input,r,d)}\x1B[0m`,_=Ae(this._input,d+1,f).replace(/\s+$/,""),W=i?o.message:o;throw`${t.getPositionFromCharacterIndex(d+1)} - ${W}
|
|
14
|
+
---> ${N}${v}${_}`}}return this._tokens}withTokenSpans(n,t){return n.map(r=>({...r,span:r.span??t}))}};import{slice as Er}from"@xaendar/common";var le=class extends M{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 rr,SyntaxKind as l,createSourceFile as nr,forEachChild as or}from"typescript";function O(e){let n="const x = ",o=nr("expression.ts",`${n}${e}`,rr.ESNext,!0).statements[0].declarationList.declarations[0].initializer,i=new Array;if(xt(o,n.length,i),i.length)throw i.reduce((s,a)=>`${s}${a.message}
|
|
15
|
+
`,"");return{node:o}}function xt(e,n,t){if(!ir(e))throw sr(e);if(or(e,r=>xt(r,n,t)),t.length)throw t[0].message}function ir(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 sr(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 ar(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 ar(e){return e>=l.FirstAssignment&&e<=l.LastAssignment}function ee(e,n,t){let r=t.span.start;return e.advance(),{type:4,expression:O(t.parts[0]).node,span:{start:r,end:e.getCurrentToken().value.span.end}}}function Et(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=ee(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 Ct(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(O(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 kt(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(Et(e,n,p));break;case 7:i.push(Ct(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(;!pr(e,r);){let p=n();p&&c.push(p)}return e.advance(),{type:0,tagName:r,attributes:o,events:i,children:c}}function pr(e,n){let t=e.peek();switch(t.type){case 24:throw new Error(`Expected closing tag ${n} while file is over`);case 4:let r=t.parts[0];if(r===n)return!0;throw`Expected closing tag ${n}, found ${r}`;default:return!1}}import{slice as te}from"@xaendar/common";import{createSourceFile as cr,isExpressionStatement as lr,isIdentifier as mr,ScriptTarget as fr}from"typescript";function D(e,n){let t=new Array;for(;e.peek().type!==21;){let r=n();r&&t.push(r)}return e.advance(),t}function gt(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after FOR, got ${T[r.type]}`;let o=ur(r.parts[0],0);e.advance(2);let i=D(e,n);return{type:8,...o,children:i}}function ur(e,n){let t=Tr(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=te(r,0,o).trim(),s=te(r,o+4).trim();if(!Nt(i))throw`'${i}' is not a valid item alias.`;let a=O(s),c=t[1].trim();if(!c.startsWith("track "))throw'Second section of @for must start with "track".';let p=te(c,6).trim(),u=O(p),d=new Map;if(t.length>=3&&t[2]!==void 0){let f=t[2].trim(),N=n+e.indexOf(t[2]);dr(f,N,d)}return{itemAlias:i,iterableExpression:a.node,iterableSource:s,trackExpression:u.node,trackSource:p,implicitAliases:d}}function dr(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=te(c,0,p).trim(),d=te(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,!Nt(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 Tr(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 Nt(e){if(!e.length)return!1;let t=cr("__id.ts",e,fr.ESNext,!1).statements[0];return!!t&&lr(t)&&mr(t.expression)&&t.expression.text===e}function Lt(e,n,t){return At(e,n,t)}function hr(e,n,t){switch(t.type){case 15:return At(e,n,t);case 14:let r=t.span.start;e.advance(2);let o=D(e,n);return{type:6,children:o,span:{start:r,end:e.getCurrentToken().value.span.end}}}}function At(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=O(i),a=D(e,n),c=null,p=e.peek();return(p.type===15||p.type===14)&&(c=hr(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 It(e,n,t){let r=new Array;for(;e.peek().type===22;){e.advance();let o=e.getCurrentToken().value.parts[0],i=xr(o);r.push(i)}return e.advance(),{type:11,specifiers:r,path:e.getCurrentToken().value.parts[0]}}function xr(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 yt(e,n,t){e.advance();let r=e.peek();if(r.type!==19)throw`Expected CONDITION after SWITCH, got ${T[r.type]}`;let o=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=D(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=D(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 vt(e,n,t){return e.advance(),{type:3,value:t.parts[0]}}var me=class{constructor(n,t){this._input=n;this._cursor=new le(this._input,t)}_input;_cursor;_states={0:vt,11:ee,10:ee,1:kt,12:Lt,13:gt,16:yt,22:It};thrown=!1;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 of 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){if(this.thrown)throw r;this.thrown=!0;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
16
|
---> ${Er(this._input,t,s)}`}}};import{slice as Gr}from"@xaendar/common";var Y=class extends g{_imports=new Array;addImport(n){this._imports.push(n)}getImportBySelector(n){return this._imports.find(t=>t.type==="component"&&t.selectors.includes(n))}};function A(e,n){return{text:e,span:n}}function I(...e){let n="",t=new Array;for(let r of e)if(typeof r=="string")n=`${n}${r}`;else{let o=n.length;n=`${n}${r.text}`,t.push({columnStart:o,columnEnd:n.length,original:r.span})}return t.length?{text:n,mappings:t}:{text:n}}function h(e){return{text:e}}function y(e){return e.map(n=>({text:" ".repeat(2)+n.text,mappings:n.mappings?.map(t=>({...t,columnStart:t.columnStart+2,columnEnd:t.columnEnd+2}))}))}function St(e,n,t){let r=new Array;if(gr(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(...Cr(e,i,t))}else r.push(...kr(e,t));let o=e.children;for(let i=0;i<o.length;i++)r.push(...n(o[i],t));return r}function Cr(e,n,t){let r=new Array,o=new Set(n.properties.entries().filter(([a,c])=>c.required).map(([a])=>a)),i=e.attributes;for(let a=0;a<i.length;a++){let{name:c,value:p}=i[a],u=n.properties.get(c);u&&(o.delete(c),r.push(h("{"),...y(typeof p=="object"?[I("(",A(x(p.expression,t,{resolver:"root"}),p.span),`) satisfies ${u.type};`)]:[h("let x!: string;"),I(A(`x satisfies ${u.type};`,i[a].span))]),h("}")))}if(o.size)throw new Error(`${e.tagName} is missing the following required properties:
|
|
17
17
|
\u25CF ${Array.from(o.values()).join(`
|
|
18
|
-
\u25CF `)}`,{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=n.events.get(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 g([],t);f.addUnresolvableIdentifier("$event");let N=u.map(v=>x(v,f,{resolver:"root"})).join(", ");r.push(h("{")),d.type!=="void"&&r.push(...y([h(`let $event!: CustomEvent<${d.type}>;`)])),r.push(...y([I(A(`root.${p}(${N});`,s[a].span))])),r.push(h("}"))}return r}function kr(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(I(A(`${x(s.expression,n,{resolver:"root"})};`,s.span)))}let o=e.events;for(let i=0;i<o.length;i++){let{handler:s,parameters:a}=o[i],c=new g([],n);c.addUnresolvableIdentifier("$event");let p=a.map(u=>x(u,c,{resolver:"root"})).join(", ");t.push(I(A(`root.${s}(${p});`,o[i].span)))}return t}function gr(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}function _t(e,n,t){let r=new Y([],t),o=re(e,"$index"),i=re(e,"$first"),s=re(e,"$last"),a=re(e,"$even"),c=re(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(I(`for (const ${e.itemAlias} of root.`,A(e.iterableSource,e.span),") {")),u.push(...y([h(`let ${o}!: number;`),h(`let ${i}!: boolean;`),h(`let ${s}!: boolean;`),h(`let ${a}!: boolean;`),h(`let ${c}!: boolean;`),I(A(`${x(e.trackExpression,t,{skipResolution:!0})};`,e.span)),...e.children.flatMap(d=>n(d,r))])),u.push(h("}")),u}function re(e,n){return e.implicitAliases.get(n)??n}function bt(e,n,t){let r=new Array,o=x(e.conditionNode,t,{resolver:"root"});r.push(I("if (",A(o,e.span),") {")),r.push(...y(e.children.flatMap(s=>n(s,t)))),r.push(h("}"));let i=e.alternate;for(;i?.type===7;){let s=x(i.conditionNode,t,{resolver:"root"});r.push(I("else if (",A(s,i.span),") {")),r.push(...y(i.children.flatMap(a=>n(a,t)))),r.push(h("}")),i=i.alternate}return i&&(r.push(h("else {")),r.push(...y(i.children.flatMap(s=>n(s,t)))),r.push(h("}"))),r}function Rt(e,n,t){let r=e.path,o=Ot(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(h(`let ${c}!: typeof import('${o}');`));break;case"default":i.push(h(`let ${c}!: typeof import('${o}')['default'];`));break;default:let p=Ot(a);i.push(h(`let ${c}!: typeof import('${o}')['${p}'];`));break}}return i}function Ot(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Ft(e,n,t){let r=x(e.expression,t,{resolver:"root"}),o=[I("switch (",A(r,e.span),") {")],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(h(` case ${c[p]}:`));else o.push(h(" default:"));o.push(...y(y([...a.children.flatMap(p=>n(p,t)),h("break;")])))}return o.push(h("}")),o}function Ie(e,n,t){return e.type===4?[I(A(`${x(e.expression,t,{resolver:"root"})};`,e.span))]:[]}import{existsSync as ye}from"fs";import{readFile as Nr}from"fs/promises";import{resolve as Lr}from"path";import{createSourceFile as Ar,getNameOfDeclaration as wt,isArrayLiteralExpression as Ir,isCallExpression as ne,isClassDeclaration as yr,isDecorator as vr,isIdentifier as B,isObjectLiteralExpression as $t,isPropertyAccessExpression as Sr,isPropertyAssignment as Pt,isPropertyDeclaration as Se,isStringLiteral as ve,isTypeReferenceNode as _r,ScriptTarget as br,SyntaxKind as Mt}from"typescript";import{slice as Or}from"@xaendar/common";async function Dt(e,n,t=process.cwd()){let r=Rr(e,t);if(!r)return;let o=await Nr(r,"utf8"),i=Ar(r,o,br.Latest,!0),s,a=i.statements;for(let c=0;c<a.length;c++){let p=a[c];if(!s&&yr(p)){let u=p.name?.text;if(u!==n)continue;let d=p.modifiers??[],f=Array.from(d).find(G=>Fr(G));if(!f)continue;let N=Pr(f);if(!N?.length)continue;let v=new Map,_=new Map,W=p.members;for(let G=0;G<W.length;G++){let $=W[G];if(!Se($))continue;let _e=$.modifiers??[],be=!1,Oe=Array.from(_e).find(S=>{let
|
|
18
|
+
\u25CF `)}`,{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=n.events.get(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 g([],t);f.addUnresolvableIdentifier("$event");let N=u.map(v=>x(v,f,{resolver:"root"})).join(", ");r.push(h("{")),d.type!=="void"&&r.push(...y([h(`let $event!: CustomEvent<${d.type}>;`)])),r.push(...y([I(A(`root.${p}(${N});`,s[a].span))])),r.push(h("}"))}return r}function kr(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(I(A(`${x(s.expression,n,{resolver:"root"})};`,s.span)))}let o=e.events;for(let i=0;i<o.length;i++){let{handler:s,parameters:a}=o[i],c=new g([],n);c.addUnresolvableIdentifier("$event");let p=a.map(u=>x(u,c,{resolver:"root"})).join(", ");t.push(I(A(`root.${s}(${p});`,o[i].span)))}return t}function gr(e){return/^[a-z][a-z0-9._\-]*-[a-z0-9._\-]*$/.test(e)}function _t(e,n,t){let r=new Y([],t),o=re(e,"$index"),i=re(e,"$first"),s=re(e,"$last"),a=re(e,"$even"),c=re(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(I(`for (const ${e.itemAlias} of root.`,A(e.iterableSource,e.span),") {")),u.push(...y([h(`let ${o}!: number;`),h(`let ${i}!: boolean;`),h(`let ${s}!: boolean;`),h(`let ${a}!: boolean;`),h(`let ${c}!: boolean;`),I(A(`${x(e.trackExpression,t,{skipResolution:!0})};`,e.span)),...e.children.flatMap(d=>n(d,r))])),u.push(h("}")),u}function re(e,n){return e.implicitAliases.get(n)??n}function bt(e,n,t){let r=new Array,o=x(e.conditionNode,t,{resolver:"root"});r.push(I("if (",A(o,e.span),") {")),r.push(...y(e.children.flatMap(s=>n(s,t)))),r.push(h("}"));let i=e.alternate;for(;i?.type===7;){let s=x(i.conditionNode,t,{resolver:"root"});r.push(I("else if (",A(s,i.span),") {")),r.push(...y(i.children.flatMap(a=>n(a,t)))),r.push(h("}")),i=i.alternate}return i&&(r.push(h("else {")),r.push(...y(i.children.flatMap(s=>n(s,t)))),r.push(h("}"))),r}function Rt(e,n,t){let r=e.path,o=Ot(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(h(`let ${c}!: typeof import('${o}');`));break;case"default":i.push(h(`let ${c}!: typeof import('${o}')['default'];`));break;default:let p=Ot(a);i.push(h(`let ${c}!: typeof import('${o}')['${p}'];`));break}}return i}function Ot(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function Ft(e,n,t){let r=x(e.expression,t,{resolver:"root"}),o=[I("switch (",A(r,e.span),") {")],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(h(` case ${c[p]}:`));else o.push(h(" default:"));o.push(...y(y([...a.children.flatMap(p=>n(p,t)),h("break;")])))}return o.push(h("}")),o}function Ie(e,n,t){return e.type===4?[I(A(`${x(e.expression,t,{resolver:"root"})};`,e.span))]:[]}import{existsSync as ye}from"fs";import{readFile as Nr}from"fs/promises";import{resolve as Lr}from"path";import{createSourceFile as Ar,getNameOfDeclaration as wt,isArrayLiteralExpression as Ir,isCallExpression as ne,isClassDeclaration as yr,isDecorator as vr,isIdentifier as B,isObjectLiteralExpression as $t,isPropertyAccessExpression as Sr,isPropertyAssignment as Pt,isPropertyDeclaration as Se,isStringLiteral as ve,isTypeReferenceNode as _r,ScriptTarget as br,SyntaxKind as Mt}from"typescript";import{slice as Or}from"@xaendar/common";async function Dt(e,n,t=process.cwd()){let r=Rr(e,t);if(!r)return;let o=await Nr(r,"utf8"),i=Ar(r,o,br.Latest,!0),s,a=i.statements;for(let c=0;c<a.length;c++){let p=a[c];if(!s&&yr(p)){let u=p.name?.text;if(u!==n)continue;let d=p.modifiers??[],f=Array.from(d).find(G=>Fr(G));if(!f)continue;let N=Pr(f);if(!N?.length)continue;let v=new Map,_=new Map,W=p.members;for(let G=0;G<W.length;G++){let $=W[G];if(!Se($))continue;let _e=$.modifiers??[],be=!1,Oe=Array.from(_e).find(S=>{let m=wr(S);return be=!!m.required,m.decorator});if(Oe){let S=wt($);if(S&&B(S)){let m=S.text,K=Dr(S,m,Oe,be);if(K){let ue=K.alias??m,Fe=v.get(ue);if(!Fe)v.set(ue,K);else{let{start:we,end:Gt}=Fe.span,{line:Ut,character:$e}=i.getLineAndCharacterOfPosition(we);throw`Failed to extract metadata from an imported component in the template - ${r}
|
|
19
19
|
[Ln ${Ut+1}, Col ${$e+1}] - A property identified by name ${ue} was already defined
|
|
20
|
-
---> ${Or(o,we-$e,Gt)}`}}}continue}let Re=Array.from(_e).find(S=>$r(S));if(Re){let S=wt($),
|
|
20
|
+
---> ${Or(o,we-$e,Gt)}`}}}continue}let Re=Array.from(_e).find(S=>$r(S));if(Re){let S=wt($),m=S&&B(S)?S.text:void 0;if(m){let K=Br(Re);K&&_.set(m,K)}}}let R=new Map;v.entries().forEach(([G,$])=>R.set(G,{name:$.name,required:$.required,type:$.type,alias:$.alias})),s={type:"component",className:u,selectors:N,properties:R,events:_}}}return s}function Rr(e,n){if(e.startsWith(".")){let t=Lr(n,e);if(ye(`${t}.ts`))return t+".ts";if(ye(`${t}/index.ts`))return`${t}/index.ts`;if(ye(t))return t}}function Fr(e){if(e.kind!==Mt.Decorator)return!1;let n=ne(e.expression)?e.expression.expression:e.expression;return B(n)&&n.text==="WebComponent"}function wr(e){if(!vr(e))return{decorator:!1};let n=e.expression;if(!ne(n))return{decorator:!1};let t=n.expression;return B(t)&&t.text==="Property"?{decorator:!0}:Sr(t)&&B(t.expression)&&t.expression.text==="Property"&&t.name.text==="required"?{decorator:!0,required:!0}:{decorator:!1}}function $r(e){if(e.kind!==Mt.Decorator)return!1;let n=ne(e.expression)?e.expression.expression:e.expression;return B(n)&&n.text==="Event"}function Pr(e){try{let n=e.expression;if(!ne(n))return[];let t=n.arguments;if(t.length===0)return[];let r=t[0];if(!r||!$t(r))return[];let o=Array.from(r.properties).find(i=>Pt(i)&&B(i.name)&&i.name.text==="selector");return Mr(o.initializer)}catch{return[]}}function Mr(e){return ve(e)?[e.text]:Ir(e)?e.elements?.filter(n=>ve(n)).map(n=>n.text):[]}function Dr(e,n,t,r){let o=t.expression,i={name:n,required:r,type:Se(t.parent)?Bt(t.parent.type):"any",span:{start:e.getStart(),end:e.getEnd()}};if(ne(o)){let s=o.arguments,c=(s.length?s.find(p=>$t(p)):void 0)?.properties?.find(p=>Pt(p)&&B(p.name)&&p.name.text==="alias");if(c&&ve(c.initializer)){let p=c.initializer;i.alias=p.text,i.span={start:p.getStart(),end:p.getEnd()}}}return i}function Br(e){let n={type:"void"};return Se(e.parent)&&(n.type=Bt(e.parent.type,!0)),n}function Bt(e,n=!1){let t=n?"void":"any";if(!e||!_r(e))return t;let r=e.typeArguments;return!r||r.length===0?t:r[0].getText()}var fe=class{constructor(n,t){this._input=n;this._ast=t}_input;_ast;_context=new Y;_states={3:Ie,4:Ie,0:St,5:bt,8:_t,9:Ft,11:Rt};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 Dt(r.path,s,n);a&&this._context.addImport(a)})))}async generate(n){try{await this.populateImportMetadata(n);let t=this._ast.flatMap(o=>this._processNode(o,this._context)),r=[h("function typeCheck() {"),...y(t),h("}")];return{text:r.map(o=>o.text).join(`
|
|
21
21
|
`),mappingTable:this.buildMappingTable(r)}}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 o?`${new M(this._input).getPositionFromCharacterIndex(o.start+1)} - ${r}
|
|
22
|
-
---> ${Gr(this._input,o.start,o.end)}}`:r}}buildMappingTable(n){let t=new Map;return n.forEach((r,o)=>{r.mappings&&t.set(o,r.mappings)}),t}_processNode=(n,t)=>{let r=this._states[n.type];if(!r)throw new Error(`No transition function for
|
|
22
|
+
---> ${Gr(this._input,o.start,o.end)}}`:r}}buildMappingTable(n){let t=new Map;return n.forEach((r,o)=>{r.mappings&&t.set(o,r.mappings)}),t}_processNode=(n,t)=>{let r=this._states[n.type];if(!r)throw new Error(`No transition function for ASTNode of type ${C[n.type]}`,{cause:n.span});return r(n,this._processNode,t)}};async function Va(e,n,t){let r=new ce(e).tokenize(),o=new me(e,r).parse();return{javascript:new oe(e,o).generate(t),typescript:await new fe(e,o).generate(n)}}function Wa(e,n){let t=e.get(n.line);if(t){let r=t.find(o=>n.character>=o.columnStart&&n.character<o.columnEnd);return r?r.original:t.reduce((o,i)=>{let s=Math.min(Math.abs(n.character-i.columnStart),Math.abs(n.character-i.columnEnd)),a=Math.min(Math.abs(n.character-o.columnStart),Math.abs(n.character-o.columnEnd));return s<a?i:o}).original}}export{M as Cursor,Va as compile,Wa as resolveTemplateSpan};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xaendar/compiler",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.16",
|
|
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.
|
|
17
|
-
"@xaendar/types": "0.9.
|
|
16
|
+
"@xaendar/common": "0.9.16",
|
|
17
|
+
"@xaendar/types": "0.9.16",
|
|
18
18
|
"typescript": "^6.0.3"
|
|
19
19
|
}
|
|
20
20
|
}
|