babel-preset-dlight
Advanced tools
Comparing version 1.0.0-beta.20 to 1.0.0-beta.21
@@ -1,2 +0,2 @@ | ||
var F=Object.defineProperty;var O=(f,e,t)=>e in f?F(f,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):f[e]=t;var C=(f,e,t)=>(O(f,typeof e!="symbol"?e+"":e,t),t);import T from"babel-plugin-syntax-typescript-new";import V from"@babel/plugin-syntax-decorators";import{minimatch as I}from"minimatch";import{parseView as S}from"@dlightjs/view-parser";import{parseReactivity as M}from"@dlightjs/reactivity-parser";import{generateSubView as j,generateView as $}from"@dlightjs/view-generator";var k=process.env.NODE_ENV==="development",E={class:"className",for:"htmlFor"},b=["push","pop","shift","unshift","splice","sort","reverse","add","delete","clear","set","delete","clear"],N=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","acronym","applet","basefont","bgsound","big","blink","center","dir","font","frame","frameset","isindex","keygen","listing","marquee","menuitem","multicol","nextid","nobr","noembed","noframes","param","plaintext","rb","rtc","spacer","strike","tt","xmp","animate","animateMotion","animateTransform","circle","clipPath","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","image","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tspan","use","view"],D=["Static","Prop","Env","Content","Children"],g="@dlightjs/dlight",x=Object.fromEntries(["createElement","setStyle","setDataset","setEvent","delegateEvent","setHTMLProp","setHTMLAttr","setHTMLProps","setHTMLAttrs","createTextNode","updateText","insertNode","ForNode","CondNode","ExpNode","EnvNode","SubViewNode","PropView","render"].map(f=>[f,`$$${f}`])),w={textContent:["*"],innerHTML:["*"],accept:["form","input"],acceptCharset:["form"],accesskey:["*"],action:["form"],align:["caption","col","colgroup","hr","iframe","img","table","tbody","td","tfoot","th","thead","tr"],allow:["iframe"],alt:["area","img","input"],async:["script"],autocapitalize:["*"],autocomplete:["form","input","select","textarea"],autofocus:["button","input","select","textarea"],autoplay:["audio","video"],background:["body","table","td","th"],bgColor:["body","col","colgroup","marquee","table","tbody","tfoot","td","th","tr"],border:["img","object","table"],buffered:["audio","video"],capture:["input"],charset:["meta"],checked:["input"],cite:["blockquote","del","ins","q"],className:["*"],color:["font","hr"],cols:["textarea"],colSpan:["td","th"],content:["meta"],contentEditable:["*"],contextmenu:["*"],controls:["audio","video"],coords:["area"],crossOrigin:["audio","img","link","script","video"],csp:["iframe"],data:["object"],dateTime:["del","ins","time"],decoding:["img"],default:["track"],defer:["script"],dir:["*"],dirname:["input","textarea"],disabled:["button","fieldset","input","optgroup","option","select","textarea"],download:["a","area"],draggable:["*"],enctype:["form"],enterKeyHint:["textarea","contenteditable"],htmlFor:["label","output"],form:["button","fieldset","input","label","meter","object","output","progress","select","textarea"],formAction:["input","button"],formEnctype:["button","input"],formMethod:["button","input"],formNoValidate:["button","input"],formTarget:["button","input"],headers:["td","th"],height:["canvas","embed","iframe","img","input","object","video"],hidden:["*"],high:["meter"],href:["a","area","base","link"],hreflang:["a","link"],httpEquiv:["meta"],id:["*"],integrity:["link","script"],intrinsicSize:["img"],inputMode:["textarea","contenteditable"],ismap:["img"],itemProp:["*"],kind:["track"],label:["optgroup","option","track"],lang:["*"],language:["script"],loading:["img","iframe"],list:["input"],loop:["audio","marquee","video"],low:["meter"],manifest:["html"],max:["input","meter","progress"],maxLength:["input","textarea"],minLength:["input","textarea"],media:["a","area","link","source","style"],method:["form"],min:["input","meter"],multiple:["input","select"],muted:["audio","video"],name:["button","form","fieldset","iframe","input","object","output","select","textarea","map","meta","param"],noValidate:["form"],open:["details","dialog"],optimum:["meter"],pattern:["input"],ping:["a","area"],placeholder:["input","textarea"],playsInline:["video"],poster:["video"],preload:["audio","video"],readonly:["input","textarea"],referrerPolicy:["a","area","iframe","img","link","script"],rel:["a","area","link"],required:["input","select","textarea"],reversed:["ol"],role:["*"],rows:["textarea"],rowSpan:["td","th"],sandbox:["iframe"],scope:["th"],scoped:["style"],selected:["option"],shape:["a","area"],size:["input","select"],sizes:["link","img","source"],slot:["*"],span:["col","colgroup"],spellcheck:["*"],src:["audio","embed","iframe","img","input","script","source","track","video"],srcdoc:["iframe"],srclang:["track"],srcset:["img","source"],start:["ol"],step:["input"],style:["*"],summary:["table"],tabIndex:["*"],target:["a","area","base","form"],title:["*"],translate:["*"],type:["button","input","embed","object","ol","script","source","style","menu","link"],usemap:["img","input","object"],value:["button","data","input","li","meter","option","progress","param","text"],width:["canvas","embed","iframe","img","input","object","video"],wrap:["textarea"],ariaAutocomplete:["*"],ariaChecked:["*"],ariaDisabled:["*"],ariaErrorMessage:["*"],ariaExpanded:["*"],ariaHasPopup:["*"],ariaHidden:["*"],ariaInvalid:["*"],ariaLabel:["*"],ariaLevel:["*"],ariaModal:["*"],ariaMultiline:["*"],ariaMultiSelectable:["*"],ariaOrientation:["*"],ariaPlaceholder:["*"],ariaPressed:["*"],ariaReadonly:["*"],ariaRequired:["*"],ariaSelected:["*"],ariaSort:["*"],ariaValuemax:["*"],ariaValuemin:["*"],ariaValueNow:["*"],ariaValueText:["*"],ariaBusy:["*"],ariaLive:["*"],ariaRelevant:["*"],ariaAtomic:["*"],ariaDropEffect:["*"],ariaGrabbed:["*"],ariaActiveDescendant:["*"],ariaColCount:["*"],ariaColIndex:["*"],ariaColSpan:["*"],ariaControls:["*"],ariaDescribedBy:["*"],ariaDescription:["*"],ariaDetails:["*"],ariaFlowTo:["*"],ariaLabelledBy:["*"],ariaOwns:["*"],ariaPosInset:["*"],ariaRowCount:["*"],ariaRowIndex:["*"],ariaRowSpan:["*"],ariaSetSize:["*"]};var v=class{dlightPackageName=g;babelApi;t;traverse;enableDevTools;includes;excludes;htmlTags;attributeMap;constructor(e,t,s,i,r,n,a){this.babelApi=e,this.t=t,this.traverse=e.traverse,this.includes=s,this.excludes=i,this.enableDevTools=k&&r,this.htmlTags=typeof n=="function"?n(N):n.includes("*")?[...new Set([...N,...n])].filter(o=>o!=="*"):n,this.attributeMap=a}classDeclarationNode;classBodyNode;propertiesContainer={};dependencyMap={};enter=!0;dLightModel=!1;enterClassNode=!1;className;programNode;allImports=[];didAlterImports=!1;clearNode(){this.classDeclarationNode=void 0,this.classBodyNode=void 0,this.propertiesContainer={},this.dependencyMap={},this.enter=!0,this.enterClassNode=!1,this.dLightModel=!1,this.className=void 0}get availableProperties(){return Object.entries(this.propertiesContainer).filter(([e,{isWatcher:t,isStatic:s,isChildren:i}])=>e!=="_$compName"&&!t&&!s&&!i).map(([e])=>e)}initNode(e){let t=e.node;if(this.classDeclarationNode=t,this.classBodyNode=t.body,this.propertiesContainer={},t.id?.name||(t.id=this.t.identifier(`Anonymous_${v.uid()}`)),this.className=t.id?.name,this.handleClassCustomDecorators(),this.enableDevTools&&this.classBodyNode.body.unshift(this.t.classProperty(this.t.identifier("_$compName"),this.t.stringLiteral(this.className))),!this.didAlterImports){let s=this.allImports.filter(i=>i.source.value===g);this.dlightPackageName!==g&&s.forEach(i=>{i.source.value=this.dlightPackageName}),this.programNode.body.unshift(this.t.importDeclaration(Object.entries(x).map(([i,r])=>this.t.importSpecifier(this.t.identifier(r),this.t.identifier(i))),this.t.stringLiteral(this.dlightPackageName))),this.didAlterImports=!0}}programEnterVisitor(e,t){if(this.enter=this.fileAllowed(t),!this.enter)return;if(this.allImports=e.node.body.filter(i=>this.t.isImportDeclaration(i)),this.allImports.filter(i=>i.source.value===g).length===0){this.enter=!1;return}this.programNode=e.node}programExitVisitor(){this.enter&&(this.didAlterImports=!1,this.allImports=[],this.programNode=void 0)}classEnter(e){this.enter&&(this.enterClassNode=this.isDLightClass(e),this.enterClassNode&&(this.initNode(e),this.resolveMounting(e)))}classExit(){this.enter&&this.enterClassNode&&(this.transformDLightClass(),this.clearNode(),this.enterClassNode=!1)}classMethodVisitor(e){if(!this.enterClassNode||!this.t.isIdentifier(e.node.key))return;let t=e.node.key.name;if(t==="View"||this.findDecoratorByName(e.node.decorators,"View"))return;let i=e.node,r=this.findDecoratorByName(i.decorators,"Watch");if(this.t.isIdentifier(i.key,{name:"constructor"})||(this.autoBindMethods(i),!r))return;let n=[],a;if(this.t.isIdentifier(r))[n,a]=this.getDependencies(i);else{let o=r.arguments.filter(l=>this.t.isStringLiteral(l)).map(l=>l.value),d=this.t.classMethod("method",i.key,[],this.t.blockStatement([this.t.expressionStatement(this.t.arrayExpression(o.map(l=>this.t.memberExpression(this.t.thisExpression(),this.t.identifier(l)))))]));[n,a]=this.getDependencies(d)}this.propertiesContainer[t]={node:i,deps:n,depsNode:a,isWatcher:!0},i.decorators=this.removeDecorators(i.decorators,["Watch"])}classPropertyVisitor(e){if(!this.enterClassNode)return;let t=e.node;if(!this.t.isIdentifier(t.key))return;let s=t.key.name;if(s==="View")return;let i=t.decorators;if(this.findDecoratorByName(i,"View"))return;let n=this.parseModel(e),a=!!this.findDecoratorByName(i,"Prop"),o=!!this.findDecoratorByName(i,"Env"),d=!!this.findDecoratorByName(t.decorators,"Children"),[l,p]=d?[[]]:this.getDependencies(t);this.propertiesContainer[s]={node:t,deps:l,depsNode:p,isStatic:!!this.findDecoratorByName(i,"Static"),isContent:!!this.findDecoratorByName(i,"Content"),isChildren:d,isPropOrEnv:a?"Prop":o?"Env":void 0,isModel:n},t.decorators=this.removeDecorators(i,D)}resolveWatcherDecorator(e,t){if(!this.t.isIdentifier(e.key))return;let s=e.key.name,i=this.classBodyNode.body.indexOf(e),r=this.t.classProperty(this.t.identifier(`$w$${s}`));this.classBodyNode.body.splice(i,0,r),e.body.body.unshift(this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(s),t]),this.t.blockStatement([this.t.returnStatement()])))}resolveChildrenDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let t=e.key.name,s=this.classBodyNode.body.indexOf(e),i=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$children")),r=this.t.classMethod("get",this.t.identifier(t),[],this.t.blockStatement([this.t.returnStatement(i)]));this.classBodyNode.body.splice(s,1,r)}resolveContentDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key)||this.classBodyNode.body.some(r=>this.t.isClassProperty(r)&&r.key.name==="_$contentKey"))return;let t=e.key.name,s=this.classBodyNode.body.indexOf(e),i=this.t.classProperty(this.t.identifier("_$contentKey"),this.t.stringLiteral(t));this.classBodyNode.body.splice(s,0,i)}resolvePropDecorator(e,t){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let s=e.key.name,i=this.classBodyNode.body.indexOf(e),r=t.toLowerCase()==="prop"?"p":"e",n=this.t.classProperty(this.t.identifier(`$${r}$${s}`));this.classBodyNode.body.splice(i,0,n)}resolveStateDecorator(e,t,s){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let i=e.key.name,r=this.classBodyNode.body.indexOf(e),n=this.dLightModel?[]:[this.t.classProperty(this.t.identifier(`$$${i}`),this.t.numericLiteral(1<<t))],a=s?[this.t.classProperty(this.t.identifier(`$s$${i}`),this.t.arrayExpression([...s].map(o=>this.t.stringLiteral(o))))]:[];this.classBodyNode.body.splice(r+1,0,...n,...a)}handleClassCustomDecorators(){if(!this.classBodyNode)return;let e=this.classDeclarationNode?.decorators;if(!e)return;this.findDecoratorByName(e,"ForwardProps")&&(this.classBodyNode.body.unshift(this.t.classProperty(this.t.identifier("_$forwardProps")),this.t.classProperty(this.t.identifier("_$forwardPropsSet"),this.t.newExpression(this.t.identifier("Set"),[])),this.t.classProperty(this.t.identifier("_$forwardPropsId"),this.t.arrayExpression([]))),this.classDeclarationNode.decorators=this.removeDecorators(e,["ForwardProps"]))}transformDLightClass(){let e=this.handleView();this.dLightModel&&(e=this.availableProperties);let t=Object.entries(this.propertiesContainer).reverse(),s=this.dependencyMapReversed();this.addAutoUpdate(e);for(let[i,{node:r,deps:n,isStatic:a,isChildren:o,isPropOrEnv:d,isWatcher:l,isContent:p,isModel:u,depsNode:h}]of t){if(o){this.resolveChildrenDecorator(r);continue}n.length>0&&(e.push(...n),l?this.resolveWatcherDecorator(r,h):u||this.handleDerivedProperty(r,h)),d&&this.resolvePropDecorator(r,d),p&&(this.resolvePropDecorator(r,"Prop"),this.resolveContentDecorator(r)),!a&&e.includes(i)&&this.resolveStateDecorator(r,this.availableProperties.indexOf(i),s[i])}}addAutoUpdate(e){if(!this.classBodyNode)return;this.classBodyNode.body.filter(s=>!((this.t.isClassProperty(s)||this.t.isClassMethod(s))&&["View","constructor","_$compName"].includes(s.key.name)||this.t.isClassMethod(s,{kind:"method"})&&this.findDecoratorByName(s.decorators,"View")||this.t.isClassMethod(s,{static:!0})||this.t.isClassProperty(s,{static:!0}))).forEach(s=>{let i=this.t.isClassProperty(s)?s.value:this.t.isClassMethod(s)?s.body:null;i&&(this.addUpdateDerived(i,e),this.addUpdateView(i))})}addUpdateDerived(e,t){let s=(i,r)=>this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$ud")),[i,this.t.stringLiteral(r)]);this.traverse(this.valueWrapper(e),{MemberExpression:i=>{if(!this.t.isThisExpression(i.node.object)||!this.t.isIdentifier(i.node.property))return;let r=i.node.property.name;if(!t.includes(r))return;let n=this.isAssignmentExpressionLeft(i);n&&(n.replaceWith(s(n.node,r)),n.skip())},CallExpression:i=>{if(!this.t.isMemberExpression(i.node.callee))return;let r=i.node.callee.property;if(!this.t.isIdentifier(r)||!b.includes(r.name))return;let n=i.get("callee").get("object");for(;this.t.isMemberExpression(n.node);)n=n.get("object");if(!this.t.isThisExpression(n?.node))return;let a=n.parentPath.node.property.name;i.replaceWith(s(i.node,a)),i.skip()}})}addUpdateView(e){let t=()=>this.t.expressionStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$updateView")),[])),s=a=>this.t.isIfStatement(a)||this.t.isLoop(a)||this.t.isTryStatement(a)||this.t.isSwitchStatement(a),i=a=>this.t.isCallExpression(a)&&this.t.isMemberExpression(a.callee)&&this.t.isThisExpression(a.callee.object)&&this.t.isIdentifier(a.callee.property,{name:"_$ud"}),r=a=>a.body.some(o=>this.t.isExpressionStatement(o)&&i(o.expression)),n=a=>{this.t.isBlockStatement(a.node.body)||i(a.node.body)&&(a.node.body=this.t.callExpression(this.t.arrowFunctionExpression([],this.t.blockStatement([this.t.variableDeclaration("const",[this.t.variableDeclarator(this.t.identifier("_$tmp"),a.node.body)]),t(),this.t.returnStatement(this.t.identifier("_$tmp"))])),[]))};this.traverse(this.valueWrapper(e),{BlockStatement:a=>{let o=a.node.body,d=o.findIndex(p=>this.t.isReturnStatement(p)),l=a.parentPath;if(d===-1){if(s(l?.node)||!r(a.node))return;o.push(t());return}(s(l?.node)||r(a.node))&&o.splice(d,0,t())},FunctionExpression:n,ArrowFunctionExpression:n})}addViewAutoUpdate(e){typeof e=="object"&&Object.entries(e).forEach(([,t])=>{t&&(t.type?.[0]&&t.type[0]!==t.type[0].toLowerCase()?this.t.isExpression(t)&&(this.addUpdateDerived(t,this.availableProperties),this.addUpdateView(t)):this.addViewAutoUpdate(t))})}handleView(){if(!this.classBodyNode)return[];let e=new Set,t,s=[];for(let o of this.classBodyNode.body){if(!this.t.isClassProperty(o)&&!this.t.isClassMethod(o)||!this.t.isIdentifier(o.key))continue;let d=this.findDecoratorByName(o.decorators,"View"),l=o.key.name==="View";if(!(!d&&!l)){if(this.t.isClassProperty(o)){let p=o.value;for(;this.t.isTSAsExpression(p);)p=p.expression;if(!this.t.isArrowFunctionExpression(p))continue;o.value=p;let u=this.arrowFunctionPropertyToMethod(o);if(!u)continue;o=u}d?(o.decorators=null,s.push(o)):t=o}}let i=s.map(o=>o.key.name),r=Object.fromEntries(s.map(o=>{let d=o.params[0];if(!d||!this.t.isObjectPattern(d))return["-",null];let l=Object.fromEntries(d.properties.map(p=>{if(!this.t.isObjectProperty(p))return["-",null];let u=p.key.name,h=this.getIdentifiers(this.t.assignmentExpression("=",this.t.objectPattern([this.t.objectProperty(this.t.numericLiteral(0),p.value)]),this.t.numericLiteral(0))).filter(m=>m!==u);return[u,h]}).filter(([p,u])=>u));return[o.key.name,l]}).filter(([o,d])=>d)),n=-1;if(t){let o;[o,n]=this.alterMainView(t,i,r),o.forEach(e.add.bind(e))}s.forEach(o=>{let d;[d,n]=this.alterSubView(o,i,r,n),d.forEach(e.add.bind(e))});let a=[];return this.availableProperties.forEach(o=>{e.has(o)&&a.push(o)}),a}alterMainView(e,t,s){let i=S(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});i.map(l=>this.addViewAutoUpdate(l));let[r,n]=M(i,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:b}),[a,o,d]=$(r,{babelApi:this.babelApi,className:this.className,importMap:x,subViewPropMap:Object.fromEntries(Object.entries(s).map(([l,p])=>[l,Object.keys(p)])),templateIdx:-1,attributeMap:this.attributeMap,alterAttributeMap:E});return e.body=a,this.classBodyNode?.body.push(...o),[n,d]}alterSubView(e,t,s,i){e.params.length===0?e.params.push(this.t.identifier("_$"),this.t.identifier("$subviewNode")):e.params.length===1?e.params.push(this.t.identifier("$subviewNode")):(e.params[1]=this.t.identifier("$subviewNode"),e.params.length=2);let r=S(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});r.map(c=>this.addViewAutoUpdate(c));let n=s[e.key.name]??[],a={};Object.entries(n).forEach(([c,y])=>{y.forEach(L=>{a[L]=[c]})});let[o,d]=M(r,{babelApi:this.babelApi,availableProperties:this.availableProperties,availableIdentifiers:Object.keys(n),dependencyMap:this.dependencyMap,dependencyParseType:"property",reactivityFuncNames:b}),[l]=M(r,{babelApi:this.babelApi,availableProperties:Object.keys(n),dependencyMap:this.dependencyMap,dependencyParseType:"identifier",identifierDepMap:a,reactivityFuncNames:b}),p=Object.fromEntries(Object.entries(s).map(([c,y])=>[c,Object.keys(y)])),[u,h,m]=j(o,l,e.params[0],{babelApi:this.babelApi,className:this.className,importMap:x,subViewPropMap:p,templateIdx:i,attributeMap:this.attributeMap,alterAttributeMap:E});return e.body=u,this.classBodyNode?.body.push(...h),[d,m]}fileAllowed(e){return this.includes.includes("*")?!0:!(!e||this.excludes.some(t=>I(e,t))||!this.includes.some(t=>I(e,t)))}isDLightView(e){let t=e.node;return(t.decorators??[]).find(r=>this.t.isIdentifier(r.expression,{name:"View"}))&&(t.superClass=this.t.identifier("View"),t.decorators=t.decorators?.filter(r=>!this.t.isIdentifier(r.expression,{name:"View"}))),this.t.isIdentifier(t.superClass,{name:"View"})}isDLightModel(e){let t=e.node;return(t.decorators??[]).find(r=>this.t.isIdentifier(r.expression,{name:"Model"}))&&(t.superClass=this.t.identifier("Model"),t.decorators=t.decorators?.filter(r=>!this.t.isIdentifier(r.expression,{name:"Model"}))),t.body.body.unshift(this.t.classProperty(this.t.identifier("_$model"))),t.body.body=t.body.body.filter(r=>!((this.t.isClassProperty(r)||this.t.isClassMethod(r,{kind:"method"}))&&(this.findDecoratorByName(r.decorators,"View")||this.t.isIdentifier(r.key)&&r.key.name==="View"))),this.dLightModel=!0,this.t.isIdentifier(t.superClass,{name:"Model"})}isDLightClass(e){return this.isDLightView(e)||this.isDLightModel(e)}parseModel(e){if(!this.allImports.some(h=>h.source.value===this.dlightPackageName&&h.specifiers.some(m=>{if(this.t.isImportSpecifier(m)&&this.t.isIdentifier(m.imported,{name:"use"}))return!0})))return;let s=e.node,i=s.key;if(!this.t.isIdentifier(i))return;let r=s.value;if(!this.t.isCallExpression(r)||!this.t.isIdentifier(r.callee,{name:"use"}))return;let n=r.arguments,a=n[1],o=n[2],d=this.t.nullLiteral();if(a){let h=[],m=[];if(this.t.isObjectExpression(a))a.properties.forEach(c=>{if(this.t.isSpreadElement(c)){let[,y]=this.getDependenciesFromNode(c.argument);h.push([c.argument,y??this.t.nullLiteral()])}else if(this.t.isObjectProperty(c)){let[,y]=this.getDependenciesFromNode(c.value);m.push([!c.computed&&this.t.isIdentifier(c.key)?this.t.stringLiteral(c.key.name):c.key,c.value,y??this.t.nullLiteral()])}else m.push([!c.computed&&this.t.isIdentifier(c.key)?this.t.stringLiteral(c.key.name):c.key,this.t.arrowFunctionExpression([],c.body),this.t.nullLiteral()])});else{let[,c]=this.getDependenciesFromNode(a);h.push([a,c??this.t.nullLiteral()])}d=this.t.objectExpression([this.t.objectProperty(this.t.identifier("m"),this.t.arrayExpression(h.map(c=>this.t.arrayExpression(c)))),this.t.objectProperty(this.t.identifier("s"),this.t.arrayExpression(m.map(c=>this.t.arrayExpression(c))))])}let l=this.t.nullLiteral();if(o){let[,h]=this.getDependenciesFromNode(o);l=this.t.arrayExpression([o,h??this.t.nullLiteral()])}n[1]=this.t.arrowFunctionExpression([],d),n[2]=this.t.arrowFunctionExpression([],l),n[3]=this.t.stringLiteral(i.name),r.callee=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$injectModel")),s.value=this.t.arrowFunctionExpression([],r);let p=this.classBodyNode.body.indexOf(s),u=this.t.classProperty(this.t.identifier(`$md$${i.name}`));return this.classBodyNode.body.splice(p,0,u),!0}removeDecorators(e,t){return e?e.filter(s=>!(this.t.isIdentifier(s.expression)&&t.includes(s.expression.name)||this.t.isCallExpression(s.expression)&&this.t.isIdentifier(s.expression.callee)&&t.includes(s.expression.callee.name))):[]}findDecoratorByName(e,t){if(e)return e.find(s=>this.t.isIdentifier(s.expression,{name:t})||this.t.isCallExpression(s.expression)&&this.t.isIdentifier(s.expression.callee,{name:t}))?.expression}geneDependencyNode(e){let t=e;for(;t?.parentPath;){let s=t.parentPath;if(!(this.t.isBinaryExpression(s.node)||this.t.isMemberExpression(s.node)))return t.node;t=s}return e.node}addConstructor(){let e=this.classBodyNode.body.find(t=>this.t.isClassMethod(t,{kind:"constructor"}));return e||(e=this.t.classMethod("constructor",this.t.identifier("constructor"),[],this.t.blockStatement([this.t.expressionStatement(this.t.callExpression(this.t.super(),[]))])),this.classBodyNode.body.unshift(e),e)}autoBindMethods(e){this.addConstructor().body.body.push(this.t.expressionStatement(this.t.assignmentExpression("=",this.t.memberExpression(this.t.thisExpression(),e.key),this.t.callExpression(this.t.memberExpression(this.t.memberExpression(this.t.thisExpression(),e.key),this.t.identifier("bind")),[this.t.thisExpression()]))))}handleDerivedProperty(e,t){if(!this.t.isIdentifier(e.key))return;let s=e.key.name,i=e.value,r=this.classBodyNode.body.indexOf(e),n=this.t.classMethod("get",this.t.identifier(`$f$${s}`),[],this.t.blockStatement([this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(s),t]),this.t.blockStatement([this.t.returnStatement(this.t.memberExpression(this.t.thisExpression(),this.t.identifier(s)))])),this.t.returnStatement(i)]));this.classBodyNode.body.splice(r+1,0,n),e.value=null}getDependenciesFromNode(e,t=!1){let s=new Set,i=new Set,r={};this.traverse(this.valueWrapper(e),{MemberExpression:o=>{if(!this.t.isIdentifier(o.node.property)||!this.t.isThisExpression(o.node.object))return;let d=o.node.property.name;this.isAssignmentExpressionLeft(o)||this.isAssignmentFunction(o)?i.add(d):this.availableProperties.includes(d)&&!this.isMemberInEscapeFunction(o,this.classDeclarationNode)&&!this.isMemberInManualFunction(o,this.classDeclarationNode)&&(s.add(d),t&&this.dependencyMap[d]?.forEach(s.add.bind(s)),r[d]||(r[d]=[]),r[d].push(this.geneDependencyNode(o)))}}),i.forEach(o=>{s.delete(o),delete r[o]});let n=Object.values(r).flat();n=n.filter((o,d)=>n.findIndex(p=>this.t.isNodesEquivalent(p,o))===d);let a=[...s];if(t&&s.size>0){let o=e.body.body[0].key.name;this.dependencyMap[o]=a}return[a,this.t.arrayExpression(n)]}getDependencies(e){if(!this.t.isIdentifier(e.key))return[[],void 0];let t=this.t.classDeclaration(null,null,this.t.classBody([e]));return this.getDependenciesFromNode(t,!0)}dependencyMapReversed(){let e={};return Object.entries(this.dependencyMap).forEach(([t,s])=>{s.forEach(i=>{e[i]||(e[i]=new Set),e[i].add(t)})}),e}resolveMounting(e){let t=e.node;if(!this.t.isIdentifier(t.id))return;let s=t.decorators??[],i=d=>{let l=s.find(p=>this.t.isIdentifier(p.expression,{name:d}));return l&&s.splice(s.findIndex(p=>p===l),1),l},r=i("Main")?"main":i("App")?"app":null,n;if(r)n=this.t.stringLiteral(r);else{let d=s.find(l=>this.t.isCallExpression(l.expression)&&this.t.isIdentifier(l.expression.callee,{name:"Mount"})&&l.expression.arguments.length===1);if(!d)return;s.splice(s.findIndex(l=>l===d),1),n=d.expression.arguments[0]}let a=e.parentPath.node;if(!this.t.isBlockStatement(a)&&!this.t.isProgram(a))return;let o=a.body.indexOf(t);a.body.splice(o+1,0,this.t.expressionStatement(this.t.callExpression(this.t.identifier(x.render),[n,t.id])))}arrowFunctionPropertyToMethod(e){if(!this.t.isArrowFunctionExpression(e.value))return;let t=e.value;if(!this.t.isBlockStatement(t.body))return;let s=this.classBodyNode.body.indexOf(e),i=this.t.classMethod("method",e.key,t.params,t.body);return this.classBodyNode.body.splice(s,1,i),i}isMemberExpressionProperty(e,t){return this.t.isMemberExpression(e)&&!e.computed&&e.property===t}isObjectKey(e,t){return this.t.isObjectProperty(e)&&e.key===t}valueWithArrowFunc(e){e.value||(e.value=this.t.identifier("undefined")),e.value=this.t.arrowFunctionExpression([],e.value)}getAllTopLevelReturnBlock(e){let t=[],s=!1;return this.traverse(this.valueWrapper(e),{Function:i=>{s||(s=!0,i.skip())},ReturnStatement:i=>{if(s)return;let r=i.parentPath.node;if(this.t.isBlockStatement(r))t.push(r);else{let n=this.t.blockStatement([i.node]);i.replaceWith(n),t.push(n)}i.skip()},exit:i=>{this.t.isFunction(i.node)&&(s=!1)}}),t}valueWrapper(e){return this.t.file(this.t.program([this.t.isStatement(e)?e:this.t.expressionStatement(e)]))}isAttrFromFunction(e,t){let s=e.parentPath,i=r=>this.t.isIdentifier(r)?r.name===t:this.t.isAssignmentPattern(r)?i(r.left):this.t.isArrayPattern(r)?r.elements.filter(Boolean).map(n=>i(n)).includes(!0):this.t.isObjectPattern(r)?r.properties.filter(n=>this.t.isObjectProperty(n)&&this.t.isIdentifier(n.key)).map(n=>n.key.name).includes(t):this.t.isRestElement(r)?i(r.argument):!1;for(;s;){let r=s.node;if(this.t.isArrowFunctionExpression(r)||this.t.isFunctionDeclaration(r)){for(let n of r.params)if(i(n))return!0}s=s.parentPath}return!1}isStandAloneIdentifier(e){let t=e.node,s=e.parentPath?.node;if(this.t.isMemberExpression(s)&&s.property===t||this.isAttrFromFunction(e,t.name))return!1;for(;e.parentPath;){if(this.t.isVariableDeclarator(e.parentPath.node)||this.t.isObjectProperty(e.parentPath.node)&&e.parentPath.node.key===e.node&&!e.parentPath.node.computed)return!1;e=e.parentPath}return!0}getIdentifiers(e){if(this.t.isIdentifier(e))return[e.name];let t=new Set;return this.traverse(this.valueWrapper(e),{Identifier:s=>{this.isStandAloneIdentifier(s)&&t.add(s.node.name)}}),[...t]}isAssignmentExpressionLeft(e){let t=e.parentPath;for(;t&&!this.t.isStatement(t.node);){if(this.t.isAssignmentExpression(t.node)){if(t.node.left===e.node)return t;let s=t.get("left");if(e.isDescendant(s))return t}else if(this.t.isUpdateExpression(t.node))return t;t=t.parentPath}return null}isAssignmentFunction(e){let t=e.parentPath;for(;t&&this.t.isMemberExpression(t.node);)t=t.parentPath;return t?this.t.isCallExpression(t.node)&&this.t.isMemberExpression(t.node.callee)&&this.t.isIdentifier(t.node.callee.property)&&b.includes(t.node.callee.property.name):!1}isMemberInEscapeFunction(e,t){let s=!1,i=e.parentPath;for(;i&&i.node!==t;){let r=i.node;if(this.t.isCallExpression(r)&&this.t.isIdentifier(r.callee)&&v.escapeNamings.includes(r.callee.name)){s=!0;break}i=i.parentPath}return s}isMemberInManualFunction(e,t){let s=!1,i=e.parentPath;for(;i&&i.node!==t;){let r=i.node,n=i.parentPath?.node,a=this.t.isFunctionExpression(r)||this.t.isArrowFunctionExpression(r),o=this.t.isCallExpression(n)&&this.t.isIdentifier(n.callee)&&n.callee.name==="manual";if(a&&o){s=!0;break}i=i.parentPath}return s}static uid(e=4){return Math.random().toString(32).slice(2,e+2)}},P=v;C(P,"escapeNamings",["escape","$"]);var A=P;function B(f,e){let{types:t}=f,{files:s="**/*.{js,ts}",excludeFiles:i="**/{dist,node_modules,lib}/*",enableDevTools:r=!1,htmlTags:n=d=>d,attributeMap:a=w}=e,o=new A(f,t,Array.isArray(s)?s:[s],Array.isArray(i)?i:[i],r,n,a);return{visitor:{Program:{enter(d,{filename:l}){return o.programEnterVisitor(d,l)},exit:o.programExitVisitor.bind(o)},ClassDeclaration:{enter:o.classEnter.bind(o),exit:o.classExit.bind(o)},ClassMethod:o.classMethodVisitor.bind(o),ClassProperty:o.classPropertyVisitor.bind(o)}}}function te(f,e){return{plugins:[T,[V.default??V,{legacy:!0}],[B,e]]}}export{te as default}; | ||
var O=Object.defineProperty;var j=(f,e,t)=>e in f?O(f,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):f[e]=t;var C=(f,e,t)=>(j(f,typeof e!="symbol"?e+"":e,t),t);import $ from"babel-plugin-syntax-typescript-new";import B from"@babel/plugin-syntax-decorators";import{minimatch as I}from"minimatch";import{parseView as S}from"@dlightjs/view-parser";import{parseReactivity as M}from"@dlightjs/reactivity-parser";import{generateSubView as F,generateView as T}from"@dlightjs/view-generator";var D=process.env.NODE_ENV==="development",N={class:"className",for:"htmlFor"},b=["push","pop","shift","unshift","splice","sort","reverse","add","delete","clear","set","delete","clear"],E=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","slot","small","source","span","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","acronym","applet","basefont","bgsound","big","blink","center","dir","font","frame","frameset","isindex","keygen","listing","marquee","menuitem","multicol","nextid","nobr","noembed","noframes","param","plaintext","rb","rtc","spacer","strike","tt","xmp","animate","animateMotion","animateTransform","circle","clipPath","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","foreignObject","g","image","line","linearGradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialGradient","rect","set","stop","svg","switch","symbol","text","textPath","tspan","use","view"],k=["Static","Prop","Env","Content","Children"],g="@dlightjs/dlight",x=Object.fromEntries(["createElement","setStyle","setDataset","setEvent","delegateEvent","setHTMLProp","setHTMLAttr","setHTMLProps","setHTMLAttrs","createTextNode","updateText","insertNode","ForNode","CondNode","ExpNode","EnvNode","SubViewNode","PropView","render"].map(f=>[f,`$$${f}`])),w={textContent:["*"],innerHTML:["*"],accept:["form","input"],acceptCharset:["form"],accesskey:["*"],action:["form"],align:["caption","col","colgroup","hr","iframe","img","table","tbody","td","tfoot","th","thead","tr"],allow:["iframe"],alt:["area","img","input"],async:["script"],autocapitalize:["*"],autocomplete:["form","input","select","textarea"],autofocus:["button","input","select","textarea"],autoplay:["audio","video"],background:["body","table","td","th"],bgColor:["body","col","colgroup","marquee","table","tbody","tfoot","td","th","tr"],border:["img","object","table"],buffered:["audio","video"],capture:["input"],charset:["meta"],checked:["input"],cite:["blockquote","del","ins","q"],className:["*"],color:["font","hr"],cols:["textarea"],colSpan:["td","th"],content:["meta"],contentEditable:["*"],contextmenu:["*"],controls:["audio","video"],coords:["area"],crossOrigin:["audio","img","link","script","video"],csp:["iframe"],data:["object"],dateTime:["del","ins","time"],decoding:["img"],default:["track"],defer:["script"],dir:["*"],dirname:["input","textarea"],disabled:["button","fieldset","input","optgroup","option","select","textarea"],download:["a","area"],draggable:["*"],enctype:["form"],enterKeyHint:["textarea","contenteditable"],htmlFor:["label","output"],form:["button","fieldset","input","label","meter","object","output","progress","select","textarea"],formAction:["input","button"],formEnctype:["button","input"],formMethod:["button","input"],formNoValidate:["button","input"],formTarget:["button","input"],headers:["td","th"],height:["canvas","embed","iframe","img","input","object","video"],hidden:["*"],high:["meter"],href:["a","area","base","link"],hreflang:["a","link"],httpEquiv:["meta"],id:["*"],integrity:["link","script"],intrinsicSize:["img"],inputMode:["textarea","contenteditable"],ismap:["img"],itemProp:["*"],kind:["track"],label:["optgroup","option","track"],lang:["*"],language:["script"],loading:["img","iframe"],list:["input"],loop:["audio","marquee","video"],low:["meter"],manifest:["html"],max:["input","meter","progress"],maxLength:["input","textarea"],minLength:["input","textarea"],media:["a","area","link","source","style"],method:["form"],min:["input","meter"],multiple:["input","select"],muted:["audio","video"],name:["button","form","fieldset","iframe","input","object","output","select","textarea","map","meta","param"],noValidate:["form"],open:["details","dialog"],optimum:["meter"],pattern:["input"],ping:["a","area"],placeholder:["input","textarea"],playsInline:["video"],poster:["video"],preload:["audio","video"],readonly:["input","textarea"],referrerPolicy:["a","area","iframe","img","link","script"],rel:["a","area","link"],required:["input","select","textarea"],reversed:["ol"],role:["*"],rows:["textarea"],rowSpan:["td","th"],sandbox:["iframe"],scope:["th"],scoped:["style"],selected:["option"],shape:["a","area"],size:["input","select"],sizes:["link","img","source"],slot:["*"],span:["col","colgroup"],spellcheck:["*"],src:["audio","embed","iframe","img","input","script","source","track","video"],srcdoc:["iframe"],srclang:["track"],srcset:["img","source"],start:["ol"],step:["input"],style:["*"],summary:["table"],tabIndex:["*"],target:["a","area","base","form"],title:["*"],translate:["*"],type:["button","input","embed","object","ol","script","source","style","menu","link"],usemap:["img","input","object"],value:["button","data","input","li","meter","option","progress","param","text"],width:["canvas","embed","iframe","img","input","object","video"],wrap:["textarea"],ariaAutocomplete:["*"],ariaChecked:["*"],ariaDisabled:["*"],ariaErrorMessage:["*"],ariaExpanded:["*"],ariaHasPopup:["*"],ariaHidden:["*"],ariaInvalid:["*"],ariaLabel:["*"],ariaLevel:["*"],ariaModal:["*"],ariaMultiline:["*"],ariaMultiSelectable:["*"],ariaOrientation:["*"],ariaPlaceholder:["*"],ariaPressed:["*"],ariaReadonly:["*"],ariaRequired:["*"],ariaSelected:["*"],ariaSort:["*"],ariaValuemax:["*"],ariaValuemin:["*"],ariaValueNow:["*"],ariaValueText:["*"],ariaBusy:["*"],ariaLive:["*"],ariaRelevant:["*"],ariaAtomic:["*"],ariaDropEffect:["*"],ariaGrabbed:["*"],ariaActiveDescendant:["*"],ariaColCount:["*"],ariaColIndex:["*"],ariaColSpan:["*"],ariaControls:["*"],ariaDescribedBy:["*"],ariaDescription:["*"],ariaDetails:["*"],ariaFlowTo:["*"],ariaLabelledBy:["*"],ariaOwns:["*"],ariaPosInset:["*"],ariaRowCount:["*"],ariaRowIndex:["*"],ariaRowSpan:["*"],ariaSetSize:["*"]};var v=class{dlightPackageName=g;babelApi;t;traverse;enableDevTools;includes;excludes;htmlTags;attributeMap;constructor(e,t,s,i,r,a,d){this.babelApi=e,this.t=t,this.traverse=e.traverse,this.includes=s,this.excludes=i,this.enableDevTools=D&&r,this.htmlTags=typeof a=="function"?a(E):a.includes("*")?[...new Set([...E,...a])].filter(o=>o!=="*"):a,this.attributeMap=d}classDeclarationNode;classBodyNode;propertiesContainer={};dependencyMap={};enter=!0;dLightModel=!1;enterClassNode=!1;className;programNode;allImports=[];didAlterImports=!1;clearNode(){this.classDeclarationNode=void 0,this.classBodyNode=void 0,this.propertiesContainer={},this.dependencyMap={},this.enter=!0,this.enterClassNode=!1,this.dLightModel=!1,this.className=void 0}get availableProperties(){return Object.entries(this.propertiesContainer).filter(([e,{isWatcher:t,isStatic:s,isChildren:i}])=>e!=="_$compName"&&!t&&!s&&!i).map(([e])=>e)}initNode(e){let t=e.node;if(this.classDeclarationNode=t,this.classBodyNode=t.body,this.propertiesContainer={},t.id?.name||(t.id=this.t.identifier(`Anonymous_${v.uid()}`)),this.className=t.id?.name,this.handleClassCustomDecorators(),this.enableDevTools&&this.classBodyNode.body.unshift(this.t.classProperty(this.t.identifier("_$compName"),this.t.stringLiteral(this.className))),!this.didAlterImports){let s=this.allImports.filter(i=>i.source.value===g);this.dlightPackageName!==g&&s.forEach(i=>{i.source.value=this.dlightPackageName}),this.programNode.body.unshift(this.t.importDeclaration(Object.entries(x).map(([i,r])=>this.t.importSpecifier(this.t.identifier(r),this.t.identifier(i))),this.t.stringLiteral(this.dlightPackageName))),this.didAlterImports=!0}}programEnterVisitor(e,t){if(this.enter=this.fileAllowed(t),!this.enter)return;if(this.allImports=e.node.body.filter(i=>this.t.isImportDeclaration(i)),this.allImports.filter(i=>i.source.value===g).length===0){this.enter=!1;return}this.programNode=e.node}programExitVisitor(){this.enter&&(this.didAlterImports=!1,this.allImports=[],this.programNode=void 0)}classEnter(e){this.enter&&(this.enterClassNode=this.isDLightClass(e),this.enterClassNode&&(this.initNode(e),this.resolveMounting(e)))}classExit(){this.enter&&this.enterClassNode&&(this.transformDLightClass(),this.clearNode(),this.enterClassNode=!1)}classMethodVisitor(e){if(!this.enterClassNode||!this.t.isIdentifier(e.node.key))return;let t=e.node.key.name;if(t==="View"||this.findDecoratorByName(e.node.decorators,"View"))return;let i=e.node,r=this.findDecoratorByName(i.decorators,"Watch");if(this.t.isIdentifier(i.key,{name:"constructor"})||(this.autoBindMethods(i),!r))return;let a=[],d;if(this.t.isIdentifier(r))[a,d]=this.getDependencies(i);else{let o=r.arguments.filter(l=>this.t.isStringLiteral(l)).map(l=>l.value),n=this.t.classMethod("method",i.key,[],this.t.blockStatement([this.t.expressionStatement(this.t.arrayExpression(o.map(l=>this.t.memberExpression(this.t.thisExpression(),this.t.identifier(l)))))]));[a,d]=this.getDependencies(n)}this.propertiesContainer[t]={node:i,deps:a,depsNode:d,isWatcher:!0},i.decorators=this.removeDecorators(i.decorators,["Watch"])}classPropertyVisitor(e){if(!this.enterClassNode)return;let t=e.node;if(!this.t.isIdentifier(t.key))return;let s=t.key.name;if(s==="View")return;let i=t.decorators;if(this.findDecoratorByName(i,"View"))return;let a=this.parseModel(e),d=!!this.findDecoratorByName(i,"Prop"),o=!!this.findDecoratorByName(i,"Env"),n=!!this.findDecoratorByName(t.decorators,"Children"),[l,c]=n?[[]]:this.getDependencies(t);this.propertiesContainer[s]={node:t,deps:l,depsNode:c,isStatic:!!this.findDecoratorByName(i,"Static"),isContent:!!this.findDecoratorByName(i,"Content"),isChildren:n,isPropOrEnv:d?"Prop":o?"Env":void 0,isModel:a},t.decorators=this.removeDecorators(i,k)}resolveWatcherDecorator(e,t){if(!this.t.isIdentifier(e.key))return;let s=e.key.name,i=this.classBodyNode.body.indexOf(e),r=this.t.classProperty(this.t.identifier(`$w$${s}`));this.classBodyNode.body.splice(i,0,r),e.body.body.unshift(this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(s),t]),this.t.blockStatement([this.t.returnStatement()])))}resolveChildrenDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let t=e.key.name,s=this.classBodyNode.body.indexOf(e),i=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$children")),r=this.t.classMethod("get",this.t.identifier(t),[],this.t.blockStatement([this.t.returnStatement(i)]));this.classBodyNode.body.splice(s,1,r)}resolveContentDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key)||this.classBodyNode.body.some(r=>this.t.isClassProperty(r)&&r.key.name==="_$contentKey"))return;let t=e.key.name,s=this.classBodyNode.body.indexOf(e),i=this.t.classProperty(this.t.identifier("_$contentKey"),this.t.stringLiteral(t));this.classBodyNode.body.splice(s,0,i)}resolvePropDecorator(e,t){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let s=e.key.name,i=this.classBodyNode.body.indexOf(e),r=t.toLowerCase()==="prop"?"p":"e",a=this.t.classProperty(this.t.identifier(`$${r}$${s}`));this.classBodyNode.body.splice(i,0,a)}resolveStateDecorator(e,t,s){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let i=e.key.name,r=this.classBodyNode.body.indexOf(e),a=this.dLightModel?[]:[this.t.classProperty(this.t.identifier(`$$${i}`),this.t.numericLiteral(1<<t))],d=s?[this.t.classProperty(this.t.identifier(`$s$${i}`),this.t.arrayExpression([...s].map(o=>this.t.stringLiteral(o))))]:[];this.classBodyNode.body.splice(r+1,0,...a,...d)}handleClassCustomDecorators(){if(!this.classBodyNode)return;let e=this.classDeclarationNode?.decorators;if(!e)return;this.findDecoratorByName(e,"ForwardProps")&&(this.classBodyNode.body.unshift(this.t.classProperty(this.t.identifier("_$forwardProps")),this.t.classProperty(this.t.identifier("_$forwardPropsSet"),this.t.newExpression(this.t.identifier("Set"),[])),this.t.classProperty(this.t.identifier("_$forwardPropsId"),this.t.arrayExpression([]))),this.classDeclarationNode.decorators=this.removeDecorators(e,["ForwardProps"]))}transformDLightClass(){let e=this.handleView();this.dLightModel&&(e=this.availableProperties);let t=Object.entries(this.propertiesContainer).reverse(),s=this.dependencyMapReversed();this.addAutoUpdate(e);for(let[i,{node:r,deps:a,isStatic:d,isChildren:o,isPropOrEnv:n,isWatcher:l,isContent:c,isModel:u,depsNode:h}]of t){if(o){this.resolveChildrenDecorator(r);continue}a.length>0&&(e.push(...a),l?this.resolveWatcherDecorator(r,h):u||this.handleDerivedProperty(r,h)),n&&this.resolvePropDecorator(r,n),c&&(this.resolvePropDecorator(r,"Prop"),this.resolveContentDecorator(r)),!d&&e.includes(i)&&this.resolveStateDecorator(r,this.availableProperties.indexOf(i),s[i])}}addAutoUpdate(e){if(!this.classBodyNode)return;this.classBodyNode.body.filter(s=>!((this.t.isClassProperty(s)||this.t.isClassMethod(s))&&["View","constructor","_$compName"].includes(s.key.name)||this.t.isClassMethod(s,{kind:"method"})&&this.findDecoratorByName(s.decorators,"View")||this.t.isClassMethod(s,{static:!0})||this.t.isClassProperty(s,{static:!0}))).forEach(s=>{let i=this.t.isClassProperty(s)?s.value:this.t.isClassMethod(s)?s.body:null;i&&this.addUpdateDerived(i,e)})}addUpdateDerived(e,t){let s=(i,r)=>this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$ud")),[i,this.t.stringLiteral(r)]);this.traverse(this.valueWrapper(e),{MemberExpression:i=>{if(!this.t.isThisExpression(i.node.object)||!this.t.isIdentifier(i.node.property))return;let r=i.node.property.name;if(!t.includes(r))return;let a=this.isAssignmentExpressionLeft(i);a&&(a.replaceWith(s(a.node,r)),a.skip())},CallExpression:i=>{if(!this.t.isMemberExpression(i.node.callee))return;let r=i.node.callee.property;if(!this.t.isIdentifier(r)||!b.includes(r.name))return;let a=i.get("callee").get("object");for(;this.t.isMemberExpression(a.node);)a=a.get("object");if(!this.t.isThisExpression(a?.node))return;let d=a.parentPath.node.property.name;i.replaceWith(s(i.node,d)),i.skip()}})}addViewAutoUpdate(e){typeof e=="object"&&Object.entries(e).forEach(([,t])=>{t&&(t.type?.[0]&&t.type[0]!==t.type[0].toLowerCase()?this.t.isExpression(t)&&this.addUpdateDerived(t,this.availableProperties):this.addViewAutoUpdate(t))})}handleView(){if(!this.classBodyNode)return[];let e=new Set,t,s=[];for(let o of this.classBodyNode.body){if(!this.t.isClassProperty(o)&&!this.t.isClassMethod(o)||!this.t.isIdentifier(o.key))continue;let n=this.findDecoratorByName(o.decorators,"View"),l=o.key.name==="View";if(!(!n&&!l)){if(this.t.isClassProperty(o)){let c=o.value;for(;this.t.isTSAsExpression(c);)c=c.expression;if(!this.t.isArrowFunctionExpression(c))continue;o.value=c;let u=this.arrowFunctionPropertyToMethod(o);if(!u)continue;o=u}n?(o.decorators=null,s.push(o)):t=o}}let i=s.map(o=>o.key.name),r=Object.fromEntries(s.map(o=>{let n=o.params[0];if(!n||!this.t.isObjectPattern(n))return["-",null];let l=Object.fromEntries(n.properties.map(c=>{if(!this.t.isObjectProperty(c))return["-",null];let u=c.key.name,h=this.getIdentifiers(this.t.assignmentExpression("=",this.t.objectPattern([this.t.objectProperty(this.t.numericLiteral(0),c.value)]),this.t.numericLiteral(0))).filter(m=>m!==u);return[u,h]}).filter(([c,u])=>u));return[o.key.name,l]}).filter(([o,n])=>n)),a=-1;if(t){let o;[o,a]=this.alterMainView(t,i,r),o.forEach(e.add.bind(e))}s.forEach(o=>{let n;[n,a]=this.alterSubView(o,i,r,a),n.forEach(e.add.bind(e))});let d=[];return this.availableProperties.forEach(o=>{e.has(o)&&d.push(o)}),d}alterMainView(e,t,s){let i=S(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});i.map(l=>this.addViewAutoUpdate(l));let[r,a]=M(i,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:b}),[d,o,n]=T(r,{babelApi:this.babelApi,className:this.className,importMap:x,subViewPropMap:Object.fromEntries(Object.entries(s).map(([l,c])=>[l,Object.keys(c)])),templateIdx:-1,attributeMap:this.attributeMap,alterAttributeMap:N});return e.body=d,this.classBodyNode?.body.push(...o),[a,n]}alterSubView(e,t,s,i){e.params.length===0?e.params.push(this.t.identifier("_$"),this.t.identifier("$subviewNode")):e.params.length===1?e.params.push(this.t.identifier("$subviewNode")):(e.params[1]=this.t.identifier("$subviewNode"),e.params.length=2);let r=S(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});r.map(p=>this.addViewAutoUpdate(p));let a=s[e.key.name]??[],d={};Object.entries(a).forEach(([p,y])=>{y.forEach(L=>{d[L]=[p]})});let[o,n]=M(r,{babelApi:this.babelApi,availableProperties:this.availableProperties,availableIdentifiers:Object.keys(a),dependencyMap:this.dependencyMap,dependencyParseType:"property",reactivityFuncNames:b}),[l]=M(r,{babelApi:this.babelApi,availableProperties:Object.keys(a),dependencyMap:this.dependencyMap,dependencyParseType:"identifier",identifierDepMap:d,reactivityFuncNames:b}),c=Object.fromEntries(Object.entries(s).map(([p,y])=>[p,Object.keys(y)])),[u,h,m]=F(o,l,e.params[0],{babelApi:this.babelApi,className:this.className,importMap:x,subViewPropMap:c,templateIdx:i,attributeMap:this.attributeMap,alterAttributeMap:N});return e.body=u,this.classBodyNode?.body.push(...h),[n,m]}fileAllowed(e){return this.includes.includes("*")?!0:!(!e||this.excludes.some(t=>I(e,t))||!this.includes.some(t=>I(e,t)))}isDLightView(e){let t=e.node;return(t.decorators??[]).find(r=>this.t.isIdentifier(r.expression,{name:"View"}))&&(t.superClass=this.t.identifier("View"),t.decorators=t.decorators?.filter(r=>!this.t.isIdentifier(r.expression,{name:"View"}))),this.t.isIdentifier(t.superClass,{name:"View"})}isDLightModel(e){let t=e.node;return(t.decorators??[]).find(r=>this.t.isIdentifier(r.expression,{name:"Model"}))&&(t.superClass=this.t.identifier("Model"),t.decorators=t.decorators?.filter(r=>!this.t.isIdentifier(r.expression,{name:"Model"}))),t.body.body.unshift(this.t.classProperty(this.t.identifier("_$model"))),t.body.body=t.body.body.filter(r=>!((this.t.isClassProperty(r)||this.t.isClassMethod(r,{kind:"method"}))&&(this.findDecoratorByName(r.decorators,"View")||this.t.isIdentifier(r.key)&&r.key.name==="View"))),this.dLightModel=!0,this.t.isIdentifier(t.superClass,{name:"Model"})}isDLightClass(e){return this.isDLightView(e)||this.isDLightModel(e)}parseModel(e){if(!this.allImports.some(h=>h.source.value===this.dlightPackageName&&h.specifiers.some(m=>{if(this.t.isImportSpecifier(m)&&this.t.isIdentifier(m.imported,{name:"use"}))return!0})))return;let s=e.node,i=s.key;if(!this.t.isIdentifier(i))return;let r=s.value;if(!this.t.isCallExpression(r)||!this.t.isIdentifier(r.callee,{name:"use"}))return;let a=r.arguments,d=a[1],o=a[2],n=this.t.nullLiteral();if(d){let h=[],m=[];if(this.t.isObjectExpression(d))d.properties.forEach(p=>{if(this.t.isSpreadElement(p)){let[,y]=this.getDependenciesFromNode(p.argument);h.push([p.argument,y??this.t.nullLiteral()])}else if(this.t.isObjectProperty(p)){let[,y]=this.getDependenciesFromNode(p.value);m.push([!p.computed&&this.t.isIdentifier(p.key)?this.t.stringLiteral(p.key.name):p.key,p.value,y??this.t.nullLiteral()])}else m.push([!p.computed&&this.t.isIdentifier(p.key)?this.t.stringLiteral(p.key.name):p.key,this.t.arrowFunctionExpression([],p.body),this.t.nullLiteral()])});else{let[,p]=this.getDependenciesFromNode(d);h.push([d,p??this.t.nullLiteral()])}n=this.t.objectExpression([this.t.objectProperty(this.t.identifier("m"),this.t.arrayExpression(h.map(p=>this.t.arrayExpression(p)))),this.t.objectProperty(this.t.identifier("s"),this.t.arrayExpression(m.map(p=>this.t.arrayExpression(p))))])}let l=this.t.nullLiteral();if(o){let[,h]=this.getDependenciesFromNode(o);l=this.t.arrayExpression([o,h??this.t.nullLiteral()])}a[1]=this.t.arrowFunctionExpression([],n),a[2]=this.t.arrowFunctionExpression([],l),a[3]=this.t.stringLiteral(i.name),r.callee=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$injectModel")),s.value=this.t.arrowFunctionExpression([],r);let c=this.classBodyNode.body.indexOf(s),u=this.t.classProperty(this.t.identifier(`$md$${i.name}`));return this.classBodyNode.body.splice(c,0,u),!0}removeDecorators(e,t){return e?e.filter(s=>!(this.t.isIdentifier(s.expression)&&t.includes(s.expression.name)||this.t.isCallExpression(s.expression)&&this.t.isIdentifier(s.expression.callee)&&t.includes(s.expression.callee.name))):[]}findDecoratorByName(e,t){if(e)return e.find(s=>this.t.isIdentifier(s.expression,{name:t})||this.t.isCallExpression(s.expression)&&this.t.isIdentifier(s.expression.callee,{name:t}))?.expression}geneDependencyNode(e){let t=e;for(;t?.parentPath;){let s=t.parentPath;if(!(this.t.isBinaryExpression(s.node)||this.t.isMemberExpression(s.node)))return t.node;t=s}return e.node}addConstructor(){let e=this.classBodyNode.body.find(t=>this.t.isClassMethod(t,{kind:"constructor"}));return e||(e=this.t.classMethod("constructor",this.t.identifier("constructor"),[],this.t.blockStatement([this.t.expressionStatement(this.t.callExpression(this.t.super(),[]))])),this.classBodyNode.body.unshift(e),e)}autoBindMethods(e){this.addConstructor().body.body.push(this.t.expressionStatement(this.t.assignmentExpression("=",this.t.memberExpression(this.t.thisExpression(),e.key),this.t.callExpression(this.t.memberExpression(this.t.memberExpression(this.t.thisExpression(),e.key),this.t.identifier("bind")),[this.t.thisExpression()]))))}handleDerivedProperty(e,t){if(!this.t.isIdentifier(e.key))return;let s=e.key.name,i=e.value,r=this.classBodyNode.body.indexOf(e),a=this.t.classMethod("get",this.t.identifier(`$f$${s}`),[],this.t.blockStatement([this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(s),t]),this.t.blockStatement([this.t.returnStatement(this.t.memberExpression(this.t.thisExpression(),this.t.identifier(s)))])),this.t.returnStatement(i)]));this.classBodyNode.body.splice(r+1,0,a),e.value=null}getDependenciesFromNode(e,t=!1){let s=new Set,i=new Set,r={};this.traverse(this.valueWrapper(e),{MemberExpression:o=>{if(!this.t.isIdentifier(o.node.property)||!this.t.isThisExpression(o.node.object))return;let n=o.node.property.name;this.isAssignmentExpressionLeft(o)||this.isAssignmentFunction(o)?i.add(n):this.availableProperties.includes(n)&&!this.isMemberInEscapeFunction(o,this.classDeclarationNode)&&!this.isMemberInManualFunction(o,this.classDeclarationNode)&&(s.add(n),t&&this.dependencyMap[n]?.forEach(s.add.bind(s)),r[n]||(r[n]=[]),r[n].push(this.geneDependencyNode(o)))}}),i.forEach(o=>{s.delete(o),delete r[o]});let a=Object.values(r).flat();a=a.filter((o,n)=>a.findIndex(c=>this.t.isNodesEquivalent(c,o))===n);let d=[...s];if(t&&s.size>0){let o=e.body.body[0].key.name;this.dependencyMap[o]=d}return[d,this.t.arrayExpression(a)]}getDependencies(e){if(!this.t.isIdentifier(e.key))return[[],void 0];let t=this.t.classDeclaration(null,null,this.t.classBody([e]));return this.getDependenciesFromNode(t,!0)}dependencyMapReversed(){let e={};return Object.entries(this.dependencyMap).forEach(([t,s])=>{s.forEach(i=>{e[i]||(e[i]=new Set),e[i].add(t)})}),e}resolveMounting(e){let t=e.node;if(!this.t.isIdentifier(t.id))return;let s=t.decorators??[],i=n=>{let l=s.find(c=>this.t.isIdentifier(c.expression,{name:n}));return l&&s.splice(s.findIndex(c=>c===l),1),l},r=i("Main")?"main":i("App")?"app":null,a;if(r)a=this.t.stringLiteral(r);else{let n=s.find(l=>this.t.isCallExpression(l.expression)&&this.t.isIdentifier(l.expression.callee,{name:"Mount"})&&l.expression.arguments.length===1);if(!n)return;s.splice(s.findIndex(l=>l===n),1),a=n.expression.arguments[0]}let d=e.parentPath.node;if(!this.t.isBlockStatement(d)&&!this.t.isProgram(d))return;let o=d.body.indexOf(t);d.body.splice(o+1,0,this.t.expressionStatement(this.t.callExpression(this.t.identifier(x.render),[a,t.id])))}arrowFunctionPropertyToMethod(e){if(!this.t.isArrowFunctionExpression(e.value))return;let t=e.value;if(!this.t.isBlockStatement(t.body))return;let s=this.classBodyNode.body.indexOf(e),i=this.t.classMethod("method",e.key,t.params,t.body);return this.classBodyNode.body.splice(s,1,i),i}isMemberExpressionProperty(e,t){return this.t.isMemberExpression(e)&&!e.computed&&e.property===t}isObjectKey(e,t){return this.t.isObjectProperty(e)&&e.key===t}valueWithArrowFunc(e){e.value||(e.value=this.t.identifier("undefined")),e.value=this.t.arrowFunctionExpression([],e.value)}getAllTopLevelReturnBlock(e){let t=[],s=!1;return this.traverse(this.valueWrapper(e),{Function:i=>{s||(s=!0,i.skip())},ReturnStatement:i=>{if(s)return;let r=i.parentPath.node;if(this.t.isBlockStatement(r))t.push(r);else{let a=this.t.blockStatement([i.node]);i.replaceWith(a),t.push(a)}i.skip()},exit:i=>{this.t.isFunction(i.node)&&(s=!1)}}),t}valueWrapper(e){return this.t.file(this.t.program([this.t.isStatement(e)?e:this.t.expressionStatement(e)]))}isAttrFromFunction(e,t){let s=e.parentPath,i=r=>this.t.isIdentifier(r)?r.name===t:this.t.isAssignmentPattern(r)?i(r.left):this.t.isArrayPattern(r)?r.elements.filter(Boolean).map(a=>i(a)).includes(!0):this.t.isObjectPattern(r)?r.properties.filter(a=>this.t.isObjectProperty(a)&&this.t.isIdentifier(a.key)).map(a=>a.key.name).includes(t):this.t.isRestElement(r)?i(r.argument):!1;for(;s;){let r=s.node;if(this.t.isArrowFunctionExpression(r)||this.t.isFunctionDeclaration(r)){for(let a of r.params)if(i(a))return!0}s=s.parentPath}return!1}isStandAloneIdentifier(e){let t=e.node,s=e.parentPath?.node;if(this.t.isMemberExpression(s)&&s.property===t||this.isAttrFromFunction(e,t.name))return!1;for(;e.parentPath;){if(this.t.isVariableDeclarator(e.parentPath.node)||this.t.isObjectProperty(e.parentPath.node)&&e.parentPath.node.key===e.node&&!e.parentPath.node.computed)return!1;e=e.parentPath}return!0}getIdentifiers(e){if(this.t.isIdentifier(e))return[e.name];let t=new Set;return this.traverse(this.valueWrapper(e),{Identifier:s=>{this.isStandAloneIdentifier(s)&&t.add(s.node.name)}}),[...t]}isAssignmentExpressionLeft(e){let t=e.parentPath;for(;t&&!this.t.isStatement(t.node);){if(this.t.isAssignmentExpression(t.node)){if(t.node.left===e.node)return t;let s=t.get("left");if(e.isDescendant(s))return t}else if(this.t.isUpdateExpression(t.node))return t;t=t.parentPath}return null}isAssignmentFunction(e){let t=e.parentPath;for(;t&&this.t.isMemberExpression(t.node);)t=t.parentPath;return t?this.t.isCallExpression(t.node)&&this.t.isMemberExpression(t.node.callee)&&this.t.isIdentifier(t.node.callee.property)&&b.includes(t.node.callee.property.name):!1}isMemberInEscapeFunction(e,t){let s=!1,i=e.parentPath;for(;i&&i.node!==t;){let r=i.node;if(this.t.isCallExpression(r)&&this.t.isIdentifier(r.callee)&&v.escapeNamings.includes(r.callee.name)){s=!0;break}i=i.parentPath}return s}isMemberInManualFunction(e,t){let s=!1,i=e.parentPath;for(;i&&i.node!==t;){let r=i.node,a=i.parentPath?.node,d=this.t.isFunctionExpression(r)||this.t.isArrowFunctionExpression(r),o=this.t.isCallExpression(a)&&this.t.isIdentifier(a.callee)&&a.callee.name==="manual";if(d&&o){s=!0;break}i=i.parentPath}return s}static uid(e=4){return Math.random().toString(32).slice(2,e+2)}},P=v;C(P,"escapeNamings",["escape","$"]);var A=P;function V(f,e){let{types:t}=f,{files:s="**/*.{js,ts}",excludeFiles:i="**/{dist,node_modules,lib}/*",enableDevTools:r=!1,htmlTags:a=n=>n,attributeMap:d=w}=e,o=new A(f,t,Array.isArray(s)?s:[s],Array.isArray(i)?i:[i],r,a,d);return{visitor:{Program:{enter(n,{filename:l}){return o.programEnterVisitor(n,l)},exit:o.programExitVisitor.bind(o)},ClassDeclaration:{enter:o.classEnter.bind(o),exit:o.classExit.bind(o)},ClassMethod:o.classMethodVisitor.bind(o),ClassProperty:o.classPropertyVisitor.bind(o)}}}function te(f,e){return{plugins:[$,[B.default??B,{legacy:!0}],[V,e]]}}export{te as default}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "babel-preset-dlight", | ||
"version": "1.0.0-beta.20", | ||
"version": "1.0.0-beta.21", | ||
"description": "DLight transpiler babel preset", | ||
@@ -5,0 +5,0 @@ "author": { |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
266909
264