driftjs-compiler 0.0.13 → 0.0.15
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/index-cjs.js +3 -3
- package/dist/index-es.js +850 -680
- package/package.json +2 -2
package/dist/index-cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("driftjs-shared"),l=require("acorn");l=s(l,1);let u=require("acorn-walk");u=s(u,1);var d={TagOpen:`TagOpen`,TagOpenSlash:`TagOpenSlash`,TagClose:`TagClose`,TagSelfClose:`TagSelfClose`,Equals:`Equals`,Identifier:`Identifier`,StringLiteral:`StringLiteral`,Text:`Text`,Interpolation:`Interpolation`,Comment:`Comment`,DirectiveIf:`DirectiveIf`,DirectiveElseIf:`DirectiveElseIf`,DirectiveElse:`DirectiveElse`,DirectiveFor:`DirectiveFor`,DirectiveSwitch:`DirectiveSwitch`,DirectiveCase:`DirectiveCase`,DirectiveDefault:`DirectiveDefault`,BlockOpen:`BlockOpen`,BlockClose:`BlockClose`,EOF:`EOF`},f={Data:`Data`,TagOpen:`TagOpen`,EndTagOpen:`EndTagOpen`,BeforeAttributeName:`BeforeAttributeName`,AttributeName:`AttributeName`,AfterAttributeName:`AfterAttributeName`,BeforeAttributeValue:`BeforeAttributeValue`,AttributeValueQuoted:`AttributeValueQuoted`,AttributeValueInterpolation:`AttributeValueInterpolation`,Comment:`Comment`,Interpolation:`Interpolation`,RawText:`RawText`,EOF:`EOF`},p=function(e){return e[e.Start=0]=`Start`,e[e.Punctuator=1]=`Punctuator`,e[e.Keyword=2]=`Keyword`,e[e.IdentifierOrLiteral=3]=`IdentifierOrLiteral`,e[e.PostfixOp=4]=`PostfixOp`,e}({}),m={Program:`Program`,Element:`Element`,Text:`Text`,Interpolation:`Interpolation`,Attribute:`Attribute`,Comment:`Comment`,If:`If`,For:`For`,Switch:`Switch`},h=class extends Error{line;column;offset;constructor(e,t,n,r){super(`LexerError [${t}:${n}]: ${e}`),this.line=t,this.column=n,this.offset=r,this.name=`DriftLexerError`}},g=class extends Error{line;column;offset;constructor(e,t,n,r){super(`ParserError [${t}:${n}]: ${e}`),this.line=t,this.column=n,this.offset=r,this.name=`DriftParserError`}},_=function(e){return e[e.RETURN=0]=`RETURN`,e[e.CREATE_ELEMENT=1]=`CREATE_ELEMENT`,e[e.CREATE_TEXT=2]=`CREATE_TEXT`,e[e.CREATE_COMMENT=3]=`CREATE_COMMENT`,e[e.APPEND_CHILD=4]=`APPEND_CHILD`,e[e.SET_ATTR=5]=`SET_ATTR`,e[e.CREATE_FRAGMENT=6]=`CREATE_FRAGMENT`,e[e.INTERPOLATE_TEXT=7]=`INTERPOLATE_TEXT`,e[e.EXEC_SCRIPT=12]=`EXEC_SCRIPT`,e[e.REACTIVE_IF=13]=`REACTIVE_IF`,e[e.REACTIVE_FOR=14]=`REACTIVE_FOR`,e[e.MOUNT_COMPONENT=15]=`MOUNT_COMPONENT`,e}({}),v={[f.Data]:[{to:f.Comment,when:`The next characters are <!--`,emits:`Comment`},{to:f.EndTagOpen,when:`The next characters are </`,emits:`TagOpenSlash`},{to:f.TagOpen,when:`The next character is '<' for a start tag`,emits:`TagOpen`},{to:f.Interpolation,when:`The next character is '{' in element content`,emits:`Interpolation`},{to:f.Data,when:`Plain content is consumed up to the next control delimiter`,emits:`Text`},{to:f.EOF,when:`The source has been fully consumed`,emits:`EOF`}],[f.TagOpen]:[{to:f.BeforeAttributeName,when:`A valid opening tag name is consumed`,emits:`Identifier`}],[f.EndTagOpen]:[{to:f.BeforeAttributeName,when:`A valid closing tag name is consumed`,emits:`Identifier`}],[f.BeforeAttributeName]:[{to:f.AttributeName,when:`An attribute name begins in an opening tag`,emits:`Identifier`},{to:f.Data,when:`A tag is closed with '>' and raw-text mode does not apply`,emits:`TagClose`},{to:f.RawText,when:`A script/style start tag is closed with '>'`,emits:`TagClose`},{to:f.Data,when:`A tag is self-closed with '/>'`,emits:`TagSelfClose`}],[f.AttributeName]:[{to:f.AfterAttributeName,when:`The attribute identifier has been fully consumed`,emits:`Identifier`}],[f.AfterAttributeName]:[{to:f.BeforeAttributeValue,when:`The next character is '='`,emits:`Equals`},{to:f.BeforeAttributeName,when:`The attribute is boolean and the lexer moves to the next attribute or tag boundary`,emits:`No token`}],[f.BeforeAttributeValue]:[{to:f.AttributeValueQuoted,when:`The attribute value starts with a quote`,emits:`StringLiteral`},{to:f.AttributeValueInterpolation,when:`The attribute value starts with '{'`,emits:`Interpolation`}],[f.AttributeValueQuoted]:[{to:f.BeforeAttributeName,when:`The closing quote is consumed`,emits:`StringLiteral`}],[f.AttributeValueInterpolation]:[{to:f.BeforeAttributeName,when:`The interpolation closes and the attribute value is complete`,emits:`Interpolation`}],[f.Comment]:[{to:f.Data,when:`The terminating --> delimiter is consumed`,emits:`Comment`}],[f.Interpolation]:[{to:f.Data,when:`A content interpolation closes with a matching brace`,emits:`Interpolation`},{to:f.BeforeAttributeName,when:`An attribute interpolation closes with a matching brace`,emits:`Interpolation`}],[f.RawText]:[{to:f.RawText,when:`Plain raw-text content is consumed before the matching closing tag`,emits:`Text`},{to:f.EndTagOpen,when:`The matching raw-text closing tag begins with </`,emits:`TagOpenSlash`},{to:f.EOF,when:`The raw-text block reaches end of input before a closing tag appears`,emits:`EOF`}],[f.EOF]:[{to:f.EOF,when:`Additional parser requests are made after end of input`,emits:`EOF`}]};function y(e){return e===`script`||e===`style`}var b=new Set([`if`,`else`,`for`,`switch`,`case`,`default`]),x=new Set([`return`,`yield`,`await`,`case`,`typeof`,`void`,`delete`,`instanceof`,`in`,`do`,`throw`,`new`]),S=class{source;offset=0;line=1;column=1;emittedTokenCount=0;eofToken=null;state={kind:f.Data};blockDepth=0;elementDepth=0;blockElementDepthStack=[];constructor(e){this.source=e}nextToken(){let e=this.readNextToken();return this.emittedTokenCount++,e}getCurrentState(){return this.state}getEmittedTokenCount(){return this.emittedTokenCount}readNextToken(){switch(this.state.kind){case f.Data:return this.readDataToken();case f.TagOpen:return this.readTagNameToken(!1);case f.EndTagOpen:return this.readTagNameToken(!0);case f.BeforeAttributeName:return this.readBeforeAttributeNameToken();case f.AttributeName:return this.readAttributeNameToken();case f.AfterAttributeName:return this.readAfterAttributeNameToken();case f.BeforeAttributeValue:return this.readBeforeAttributeValueToken();case f.Comment:case f.Interpolation:case f.AttributeValueQuoted:case f.AttributeValueInterpolation:throw Error(`Lexer entered transient state '${this.state.kind}' unexpectedly.`);case f.RawText:return this.readRawTextToken();case f.EOF:return this.getOrCreateEOFToken()}}readDataToken(){let e=this.getLocation();if(this.isAtEnd())return this.transitionTo({kind:f.EOF}),this.getOrCreateEOFToken(e);if(this.startsWith(`<!--`))return this.consumePattern(`<!--`),this.transitionTo({kind:f.Comment}),this.readCommentToken(e);if(this.startsWith(`</`))return this.consumePattern(`</`),this.transitionTo({kind:f.EndTagOpen}),this.createToken(d.TagOpenSlash,`</`,e);if(this.peek()===`<`)return this.advance(),this.transitionTo({kind:f.TagOpen}),this.createToken(d.TagOpen,`<`,e);if(this.peek()===`{`)return this.advance(),this.transitionTo({kind:f.Interpolation,context:`content`,tagName:null}),this.readInterpolationToken(e,`content`,null);let t=this.blockDepth>0&&this.blockElementDepthStack.length>0&&this.elementDepth===this.blockElementDepthStack[this.blockElementDepthStack.length-1];return this.peek()===`}`&&t?(this.advance(),this.blockDepth--,this.blockElementDepthStack.pop(),this.createToken(d.BlockClose,`}`,e)):this.peek()===`@`?this.readDirectiveToken(e):this.readTextToken()}readDirectiveToken(e){this.advance();let t=``;for(;!this.isAtEnd()&&/[a-zA-Z]/.test(this.peek());)t+=this.advance();if(!b.has(t))throw new h(`Unknown directive '@${t}'`,e.line,e.column,e.offset);if(t===`if`)return this.readDirectiveHeader(e,d.DirectiveIf);if(t===`else`){if(this.skipWhitespace(),this.startsWith(`if`)&&!/[a-zA-Z0-9_]/.test(this.peek(2)))return this.consumePattern(`if`),this.readDirectiveHeader(e,d.DirectiveElseIf);if(this.skipWhitespace(),this.peek()===`{`)return this.advance(),this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth),this.createToken(d.DirectiveElse,``,e);throw new h(`Expected '{' after @else directive`,e.line,e.column,e.offset)}else if(t===`for`)return this.readDirectiveHeader(e,d.DirectiveFor);else if(t===`switch`)return this.readDirectiveHeader(e,d.DirectiveSwitch);else if(t===`case`)return this.readDirectiveHeader(e,d.DirectiveCase);else return this.skipWhitespace(),this.peek()===`{`&&(this.advance(),this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth)),this.createToken(d.DirectiveDefault,``,e)}readDirectiveHeader(e,t){this.skipWhitespace();let n=``,r=0,i=0,a=0,o=[],s=null,c=!1,l=!1,u=!1,d=!1,f=!1,m=p.Start;for(;!this.isAtEnd();){let h=this.advance();if(l){n+=h,h===`
|
|
2
|
-
`&&(l=!1);continue}if(u){n+=h,h===`/`&&n.endsWith(`*/`)&&(u=!1);continue}if(d){n+=h,c?c=!1:h===`\\`?c=!0:h===`[`?f=!0:h===`]`&&f?f=!1:h===`/`&&!f&&(d=!1,m=p.IdentifierOrLiteral);continue}if(s!==null){if(n+=h,c)c=!1;else if(h===`\\`)c=!0;else if(h===s)s=null,m=p.IdentifierOrLiteral;else if(s==="`"&&h===`{`&&n.endsWith("${")){let e=0;for(let t=n.length-3;t>=0&&n[t]===`\\`;t--)e++;e%2==0&&(o.push(a),s=null,a++,m=p.Start)}continue}if(h===`/`&&!c){let e=this.peek();if(e===`/`){l=!0,n+=h;continue}else if(e===`*`){u=!0,n+=h;continue}else if(this.isRegexStart(m)){d=!0,f=!1,n+=h;continue}else m=p.Punctuator}if(h===`"`||h===`'`||h==="`"){s=h,n+=h;continue}if(h===`(`){r++,m=p.Start,n+=h;continue}if(h===`)`){r>0&&r--,m=p.IdentifierOrLiteral,n+=h;continue}if(h===`[`){i++,m=p.Start,n+=h;continue}if(h===`]`){i>0&&i--,m=p.IdentifierOrLiteral,n+=h;continue}if(h===`{`){if(r===0&&i===0&&a===0&&o.length===0)return this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth),this.createToken(t,n.trim(),e);a++,m=p.Start,n+=h;continue}if(h===`}`){a--,o.length>0&&a===o[o.length-1]&&(o.pop(),s="`"),m=p.IdentifierOrLiteral,n+=h;continue}if(h===`+`||h===`-`){if(this.peek()===h){let e=this.advance();n+=h+e,m=m===p.IdentifierOrLiteral?p.PostfixOp:p.Start;continue}m=p.Punctuator,n+=h;continue}if(`=(,:;!&|?*%<>~^`.includes(h)){m=p.Punctuator,n+=h;continue}if(/[a-zA-Z0-9_$]/.test(h)){let e=h;for(;!this.isAtEnd()&&/[a-zA-Z0-9_$]/.test(this.peek());)e+=this.advance();m=x.has(e)?p.Keyword:p.IdentifierOrLiteral,n+=e;continue}n+=h}throw new h(`Unterminated directive header, expected '{'`,e.line,e.column,e.offset)}readTagNameToken(e){if(this.isAtEnd())throw this.createUnexpectedEOFError(e?`after closing tag opener`:`after opening tag opener`);let t=this.getLocation(),n=this.peek();if(!this.isIdentifierStart(n))throw new h(`Expected tag name but found '${n||`EOF`}'`,t.line,t.column,t.offset);let r=this.readIdentifierValue(),i=!e&&y(r);return this.transitionTo({kind:f.BeforeAttributeName,tagName:r,isClosingTag:e,entersRawText:i}),this.createToken(d.Identifier,r,t)}readBeforeAttributeNameToken(){let e=this.state;if(e.kind!==f.BeforeAttributeName)throw Error(`Expected BeforeAttributeName state but found '${e.kind}'.`);if(this.skipWhitespace(),this.isAtEnd())throw this.createUnexpectedEOFError(`inside tag <${e.tagName}>`);let t=this.getLocation();if(e.isClosingTag){if(this.peek()!==`>`)throw new h(`Unexpected character '${this.peek()}' inside closing tag </${e.tagName}>`,t.line,t.column,t.offset);return this.advance(),this.elementDepth>0&&this.elementDepth--,this.transitionTo({kind:f.Data}),this.createToken(d.TagClose,`>`,t)}if(this.peek()===`/`){let e=1;for(;this.peek(e)===` `||this.peek(e)===` `||this.peek(e)===`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("driftjs-shared"),l=require("acorn");l=s(l,1);let u=require("acorn-walk");u=s(u,1);var d={TagOpen:`TagOpen`,TagOpenSlash:`TagOpenSlash`,TagClose:`TagClose`,TagSelfClose:`TagSelfClose`,Equals:`Equals`,Identifier:`Identifier`,StringLiteral:`StringLiteral`,Text:`Text`,Interpolation:`Interpolation`,Comment:`Comment`,DirectiveIf:`DirectiveIf`,DirectiveElseIf:`DirectiveElseIf`,DirectiveElse:`DirectiveElse`,DirectiveFor:`DirectiveFor`,DirectiveSwitch:`DirectiveSwitch`,DirectiveCase:`DirectiveCase`,DirectiveDefault:`DirectiveDefault`,DirectiveAsync:`DirectiveAsync`,DirectiveFallback:`DirectiveFallback`,DirectiveCatch:`DirectiveCatch`,BlockOpen:`BlockOpen`,BlockClose:`BlockClose`,EOF:`EOF`},f={Data:`Data`,TagOpen:`TagOpen`,EndTagOpen:`EndTagOpen`,BeforeAttributeName:`BeforeAttributeName`,AttributeName:`AttributeName`,AfterAttributeName:`AfterAttributeName`,BeforeAttributeValue:`BeforeAttributeValue`,AttributeValueQuoted:`AttributeValueQuoted`,AttributeValueInterpolation:`AttributeValueInterpolation`,Comment:`Comment`,Interpolation:`Interpolation`,RawText:`RawText`,EOF:`EOF`},p=function(e){return e[e.Start=0]=`Start`,e[e.Punctuator=1]=`Punctuator`,e[e.Keyword=2]=`Keyword`,e[e.IdentifierOrLiteral=3]=`IdentifierOrLiteral`,e[e.PostfixOp=4]=`PostfixOp`,e}({}),m={Program:`Program`,Element:`Element`,Text:`Text`,Interpolation:`Interpolation`,Attribute:`Attribute`,Comment:`Comment`,If:`If`,For:`For`,Switch:`Switch`,Async:`Async`},h=class extends Error{line;column;offset;constructor(e,t,n,r){super(`LexerError [${t}:${n}]: ${e}`),this.line=t,this.column=n,this.offset=r,this.name=`DriftLexerError`}},g=class extends Error{line;column;offset;constructor(e,t,n,r){super(`ParserError [${t}:${n}]: ${e}`),this.line=t,this.column=n,this.offset=r,this.name=`DriftParserError`}},_=function(e){return e[e.RETURN=0]=`RETURN`,e[e.CREATE_ELEMENT=1]=`CREATE_ELEMENT`,e[e.CREATE_TEXT=2]=`CREATE_TEXT`,e[e.CREATE_COMMENT=3]=`CREATE_COMMENT`,e[e.APPEND_CHILD=4]=`APPEND_CHILD`,e[e.SET_ATTR=5]=`SET_ATTR`,e[e.CREATE_FRAGMENT=6]=`CREATE_FRAGMENT`,e[e.INTERPOLATE_TEXT=7]=`INTERPOLATE_TEXT`,e[e.EXEC_SCRIPT=12]=`EXEC_SCRIPT`,e[e.REACTIVE_IF=13]=`REACTIVE_IF`,e[e.REACTIVE_FOR=14]=`REACTIVE_FOR`,e[e.MOUNT_COMPONENT=15]=`MOUNT_COMPONENT`,e[e.REACTIVE_ASYNC=16]=`REACTIVE_ASYNC`,e[e.REACTIVE_SWITCH=17]=`REACTIVE_SWITCH`,e}({}),v={[f.Data]:[{to:f.Comment,when:`The next characters are <!--`,emits:`Comment`},{to:f.EndTagOpen,when:`The next characters are </`,emits:`TagOpenSlash`},{to:f.TagOpen,when:`The next character is '<' for a start tag`,emits:`TagOpen`},{to:f.Interpolation,when:`The next character is '{' in element content`,emits:`Interpolation`},{to:f.Data,when:`Plain content is consumed up to the next control delimiter`,emits:`Text`},{to:f.EOF,when:`The source has been fully consumed`,emits:`EOF`}],[f.TagOpen]:[{to:f.BeforeAttributeName,when:`A valid opening tag name is consumed`,emits:`Identifier`}],[f.EndTagOpen]:[{to:f.BeforeAttributeName,when:`A valid closing tag name is consumed`,emits:`Identifier`}],[f.BeforeAttributeName]:[{to:f.AttributeName,when:`An attribute name begins in an opening tag`,emits:`Identifier`},{to:f.Data,when:`A tag is closed with '>' and raw-text mode does not apply`,emits:`TagClose`},{to:f.RawText,when:`A script/style start tag is closed with '>'`,emits:`TagClose`},{to:f.Data,when:`A tag is self-closed with '/>'`,emits:`TagSelfClose`}],[f.AttributeName]:[{to:f.AfterAttributeName,when:`The attribute identifier has been fully consumed`,emits:`Identifier`}],[f.AfterAttributeName]:[{to:f.BeforeAttributeValue,when:`The next character is '='`,emits:`Equals`},{to:f.BeforeAttributeName,when:`The attribute is boolean and the lexer moves to the next attribute or tag boundary`,emits:`No token`}],[f.BeforeAttributeValue]:[{to:f.AttributeValueQuoted,when:`The attribute value starts with a quote`,emits:`StringLiteral`},{to:f.AttributeValueInterpolation,when:`The attribute value starts with '{'`,emits:`Interpolation`}],[f.AttributeValueQuoted]:[{to:f.BeforeAttributeName,when:`The closing quote is consumed`,emits:`StringLiteral`}],[f.AttributeValueInterpolation]:[{to:f.BeforeAttributeName,when:`The interpolation closes and the attribute value is complete`,emits:`Interpolation`}],[f.Comment]:[{to:f.Data,when:`The terminating --> delimiter is consumed`,emits:`Comment`}],[f.Interpolation]:[{to:f.Data,when:`A content interpolation closes with a matching brace`,emits:`Interpolation`},{to:f.BeforeAttributeName,when:`An attribute interpolation closes with a matching brace`,emits:`Interpolation`}],[f.RawText]:[{to:f.RawText,when:`Plain raw-text content is consumed before the matching closing tag`,emits:`Text`},{to:f.EndTagOpen,when:`The matching raw-text closing tag begins with </`,emits:`TagOpenSlash`},{to:f.EOF,when:`The raw-text block reaches end of input before a closing tag appears`,emits:`EOF`}],[f.EOF]:[{to:f.EOF,when:`Additional parser requests are made after end of input`,emits:`EOF`}]};function y(e){return e===`script`||e===`style`}var b=new Set([`if`,`else`,`for`,`switch`,`case`,`default`,`async`,`fallback`,`catch`]),x=new Set([`return`,`yield`,`await`,`case`,`typeof`,`void`,`delete`,`instanceof`,`in`,`do`,`throw`,`new`]),S=class{source;offset=0;line=1;column=1;emittedTokenCount=0;eofToken=null;state={kind:f.Data};blockDepth=0;elementDepth=0;blockElementDepthStack=[];constructor(e){this.source=e}nextToken(){let e=this.readNextToken();return this.emittedTokenCount++,e}getCurrentState(){return this.state}getEmittedTokenCount(){return this.emittedTokenCount}readNextToken(){switch(this.state.kind){case f.Data:return this.readDataToken();case f.TagOpen:return this.readTagNameToken(!1);case f.EndTagOpen:return this.readTagNameToken(!0);case f.BeforeAttributeName:return this.readBeforeAttributeNameToken();case f.AttributeName:return this.readAttributeNameToken();case f.AfterAttributeName:return this.readAfterAttributeNameToken();case f.BeforeAttributeValue:return this.readBeforeAttributeValueToken();case f.Comment:case f.Interpolation:case f.AttributeValueQuoted:case f.AttributeValueInterpolation:throw Error(`Lexer entered transient state '${this.state.kind}' unexpectedly.`);case f.RawText:return this.readRawTextToken();case f.EOF:return this.getOrCreateEOFToken()}}readDataToken(){let e=this.getLocation();if(this.isAtEnd())return this.transitionTo({kind:f.EOF}),this.getOrCreateEOFToken(e);if(this.startsWith(`<!--`))return this.consumePattern(`<!--`),this.transitionTo({kind:f.Comment}),this.readCommentToken(e);if(this.startsWith(`</`))return this.consumePattern(`</`),this.transitionTo({kind:f.EndTagOpen}),this.createToken(d.TagOpenSlash,`</`,e);if(this.peek()===`<`)return this.advance(),this.transitionTo({kind:f.TagOpen}),this.createToken(d.TagOpen,`<`,e);if(this.peek()===`{`)return this.advance(),this.transitionTo({kind:f.Interpolation,context:`content`,tagName:null}),this.readInterpolationToken(e,`content`,null);let t=this.blockDepth>0&&this.blockElementDepthStack.length>0&&this.elementDepth===this.blockElementDepthStack[this.blockElementDepthStack.length-1];return this.peek()===`}`&&t?(this.advance(),this.blockDepth--,this.blockElementDepthStack.pop(),this.createToken(d.BlockClose,`}`,e)):this.peek()===`@`?this.readDirectiveToken(e):this.readTextToken()}readDirectiveToken(e){this.advance();let t=``;for(;!this.isAtEnd()&&/[a-zA-Z]/.test(this.peek());)t+=this.advance();if(!b.has(t))throw new h(`Unknown directive '@${t}'`,e.line,e.column,e.offset);if(t===`if`)return this.readDirectiveHeader(e,d.DirectiveIf);if(t===`else`){if(this.skipWhitespace(),this.startsWith(`if`)&&!/[a-zA-Z0-9_]/.test(this.peek(2)))return this.consumePattern(`if`),this.readDirectiveHeader(e,d.DirectiveElseIf);if(this.skipWhitespace(),this.peek()===`{`)return this.advance(),this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth),this.createToken(d.DirectiveElse,``,e);throw new h(`Expected '{' after @else directive`,e.line,e.column,e.offset)}else if(t===`for`)return this.readDirectiveHeader(e,d.DirectiveFor);else if(t===`switch`)return this.readDirectiveHeader(e,d.DirectiveSwitch);else if(t===`case`)return this.readDirectiveHeader(e,d.DirectiveCase);else if(t===`async`)return this.readDirectiveHeader(e,d.DirectiveAsync);else if(t===`catch`)return this.readDirectiveHeader(e,d.DirectiveCatch);else if(t===`fallback`){if(this.skipWhitespace(),this.peek()===`{`)return this.advance(),this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth),this.createToken(d.DirectiveFallback,``,e);throw new h(`Expected '{' after @fallback directive`,e.line,e.column,e.offset)}else return this.skipWhitespace(),this.peek()===`{`&&(this.advance(),this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth)),this.createToken(d.DirectiveDefault,``,e)}readDirectiveHeader(e,t){this.skipWhitespace();let n=``,r=0,i=0,a=0,o=[],s=null,c=!1,l=!1,u=!1,d=!1,f=!1,m=p.Start;for(;!this.isAtEnd();){let h=this.advance();if(l){n+=h,h===`
|
|
2
|
+
`&&(l=!1);continue}if(u){n+=h,h===`/`&&n.endsWith(`*/`)&&(u=!1);continue}if(d){n+=h,c?c=!1:h===`\\`?c=!0:h===`[`?f=!0:h===`]`&&f?f=!1:h===`/`&&!f&&(d=!1,m=p.IdentifierOrLiteral);continue}if(s!==null){if(n+=h,c)c=!1;else if(h===`\\`)c=!0;else if(h===s)s=null,m=p.IdentifierOrLiteral;else if(s==="`"&&h===`{`&&n.endsWith("${")){let e=0;for(let t=n.length-3;t>=0&&n[t]===`\\`;t--)e++;e%2==0&&(o.push(a),s=null,a++,m=p.Start)}continue}if(h===`/`&&!c){let e=this.peek();if(e===`/`){l=!0,n+=h;continue}else if(e===`*`){u=!0,n+=h;continue}else if(this.isRegexStart(m)){d=!0,f=!1,n+=h;continue}else m=p.Punctuator}if(h===`"`||h===`'`||h==="`"){s=h,n+=h;continue}if(h===`(`){r++,m=p.Start,n+=h;continue}if(h===`)`){r>0&&r--,m=p.IdentifierOrLiteral,n+=h;continue}if(h===`[`){i++,m=p.Start,n+=h;continue}if(h===`]`){i>0&&i--,m=p.IdentifierOrLiteral,n+=h;continue}if(h===`{`){if(!/\b(as|catch)\s*$/.test(n)&&r===0&&i===0&&a===0&&o.length===0)return this.blockDepth++,this.blockElementDepthStack.push(this.elementDepth),this.createToken(t,n.trim(),e);a++,m=p.Start,n+=h;continue}if(h===`}`){a--,o.length>0&&a===o[o.length-1]&&(o.pop(),s="`"),m=p.IdentifierOrLiteral,n+=h;continue}if(h===`+`||h===`-`){if(this.peek()===h){let e=this.advance();n+=h+e,m=m===p.IdentifierOrLiteral?p.PostfixOp:p.Start;continue}m=p.Punctuator,n+=h;continue}if(`=(,:;!&|?*%<>~^`.includes(h)){m=p.Punctuator,n+=h;continue}if(/[a-zA-Z0-9_$]/.test(h)){let e=h;for(;!this.isAtEnd()&&/[a-zA-Z0-9_$]/.test(this.peek());)e+=this.advance();m=x.has(e)?p.Keyword:p.IdentifierOrLiteral,n+=e;continue}n+=h}throw new h(`Unterminated directive header, expected '{'`,e.line,e.column,e.offset)}readTagNameToken(e){if(this.isAtEnd())throw this.createUnexpectedEOFError(e?`after closing tag opener`:`after opening tag opener`);let t=this.getLocation(),n=this.peek();if(!this.isIdentifierStart(n))throw new h(`Expected tag name but found '${n||`EOF`}'`,t.line,t.column,t.offset);let r=this.readIdentifierValue(),i=!e&&y(r);return this.transitionTo({kind:f.BeforeAttributeName,tagName:r,isClosingTag:e,entersRawText:i}),this.createToken(d.Identifier,r,t)}readBeforeAttributeNameToken(){let e=this.state;if(e.kind!==f.BeforeAttributeName)throw Error(`Expected BeforeAttributeName state but found '${e.kind}'.`);if(this.skipWhitespace(),this.isAtEnd())throw this.createUnexpectedEOFError(`inside tag <${e.tagName}>`);let t=this.getLocation();if(e.isClosingTag){if(this.peek()!==`>`)throw new h(`Unexpected character '${this.peek()}' inside closing tag </${e.tagName}>`,t.line,t.column,t.offset);return this.advance(),this.elementDepth>0&&this.elementDepth--,this.transitionTo({kind:f.Data}),this.createToken(d.TagClose,`>`,t)}if(this.peek()===`/`){let e=1;for(;this.peek(e)===` `||this.peek(e)===` `||this.peek(e)===`
|
|
3
3
|
`||this.peek(e)===`\r`;)e++;if(this.peek(e)===`>`){for(let t=0;t<=e;t++)this.advance();return this.transitionTo({kind:f.Data}),this.createToken(d.TagSelfClose,`/>`,t)}}if(this.peek()===`>`)return this.advance(),c.VOID_ELEMENTS.has(e.tagName.toLowerCase())||this.elementDepth++,e.entersRawText&&y(e.tagName)?this.transitionTo({kind:f.RawText,tagName:e.tagName}):this.transitionTo({kind:f.Data}),this.createToken(d.TagClose,`>`,t);if(!this.isIdentifierStart(this.peek()))throw new h(`Unexpected character '${this.peek()}' inside tag <${e.tagName}>`,t.line,t.column,t.offset);return this.transitionTo({kind:f.AttributeName,tagName:e.tagName,attributeName:null}),this.readAttributeNameToken()}readAttributeNameToken(){let e=this.state;if(e.kind!==f.AttributeName)throw Error(`Expected AttributeName state but found '${e.kind}'.`);let t=this.getLocation();if(!this.isIdentifierStart(this.peek()))throw new h(`Expected attribute name but found '${this.peek()||`EOF`}'`,t.line,t.column,t.offset);let n=this.readIdentifierValue(),r=e.tagName;return this.transitionTo({kind:f.AfterAttributeName,tagName:r,attributeName:n}),this.createToken(d.Identifier,n,t)}readAfterAttributeNameToken(){let e=this.state;if(e.kind!==f.AfterAttributeName)throw Error(`Expected AfterAttributeName state but found '${e.kind}'.`);let t=e.tagName,n=e.attributeName;if(this.skipWhitespace(),this.isAtEnd())throw this.createUnexpectedEOFError(`after attribute '${n}' in <${t}>`);if(this.peek()===`=`){let e=this.getLocation();return this.advance(),this.transitionTo({kind:f.BeforeAttributeValue,tagName:t,attributeName:n}),this.createToken(d.Equals,`=`,e)}return this.transitionTo({kind:f.BeforeAttributeName,tagName:t,isClosingTag:!1,entersRawText:y(t)}),this.readBeforeAttributeNameToken()}readBeforeAttributeValueToken(){let e=this.state;if(e.kind!==f.BeforeAttributeValue)throw Error(`Expected BeforeAttributeValue state but found '${e.kind}'.`);let t=e.tagName,n=e.attributeName;if(this.skipWhitespace(),this.isAtEnd())throw this.createUnexpectedEOFError(`before value for attribute '${n}' in <${t}>`);let r=this.getLocation(),i=this.peek();if(i===`"`||i===`'`)return this.advance(),this.transitionTo({kind:f.AttributeValueQuoted,tagName:t,attributeName:n,quote:i}),this.readQuotedStringToken(r,i,t);if(i===`{`)return this.advance(),this.transitionTo({kind:f.AttributeValueInterpolation,tagName:t,attributeName:n}),this.readInterpolationToken(r,`attribute`,t);throw new h(`Expected quoted string or interpolation for attribute '${n}' in <${t}>`,r.line,r.column,r.offset)}readCommentToken(e){let t=``;for(;!this.isAtEnd();){if(this.startsWith(`-->`))return this.consumePattern(`-->`),this.transitionTo({kind:f.Data}),this.createToken(d.Comment,t,e);t+=this.advance()}throw new h(`Unterminated XML comment`,e.line,e.column,e.offset)}isRegexStart(e){return e===p.Start||e===p.Punctuator||e===p.Keyword}readInterpolationToken(e,t,n){let r=1,i=null,a=!1,o=!1,s=!1,c=!1,l=!1,u=p.Start,m=[],g=``;for(;!this.isAtEnd();){let h=this.advance();if(o){g+=h,h===`
|
|
4
4
|
`&&(o=!1);continue}if(s){g+=h,h===`/`&&g.endsWith(`*/`)&&(s=!1);continue}if(c){g+=h,a?a=!1:h===`\\`?a=!0:h===`[`?l=!0:h===`]`&&l?l=!1:h===`/`&&!l&&(c=!1,u=p.IdentifierOrLiteral);continue}if(i!==null){if(g+=h,a)a=!1;else if(h===`\\`)a=!0;else if(h===i)i=null,u=p.IdentifierOrLiteral;else if(i==="`"&&h===`{`&&g.endsWith("${")){let e=0;for(let t=g.length-3;t>=0&&g[t]===`\\`;t--)e++;e%2==0&&(m.push(r),i=null,r++,u=p.Start)}continue}if(h===`/`&&!a){let e=this.peek();if(e===`/`){o=!0,g+=h;continue}else if(e===`*`){s=!0,g+=h;continue}else if(this.isRegexStart(u)){c=!0,l=!1,g+=h;continue}else u=p.Punctuator}if(h===`"`||h===`'`||h==="`"){inQuote:i=h;g+=h;continue}if(h===`(`){u=p.Start,g+=h;continue}if(h===`)`){u=p.IdentifierOrLiteral,g+=h;continue}if(h===`[`){u=p.Start,g+=h;continue}if(h===`]`){u=p.IdentifierOrLiteral,g+=h;continue}if(h===`{`){r++,u=p.Start,g+=h;continue}if(h===`}`){if(r--,m.length>0&&r===m[m.length-1]&&(m.pop(),i="`"),u=p.IdentifierOrLiteral,r===0)return t===`attribute`&&n!==null?this.transitionTo({kind:f.BeforeAttributeName,tagName:n,isClosingTag:!1,entersRawText:y(n)}):this.transitionTo({kind:f.Data}),this.createToken(d.Interpolation,g,e);g+=h;continue}if(h===`+`||h===`-`){if(this.peek()===h){let e=this.advance();g+=h+e,u=u===p.IdentifierOrLiteral?p.PostfixOp:p.Start;continue}u=p.Punctuator,g+=h;continue}if(`=(,:;!&|?*%<>~^`.includes(h)){u=p.Punctuator,g+=h;continue}if(/[a-zA-Z0-9_$]/.test(h)){let e=h;for(;!this.isAtEnd()&&/[a-zA-Z0-9_$]/.test(this.peek());)e+=this.advance();u=x.has(e)?p.Keyword:p.IdentifierOrLiteral,g+=e;continue}g+=h}throw new h(`Unterminated interpolation expression, expected closing brace '}'`,e.line,e.column,e.offset)}readRawTextToken(){let e=this.state;if(e.kind!==f.RawText)throw Error(`Expected RawText state but found '${e.kind}'.`);let t=this.getLocation(),n=`</${e.tagName}`;if(this.isAtEnd())return this.transitionTo({kind:f.EOF}),this.getOrCreateEOFToken(t);if(this.isRawTextClosingTagAhead(n))return this.consumePattern(`</`),this.transitionTo({kind:f.EndTagOpen}),this.createToken(d.TagOpenSlash,`</`,t);let r=``;for(;!this.isAtEnd()&&!this.isRawTextClosingTagAhead(n);)r+=this.advance();return r.length>0?this.createToken(d.Text,r,t):(this.transitionTo({kind:f.EOF}),this.getOrCreateEOFToken(t))}readTextToken(){let e=this.getLocation(),t=``,n=()=>this.blockDepth>0&&this.blockElementDepthStack.length>0&&this.elementDepth===this.blockElementDepthStack[this.blockElementDepthStack.length-1];for(;!this.isAtEnd();){let e=this.peek();if(e===`<`||e===`{`||e===`@`||e===`}`&&n())break;t+=this.advance()}return this.createToken(d.Text,t,e)}readQuotedStringToken(e,t,n){let r=``,i=!1;for(;!this.isAtEnd();){let a=this.peek();if(i){i=!1,r+=this.advance();continue}if(a===`\\`){i=!0,this.advance();continue}if(a===t)return this.advance(),this.transitionTo({kind:f.BeforeAttributeName,tagName:n,isClosingTag:!1,entersRawText:y(n)}),this.createToken(d.StringLiteral,r,e);r+=this.advance()}throw new h(`Unterminated string literal, expected closing quote ${t}`,e.line,e.column,e.offset)}readIdentifierValue(){let e=``;for(;!this.isAtEnd()&&this.isIdentifierChar(this.peek());)e+=this.advance();return e}getOrCreateEOFToken(e=this.getLocation()){return this.eofToken===null&&(this.eofToken={type:d.EOF,value:``,loc:{start:e,end:e}}),this.eofToken}createToken(e,t,n){return{type:e,value:t,loc:{start:n,end:this.getLocation()}}}createUnexpectedEOFError(e){let t=this.getLocation();return new h(`Unexpected end of input ${e}`,t.line,t.column,t.offset)}transitionTo(e){if(!v[this.state.kind].some(t=>t.to===e.kind))throw Error(`Invalid lexer transition from '${this.state.kind}' to '${e.kind}'.`);this.state=e}getLocation(){return{line:this.line,column:this.column,offset:this.offset}}isAtEnd(){return this.offset>=this.source.length}peek(e=0){let t=this.offset+e;return t>=this.source.length?``:this.source[t]??``}advance(){let e=this.source[this.offset]??``;return this.offset++,e===`
|
|
5
5
|
`?(this.line++,this.column=1):this.column++,e}startsWith(e){return this.source.startsWith(e,this.offset)}consumePattern(e){for(let t=0;t<e.length;t++)this.advance()}skipWhitespace(){for(;!this.isAtEnd();){let e=this.peek();if(e===` `||e===` `||e===`\r`||e===`
|
|
6
6
|
`)this.advance();else break}}isIdentifierStart(e){if(e.length===0)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122||t===95||t===36}isIdentifierChar(e){if(e.length===0)return!1;let t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122||t>=48&&t<=57||t===95||t===36||t===45}isRawTextClosingTagAhead(e){let t=e.length;if(this.source.slice(this.offset,this.offset+t).toLowerCase()!==e.toLowerCase())return!1;let n=this.peek(t);return n===``||n===`>`||n===` `||n===` `||n===`\r`||n===`
|
|
7
|
-
`}},C=class{tokens;current=0;constructor(e){this.tokens=e}nextToken(){if(this.current>=this.tokens.length)return this.tokens[this.tokens.length-1];let e=this.tokens[this.current];return this.current++,e}},w={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,laquo:`«`,raquo:`»`,ldquo:`“`,rdquo:`”`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,bdquo:`„`,bull:`•`,times:`×`,divide:`÷`,plusmn:`±`,euro:`€`,pound:`£`,yen:`¥`,cent:`¢`,deg:`°`,para:`¶`,sect:`§`,micro:`µ`,middot:`·`,frac14:`¼`,frac12:`½`,frac34:`¾`,sup1:`¹`,sup2:`²`,sup3:`³`,dagger:`†`,Dagger:`‡`,permil:`‰`,prime:`′`,Prime:`″`,infin:`∞`,radic:`√`,sim:`∼`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,sum:`∑`,prod:`∏`,minus:`−`,lowast:`∗`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,cong:`≅`,ang:`∠`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`};function T(e){return!e||!e.includes(`&`)?e:e.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z0-9]+));/g,(e,t,n,r)=>{if(t){let e=parseInt(t,10);try{return!isNaN(e)&&e>=0&&e<=1114111&&(e<55296||e>57343)?String.fromCodePoint?String.fromCodePoint(e):String.fromCharCode(e):`�`}catch{return`�`}}if(n){let e=parseInt(n,16);try{return!isNaN(e)&&e>=0&&e<=1114111&&(e<55296||e>57343)?String.fromCodePoint?String.fromCodePoint(e):String.fromCharCode(e):`�`}catch{return`�`}}return r&&w[r]||e})}var E=class{tokenSource;lookahead=[];constructor(e){this.tokenSource=Array.isArray(e)?new C(e):e}parse(){return this.lookahead.length=0,this.parseProgram()}parseProgram(){let e=this.peek().loc.start,t=[];for(;!this.isAtEnd();)t.push(this.parseChild());let n=this.peek().loc.end;return{type:m.Program,body:t,loc:{start:e,end:n}}}parseChild(){let e=this.peek();if(e.type===d.Comment)return this.advance(),{type:m.Comment,content:e.value,loc:e.loc};if(e.type===d.Interpolation)return this.advance(),{type:m.Interpolation,expression:e.value,loc:e.loc};if(e.type===d.TagOpen)return this.parseElement();if(e.type===d.DirectiveIf)return this.parseIfDirective();if(e.type===d.DirectiveFor)return this.parseForDirective();if(e.type===d.DirectiveSwitch)return this.parseSwitchDirective();if(e.type===d.Text)return this.advance(),{type:m.Text,content:T(e.value),loc:e.loc};throw e.type===d.TagOpenSlash?new g(`Unexpected closing tag '</${this.peek(1).value}>' without opening tag`,e.loc.start.line,e.loc.start.column,e.loc.start.offset):new g(`Unexpected token '${e.value}' of type '${e.type}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}parseElement(){let e=this.consume(d.TagOpen,`Expected opening tag bracket`).loc.start,t=this.consume(d.Identifier,`Expected tag name after opening bracket`).value,n=[];for(;!this.check(d.TagClose)&&!this.check(d.TagSelfClose)&&!this.isAtEnd();)n.push(this.parseAttribute());if(this.check(d.TagSelfClose)){let r=this.advance();return{type:m.Element,tagName:t,attributes:n,children:[],isSelfClosing:!0,loc:{start:e,end:r.loc.end}}}let r=this.consume(d.TagClose,`Expected closing bracket after attributes`);if(c.VOID_ELEMENTS.has(t.toLowerCase()))return{type:m.Element,tagName:t,attributes:n,children:[],isSelfClosing:!0,loc:{start:e,end:r.loc.end}};let i=t.toLowerCase()===`script`||t.toLowerCase()===`style`,a=[];for(;!this.check(d.TagOpenSlash)&&!this.isAtEnd();)if(i&&this.check(d.Text)){let e=this.advance();a.push({type:m.Text,content:e.value,loc:e.loc})}else a.push(this.parseChild());if(this.isAtEnd())throw new g(`Unclosed element '<${t}>', expected closing tag '</${t}>'`,e.line,e.column,e.offset);this.consume(d.TagOpenSlash,`Expected closing tag '</${t}>'`);let o=this.consume(d.Identifier,`Expected closing tag name`);if(o.value!==t&&o.value.toLowerCase()!==t.toLowerCase())throw new g(`Mismatched closing tag. Expected '</${t}>' but got '</${o.value}>'`,o.loc.start.line,o.loc.start.column,o.loc.start.offset);let s=this.consume(d.TagClose,`Expected '>' after closing tag name`);return{type:m.Element,tagName:t,attributes:n,children:a,isSelfClosing:!1,loc:{start:e,end:s.loc.end}}}parseAttribute(){let e=this.consume(d.Identifier,`Expected attribute name`),t=e.loc.start,n=e.value;if(this.matchToken(d.Equals)){let e=this.peek();if(e.type===d.StringLiteral)return this.advance(),{type:m.Attribute,name:n,value:T(e.value),loc:{start:t,end:e.loc.end}};if(e.type===d.Interpolation){this.advance();let r={type:m.Interpolation,expression:e.value,loc:e.loc};return{type:m.Attribute,name:n,value:r,loc:{start:t,end:e.loc.end}}}throw new g(`Expected string literal or interpolation after '=' for attribute '${n}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{type:m.Attribute,name:n,value:null,loc:{start:t,end:e.loc.end}}}parseIfDirective(){let e=this.consume(d.DirectiveIf,`Expected @if directive`),t=e.loc.start,n=e.value,r=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)r.push(this.parseChild());let i=this.consume(d.BlockClose,`Expected closing brace } for @if block`),a=null,o=i.loc.end;if(this.skipWhitespaceTokens(),this.check(d.DirectiveElseIf))a=this.parseElseIfChain(),o=a.loc.end;else if(this.check(d.DirectiveElse)){this.advance();let e=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)e.push(this.parseChild());let t=this.consume(d.BlockClose,`Expected closing brace } for @else block`);a=e,o=t.loc.end}return{type:m.If,test:n,consequent:r,alternate:a,loc:{start:t,end:o}}}parseElseIfChain(){let e=this.consume(d.DirectiveElseIf,`Expected @else if directive`),t=e.loc.start,n=e.value,r=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)r.push(this.parseChild());let i=this.consume(d.BlockClose,`Expected closing brace } for @else if block`),a=null,o=i.loc.end;if(this.skipWhitespaceTokens(),this.check(d.DirectiveElseIf))a=this.parseElseIfChain(),o=a.loc.end;else if(this.check(d.DirectiveElse)){this.advance();let e=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)e.push(this.parseChild());let t=this.consume(d.BlockClose,`Expected closing brace } for @else block`);a=e,o=t.loc.end}return{type:m.If,test:n,consequent:r,alternate:a,loc:{start:t,end:o}}}parseForDirective(){let e=this.consume(d.DirectiveFor,`Expected @for directive`),t=e.loc.start,n=e.value.trim();function r(e){return(0,c.scanBalancedDelimiters)(e,(t,n)=>{if(n===`i`&&e[t+1]===`n`){let n=t===0||!/[a-zA-Z0-9_$]/.test(e[t-1]),r=t+2>=e.length||!/[a-zA-Z0-9_$]/.test(e[t+2]);if(n&&r){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0||e[n]!==`.`)return!0}}})}function i(e){return(0,c.findTopLevelChar)(e,`,`)}function a(e){let t=-1;return(0,c.scanBalancedDelimiters)(e,n=>{if(e.slice(n,n+3)===`key`){let r=n===0||!/[a-zA-Z0-9_$]/.test(e[n-1]),i=n+3>=e.length||!/[a-zA-Z0-9_$]/.test(e[n+3]);if(r&&i){let r=n-1;for(;r>=0&&/\s/.test(e[r]);)r--;if((r<0||e[r]!==`.`&&e[r]!==`?`)&&e.slice(n+3).trim().length>0)return t=n,!0}}}),t===-1?null:{index:t,keyExpr:e.slice(t+3).trim()}}for(;(0,c.hasMatchingOuterParens)(n);)n=n.slice(1,-1).trim();let o=r(n);if(o===-1&&(0,c.hasMatchingOuterParens)(n)){let e=n.slice(1,-1).trim(),t=r(e);t!==-1&&(n=e,o=t)}if(o===-1)throw new g(`Invalid @for header syntax '${n}'. Expected format: 'item in list' or '(item, index) in list'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let s=n.slice(0,o).trim(),l=n.slice(o+2).trim(),u=null,f=a(l);f&&(u=f.keyExpr,l=l.slice(0,f.index).trim());let p=l,h=s,_=null;for(;(0,c.hasMatchingOuterParens)(h);)h=h.slice(1,-1).trim();let v=i(h);if(v!==-1){let e=h.slice(0,v).trim();for(_=h.slice(v+1).trim()||null,h=e;(0,c.hasMatchingOuterParens)(h);)h=h.slice(1,-1).trim()}if(!h||!p)throw new g(`Invalid @for header syntax '${e.value.trim()}'. Expected format: 'item in list' or '(item, index) in list'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let y=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)y.push(this.parseChild());let b=this.consume(d.BlockClose,`Expected closing brace } for @for block`);return{type:m.For,item:h,index:_,iterable:p,key:u,body:y,loc:{start:t,end:b.loc.end}}}parseSwitchDirective(){let e=this.consume(d.DirectiveSwitch,`Expected @switch directive`),t=e.loc.start,n=e.value,r=[];for(this.skipWhitespaceTokens();!this.check(d.BlockClose)&&!this.isAtEnd();){if(this.check(d.DirectiveCase)){let e=this.advance(),t=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)t.push(this.parseChild());let n=this.consume(d.BlockClose,`Expected closing brace } for @case block`);r.push({expression:e.value,body:t,loc:{start:e.loc.start,end:n.loc.end}})}else if(this.check(d.DirectiveDefault)){let e=this.advance(),t=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)t.push(this.parseChild());let n=this.consume(d.BlockClose,`Expected closing brace } for @default block`);r.push({expression:null,body:t,loc:{start:e.loc.start,end:n.loc.end}})}else throw new g(`Unexpected token '${this.peek().value}' inside @switch block. Expected @case or @default.`,this.peek().loc.start.line,this.peek().loc.start.column,this.peek().loc.start.offset);this.skipWhitespaceTokens()}let i=this.consume(d.BlockClose,`Expected closing brace } for @switch block`);return{type:m.Switch,discriminant:n,cases:r,loc:{start:t,end:i.loc.end}}}skipWhitespaceTokens(){for(;this.check(d.Text)&&this.peek().value.trim().length===0;)this.advance()}isAtEnd(){return this.peek().type===d.EOF}peek(e=0){return this.ensureLookahead(e),this.lookahead[Math.min(e,this.lookahead.length-1)]}advance(){let e=this.peek();return e.type!==d.EOF&&this.lookahead.shift(),e}check(e){return this.peek().type===e}matchToken(e){return this.check(e)?(this.advance(),!0):!1}consume(e,t){if(this.check(e))return this.advance();let n=this.peek();throw new g(t,n.loc.start.line,n.loc.start.column,n.loc.start.offset)}ensureLookahead(e){for(;this.lookahead.length<=e;){let e=this.tokenSource.nextToken();if(this.lookahead.push(e),e.type===d.EOF)break}}};function D(e,t){function n(e,t){let n=[];for(let i of e){let e=r(i,t);e!==null&&(Array.isArray(e)?n.push(...e):n.push(e))}return n}function r(e,i){if(!e||typeof e!=`object`)return e;let a=e;if(t.enter){let e=t.enter(a,i);if(e!==void 0){if(e===null||Array.isArray(e))return e;a=e}}let o=t[a.type];if(o){let e=o(a,i);if(e!==void 0){if(e===null||Array.isArray(e))return e;a=e}}switch(a.type){case m.Program:{let e=n(a.body,a);a={...a,body:e};break}case m.Element:{let e=a.attributes;if(t.Attribute&&Array.isArray(a.attributes)){let n=[];for(let e of a.attributes){let r=t.Attribute(e,a);r==null?r===void 0&&n.push(e):n.push(r)}e=n}let r=n(a.children,a);a={...a,attributes:e,children:r};break}case m.If:{let e=n(a.consequent,a),t=a.alternate;Array.isArray(a.alternate)?t=n(a.alternate,a):a.alternate!==null&&typeof a.alternate==`object`&&(t=r(a.alternate,a)),a={...a,consequent:e,alternate:t};break}case m.For:{let e=n(a.body,a);a={...a,body:e};break}case m.Switch:if(Array.isArray(a.cases)){let e=a.cases.map(e=>({...e,body:n(e.body,a)}));a={...a,cases:e}}break}if(t.leave){let e=t.leave(a,i);if(e!==void 0)return e}return a}return r(e,null)}var O=class{rawAst;switchCounter=0;constructor(e){this.rawAst=e}transform(){return D(D(D(this.rawAst,{Text:e=>{if(typeof e.content==`string`&&this.isWhitespaceOnly(e.content))return null}}),{Switch:e=>this.transformSwitchToIfChain(e)}),{Interpolation:e=>this.transformInterpolation(e),Element:e=>{if(e.tagName===`script`)return this.transformScriptElement(e);if(e.attributes.some(e=>e.value!==null&&typeof e.value!=`string`))return{...e,attributes:e.attributes.map(e=>e.type===m.Attribute&&e.value!==null&&typeof e.value!=`string`&&e.value.type===m.Interpolation?{...e,value:this.transformInterpolation(e.value)}:e)}},If:e=>{if(typeof e.test==`string`&&e.test.trim().length>0)return{...e,test:l.parseExpressionAt(e.test,0,{ecmaVersion:`latest`})}},For:e=>({...e,iterable:typeof e.iterable==`string`?l.parseExpressionAt(e.iterable,0,{ecmaVersion:`latest`}):e.iterable,key:typeof e.key==`string`&&e.key.trim().length>0?l.parseExpressionAt(e.key,0,{ecmaVersion:`latest`}):e.key??null})})}transformSwitchToIfChain(e){let t=typeof e.discriminant==`string`?l.parseExpressionAt(e.discriminant,0,{ecmaVersion:`latest`}):e.discriminant,n=t.type===`Identifier`||t.type===`Literal`||t.type===`MemberExpression`,r=`__drift_sw_${this.switchCounter++}`,i=!0,a=o=>{let s=e.cases[o];if(!s)return null;if(s.expression===null){let e=[...s.body],t=a(o+1),n=null;return(Array.isArray(t)||t!==null&&t.type===m.If)&&(n=t),o>0&&n===null?e:{type:m.If,test:{type:`Literal`,value:!0,raw:`true`,start:0,end:0},consequent:e,alternate:n,loc:s.loc}}let c=typeof s.expression==`string`&&s.expression.trim().length>0?l.parseExpressionAt(s.expression,0,{ecmaVersion:`latest`}):s.expression,u;n?u=structuredClone(t):i?(i=!1,u={type:`AssignmentExpression`,operator:`=`,left:{type:`Identifier`,name:r,start:0,end:0},right:structuredClone(t),start:0,end:0}):u={type:`Identifier`,name:r,start:0,end:0};let d={type:`BinaryExpression`,operator:`===`,left:u,right:c,start:0,end:0},f=[...s.body],p=a(o+1),h=null;return(Array.isArray(p)||p!==null&&p.type===m.If)&&(h=p),{type:m.If,test:d,consequent:f,alternate:h,extraDeps:structuredClone(t),loc:s.loc}},o=a(0);return o?Array.isArray(o)?o.length===0?{type:m.Comment,content:`empty switch`,loc:e.loc}:{type:m.If,test:{type:`Literal`,value:!0,raw:`true`,start:0,end:0},consequent:o,alternate:null,loc:e.loc}:o:{type:m.Comment,content:`empty switch`,loc:e.loc}}transformInterpolation(e){if(typeof e.expression!=`string`)return e;let t;try{t=l.parseExpressionAt(e.expression,0,{ecmaVersion:`latest`,allowAwaitOutsideFunction:!0})}catch(t){throw new g(`Failed to parse JS expression in interpolation: ${t instanceof Error?t.message:String(t)}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{...e,expression:t}}transformScriptElement(e){let t=e.children.map(e=>{if(e.type===m.Text&&typeof e.content==`string`){let t;try{let n=l.parse(e.content,{ecmaVersion:`latest`,sourceType:`module`,allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0});t=n.body.length===1&&n.body[0]!==void 0?n.body[0]:n.body}catch(t){throw new g(`Failed to parse script tag JS content: ${t instanceof Error?t.message:String(t)}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{...e,content:t}}return e});return{...e,children:t}}isWhitespaceOnly(e){return e.length>0&&/^\s*$/.test(e)}},k=class{ast;bytecode=[];constants=[];nextRegisterId=0;declaredVars=new Set;imports=[];bindingPositions=new Map;derivedBindings=[];pendingDerived=[];effectBindings=[];pendingEffects=[];constructor(e){this.ast=e}generate(){if(this.bytecode=[],this.constants=[],this.nextRegisterId=0,this.declaredVars=new Set,this.imports=[],this.bindingPositions=new Map,this.derivedBindings=[],this.pendingDerived=[],this.effectBindings=[],this.pendingEffects=[],this.collectDeclaredVars(this.ast.body),this.processDerivedBindings(),this.processEffectBindings(),this.ast.body.length===0){let e=this.allocRegister();return this.emit(_.CREATE_FRAGMENT,e),{bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings(),declaredVars:[...this.declaredVars],derived:this.derivedBindings,effects:this.effectBindings,imports:this.imports}}if(this.ast.body.length===1&&this.ast.body[0]?.type===m.Element){let e=this.allocRegister();this.compileElement(this.ast.body[0],e)}else{let e=this.allocRegister();this.emit(_.CREATE_FRAGMENT,e);for(let t of this.ast.body)this.compileNode(t,e)}return{bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings(),declaredVars:[...this.declaredVars],derived:this.derivedBindings,effects:this.effectBindings,imports:this.imports}}compileNode(e,t){switch(e.type){case m.Element:e.tagName===`script`?this.compileScriptElement(e):this.compileElementNode(e,t);break;case m.Text:this.compileTextNode(e,t);break;case m.Interpolation:this.compileInterpolationNode(e,t);break;case m.Comment:this.compileCommentNode(e,t);break;case m.If:this.compileIfNode(e,t);break;case m.For:this.compileForNode(e,t);break}}filterRuntimeScriptAst(e){if(Array.isArray(e)){let t=e.map(e=>this.filterScriptStatement(e)).filter(Boolean);return t.length===1?t[0]:t}return this.filterScriptStatement(e)}filterScriptStatement(e){if(!e||typeof e!=`object`)return e;if(e.type===`ImportDeclaration`||e.type===`ExpressionStatement`&&e.expression?.type===`CallExpression`&&e.expression.callee?.type===`Identifier`&&e.expression.callee.name===`effect`)return null;if(e.type===`VariableDeclaration`){let t=e.declarations.filter(e=>!(e.init?.type===`CallExpression`&&e.init.callee?.type===`Identifier`&&e.init.callee.name===`derive`));return t.length===0?null:{...e,declarations:t}}return e}compileScriptElement(e){for(let t of e.children)if(t.type===m.Text&&typeof t.content==`object`&&t.content!==null){let e=this.filterRuntimeScriptAst(t.content);if(e!==null&&(!Array.isArray(e)||e.length>0)){let t=this.addConstant(e);this.emit(_.EXEC_SCRIPT,t)}}}isComponentTag(e){if(this.imports.some(t=>t.localName===e))return!0;let t=e.charAt(0);return t!==``&&t===t.toUpperCase()&&t!==t.toLowerCase()}compileElement(e,t){let n=this.isComponentTag(e.tagName),r=this.addConstant(e.tagName);if(n){let n={__drift_props__:!0};for(let t of e.attributes)if(t.type===m.Attribute){if(t.value===null)n[t.name]=!0;else if(typeof t.value==`string`)n[t.name]=t.value;else if(t.value.type===m.Interpolation){let e=t.value.expression;if(e&&typeof e==`object`&&e.type){let r=F(e);n[t.name]={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => (${r})`}}else n[t.name]=e}}let i=null;if(e.children&&e.children.length>0){let t=e.children.filter(e=>!(e.type===m.Text&&typeof e.content==`string`&&e.content.trim()===``));t.length>0&&(i=this.compileNodesToSubModule(t),n.__drift_children__=this.addConstant(i))}let a=Object.keys(n).length>1?this.addConstant(n):255,o=this.bytecode.length;this.emit(_.MOUNT_COMPONENT,t,r,a),this.emit(_.RETURN);for(let t of e.attributes)t.type===m.Attribute&&t.value!==null&&typeof t.value!=`string`&&t.value.type===m.Interpolation&&this.recordBindingPositions(t.value.expression,o);if(i)for(let e of i.reactiveBindings)this.declaredVars.has(e.variable)&&(this.bindingPositions.has(e.variable)||this.bindingPositions.set(e.variable,[]),this.bindingPositions.get(e.variable).push(o))}else{this.emit(_.CREATE_ELEMENT,t,r);for(let n of e.attributes)this.compileAttributeNode(n,t);for(let n of e.children)this.compileNode(n,t)}}compileElementNode(e,t){let n=this.allocRegister();this.compileElement(e,n),this.emit(_.APPEND_CHILD,t,n)}compileAttributeNode(e,t){let n=this.addConstant(e.name);if(e.value===null){let e=this.addConstant(!0);this.emit(_.SET_ATTR,t,n,e,0)}else if(typeof e.value==`string`){let r=this.addConstant(e.value);this.emit(_.SET_ATTR,t,n,r,0)}else if(e.value.type===m.Interpolation){let r=this.addConstant(e.value.expression),i=this.bytecode.length;this.emit(_.SET_ATTR,t,n,r,1),this.emit(_.RETURN),this.recordBindingPositions(e.value.expression,i)}}compileTextNode(e,t){let n=this.allocRegister(),r=this.addConstant(e.content);this.emit(_.CREATE_TEXT,n,r),this.emit(_.APPEND_CHILD,t,n)}compileInterpolationNode(e,t){let n=this.allocRegister(),r=this.addConstant(e.expression),i=this.bytecode.length;this.emit(_.INTERPOLATE_TEXT,n,r),this.emit(_.RETURN),this.emit(_.APPEND_CHILD,t,n),this.recordBindingPositions(e.expression,i)}compileCommentNode(e,t){let n=this.allocRegister(),r=this.addConstant(e.content);this.emit(_.CREATE_COMMENT,n,r),this.emit(_.APPEND_CHILD,t,n)}compileNodesToSubModule(e){let t=this.bytecode,n=this.constants,r=this.nextRegisterId,i=this.bindingPositions;this.bytecode=[],this.constants=[],this.nextRegisterId=0,this.bindingPositions=new Map;let a=this.allocRegister();this.emit(_.CREATE_FRAGMENT,a);for(let t of e)this.compileNode(t,a);let o={bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings()};return this.bytecode=t,this.constants=n,this.nextRegisterId=r,this.bindingPositions=i,o}collectDepsFromSubModule(e,t){let n=new Set;for(let t=0;t<e.reactiveBindings.length;t++)n.add(e.reactiveBindings[t].variable);if(t)for(let e of this.extractIdentifiers(t))this.declaredVars.has(e)&&n.add(e);return[...n]}compileIfNode(e,t){let n=this.compileNodesToSubModule(e.consequent),r=this.addConstant(n),i=255,a=null;if(e.alternate!==null){let t;t=Array.isArray(e.alternate)?e.alternate:[e.alternate],a=this.compileNodesToSubModule(t),i=this.addConstant(a)}let o=new Set(this.collectDepsFromSubModule(n,e.test));if(e.extraDeps){for(let t of this.extractIdentifiers(e.extraDeps))this.declaredVars.has(t)&&o.add(t);let t=Array.from(o);n.constants&&!n.constants.some(e=>Array.isArray(e))&&n.constants.push(t)}if(a)for(let e of this.collectDepsFromSubModule(a))o.add(e);let s=this.addConstant(Array.from(o)),c=this.addConstant(e.test);this.emit(_.REACTIVE_IF,t,c,r,i,s)}compileForNode(e,t){let n=this.compileNodesToSubModule(e.body),r=this.addConstant(n),i=this.addConstant(e.iterable),a=this.addConstant(e.item),o=e.index===null?255:this.addConstant(e.index),s=e.key?this.addConstant(e.key):255,c=this.collectDepsFromSubModule(n,e.iterable),l=this.addConstant(c);this.emit(_.REACTIVE_FOR,t,i,a,o,s,r,l)}collectDeclaredVars(e){for(let t of e)if(t.type===m.Element&&t.tagName===`script`){for(let e of t.children)if(e.type===m.Text&&typeof e.content==`object`&&e.content!==null){let t=e.content;if(Array.isArray(t))for(let e of t)this.extractVarNames(e);else this.extractVarNames(t)}}}extractVarNames(e){if(!(!e||typeof e!=`object`)){if(e.type===`VariableDeclaration`)for(let t of e.declarations){for(let e of j(t.id))this.declaredVars.add(e);t.id?.type===`Identifier`&&t.init?.type===`CallExpression`&&t.init.callee?.type===`Identifier`&&t.init.callee.name===`derive`&&t.init.arguments&&t.init.arguments.length>0&&this.pendingDerived.push({name:t.id.name,arg:t.init.arguments[0]})}else if(e.type===`ExpressionStatement`&&e.expression?.type===`CallExpression`&&e.expression.callee?.type===`Identifier`&&e.expression.callee.name===`effect`&&Array.isArray(e.expression.arguments)&&e.expression.arguments.length>0)this.pendingEffects.push({arg:e.expression.arguments[0]});else if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.type===`Identifier`)this.declaredVars.add(e.id.name);else if(e.type===`ImportDeclaration`&&Array.isArray(e.specifiers)){let t=typeof e.source?.value==`string`?e.source.value:``;if(e.specifiers.length===0)this.imports.push({localName:``,source:t,isDefault:!1,isSideEffect:!0});else for(let n of e.specifiers)if(n.local?.type===`Identifier`){let e=n.local.name;this.declaredVars.add(e);let r=n.type===`ImportDefaultSpecifier`,i=n.type===`ImportNamespaceSpecifier`,a=n.type===`ImportSpecifier`&&n.imported?.type===`Identifier`?n.imported.name:void 0;this.imports.push({localName:e,source:t,isDefault:r,isNamespace:i,importedName:a})}}}}processDerivedBindings(){for(let e of this.pendingDerived){let{name:t,arg:n}=e,r=n,i=!1;(n.type===`ArrowFunctionExpression`||n.type===`FunctionExpression`)&&(n.body?.type===`BlockStatement`&&(i=!0),r=n.body);let a=[...this.extractIdentifiers(r)].filter(e=>e!==t&&this.declaredVars.has(e)),o=F(r),s;s=i?{__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => ${o}`}:{__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => (${o})`};let c=this.addConstant(s);this.derivedBindings.push({name:t,deps:a,exprIdx:c})}}processEffectBindings(){for(let e of this.pendingEffects){let{arg:t}=e,n=t,r=!1,i=!!t?.async;(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)&&(t.body?.type===`BlockStatement`&&(r=!0),n=t.body);let a=[...this.extractIdentifiers(n)].filter(e=>this.declaredVars.has(e)),o=F(n),s=i?`async `:``,c;c=r?{__drift_fn__:`${s}(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => ${o}`}:{__drift_fn__:`${s}(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => (${o})`};let l=this.addConstant(c);this.effectBindings.push({deps:a,exprIdx:l})}}extractIdentifiers(e){let t=new Set;if(!e||typeof e!=`object`)return t;try{u.ancestor(e,{Identifier(e,n){let r=n[n.length-2];r&&(r.type===`MemberExpression`&&r.property===e&&!r.computed||(r.type===`Property`||r.type===`MethodDefinition`||r.type===`PropertyDefinition`)&&r.key===e&&!r.computed)||t.add(e.name)}})}catch{}return t}recordBindingPositions(e,t){if(this.declaredVars.size===0)return;let n=this.extractIdentifiers(e);for(let e of n)this.declaredVars.has(e)&&(this.bindingPositions.has(e)||this.bindingPositions.set(e,[]),this.bindingPositions.get(e).push(t))}buildReactiveBindings(){let e=[];for(let[t,n]of this.bindingPositions)e.push({variable:t,positions:n});return e}allocRegister(){return this.nextRegisterId++}addConstant(e){e&&typeof e==`object`&&e.type&&typeof e.type==`string`?e={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => (${F(e)})`}:Array.isArray(e)&&e.length>0&&typeof e[0]==`object`&&e[0]?.type&&(e={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, _get) => { ${F(e)}; }`});let t=this.constants.findIndex(t=>this.isConstantEqual(t,e));return t===-1?(this.constants.push(e),this.constants.length-1):t}isConstantEqual(e,t){return e===t||typeof e==`object`&&typeof t==`object`&&e!==null&&t!==null&&JSON.stringify(e)===JSON.stringify(t)}emit(e,...t){this.bytecode.push(e,...t)}};function A(e){return!e||typeof e!=`object`?null:e.type===`Identifier`?e.name:e.type===`MemberExpression`?A(e.object):null}function j(e){let t=[];function n(e){if(!(!e||typeof e!=`object`))if(e.type===`Identifier`)t.push(e.name);else if(e.type===`ObjectPattern`&&Array.isArray(e.properties))for(let t of e.properties)t.type===`Property`?n(t.value):t.type===`RestElement`&&n(t.argument);else if(e.type===`ArrayPattern`&&Array.isArray(e.elements))for(let t of e.elements)t&&n(t);else e.type===`AssignmentPattern`?n(e.left):e.type===`RestElement`&&n(e.argument)}return n(e),t}function M(e,t){if(!e)return``;switch(e.type){case`Identifier`:return e.name;case`AssignmentPattern`:return`${M(e.left,t)} = ${F(e.right,t)}`;case`RestElement`:return`...${M(e.argument,t)}`;case`ArrayPattern`:return`[${(e.elements||[]).map(e=>e?M(e,t):``).join(`, `)}]`;case`ObjectPattern`:return`{ ${(e.properties||[]).map(e=>{if(e.type===`Property`){let n=e.key?.name||(typeof e.key?.value==`string`?JSON.stringify(e.key.value):e.key?.value?String(e.key.value):F(e.key,t));if(e.value?.type===`AssignmentPattern`){let r=e.value.left?.name||M(e.value.left,t),i=F(e.value.right,t);return n===r||e.shorthand?`${n} = ${i}`:`${n}: ${r} = ${i}`}else if(e.value?.type===`Identifier`&&e.value.name===n)return n;else return`${n}: ${M(e.value,t)}`}else if(e.type===`RestElement`)return`...${M(e.argument,t)}`;return``}).filter(Boolean).join(`, `)} }`;default:return e.name||F(e,t)}}function N(e,t,n){return n&&n.has(e)?`(${e} = ${t})`:`(typeof setScopeValue === 'function' && scope ? setScopeValue(scope, ${JSON.stringify(e)}, ${t}) : ((scope || {})[${JSON.stringify(e)}] = ${t}))`}function P(e,t,n,r={count:0}){let i=[];if(!e)return i;if(e.type===`Identifier`)return i.push(N(e.name,t,n)),i;if(e.type===`AssignmentPattern`){let a=`((${t} !== undefined) ? ${t} : ${F(e.right,n)})`;if(e.left?.type===`Identifier`)i.push(N(e.left.name,a,n));else{let t=`_t${r.count++}`;i.push(`const ${t} = ${a}`),i.push(...P(e.left,t,n,r))}return i}if(e.type===`ObjectPattern`){for(let a of e.properties||[])if(a.type===`Property`){let e=a.computed?F(a.key,n):a.key?.name===void 0?typeof a.key?.value==`string`||typeof a.key?.value==`number`?JSON.stringify(a.key.value):F(a.key,n):JSON.stringify(a.key.name);if(a.value?.type===`Identifier`){let r=`(${t} ? ${t}[${e}] : undefined)`;i.push(N(a.value.name,r,n))}else if(a.value?.type===`AssignmentPattern`){let o=`((${t} && ${t}[${e}] !== undefined) ? ${t}[${e}] : ${F(a.value.right,n)})`;if(a.value.left?.type===`Identifier`)i.push(N(a.value.left.name,o,n));else{let e=`_t${r.count++}`;i.push(`const ${e} = ${o}`),i.push(...P(a.value.left,e,n,r))}}else if(a.value?.type===`ObjectPattern`||a.value?.type===`ArrayPattern`){let o=`_t${r.count++}`,s=`(${t} ? ${t}[${e}] : undefined)`;i.push(`const ${o} = ${s}`),i.push(...P(a.value,o,n,r))}else{let r=a.value?.name||F(a.value,n);if(r){let a=`(${t} ? ${t}[${e}] : undefined)`;i.push(N(r,a,n))}}}else if(a.type===`RestElement`){let r=a.argument?.name||F(a.argument,n);if(r){let a=(e.properties||[]).filter(e=>e.type===`Property`).map(e=>e.key?.name||(typeof e.key?.value==`string`?e.key.value:``)).filter(Boolean),o=`(() => { const _r = Object.assign({}, ${t}); ${JSON.stringify(a)}.forEach(k => delete _r[k]); return _r; })()`;i.push(N(r,o,n))}}return i}if(e.type===`ArrayPattern`){let a=`_a${r.count++}`;i.push(`const ${a} = (typeof resolveIterable === 'function' ? resolveIterable(${t}) : (${t} || []))`);let o=e.elements||[];for(let e=0;e<o.length;e++){let t=o[e];if(t){if(t.type===`Identifier`){let r=`(${a} ? ${a}[${e}] : undefined)`;i.push(N(t.name,r,n))}else if(t.type===`AssignmentPattern`){let o=F(t.right,n),s=`((${a} && ${a}[${e}] !== undefined) ? ${a}[${e}] : ${o})`;if(t.left?.type===`Identifier`)i.push(N(t.left.name,s,n));else{let e=`_t${r.count++}`;i.push(`const ${e} = ${s}`),i.push(...P(t.left,e,n,r))}}else if(t.type===`RestElement`){let r=t.argument?.name||F(t.argument,n);if(r){let t=`((${a} && typeof ${a}.slice === 'function') ? ${a}.slice(${e}) : [])`;i.push(N(r,t,n))}}else if(t.type===`ObjectPattern`||t.type===`ArrayPattern`){let o=`_t${r.count++}`,s=`(${a} ? ${a}[${e}] : undefined)`;i.push(`const ${o} = ${s}`),i.push(...P(t,o,n,r))}}}return i}return i}function F(e,t){if(e==null)return`undefined`;if(typeof e!=`object`)return typeof e==`string`?JSON.stringify(e):String(e);if(Array.isArray(e))return e.map(e=>F(e,t)).join(`; `);switch(e.type){case`Identifier`:return t&&t.has(e.name)?e.name:`(typeof _get === 'function' ? _get(scope, ${JSON.stringify(e.name)}) : (typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(e.name)}) ? scope[${JSON.stringify(e.name)}] : (typeof globalThis !== 'undefined' && globalThis && (${JSON.stringify(e.name)} in globalThis) ? globalThis[${JSON.stringify(e.name)}] : (scope || {})[${JSON.stringify(e.name)}])))`;case`Literal`:return typeof e.raw==`string`?e.raw:typeof e.value==`string`?JSON.stringify(e.value):String(e.value);case`BinaryExpression`:case`LogicalExpression`:return`(${F(e.left,t)} ${e.operator} ${F(e.right,t)})`;case`UnaryExpression`:return`(${e.operator} ${F(e.argument,t)})`;case`AwaitExpression`:return`(await ${F(e.argument,t)})`;case`YieldExpression`:return e.delegate?`(yield* ${e.argument?F(e.argument,t):``})`:`(yield ${e.argument?F(e.argument,t):``})`;case`ConditionalExpression`:return`(${F(e.test,t)} ? ${F(e.consequent,t)} : ${F(e.alternate,t)})`;case`MemberExpression`:{let n=e.optional?`?.`:`.`;return e.computed?e.optional?`(${F(e.object,t)}?.[${F(e.property,t)}])`:`(${F(e.object,t)}[${F(e.property,t)}])`:`(${F(e.object,t)}${n}${e.property.name})`}case`CallExpression`:{let n=F(e.callee,t),r=e.arguments?e.arguments.map(e=>F(e,t)).join(`, `):``,i=`(${n}${e.optional?`?.(`:`(`}${r}))`;if(e.callee?.type===`MemberExpression`&&e.callee.property?.type===`Identifier`){let n=A(e.callee.object),r=e.callee.property.name;if(n&&[`push`,`pop`,`shift`,`unshift`,`splice`,`sort`,`reverse`].includes(r)&&(!t||!t.has(n)))return`(() => { const _res = ${i}; if (typeof setScopeValue === 'function' && scope && typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(n)})) setScopeValue(scope, ${JSON.stringify(n)}, scope[${JSON.stringify(n)}]); return _res; })()`}return i}case`AssignmentExpression`:{let n=F(e.right,t);if(e.left?.type===`Identifier`){let r=e.left.name;if(t&&t.has(r))return`(${r} ${e.operator} ${n})`;if(e.operator===`=`)return`(typeof setScopeValue === 'function' ? setScopeValue(scope, ${JSON.stringify(r)}, ${n}) : ((scope || {})[${JSON.stringify(r)}] = ${n}))`;{let t=e.operator.slice(0,-1);return`(typeof setScopeValue === 'function' ? setScopeValue(scope, ${JSON.stringify(r)}, (scope[${JSON.stringify(r)}] ${t} ${n})) : ((scope || {})[${JSON.stringify(r)}] ${e.operator} ${n}))`}}if(e.left?.type===`MemberExpression`){let r=A(e.left),i=`(${F(e.left,t)} ${e.operator} ${n})`;if(r&&(!t||!t.has(r)))return`(() => { const _res = ${i}; if (typeof setScopeValue === 'function' && scope && typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(r)})) setScopeValue(scope, ${JSON.stringify(r)}, scope[${JSON.stringify(r)}]); return _res; })()`}return e.left?.type===`ObjectPattern`||e.left?.type===`ArrayPattern`?`((_val) => { ${P(e.left,`_val`,t).join(`; `)}; return _val; })(${n})`:`(${F(e.left,t)} ${e.operator} ${n})`}case`UpdateExpression`:if(e.argument?.type===`Identifier`){let n=e.argument.name;if(t&&t.has(n))return e.prefix?`(${e.operator}${n})`:`(${n}${e.operator})`;let r=e.operator===`++`?`+`:`-`;return e.prefix?`(typeof setScopeValue === 'function' ? (setScopeValue(scope, ${JSON.stringify(n)}, (Number(scope[${JSON.stringify(n)}]) || 0) ${r} 1), scope[${JSON.stringify(n)}]) : ((scope || {})[${JSON.stringify(n)}] = (Number((scope || {})[${JSON.stringify(n)}]) || 0) ${r} 1))`:`(() => { const _v = Number(scope[${JSON.stringify(n)}]) || 0; if (typeof setScopeValue === 'function') setScopeValue(scope, ${JSON.stringify(n)}, _v ${r} 1); else (scope || {})[${JSON.stringify(n)}] = _v ${r} 1; return _v; })()`}if(e.argument?.type===`MemberExpression`){let n=A(e.argument),r=e.prefix?`(${e.operator}${F(e.argument,t)})`:`(${F(e.argument,t)}${e.operator})`;if(n&&(!t||!t.has(n)))return`(() => { const _res = ${r}; if (typeof setScopeValue === 'function' && scope && typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(n)})) setScopeValue(scope, ${JSON.stringify(n)}, scope[${JSON.stringify(n)}]); return _res; })()`}return e.prefix?`(${e.operator}${F(e.argument,t)})`:`(${F(e.argument,t)}${e.operator})`;case`SequenceExpression`:return`(${e.expressions?e.expressions.map(e=>F(e,t)).join(`, `):``})`;case`ArrayExpression`:return`[${e.elements?e.elements.map(e=>e?.type===`SpreadElement`?`...`+F(e.argument,t):F(e,t)).join(`, `):``}]`;case`ObjectExpression`:return`{${e.properties?e.properties.map(e=>{if(e.type===`SpreadElement`)return`...`+F(e.argument,t);let n=e.computed?`[${F(e.key,t)}]`:e.key?.name||(typeof e.key?.value==`string`?JSON.stringify(e.key.value):String(e.key?.value??``));if(e.kind===`get`||e.kind===`set`){let r=e.value,i=new Set(t),a=[];if(r.params)for(let e of r.params){for(let t of j(e))i.add(t);a.push(M(e,i))}let o=r.body?.type===`BlockStatement`?`{ ${r.body.body.map(e=>F(e,i)).filter(Boolean).join(`; `)}; }`:`{ ${F(r.body,i)}; }`;return`${e.kind} ${n}(${a.join(`, `)}) ${o}`}if(e.method){let r=e.value,i=new Set(t),a=[];if(r.params)for(let e of r.params){for(let t of j(e))i.add(t);a.push(M(e,i))}let o=r.async?`async `:``,s=r.generator?`*`:``,c=r.body?.type===`BlockStatement`?`{ ${r.body.body.map(e=>F(e,i)).filter(Boolean).join(`; `)}; }`:`{ ${F(r.body,i)}; }`;return`${o}${s}${n}(${a.join(`, `)}) ${c}`}return`${n}: ${F(e.value,t)}`}).join(`, `):``}}`;case`RestElement`:case`SpreadElement`:return`...${F(e.argument,t)}`;case`AssignmentPattern`:return`${F(e.left,t)} = ${F(e.right,t)}`;case`TemplateLiteral`:return`\`${e.quasis?e.quasis.map((n,r)=>(n.value?.raw??``)+(e.expressions&&e.expressions[r]?"${"+F(e.expressions[r],t)+`}`:``)).join(``):``}\``;case`TaggedTemplateExpression`:return`${F(e.tag,t)}${F(e.quasi,t)}`;case`ThisExpression`:return`this`;case`Super`:return`super`;case`BlockStatement`:{let n=new Set(t);if(Array.isArray(e.body))for(let t of e.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of j(e.id))n.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&n.add(t.id.name);return`{ ${(e.body?e.body.map(e=>F(e,n)).filter(Boolean):[]).join(`; `)}; }`}case`ExpressionStatement`:return F(e.expression,t);case`ReturnStatement`:return`return ${e.argument?F(e.argument,t):``}`;case`ThrowStatement`:return`throw ${e.argument?F(e.argument,t):``}`;case`BreakStatement`:return e.label?`break ${e.label.name}`:`break`;case`ContinueStatement`:return e.label?`continue ${e.label.name}`:`continue`;case`LabeledStatement`:return`${e.label.name}: ${F(e.body,t)}`;case`TryStatement`:return`try ${F(e.block,t)} ${e.handler?F(e.handler,t):``} ${e.finalizer?`finally ${F(e.finalizer,t)}`:``}`.trim();case`CatchClause`:{let n=new Set(t),r=``;if(e.param){for(let t of j(e.param))n.add(t);r=M(e.param,n)}let i=F(e.body,n);return r?`catch (${r}) ${i}`:`catch ${i}`}case`SwitchStatement`:return`switch (${F(e.discriminant,t)}) { ${e.cases?e.cases.map(e=>F(e,t)).join(` `):``} }`;case`SwitchCase`:{let n=e.test?`case ${F(e.test,t)}:`:`default:`,r=e.consequent?e.consequent.map(e=>F(e,t)).filter(Boolean).join(`; `):``;return`${n} ${r?r+`;`:``}`}case`IfStatement`:return`if (${F(e.test,t)}) ${e.consequent.type===`BlockStatement`?F(e.consequent,t):`{ ${F(e.consequent,t)}; }`}${e.alternate?` else ${e.alternate.type===`BlockStatement`||e.alternate.type===`IfStatement`?F(e.alternate,t):`{ ${F(e.alternate,t)}; }`}`:``}`;case`ForStatement`:{let n=new Set(t);if(e.init?.type===`VariableDeclaration`&&e.init.declarations)for(let t of e.init.declarations)for(let e of j(t.id))n.add(e);let r=``;e.init?.type===`VariableDeclaration`&&e.init.declarations?r=(e.init.kind||`let`)+` `+e.init.declarations.map(e=>`${e.id?.type===`Identifier`?e.id.name:F(e.id,n)}${e.init?` = ${F(e.init,n)}`:``}`).join(`, `):e.init&&(r=F(e.init,n));let i=e.test?F(e.test,n):``,a=e.update?F(e.update,n):``,o=e.body?.type===`BlockStatement`?F(e.body,n):`{ ${e.body?F(e.body,n):``}; }`;return`for (${r}; ${i}; ${a}) ${o}`}case`ForOfStatement`:{let n=new Set(t),r=``;if(e.left?.type===`VariableDeclaration`){let t=e.left.kind||`let`,i=e.left.declarations?.[0];if(i){for(let e of j(i.id))n.add(e);r=`${t} ${i.id?.type===`Identifier`?i.id.name:F(i.id,n)}`}}else e.left?.type===`Identifier`?(n.add(e.left.name),r=e.left.name):e.left&&(r=F(e.left,n));let i=`(typeof resolveIterable === 'function' ? resolveIterable : (x) => x || [])(${F(e.right,t)})`,a=e.body?.type===`BlockStatement`?F(e.body,n):`{ ${e.body?F(e.body,n):``}; }`;return`for ${e.await?`await `:``}(${r} of ${i}) ${a}`}case`ForInStatement`:{let n=new Set(t),r=``;if(e.left?.type===`VariableDeclaration`){let t=e.left.kind||`let`,i=e.left.declarations?.[0];if(i){for(let e of j(i.id))n.add(e);r=`${t} ${i.id?.type===`Identifier`?i.id.name:F(i.id,n)}`}}else e.left?.type===`Identifier`?(n.add(e.left.name),r=e.left.name):e.left&&(r=F(e.left,n));let i=F(e.right,t),a=e.body?.type===`BlockStatement`?F(e.body,n):`{ ${e.body?F(e.body,n):``}; }`;return`for (${r} in ${i}) ${a}`}case`WhileStatement`:return`while (${F(e.test,t)}) ${e.body?.type===`BlockStatement`?F(e.body,t):`{ ${e.body?F(e.body,t):``}; }`}`;case`DoWhileStatement`:{let n=F(e.test,t);return`do ${e.body?.type===`BlockStatement`?F(e.body,t):`{ ${e.body?F(e.body,t):``}; }`} while (${n})`}case`ArrayPattern`:return`[ ${e.elements?e.elements.map(e=>e?e.type===`RestElement`?`...`+F(e.argument,t):e.type===`AssignmentPattern`?`${F(e.left,t)} = ${F(e.right,t)}`:e.name||F(e,t):``).join(`, `):``} ]`;case`ObjectPattern`:return`{ ${e.properties?e.properties.map(e=>{if(e.type===`Property`){let n=e.key?.name||F(e.key,t),r=e.value?.name||F(e.value,t);return n===r?n:`${n}: ${r}`}return e.type===`RestElement`?`...${F(e.argument,t)}`:``}).filter(Boolean).join(`, `):``} }`;case`VariableDeclaration`:{if(t){let n=[];if(e.declarations)for(let r of e.declarations){let e=r.id?.type===`Identifier`?r.id.name:F(r.id,t),i=r.init?F(r.init,t):void 0;i===void 0?n.push(`${e}`):n.push(`${e} = ${i}`)}return`${e.kind||`let`} ${n.join(`, `)}`}let n=[];if(e.declarations)for(let r of e.declarations)if(r.id?.type===`ObjectPattern`||r.id?.type===`ArrayPattern`){let e=r.init?F(r.init,t):`undefined`,i=P(r.id,`_init`,t);n.push(`((_init) => { ${i.join(`; `)}; return _init; })(${e})`)}else{let e=r.id?.name||F(r.id,t),i=r.init?F(r.init,t):`undefined`;n.push(`((scope || {})[${JSON.stringify(e)}] = ${i})`)}return`(${n.filter(Boolean).join(`, `)||`undefined`})`}case`FunctionDeclaration`:{let n=e.id?.name,r=new Set(t);n&&r.add(n);let i=[];if(e.params)for(let t of e.params){for(let e of j(t))r.add(e);i.push(M(t,r))}if(e.body?.type===`BlockStatement`&&Array.isArray(e.body.body))for(let t of e.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of j(e.id))r.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&r.add(t.id.name);let a=i.join(`, `),o=e.body?.type===`BlockStatement`?`{ ${e.body.body.map(e=>F(e,r)).filter(Boolean).join(`; `)}; }`:`{ ${F(e.body,r)}; }`,s=`${e.async?`async `:``}function${e.generator?`*`:``} ${n||``}(${a}) ${o}`;return n?`((scope || {})[${JSON.stringify(n)}] = ${s})`:s}case`ArrowFunctionExpression`:case`FunctionExpression`:{let n=new Set(t);e.id?.name&&n.add(e.id.name);let r=[];if(e.params)for(let t of e.params){for(let e of j(t))n.add(e);r.push(M(t,n))}if(e.body?.type===`BlockStatement`&&Array.isArray(e.body.body))for(let t of e.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of j(e.id))n.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&n.add(t.id.name);let i=r.join(`, `),a=e.async?`async `:``;if(e.type===`ArrowFunctionExpression`)return e.body?.type===`BlockStatement`?`(${a}(${i}) => ${`{ ${e.body.body.map(e=>F(e,n)).filter(Boolean).join(`; `)}; }`})`:`(${a}(${i}) => ${F(e.body,n)})`;{let t=e.generator?`*`:``,r=e.body?.type===`BlockStatement`?`{ ${e.body.body.map(e=>F(e,n)).filter(Boolean).join(`; `)}; }`:`{ ${F(e.body,n)}; }`;return`(${a}function${t} ${e.id?.name||``}(${i}) ${r})`}}case`ClassDeclaration`:case`ClassExpression`:{let n=e.id?.name,r=new Set(t);n&&r.add(n);let i=e.superClass?` extends ${F(e.superClass,t)}`:``,a=F(e.body,r),o=`class ${n||``}${i} ${a}`;return e.type===`ClassDeclaration`&&n?`((scope || {})[${JSON.stringify(n)}] = ${o})`:`(${o})`}case`ClassBody`:return`{ ${(e.body?e.body.map(e=>F(e,t)).filter(Boolean):[]).join(`; `)} }`;case`MethodDefinition`:{let n=e.static?`static `:``,r=e.kind===`get`||e.kind===`set`?`${e.kind} `:``,i=e.value?.async?`async `:``,a=e.value?.generator?`*`:``,o=e.computed?`[${F(e.key,t)}]`:e.key?.name||F(e.key,t),s=new Set(t),c=[];if(e.value?.params)for(let t of e.value.params){for(let e of j(t))s.add(e);c.push(M(t,s))}if(e.value?.body?.type===`BlockStatement`&&Array.isArray(e.value.body.body))for(let t of e.value.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of j(e.id))s.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&s.add(t.id.name);return`${n}${i}${a}${r}${o}(${c.join(`, `)}) ${e.value?.body?F(e.value.body,s):`{}`}`}case`PropertyDefinition`:return`${e.static?`static `:``}${e.computed?`[${F(e.key,t)}]`:e.key?.name||F(e.key,t)}${e.value?` = ${F(e.value,t)}`:``}`;case`NewExpression`:return`new (${F(e.callee,t)})(${e.arguments?e.arguments.map(e=>F(e,t)).join(`, `):``})`;case`EmptyStatement`:case`ImportDeclaration`:case`ImportSpecifier`:case`ImportDefaultSpecifier`:case`ImportNamespaceSpecifier`:return``;case`ParenthesizedExpression`:case`ChainExpression`:return F(e.expression,t);default:return``}}function I(e,t=!1){let n=new O(new E(new S(e)).parse()).transform(),r=new k(n).generate();return t&&(console.log(`--- Transformed AST ---`),console.log(JSON.stringify(n,null,2)),console.log(`--- Compiled Module ---`),console.log(JSON.stringify(r,null,2))),r}exports.ASTNodeType=m,exports.DriftGenerator=k,exports.DriftLexer=S,exports.DriftLexerError=h,exports.DriftParser=E,exports.DriftParserError=g,exports.DriftTransformer=O,exports.ExprTokenKind=p,exports.LexerStateKind=f,exports.Opcode=_,exports.TokenType=d,exports.astToJS=F,exports.compile=I,exports.extractBindingNames=j,exports.traverseTemplateAST=D;
|
|
7
|
+
`}},C=class{tokens;current=0;constructor(e){this.tokens=e}nextToken(){if(this.current>=this.tokens.length)return this.tokens[this.tokens.length-1];let e=this.tokens[this.current];return this.current++,e}},w={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:`\xA0`,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,laquo:`«`,raquo:`»`,ldquo:`“`,rdquo:`”`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,bdquo:`„`,bull:`•`,times:`×`,divide:`÷`,plusmn:`±`,euro:`€`,pound:`£`,yen:`¥`,cent:`¢`,deg:`°`,para:`¶`,sect:`§`,micro:`µ`,middot:`·`,frac14:`¼`,frac12:`½`,frac34:`¾`,sup1:`¹`,sup2:`²`,sup3:`³`,dagger:`†`,Dagger:`‡`,permil:`‰`,prime:`′`,Prime:`″`,infin:`∞`,radic:`√`,sim:`∼`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,sum:`∑`,prod:`∏`,minus:`−`,lowast:`∗`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,and:`∧`,or:`∨`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,cong:`≅`,ang:`∠`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`};function T(e){return!e||!e.includes(`&`)?e:e.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|([a-zA-Z0-9]+));/g,(e,t,n,r)=>{if(t){let e=parseInt(t,10);try{return!isNaN(e)&&e>=0&&e<=1114111&&(e<55296||e>57343)?String.fromCodePoint?String.fromCodePoint(e):String.fromCharCode(e):`�`}catch{return`�`}}if(n){let e=parseInt(n,16);try{return!isNaN(e)&&e>=0&&e<=1114111&&(e<55296||e>57343)?String.fromCodePoint?String.fromCodePoint(e):String.fromCharCode(e):`�`}catch{return`�`}}return r&&w[r]||e})}function E(e){let t=e.trim();if(!t.startsWith(`(`)||!t.endsWith(`)`))return!1;let n=0,r=null,i=!1;for(let e=0;e<t.length-1;e++){let a=t[e];if(r!==null){i?i=!1:a===`\\`?i=!0:a===r&&(r=null);continue}if(a===`"`||a===`'`||a==="`"){r=a;continue}if(a===`(`?n++:a===`)`&&n--,n===0)return!1}return n===1}var D=class{tokenSource;lookahead=[];constructor(e){this.tokenSource=Array.isArray(e)?new C(e):e}parse(){return this.lookahead.length=0,this.parseProgram()}parseProgram(){let e=this.peek().loc.start,t=[];for(;!this.isAtEnd();)t.push(this.parseChild());let n=this.peek().loc.end;return{type:m.Program,body:t,loc:{start:e,end:n}}}parseChild(){let e=this.peek();if(e.type===d.Comment)return this.advance(),{type:m.Comment,content:e.value,loc:e.loc};if(e.type===d.Interpolation)return this.advance(),{type:m.Interpolation,expression:e.value,loc:e.loc};if(e.type===d.TagOpen)return this.parseElement();if(e.type===d.DirectiveIf)return this.parseIfDirective();if(e.type===d.DirectiveFor)return this.parseForDirective();if(e.type===d.DirectiveSwitch)return this.parseSwitchDirective();if(e.type===d.DirectiveAsync)return this.parseAsyncDirective();if(e.type===d.Text)return this.advance(),{type:m.Text,content:T(e.value),loc:e.loc};throw e.type===d.TagOpenSlash?new g(`Unexpected closing tag '</${this.peek(1).value}>' without opening tag`,e.loc.start.line,e.loc.start.column,e.loc.start.offset):new g(`Unexpected token '${e.value}' of type '${e.type}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}parseElement(){let e=this.consume(d.TagOpen,`Expected opening tag bracket`).loc.start,t=this.consume(d.Identifier,`Expected tag name after opening bracket`).value,n=[];for(;!this.check(d.TagClose)&&!this.check(d.TagSelfClose)&&!this.isAtEnd();)n.push(this.parseAttribute());if(this.check(d.TagSelfClose)){let r=this.advance();return{type:m.Element,tagName:t,attributes:n,children:[],isSelfClosing:!0,loc:{start:e,end:r.loc.end}}}let r=this.consume(d.TagClose,`Expected closing bracket after attributes`);if(c.VOID_ELEMENTS.has(t.toLowerCase()))return{type:m.Element,tagName:t,attributes:n,children:[],isSelfClosing:!0,loc:{start:e,end:r.loc.end}};let i=t.toLowerCase()===`script`||t.toLowerCase()===`style`,a=[];for(;!this.check(d.TagOpenSlash)&&!this.isAtEnd();)if(i&&this.check(d.Text)){let e=this.advance();a.push({type:m.Text,content:e.value,loc:e.loc})}else a.push(this.parseChild());if(this.isAtEnd())throw new g(`Unclosed element '<${t}>', expected closing tag '</${t}>'`,e.line,e.column,e.offset);this.consume(d.TagOpenSlash,`Expected closing tag '</${t}>'`);let o=this.consume(d.Identifier,`Expected closing tag name`);if(o.value!==t&&o.value.toLowerCase()!==t.toLowerCase())throw new g(`Mismatched closing tag. Expected '</${t}>' but got '</${o.value}>'`,o.loc.start.line,o.loc.start.column,o.loc.start.offset);let s=this.consume(d.TagClose,`Expected '>' after closing tag name`);return{type:m.Element,tagName:t,attributes:n,children:a,isSelfClosing:!1,loc:{start:e,end:s.loc.end}}}parseAttribute(){let e=this.consume(d.Identifier,`Expected attribute name`),t=e.loc.start,n=e.value;if(this.matchToken(d.Equals)){let e=this.peek();if(e.type===d.StringLiteral)return this.advance(),{type:m.Attribute,name:n,value:T(e.value),loc:{start:t,end:e.loc.end}};if(e.type===d.Interpolation){this.advance();let r={type:m.Interpolation,expression:e.value,loc:e.loc};return{type:m.Attribute,name:n,value:r,loc:{start:t,end:e.loc.end}}}throw new g(`Expected string literal or interpolation after '=' for attribute '${n}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{type:m.Attribute,name:n,value:null,loc:{start:t,end:e.loc.end}}}parseIfDirective(){let e=this.consume(d.DirectiveIf,`Expected @if directive`),t=e.loc.start,n=e.value,r=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)r.push(this.parseChild());let i=this.consume(d.BlockClose,`Expected closing brace } for @if block`),a=null,o=i.loc.end;if(this.skipWhitespaceTokens(),this.check(d.DirectiveElseIf))a=this.parseElseIfChain(),o=a.loc.end;else if(this.check(d.DirectiveElse)){this.advance();let e=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)e.push(this.parseChild());let t=this.consume(d.BlockClose,`Expected closing brace } for @else block`);a=e,o=t.loc.end}return{type:m.If,test:n,consequent:r,alternate:a,loc:{start:t,end:o}}}parseElseIfChain(){let e=this.consume(d.DirectiveElseIf,`Expected @else if directive`),t=e.loc.start,n=e.value,r=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)r.push(this.parseChild());let i=this.consume(d.BlockClose,`Expected closing brace } for @else if block`),a=null,o=i.loc.end;if(this.skipWhitespaceTokens(),this.check(d.DirectiveElseIf))a=this.parseElseIfChain(),o=a.loc.end;else if(this.check(d.DirectiveElse)){this.advance();let e=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)e.push(this.parseChild());let t=this.consume(d.BlockClose,`Expected closing brace } for @else block`);a=e,o=t.loc.end}return{type:m.If,test:n,consequent:r,alternate:a,loc:{start:t,end:o}}}parseForDirective(){let e=this.consume(d.DirectiveFor,`Expected @for directive`),t=e.loc.start,n=e.value.trim();for(;E(n);)n=n.slice(1,-1).trim();let r=null,i=0,a=0,o=0,s=null;try{let e=l.tokenizer(n,{ecmaVersion:`latest`});for(let t of e)if(t.type===l.tokTypes.parenL)i++;else if(t.type===l.tokTypes.parenR)i=Math.max(0,i-1);else if(t.type===l.tokTypes.bracketL)a++;else if(t.type===l.tokTypes.bracketR)a=Math.max(0,a-1);else if(t.type===l.tokTypes.braceL||t.type===l.tokTypes.dollarBraceL)o++;else if(t.type===l.tokTypes.braceR)o=Math.max(0,o-1);else if(t.type===l.tokTypes._in&&i===0&&a===0&&o===0){r=t;break}}catch(e){s=e}if(!r)throw s?new g(`Syntax error in @for header: ${s.message}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset):new g(`Invalid @for header syntax '${e.value.trim()}'. Expected format: 'item in list' or '(item, index) in list'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let c=n.slice(0,r.start).trim();if(c.length===0)throw new g(`Invalid @for header syntax '${e.value.trim()}'. Expected format: 'item in list' or '(item, index) in list'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let u=``,f=null;if(E(c)){let t=c.slice(1,-1).trim(),n=[],r=0,i=0,a=0;try{let e=l.tokenizer(t,{ecmaVersion:`latest`});for(let t of e)t.type===l.tokTypes.parenL?r++:t.type===l.tokTypes.parenR?r=Math.max(0,r-1):t.type===l.tokTypes.bracketL?i++:t.type===l.tokTypes.bracketR?i=Math.max(0,i-1):t.type===l.tokTypes.braceL||t.type===l.tokTypes.dollarBraceL?a++:t.type===l.tokTypes.braceR?a=Math.max(0,a-1):t.type===l.tokTypes.comma&&r===0&&i===0&&a===0&&n.push(t.start)}catch(t){throw new g(`Invalid @for target bindings '${c}': ${t.message}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}if(n.length===0)u=t;else if(n.length===1){let e=n[0];u=t.slice(0,e).trim(),f=t.slice(e+1).trim()}else throw new g(`Invalid @for target bindings. Expected at most 2 variables (item, index).`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}else{let t=0,n=0,r=0,i=!1;try{let e=l.tokenizer(c,{ecmaVersion:`latest`});for(let a of e)if(a.type===l.tokTypes.parenL)t++;else if(a.type===l.tokTypes.parenR)t=Math.max(0,t-1);else if(a.type===l.tokTypes.bracketL)n++;else if(a.type===l.tokTypes.bracketR)n=Math.max(0,n-1);else if(a.type===l.tokTypes.braceL||a.type===l.tokTypes.dollarBraceL)r++;else if(a.type===l.tokTypes.braceR)r=Math.max(0,r-1);else if(a.type===l.tokTypes.comma&&t===0&&n===0&&r===0){i=!0;break}}catch{}if(i)throw new g(`Invalid @for target bindings '${c}'. Multiple loop variables must be enclosed in parentheses: '(${c})'.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);u=c}if(u.length===0)throw new g(`Expected item identifier in @for target bindings.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let p=null;try{let e=l.parse(`let ${u} = 0;`,{ecmaVersion:`latest`});if(!e||!Array.isArray(e.body)||e.body.length!==1||e.body[0].type!==`VariableDeclaration`||!Array.isArray(e.body[0].declarations)||e.body[0].declarations.length!==1)throw Error();p=e.body[0].declarations[0].id}catch{throw new g(`Invalid @for item binding '${u}'. Expected a valid variable identifier or destructuring pattern.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}if(f!==null){if(f.length===0)throw new g(`Unexpected trailing comma in @for target bindings. Expected index identifier.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);try{let e=l.parseExpressionAt(f,0,{ecmaVersion:`latest`});if(e.type!==`Identifier`||f.slice(e.end).trim().length>0)throw Error()}catch{throw new g(`Invalid @for index binding '${f}'. Array index must be a valid identifier.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}}let h=r.end,_=n.slice(h),v=h+(_.length-_.trimStart().length),y=``,b=null;try{b=l.parseExpressionAt(n,v,{ecmaVersion:`latest`}),y=n.slice(v,b.end).trim()}catch{throw new g(`Invalid @for iterable expression in '${e.value.trim()}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}let x=null,S=n.slice(b.end).trim();if(S.length>0){let t=null;try{t=l.tokenizer(S,{ecmaVersion:`latest`}).getToken()}catch{}if(t&&t.type===l.tokTypes.name&&t.value===`key`){let n=t.end,r=S.slice(n).trim();try{let t=l.parseExpressionAt(r,0,{ecmaVersion:`latest`});x=r.slice(0,t.end).trim();let n=r.slice(t.end).trim();if(n.length>0)throw new g(`Unexpected token '${n}' after key expression in @for directive.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}catch(t){throw t instanceof g?t:new g(`Invalid key expression in @for directive: '${r}'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}}else throw new g(`Unexpected token '${S}' in @for header. Expected 'key <expression>' or block opening '{'.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}let C=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)C.push(this.parseChild());let w=this.consume(d.BlockClose,`Expected closing brace } for @for block`);return{type:m.For,item:u,pattern:p,index:f,iterable:y,key:x,body:C,loc:{start:t,end:w.loc.end}}}parseSwitchDirective(){let e=this.consume(d.DirectiveSwitch,`Expected @switch directive`),t=e.loc.start,n=e.value,r=[];for(this.skipWhitespaceTokens();!this.check(d.BlockClose)&&!this.isAtEnd();){if(this.check(d.DirectiveCase)){let e=this.advance(),t=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)t.push(this.parseChild());let n=this.consume(d.BlockClose,`Expected closing brace } for @case block`);r.push({expression:e.value,body:t,loc:{start:e.loc.start,end:n.loc.end}})}else if(this.check(d.DirectiveDefault)){let e=this.advance(),t=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)t.push(this.parseChild());let n=this.consume(d.BlockClose,`Expected closing brace } for @default block`);r.push({expression:null,body:t,loc:{start:e.loc.start,end:n.loc.end}})}else throw new g(`Unexpected token '${this.peek().value}' inside @switch block. Expected @case or @default.`,this.peek().loc.start.line,this.peek().loc.start.column,this.peek().loc.start.offset);this.skipWhitespaceTokens()}let i=this.consume(d.BlockClose,`Expected closing brace } for @switch block`);return{type:m.Switch,discriminant:n,cases:r,loc:{start:t,end:i.loc.end}}}parseAsyncDirective(){let e=this.consume(d.DirectiveAsync,`Expected @async directive`),t=e.loc.start,n=e.value.trim();for(;E(n);)n=n.slice(1,-1).trim();let r=null;try{r=l.parseExpressionAt(n,0,{ecmaVersion:`latest`})}catch{throw new g(`Invalid @async header syntax '${e.value.trim()}'. Expected format: '@async <promise> as <alias>'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}let i=n.slice(0,r.end).trim(),a=n.slice(r.end).trim(),o=`data`,s=null;if(a.length>0){let t=null;try{t=l.tokenizer(a,{ecmaVersion:`latest`}).getToken()}catch{}if(t&&t.type===l.tokTypes.name&&t.value===`as`){let e=a.slice(t.end).trim();for(;E(e);)e=e.slice(1,-1).trim();o=e;try{let t=l.parse(`let ${e} = 0;`,{ecmaVersion:`latest`});t&&Array.isArray(t.body)&&t.body.length===1&&t.body[0].type===`VariableDeclaration`&&Array.isArray(t.body[0].declarations)&&t.body[0].declarations.length===1&&(s=t.body[0].declarations[0].id)}catch{}}else throw new g(`Unexpected token '${a}' in @async header. Expected 'as <alias>'.`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}if(!i||!o)throw new g(`Invalid @async header syntax '${e.value.trim()}'. Expected format: '@async <promise> as <alias>'`,e.loc.start.line,e.loc.start.column,e.loc.start.offset);let c=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)c.push(this.parseChild());let u=this.consume(d.BlockClose,`Expected closing brace } for @async block`),f=null,p=null;for(;!this.isAtEnd();)if(this.skipWhitespaceTokens(),this.check(d.DirectiveFallback)){if(f!==null){let e=this.peek();throw new g(`Duplicate @fallback directive for @async block`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}this.consume(d.DirectiveFallback,`Expected @fallback directive`);let e=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)e.push(this.parseChild());u=this.consume(d.BlockClose,`Expected closing brace } for @fallback block`),f=e}else if(this.check(d.DirectiveCatch)){if(p!==null){let e=this.peek();throw new g(`Duplicate @catch directive for @async block`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}let e=this.consume(d.DirectiveCatch,`Expected @catch directive`),t=e.value.trim()||`error`;for(;E(t);)t=t.slice(1,-1).trim();let n=[];for(;!this.check(d.BlockClose)&&!this.isAtEnd();)n.push(this.parseChild());u=this.consume(d.BlockClose,`Expected closing brace } for @catch block`),p={errorVar:t,body:n,loc:{start:e.loc.start,end:u.loc.end}}}else break;return{type:m.Async,promise:i,alias:o,aliasAst:s,body:c,fallback:f,catchBranch:p,loc:{start:t,end:u.loc.end}}}skipWhitespaceTokens(){for(;this.check(d.Text)&&this.peek().value.trim().length===0;)this.advance()}isAtEnd(){return this.peek().type===d.EOF}peek(e=0){return this.ensureLookahead(e),this.lookahead[Math.min(e,this.lookahead.length-1)]}advance(){let e=this.peek();return e.type!==d.EOF&&this.lookahead.shift(),e}check(e){return this.peek().type===e}matchToken(e){return this.check(e)?(this.advance(),!0):!1}consume(e,t){if(this.check(e))return this.advance();let n=this.peek();throw new g(t,n.loc.start.line,n.loc.start.column,n.loc.start.offset)}ensureLookahead(e){for(;this.lookahead.length<=e;){let e=this.tokenSource.nextToken();if(this.lookahead.push(e),e.type===d.EOF)break}}};function O(e,t){function n(e,t){let n=[];for(let i of e){let e=r(i,t);e!==null&&(Array.isArray(e)?n.push(...e):n.push(e))}return n}function r(e,i){if(!e||typeof e!=`object`)return e;let a=e;if(t.enter){let e=t.enter(a,i);if(e!==void 0){if(e===null||Array.isArray(e))return e;a=e}}let o=t[a.type];if(o){let e=o(a,i);if(e!==void 0){if(e===null||Array.isArray(e))return e;a=e}}switch(a.type){case m.Program:{let e=n(a.body,a);a={...a,body:e};break}case m.Element:{let e=a.attributes;if(t.Attribute&&Array.isArray(a.attributes)){let n=[];for(let e of a.attributes){let r=t.Attribute(e,a);r==null?r===void 0&&n.push(e):n.push(r)}e=n}let r=n(a.children,a);a={...a,attributes:e,children:r};break}case m.If:{let e=n(a.consequent,a),t=a.alternate;Array.isArray(a.alternate)?t=n(a.alternate,a):a.alternate!==null&&typeof a.alternate==`object`&&(t=r(a.alternate,a)),a={...a,consequent:e,alternate:t};break}case m.For:{let e=n(a.body,a);a={...a,body:e};break}case m.Switch:if(Array.isArray(a.cases)){let e=a.cases.map(e=>({...e,body:n(e.body,a)}));a={...a,cases:e}}break;case m.Async:{let e=n(a.body,a),t=a.fallback?n(a.fallback,a):null,r=a.catchBranch;a.catchBranch&&(r={...a.catchBranch,body:n(a.catchBranch.body,a)}),a={...a,body:e,fallback:t,catchBranch:r};break}}if(t.leave){let e=t.leave(a,i);if(e!==void 0)return e}return a}return r(e,null)}var k=class{rawAst;constructor(e){this.rawAst=e}transform(){return O(O(this.rawAst,{Text:e=>{if(typeof e.content==`string`&&this.isWhitespaceOnly(e.content))return null}}),{Interpolation:e=>this.transformInterpolation(e),Element:e=>{if(e.tagName===`script`)return this.transformScriptElement(e);if(e.attributes.some(e=>e.value!==null&&typeof e.value!=`string`))return{...e,attributes:e.attributes.map(e=>e.type===m.Attribute&&e.value!==null&&typeof e.value!=`string`&&e.value.type===m.Interpolation?{...e,value:this.transformInterpolation(e.value)}:e)}},If:e=>{if(typeof e.test==`string`&&e.test.trim().length>0)return{...e,test:l.parseExpressionAt(e.test,0,{ecmaVersion:`latest`})}},For:e=>({...e,iterable:typeof e.iterable==`string`?l.parseExpressionAt(e.iterable,0,{ecmaVersion:`latest`}):e.iterable,key:typeof e.key==`string`&&e.key.trim().length>0?l.parseExpressionAt(e.key,0,{ecmaVersion:`latest`}):e.key??null}),Switch:e=>{let t=typeof e.discriminant==`string`&&e.discriminant.trim().length>0?l.parseExpressionAt(e.discriminant,0,{ecmaVersion:`latest`}):e.discriminant,n=e.cases.map(e=>{let t=e.expression!==null&&typeof e.expression==`string`&&e.expression.trim().length>0?l.parseExpressionAt(e.expression,0,{ecmaVersion:`latest`}):e.expression;return{...e,expression:t}});return{...e,discriminant:t,cases:n}},Async:e=>({...e,promise:typeof e.promise==`string`&&e.promise.trim().length>0?l.parseExpressionAt(e.promise,0,{ecmaVersion:`latest`}):e.promise})})}transformInterpolation(e){if(typeof e.expression!=`string`)return e;let t;try{t=l.parseExpressionAt(e.expression,0,{ecmaVersion:`latest`,allowAwaitOutsideFunction:!0})}catch(t){throw new g(`Failed to parse JS expression in interpolation: ${t instanceof Error?t.message:String(t)}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{...e,expression:t}}transformScriptElement(e){let t=e.children.map(e=>{if(e.type===m.Text&&typeof e.content==`string`){let t;try{let n=l.parse(e.content,{ecmaVersion:`latest`,sourceType:`module`,allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:!0});t=n.body.length===1&&n.body[0]!==void 0?n.body[0]:n.body}catch(t){throw new g(`Failed to parse script tag JS content: ${t instanceof Error?t.message:String(t)}`,e.loc.start.line,e.loc.start.column,e.loc.start.offset)}return{...e,content:t}}return e});return{...e,children:t}}isWhitespaceOnly(e){return e.length>0&&/^\s*$/.test(e)}},A=class{ast;bytecode=[];constants=[];nextRegisterId=0;declaredVars=new Set;imports=[];bindingPositions=new Map;derivedBindings=[];pendingDerived=[];effectBindings=[];pendingEffects=[];constructor(e){this.ast=e}generate(){if(this.bytecode=[],this.constants=[],this.nextRegisterId=0,this.declaredVars=new Set,this.imports=[],this.bindingPositions=new Map,this.derivedBindings=[],this.pendingDerived=[],this.effectBindings=[],this.pendingEffects=[],this.collectDeclaredVars(this.ast.body),this.processDerivedBindings(),this.processEffectBindings(),this.ast.body.length===0){let e=this.allocRegister();return this.emit(_.CREATE_FRAGMENT,e),{bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings(),declaredVars:[...this.declaredVars],derived:this.derivedBindings,effects:this.effectBindings,imports:this.imports}}if(this.ast.body.length===1&&this.ast.body[0]?.type===m.Element){let e=this.allocRegister();this.compileElement(this.ast.body[0],e)}else{let e=this.allocRegister();this.emit(_.CREATE_FRAGMENT,e);for(let t of this.ast.body)this.compileNode(t,e)}return{bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings(),declaredVars:[...this.declaredVars],derived:this.derivedBindings,effects:this.effectBindings,imports:this.imports}}compileNode(e,t){switch(e.type){case m.Element:e.tagName===`script`?this.compileScriptElement(e):this.compileElementNode(e,t);break;case m.Text:this.compileTextNode(e,t);break;case m.Interpolation:this.compileInterpolationNode(e,t);break;case m.Comment:this.compileCommentNode(e,t);break;case m.If:this.compileIfNode(e,t);break;case m.Switch:this.compileSwitchNode(e,t);break;case m.For:this.compileForNode(e,t);break;case m.Async:this.compileAsyncNode(e,t);break}}filterRuntimeScriptAst(e){if(Array.isArray(e)){let t=e.map(e=>this.filterScriptStatement(e)).filter(Boolean);return t.length===1?t[0]:t}return this.filterScriptStatement(e)}filterScriptStatement(e){if(!e||typeof e!=`object`)return e;if(e.type===`ImportDeclaration`||e.type===`ExpressionStatement`&&e.expression?.type===`CallExpression`&&e.expression.callee?.type===`Identifier`&&e.expression.callee.name===`effect`)return null;if(e.type===`VariableDeclaration`){let t=e.declarations.filter(e=>!(e.init?.type===`CallExpression`&&e.init.callee?.type===`Identifier`&&e.init.callee.name===`derive`));return t.length===0?null:{...e,declarations:t}}return e}compileScriptElement(e){for(let t of e.children)if(t.type===m.Text&&typeof t.content==`object`&&t.content!==null){let e=this.filterRuntimeScriptAst(t.content);if(e!==null&&(!Array.isArray(e)||e.length>0)){let t=this.addScriptConstant(e);this.emit(_.EXEC_SCRIPT,t)}}}isComponentTag(e){if(this.imports.some(t=>t.localName===e))return!0;let t=e.charAt(0);return t!==``&&t===t.toUpperCase()&&t!==t.toLowerCase()}compileElement(e,t){let n=this.isComponentTag(e.tagName),r=this.addConstant(e.tagName);if(n){let n={__drift_props__:!0};for(let t of e.attributes)if(t.type===m.Attribute){if(t.value===null)n[t.name]=!0;else if(typeof t.value==`string`)n[t.name]=t.value;else if(t.value.type===m.Interpolation){let e=t.value.expression;if(e&&typeof e==`object`&&e.type){let r=L(e);n[t.name]={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => (${r})`}}else n[t.name]=e}}let i=null;if(e.children&&e.children.length>0){let t=e.children.filter(e=>!(e.type===m.Text&&typeof e.content==`string`&&e.content.trim()===``));t.length>0&&(i=this.compileNodesToSubModule(t),n.__drift_children__=this.addConstant(i))}let a=Object.keys(n).length>1?this.addConstant(n):255,o=this.bytecode.length;this.emit(_.MOUNT_COMPONENT,t,r,a),this.emit(_.RETURN);for(let t of e.attributes)t.type===m.Attribute&&t.value!==null&&typeof t.value!=`string`&&t.value.type===m.Interpolation&&this.recordBindingPositions(t.value.expression,o);if(i)for(let e of i.reactiveBindings)this.declaredVars.has(e.variable)&&(this.bindingPositions.has(e.variable)||this.bindingPositions.set(e.variable,[]),this.bindingPositions.get(e.variable).push(o))}else{this.emit(_.CREATE_ELEMENT,t,r);for(let n of e.attributes)this.compileAttributeNode(n,t);for(let n of e.children)this.compileNode(n,t)}}compileElementNode(e,t){let n=this.allocRegister();this.compileElement(e,n),this.emit(_.APPEND_CHILD,t,n)}compileAttributeNode(e,t){let n=this.addConstant(e.name);if(e.value===null){let e=this.addConstant(!0);this.emit(_.SET_ATTR,t,n,e,0)}else if(typeof e.value==`string`){let r=this.addConstant(e.value);this.emit(_.SET_ATTR,t,n,r,0)}else if(e.value.type===m.Interpolation){let r=this.addExpressionConstant(e.value.expression),i=this.bytecode.length;this.emit(_.SET_ATTR,t,n,r,1),this.emit(_.RETURN),this.recordBindingPositions(e.value.expression,i)}}compileTextNode(e,t){let n=this.allocRegister(),r=this.addConstant(e.content);this.emit(_.CREATE_TEXT,n,r),this.emit(_.APPEND_CHILD,t,n)}compileInterpolationNode(e,t){let n=this.allocRegister(),r=this.addExpressionConstant(e.expression),i=this.bytecode.length;this.emit(_.INTERPOLATE_TEXT,n,r),this.emit(_.RETURN),this.emit(_.APPEND_CHILD,t,n),this.recordBindingPositions(e.expression,i)}compileCommentNode(e,t){let n=this.allocRegister(),r=this.addConstant(e.content);this.emit(_.CREATE_COMMENT,n,r),this.emit(_.APPEND_CHILD,t,n)}compileNodesToSubModule(e){let t=this.bytecode,n=this.constants,r=this.nextRegisterId,i=this.bindingPositions;this.bytecode=[],this.constants=[],this.nextRegisterId=0,this.bindingPositions=new Map;let a=this.allocRegister();this.emit(_.CREATE_FRAGMENT,a);for(let t of e)this.compileNode(t,a);let o={bytecode:this.bytecode,constants:this.constants,reactiveBindings:this.buildReactiveBindings()};return this.bytecode=t,this.constants=n,this.nextRegisterId=r,this.bindingPositions=i,o}collectDepsFromSubModule(e,t){let n=new Set;for(let t=0;t<e.reactiveBindings.length;t++)n.add(e.reactiveBindings[t].variable);if(t)for(let e of this.extractIdentifiers(t))this.declaredVars.has(e)&&n.add(e);return[...n]}compileIfNode(e,t){let n=this.compileNodesToSubModule(e.consequent),r=this.addConstant(n),i=255,a=null;if(e.alternate!==null){let t;t=Array.isArray(e.alternate)?e.alternate:[e.alternate],a=this.compileNodesToSubModule(t),i=this.addConstant(a)}let o=new Set(this.collectDepsFromSubModule(n,e.test));if(e.extraDeps){for(let t of this.extractIdentifiers(e.extraDeps))this.declaredVars.has(t)&&o.add(t);let t=Array.from(o);n.constants&&!n.constants.some(e=>Array.isArray(e))&&n.constants.push(t)}if(a)for(let e of this.collectDepsFromSubModule(a))o.add(e);let s=this.addConstant(Array.from(o)),c=this.addExpressionConstant(e.test);this.emit(_.REACTIVE_IF,t,c,r,i,s)}compileSwitchNode(e,t){let n=this.addExpressionConstant(e.discriminant),r=[],i=255,a=[];for(let t of e.cases)if(t.expression===null){let e=this.compileNodesToSubModule(t.body);a.push(e),i=this.addConstant(e)}else{let e=this.addExpressionConstant(t.expression),n=this.compileNodesToSubModule(t.body);a.push(n);let i=this.addConstant(n);r.push({testIdx:e,modIdx:i})}let o=this.addConstant(r),s=new Set;for(let t of this.extractIdentifiers(e.discriminant))this.declaredVars.has(t)&&s.add(t);for(let t of e.cases)if(t.expression!==null)for(let e of this.extractIdentifiers(t.expression))this.declaredVars.has(e)&&s.add(e);for(let e of a)for(let t of this.collectDepsFromSubModule(e))s.add(t);let c=this.addConstant(Array.from(s));this.emit(_.REACTIVE_SWITCH,t,n,o,i,c)}compileForNode(e,t){let n=new Set;if(e.pattern)for(let t of M(e.pattern))n.add(t);else e.item&&n.add(e.item);e.index!==null&&n.add(e.index);let r=[];for(let e of n)this.declaredVars.has(e)||(this.declaredVars.add(e),r.push(e));let i=this.compileNodesToSubModule(e.body);for(let e of r)this.declaredVars.delete(e);let a=this.addConstant(i),o=this.addExpressionConstant(e.iterable),s=this.addConstant(e.item),c=e.index===null?255:this.addConstant(e.index),l=e.key?this.addExpressionConstant(e.key):255,u=255;e.pattern&&(u=this.addConstant(I(e.pattern,e.index)));let d=new Set;for(let t of this.extractIdentifiers(e.iterable))this.declaredVars.has(t)&&d.add(t);if(e.key)for(let t of this.extractIdentifiers(e.key))this.declaredVars.has(t)&&d.add(t);let f=this.addConstant([...d]),p=new Set;for(let e of i.reactiveBindings)!d.has(e.variable)&&!n.has(e.variable)&&p.add(e.variable);let m=this.addConstant([...p]),h=[...d,...p],g=this.addConstant(h);this.emit(_.REACTIVE_FOR,t,o,s,c,l,a,g,f,m,u)}compileAsyncNode(e,t){let n=this.compileNodesToSubModule(e.body),r=this.addConstant(n),i=e.fallback?this.compileNodesToSubModule(e.fallback):null,a=i?this.addConstant(i):255,o=255;if(e.catchBranch){let t=this.compileNodesToSubModule(e.catchBranch.body);o=this.addConstant({errorVar:e.catchBranch.errorVar,module:t})}let s=this.addExpressionConstant(e.promise),c=this.addConstant(e.alias),l=255;e.aliasAst&&(l=this.addConstant(I(e.aliasAst,null)));let u=new Set;for(let t of this.collectDepsFromSubModule(n,e.promise))u.add(t);if(i)for(let e of this.collectDepsFromSubModule(i))u.add(e);let d=this.addConstant(Array.from(u));this.emit(_.REACTIVE_ASYNC,t,s,c,r,a,o,d,l)}collectDeclaredVars(e){for(let t of e)if(t.type===m.Element&&t.tagName===`script`){for(let e of t.children)if(e.type===m.Text&&typeof e.content==`object`&&e.content!==null){let t=e.content;if(Array.isArray(t))for(let e of t)this.extractVarNames(e);else this.extractVarNames(t)}}}extractVarNames(e){if(!(!e||typeof e!=`object`)){if(e.type===`VariableDeclaration`)for(let t of e.declarations){for(let e of M(t.id))this.declaredVars.add(e);t.id?.type===`Identifier`&&t.init?.type===`CallExpression`&&t.init.callee?.type===`Identifier`&&t.init.callee.name===`derive`&&t.init.arguments&&t.init.arguments.length>0&&this.pendingDerived.push({name:t.id.name,arg:t.init.arguments[0]})}else if(e.type===`ExpressionStatement`&&e.expression?.type===`CallExpression`&&e.expression.callee?.type===`Identifier`&&e.expression.callee.name===`effect`&&Array.isArray(e.expression.arguments)&&e.expression.arguments.length>0)this.pendingEffects.push({arg:e.expression.arguments[0]});else if((e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&e.id?.type===`Identifier`)this.declaredVars.add(e.id.name);else if(e.type===`ImportDeclaration`&&Array.isArray(e.specifiers)){let t=typeof e.source?.value==`string`?e.source.value:``;if(e.specifiers.length===0)this.imports.push({localName:``,source:t,isDefault:!1,isSideEffect:!0});else for(let n of e.specifiers)if(n.local?.type===`Identifier`){let e=n.local.name;this.declaredVars.add(e);let r=n.type===`ImportDefaultSpecifier`,i=n.type===`ImportNamespaceSpecifier`,a=n.type===`ImportSpecifier`&&n.imported?.type===`Identifier`?n.imported.name:void 0;this.imports.push({localName:e,source:t,isDefault:r,isNamespace:i,importedName:a})}}}}processDerivedBindings(){for(let e of this.pendingDerived){let{name:t,arg:n}=e,r=n,i=!1;(n.type===`ArrowFunctionExpression`||n.type===`FunctionExpression`)&&(n.body?.type===`BlockStatement`&&(i=!0),r=n.body);let a=[...this.extractIdentifiers(r)].filter(e=>e!==t&&this.declaredVars.has(e)),o=L(r),s;s=i?{__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => ${o}`}:{__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => (${o})`};let c=this.addConstant(s);this.derivedBindings.push({name:t,deps:a,exprIdx:c})}}processEffectBindings(){for(let e of this.pendingEffects){let{arg:t}=e,n=t,r=!1,i=!!t?.async;(t.type===`ArrowFunctionExpression`||t.type===`FunctionExpression`)&&(t.body?.type===`BlockStatement`&&(r=!0),n=t.body);let a=[...this.extractIdentifiers(n)].filter(e=>this.declaredVars.has(e)),o=L(n),s=i?`async `:``,c;c=r?{__drift_fn__:`${s}(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => ${o}`}:{__drift_fn__:`${s}(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => (${o})`};let l=this.addConstant(c);this.effectBindings.push({deps:a,exprIdx:l})}}extractIdentifiers(e){let t=new Set;if(!e||typeof e!=`object`)return t;try{u.ancestor(e,{Identifier(e,n){let r=n[n.length-2];r&&(r.type===`MemberExpression`&&r.property===e&&!r.computed||(r.type===`Property`||r.type===`MethodDefinition`||r.type===`PropertyDefinition`)&&r.key===e&&!r.computed)||t.add(e.name)}})}catch{}return t}recordBindingPositions(e,t){if(this.declaredVars.size===0)return;let n=this.extractIdentifiers(e);for(let e of n)this.declaredVars.has(e)&&(this.bindingPositions.has(e)||this.bindingPositions.set(e,[]),this.bindingPositions.get(e).push(t))}buildReactiveBindings(){let e=[];for(let[t,n]of this.bindingPositions)e.push({variable:t,positions:n});return e}allocRegister(){return this.nextRegisterId++}addExpressionConstant(e){let t=L(e),n=[];for(let t of this.extractIdentifiers(e))this.declaredVars.has(t)&&n.push(t);let r={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => (${t})`,deps:n};return this.addConstant(r)}addScriptConstant(e){let t={__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => { ${L(e)}; }`};return this.addConstant(t)}addConstant(e){let t=this.constants.findIndex(t=>this.isConstantEqual(t,e));return t===-1?(this.constants.push(e),this.constants.length-1):t}isConstantEqual(e,t){return e===t||typeof e==`object`&&typeof t==`object`&&e!==null&&t!==null&&JSON.stringify(e)===JSON.stringify(t)}emit(e,...t){this.bytecode.push(e,...t)}};function j(e){return!e||typeof e!=`object`?null:e.type===`Identifier`?e.name:e.type===`MemberExpression`?j(e.object):null}function M(e){let t=[];function n(e){if(!(!e||typeof e!=`object`))if(e.type===`Identifier`)t.push(e.name);else if(e.type===`ObjectPattern`&&Array.isArray(e.properties))for(let t of e.properties)t.type===`Property`?n(t.value):t.type===`RestElement`&&n(t.argument);else if(e.type===`ArrayPattern`&&Array.isArray(e.elements))for(let t of e.elements)t&&n(t);else e.type===`AssignmentPattern`?n(e.left):e.type===`RestElement`&&n(e.argument)}return n(e),t}function N(e,t){if(!e)return``;switch(e.type){case`Identifier`:return e.name;case`AssignmentPattern`:return`${N(e.left,t)} = ${L(e.right,t)}`;case`RestElement`:return`...${N(e.argument,t)}`;case`ArrayPattern`:return`[${(e.elements||[]).map(e=>e?N(e,t):``).join(`, `)}]`;case`ObjectPattern`:return`{ ${(e.properties||[]).map(e=>{if(e.type===`Property`){let n=e.key?.name||(typeof e.key?.value==`string`?JSON.stringify(e.key.value):e.key?.value?String(e.key.value):L(e.key,t));if(e.value?.type===`AssignmentPattern`){let r=e.value.left?.name||N(e.value.left,t),i=L(e.value.right,t);return n===r||e.shorthand?`${n} = ${i}`:`${n}: ${r} = ${i}`}else if(e.value?.type===`Identifier`&&e.value.name===n)return n;else return`${n}: ${N(e.value,t)}`}else if(e.type===`RestElement`)return`...${N(e.argument,t)}`;return``}).filter(Boolean).join(`, `)} }`;default:return e.name||L(e,t)}}function P(e,t,n){return n&&n.has(e)?`(${e} = ${t})`:`(typeof setScopeValue === 'function' && scope ? setScopeValue(scope, ${JSON.stringify(e)}, ${t}) : ((scope || {})[${JSON.stringify(e)}] = ${t}))`}function F(e,t,n,r={count:0}){let i=[];if(!e)return i;if(e.type===`Identifier`)return i.push(P(e.name,t,n)),i;if(e.type===`AssignmentPattern`){let a=`((${t} !== undefined) ? ${t} : ${L(e.right,n)})`;if(e.left?.type===`Identifier`)i.push(P(e.left.name,a,n));else{let t=`_t${r.count++}`;i.push(`const ${t} = ${a}`),i.push(...F(e.left,t,n,r))}return i}if(e.type===`ObjectPattern`){for(let a of e.properties||[])if(a.type===`Property`){let e=a.computed?L(a.key,n):a.key?.name===void 0?typeof a.key?.value==`string`||typeof a.key?.value==`number`?JSON.stringify(a.key.value):L(a.key,n):JSON.stringify(a.key.name);if(a.value?.type===`Identifier`){let r=`(${t} ? ${t}[${e}] : undefined)`;i.push(P(a.value.name,r,n))}else if(a.value?.type===`AssignmentPattern`){let o=`((${t} && ${t}[${e}] !== undefined) ? ${t}[${e}] : ${L(a.value.right,n)})`;if(a.value.left?.type===`Identifier`)i.push(P(a.value.left.name,o,n));else{let e=`_t${r.count++}`;i.push(`const ${e} = ${o}`),i.push(...F(a.value.left,e,n,r))}}else if(a.value?.type===`ObjectPattern`||a.value?.type===`ArrayPattern`){let o=`_t${r.count++}`,s=`(${t} ? ${t}[${e}] : undefined)`;i.push(`const ${o} = ${s}`),i.push(...F(a.value,o,n,r))}else{let r=a.value?.name||L(a.value,n);if(r){let a=`(${t} ? ${t}[${e}] : undefined)`;i.push(P(r,a,n))}}}else if(a.type===`RestElement`){let r=a.argument?.name||L(a.argument,n);if(r){(e.properties||[]).filter(e=>e.type===`Property`).map(e=>{let t=e.key?.name===void 0?typeof e.key?.value==`string`?e.key.value:null:e.key.name;return t==null?null:JSON.stringify(t)}).filter(Boolean);let a=(e.properties||[]).filter(e=>e.type===`Property`).map(e=>{let t=e.key?.name===void 0?typeof e.key?.value==`string`?e.key.value:null:e.key.name;return t==null?null:String(t)}).filter(Boolean).join(`, `),o=`(((${a.length>0?`{ ${a}, ...${r} }`:`{ ...${r} }`}) => ${r})(${t} ?? {}))`;i.push(P(r,o,n))}}return i}if(e.type===`ArrayPattern`){let a=`_a${r.count++}`;i.push(`const ${a} = (typeof resolveIterable === 'function' ? resolveIterable(${t}) : (${t} || []))`);let o=e.elements||[];for(let e=0;e<o.length;e++){let t=o[e];if(t){if(t.type===`Identifier`){let r=`(${a} ? ${a}[${e}] : undefined)`;i.push(P(t.name,r,n))}else if(t.type===`AssignmentPattern`){let o=L(t.right,n),s=`((${a} && ${a}[${e}] !== undefined) ? ${a}[${e}] : ${o})`;if(t.left?.type===`Identifier`)i.push(P(t.left.name,s,n));else{let e=`_t${r.count++}`;i.push(`const ${e} = ${s}`),i.push(...F(t.left,e,n,r))}}else if(t.type===`RestElement`){let r=t.argument?.name||L(t.argument,n);if(r){let t=`((${a} && typeof ${a}.slice === 'function') ? ${a}.slice(${e}) : [])`;i.push(P(r,t,n))}}else if(t.type===`ObjectPattern`||t.type===`ArrayPattern`){let o=`_t${r.count++}`,s=`(${a} ? ${a}[${e}] : undefined)`;i.push(`const ${o} = ${s}`),i.push(...F(t,o,n,r))}}}return i}return i}function I(e,t){let n=[],r=F(e,`_item`,void 0,{count:0});return n.push(...r),t&&n.push(P(t,`_index`,void 0)),{__drift_fn__:`(scope, declaredVars, setScopeValue, inScopeChain, resolveIterable, getScopeValue) => (_item, _index) => { ${n.join(`; `)}; }`}}function L(e,t){if(e==null)return`undefined`;if(typeof e!=`object`)return typeof e==`string`?JSON.stringify(e):String(e);if(Array.isArray(e))return e.map(e=>L(e,t)).join(`; `);switch(e.type){case`Identifier`:return t&&t.has(e.name)?e.name:e.name===`undefined`?`undefined`:`getScopeValue(scope, ${JSON.stringify(e.name)})`;case`Literal`:return typeof e.raw==`string`?e.raw:typeof e.value==`string`?JSON.stringify(e.value):String(e.value);case`BinaryExpression`:case`LogicalExpression`:return`(${L(e.left,t)} ${e.operator} ${L(e.right,t)})`;case`UnaryExpression`:return`(${e.operator} ${L(e.argument,t)})`;case`AwaitExpression`:return`(await ${L(e.argument,t)})`;case`YieldExpression`:return e.delegate?`(yield* ${e.argument?L(e.argument,t):``})`:`(yield ${e.argument?L(e.argument,t):``})`;case`ConditionalExpression`:return`(${L(e.test,t)} ? ${L(e.consequent,t)} : ${L(e.alternate,t)})`;case`MemberExpression`:{let n=e.optional?`?.`:`.`;return e.computed?e.optional?`(${L(e.object,t)}?.[${L(e.property,t)}])`:`(${L(e.object,t)}[${L(e.property,t)}])`:`(${L(e.object,t)}${n}${e.property.name})`}case`CallExpression`:{let n=L(e.callee,t),r=e.arguments?e.arguments.map(e=>L(e,t)).join(`, `):``;return`(${n}${e.optional?`?.(`:`(`}${r}))`}case`AssignmentExpression`:{let n=L(e.right,t);if(e.left?.type===`Identifier`){let r=e.left.name;if(t&&t.has(r))return`(${r} ${e.operator} ${n})`;if(e.operator===`=`)return`(typeof setScopeValue === 'function' ? setScopeValue(scope, ${JSON.stringify(r)}, ${n}) : ((scope || {})[${JSON.stringify(r)}] = ${n}))`;{let t=e.operator.slice(0,-1);return`(typeof setScopeValue === 'function' ? setScopeValue(scope, ${JSON.stringify(r)}, (scope[${JSON.stringify(r)}] ${t} ${n})) : ((scope || {})[${JSON.stringify(r)}] ${e.operator} ${n}))`}}if(e.left?.type===`MemberExpression`){let r=j(e.left),i=`(${L(e.left,t)} ${e.operator} ${n})`;if(r&&(!t||!t.has(r)))return`(() => { const _res = ${i}; if (typeof setScopeValue === 'function' && scope && typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(r)})) setScopeValue(scope, ${JSON.stringify(r)}, scope[${JSON.stringify(r)}]); return _res; })()`}return e.left?.type===`ObjectPattern`||e.left?.type===`ArrayPattern`?`((_val) => { ${F(e.left,`_val`,t).join(`; `)}; return _val; })(${n})`:`(${L(e.left,t)} ${e.operator} ${n})`}case`UpdateExpression`:if(e.argument?.type===`Identifier`){let n=e.argument.name;if(t&&t.has(n))return e.prefix?`(${e.operator}${n})`:`(${n}${e.operator})`;let r=e.operator===`++`?`+`:`-`;return e.prefix?`(typeof setScopeValue === 'function' ? (setScopeValue(scope, ${JSON.stringify(n)}, (Number(scope[${JSON.stringify(n)}]) || 0) ${r} 1), scope[${JSON.stringify(n)}]) : ((scope || {})[${JSON.stringify(n)}] = (Number((scope || {})[${JSON.stringify(n)}]) || 0) ${r} 1))`:`(() => { const _v = Number(scope[${JSON.stringify(n)}]) || 0; if (typeof setScopeValue === 'function') setScopeValue(scope, ${JSON.stringify(n)}, _v ${r} 1); else (scope || {})[${JSON.stringify(n)}] = _v ${r} 1; return _v; })()`}if(e.argument?.type===`MemberExpression`){let n=j(e.argument),r=e.prefix?`(${e.operator}${L(e.argument,t)})`:`(${L(e.argument,t)}${e.operator})`;if(n&&(!t||!t.has(n)))return`(() => { const _res = ${r}; if (typeof setScopeValue === 'function' && scope && typeof inScopeChain === 'function' && inScopeChain(scope, ${JSON.stringify(n)})) setScopeValue(scope, ${JSON.stringify(n)}, scope[${JSON.stringify(n)}]); return _res; })()`}return e.prefix?`(${e.operator}${L(e.argument,t)})`:`(${L(e.argument,t)}${e.operator})`;case`SequenceExpression`:return`(${e.expressions?e.expressions.map(e=>L(e,t)).join(`, `):``})`;case`ArrayExpression`:return`[${e.elements?e.elements.map(e=>e?.type===`SpreadElement`?`...`+L(e.argument,t):L(e,t)).join(`, `):``}]`;case`ObjectExpression`:return`{${e.properties?e.properties.map(e=>{if(e.type===`SpreadElement`)return`...`+L(e.argument,t);let n=e.computed?`[${L(e.key,t)}]`:e.key?.name||(typeof e.key?.value==`string`?JSON.stringify(e.key.value):String(e.key?.value??``));if(e.kind===`get`||e.kind===`set`){let r=e.value,i=new Set(t),a=[];if(r.params)for(let e of r.params){for(let t of M(e))i.add(t);a.push(N(e,i))}let o=r.body?.type===`BlockStatement`?`{ ${r.body.body.map(e=>L(e,i)).filter(Boolean).join(`; `)}; }`:`{ ${L(r.body,i)}; }`;return`${e.kind} ${n}(${a.join(`, `)}) ${o}`}if(e.method){let r=e.value,i=new Set(t),a=[];if(r.params)for(let e of r.params){for(let t of M(e))i.add(t);a.push(N(e,i))}let o=r.async?`async `:``,s=r.generator?`*`:``,c=r.body?.type===`BlockStatement`?`{ ${r.body.body.map(e=>L(e,i)).filter(Boolean).join(`; `)}; }`:`{ ${L(r.body,i)}; }`;return`${o}${s}${n}(${a.join(`, `)}) ${c}`}return`${n}: ${L(e.value,t)}`}).join(`, `):``}}`;case`RestElement`:case`SpreadElement`:return`...${L(e.argument,t)}`;case`AssignmentPattern`:return`${L(e.left,t)} = ${L(e.right,t)}`;case`TemplateLiteral`:return`\`${e.quasis?e.quasis.map((n,r)=>(n.value?.raw??``)+(e.expressions&&e.expressions[r]?"${"+L(e.expressions[r],t)+`}`:``)).join(``):``}\``;case`TaggedTemplateExpression`:return`${L(e.tag,t)}${L(e.quasi,t)}`;case`ThisExpression`:return`this`;case`Super`:return`super`;case`BlockStatement`:{let n=new Set(t);if(Array.isArray(e.body))for(let t of e.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of M(e.id))n.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&n.add(t.id.name);return`{ ${(e.body?e.body.map(e=>L(e,n)).filter(Boolean):[]).join(`; `)}; }`}case`ExpressionStatement`:return L(e.expression,t);case`ReturnStatement`:return`return ${e.argument?L(e.argument,t):``}`;case`ThrowStatement`:return`throw ${e.argument?L(e.argument,t):``}`;case`BreakStatement`:return e.label?`break ${e.label.name}`:`break`;case`ContinueStatement`:return e.label?`continue ${e.label.name}`:`continue`;case`LabeledStatement`:return`${e.label.name}: ${L(e.body,t)}`;case`TryStatement`:return`try ${L(e.block,t)} ${e.handler?L(e.handler,t):``} ${e.finalizer?`finally ${L(e.finalizer,t)}`:``}`.trim();case`CatchClause`:{let n=new Set(t),r=``;if(e.param){for(let t of M(e.param))n.add(t);r=N(e.param,n)}let i=L(e.body,n);return r?`catch (${r}) ${i}`:`catch ${i}`}case`SwitchStatement`:return`switch (${L(e.discriminant,t)}) { ${e.cases?e.cases.map(e=>L(e,t)).join(` `):``} }`;case`SwitchCase`:{let n=e.test?`case ${L(e.test,t)}:`:`default:`,r=e.consequent?e.consequent.map(e=>L(e,t)).filter(Boolean).join(`; `):``;return`${n} ${r?r+`;`:``}`}case`IfStatement`:return`if (${L(e.test,t)}) ${e.consequent.type===`BlockStatement`?L(e.consequent,t):`{ ${L(e.consequent,t)}; }`}${e.alternate?` else ${e.alternate.type===`BlockStatement`||e.alternate.type===`IfStatement`?L(e.alternate,t):`{ ${L(e.alternate,t)}; }`}`:``}`;case`ForStatement`:{let n=new Set(t);if(e.init?.type===`VariableDeclaration`&&e.init.declarations)for(let t of e.init.declarations)for(let e of M(t.id))n.add(e);let r=``;e.init?.type===`VariableDeclaration`&&e.init.declarations?r=(e.init.kind||`let`)+` `+e.init.declarations.map(e=>`${e.id?.type===`Identifier`?e.id.name:L(e.id,n)}${e.init?` = ${L(e.init,n)}`:``}`).join(`, `):e.init&&(r=L(e.init,n));let i=e.test?L(e.test,n):``,a=e.update?L(e.update,n):``,o=e.body?.type===`BlockStatement`?L(e.body,n):`{ ${e.body?L(e.body,n):``}; }`;return`for (${r}; ${i}; ${a}) ${o}`}case`ForOfStatement`:{let n=new Set(t),r=``;if(e.left?.type===`VariableDeclaration`){let t=e.left.kind||`let`,i=e.left.declarations?.[0];if(i){for(let e of M(i.id))n.add(e);r=`${t} ${i.id?.type===`Identifier`?i.id.name:L(i.id,n)}`}}else e.left?.type===`Identifier`?(n.add(e.left.name),r=e.left.name):e.left&&(r=L(e.left,n));let i=`(typeof resolveIterable === 'function' ? resolveIterable : (x) => x || [])(${L(e.right,t)})`,a=e.body?.type===`BlockStatement`?L(e.body,n):`{ ${e.body?L(e.body,n):``}; }`;return`for ${e.await?`await `:``}(${r} of ${i}) ${a}`}case`ForInStatement`:{let n=new Set(t),r=``;if(e.left?.type===`VariableDeclaration`){let t=e.left.kind||`let`,i=e.left.declarations?.[0];if(i){for(let e of M(i.id))n.add(e);r=`${t} ${i.id?.type===`Identifier`?i.id.name:L(i.id,n)}`}}else e.left?.type===`Identifier`?(n.add(e.left.name),r=e.left.name):e.left&&(r=L(e.left,n));let i=L(e.right,t),a=e.body?.type===`BlockStatement`?L(e.body,n):`{ ${e.body?L(e.body,n):``}; }`;return`for (${r} in ${i}) ${a}`}case`WhileStatement`:return`while (${L(e.test,t)}) ${e.body?.type===`BlockStatement`?L(e.body,t):`{ ${e.body?L(e.body,t):``}; }`}`;case`DoWhileStatement`:{let n=L(e.test,t);return`do ${e.body?.type===`BlockStatement`?L(e.body,t):`{ ${e.body?L(e.body,t):``}; }`} while (${n})`}case`ArrayPattern`:return`[ ${e.elements?e.elements.map(e=>e?e.type===`RestElement`?`...`+L(e.argument,t):e.type===`AssignmentPattern`?`${L(e.left,t)} = ${L(e.right,t)}`:e.name||L(e,t):``).join(`, `):``} ]`;case`ObjectPattern`:return`{ ${e.properties?e.properties.map(e=>{if(e.type===`Property`){let n=e.key?.name||L(e.key,t),r=e.value?.name||L(e.value,t);return n===r?n:`${n}: ${r}`}return e.type===`RestElement`?`...${L(e.argument,t)}`:``}).filter(Boolean).join(`, `):``} }`;case`VariableDeclaration`:{if(t){let n=[];if(e.declarations)for(let r of e.declarations){let e=r.id?.type===`Identifier`?r.id.name:L(r.id,t),i=r.init?L(r.init,t):void 0;i===void 0?n.push(`${e}`):n.push(`${e} = ${i}`)}return`${e.kind||`let`} ${n.join(`, `)}`}let n=[];if(e.declarations)for(let r of e.declarations)if(r.id?.type===`ObjectPattern`||r.id?.type===`ArrayPattern`){let e=r.init?L(r.init,t):`undefined`,i=F(r.id,`_init`,t);n.push(`((_init) => { ${i.join(`; `)}; return _init; })(${e})`)}else{let e=r.id?.name||L(r.id,t),i=r.init?L(r.init,t):`undefined`;n.push(`((scope || {})[${JSON.stringify(e)}] = ${i})`)}return`(${n.filter(Boolean).join(`, `)||`undefined`})`}case`FunctionDeclaration`:{let n=e.id?.name,r=new Set(t);n&&r.add(n);let i=[];if(e.params)for(let t of e.params){for(let e of M(t))r.add(e);i.push(N(t,r))}if(e.body?.type===`BlockStatement`&&Array.isArray(e.body.body))for(let t of e.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of M(e.id))r.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&r.add(t.id.name);let a=i.join(`, `),o=e.body?.type===`BlockStatement`?`{ ${e.body.body.map(e=>L(e,r)).filter(Boolean).join(`; `)}; }`:`{ ${L(e.body,r)}; }`,s=`${e.async?`async `:``}function${e.generator?`*`:``} ${n||``}(${a}) ${o}`;return n?`((scope || {})[${JSON.stringify(n)}] = ${s})`:s}case`ArrowFunctionExpression`:case`FunctionExpression`:{let n=new Set(t);e.id?.name&&n.add(e.id.name);let r=[];if(e.params)for(let t of e.params){for(let e of M(t))n.add(e);r.push(N(t,n))}if(e.body?.type===`BlockStatement`&&Array.isArray(e.body.body))for(let t of e.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of M(e.id))n.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&n.add(t.id.name);let i=r.join(`, `),a=e.async?`async `:``;if(e.type===`ArrowFunctionExpression`)return e.body?.type===`BlockStatement`?`(${a}(${i}) => ${`{ ${e.body.body.map(e=>L(e,n)).filter(Boolean).join(`; `)}; }`})`:`(${a}(${i}) => ${L(e.body,n)})`;{let t=e.generator?`*`:``,r=e.body?.type===`BlockStatement`?`{ ${e.body.body.map(e=>L(e,n)).filter(Boolean).join(`; `)}; }`:`{ ${L(e.body,n)}; }`;return`(${a}function${t} ${e.id?.name||``}(${i}) ${r})`}}case`ClassDeclaration`:case`ClassExpression`:{let n=e.id?.name,r=new Set(t);n&&r.add(n);let i=e.superClass?` extends ${L(e.superClass,t)}`:``,a=L(e.body,r),o=`class ${n||``}${i} ${a}`;return e.type===`ClassDeclaration`&&n?`((scope || {})[${JSON.stringify(n)}] = ${o})`:`(${o})`}case`ClassBody`:return`{ ${(e.body?e.body.map(e=>L(e,t)).filter(Boolean):[]).join(`; `)} }`;case`MethodDefinition`:{let n=e.static?`static `:``,r=e.kind===`get`||e.kind===`set`?`${e.kind} `:``,i=e.value?.async?`async `:``,a=e.value?.generator?`*`:``,o=e.computed?`[${L(e.key,t)}]`:e.key?.name||L(e.key,t),s=new Set(t),c=[];if(e.value?.params)for(let t of e.value.params){for(let e of M(t))s.add(e);c.push(N(t,s))}if(e.value?.body?.type===`BlockStatement`&&Array.isArray(e.value.body.body))for(let t of e.value.body.body)if(t.type===`VariableDeclaration`&&Array.isArray(t.declarations))for(let e of t.declarations)for(let t of M(e.id))s.add(t);else t.type===`FunctionDeclaration`&&t.id?.name&&s.add(t.id.name);return`${n}${i}${a}${r}${o}(${c.join(`, `)}) ${e.value?.body?L(e.value.body,s):`{}`}`}case`PropertyDefinition`:return`${e.static?`static `:``}${e.computed?`[${L(e.key,t)}]`:e.key?.name||L(e.key,t)}${e.value?` = ${L(e.value,t)}`:``}`;case`NewExpression`:return`new (${L(e.callee,t)})(${e.arguments?e.arguments.map(e=>L(e,t)).join(`, `):``})`;case`EmptyStatement`:case`ImportDeclaration`:case`ImportSpecifier`:case`ImportDefaultSpecifier`:case`ImportNamespaceSpecifier`:return``;case`ParenthesizedExpression`:case`ChainExpression`:return L(e.expression,t);default:return``}}function R(e,t=!1){let n=new k(new D(new S(e)).parse()).transform(),r=new A(n).generate();return t&&(console.log(`--- Transformed AST ---`),console.log(JSON.stringify(n,null,2)),console.log(`--- Compiled Module ---`),console.log(JSON.stringify(r,null,2))),r}exports.ASTNodeType=m,exports.DriftGenerator=A,exports.DriftLexer=S,exports.DriftLexerError=h,exports.DriftParser=D,exports.DriftParserError=g,exports.DriftTransformer=k,exports.ExprTokenKind=p,exports.LexerStateKind=f,exports.Opcode=_,exports.TokenType=d,exports.astToJS=L,exports.compile=R,exports.extractBindingNames=M,exports.traverseTemplateAST=O;
|