babel-preset-dlight
Advanced tools
Comparing version 1.0.0-beta.4 to 1.0.0-beta.5
@@ -1,2 +0,2 @@ | ||
var B=Object.defineProperty;var j=(u,e,t)=>e in u?B(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var C=(u,e,t)=>(j(u,typeof e!="symbol"?e+"":e,t),t);import T from"babel-plugin-syntax-typescript-new";import L from"@babel/plugin-syntax-decorators";import{minimatch as w}from"minimatch";import{parseView as I}from"@dlightjs/view-parser";import{parseReactivity as E}from"@dlightjs/reactivity-parser";import{generateSubView as O,generateView as F}from"@dlightjs/view-generator";var M=process.env.NODE_ENV==="development",m=["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"],b="@dlightjs/dlight",g=Object.fromEntries(["createElement","setStyle","setDataset","setEvent","delegateEvent","setHTMLProp","setHTMLAttr","setHTMLProps","setHTMLAttrs","createTextNode","updateText","insertNode","ForNode","CondNode","ExpNode","EnvNode","SubViewNode","PropView"].map(u=>[u,u])),k={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"],class:["*"],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"],for:["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 P=class{dlightPackageName=b;babelApi;t;traverse;enableDevTools;includes;excludes;htmlTags;attributeMap;constructor(e,t,i,s,r,a,d){this.babelApi=e,this.t=t,this.traverse=e.traverse,this.includes=i,this.excludes=s,this.enableDevTools=M&&r,this.htmlTags=typeof a=="function"?a(N):a.includes("*")?[...new Set([...N,...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:i,isChildren:s}])=>e!=="_$compName"&&!t&&!i&&!s).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_${P.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 i=this.allImports.filter(s=>s.source.value===b);this.dlightPackageName!==b&&i.forEach(s=>{s.source.value=this.dlightPackageName}),this.programNode.body.unshift(this.t.importDeclaration(Object.entries(g).map(([s,r])=>this.t.importSpecifier(this.t.identifier(r),this.t.identifier(s))),this.t.stringLiteral(this.dlightPackageName))),this.didAlterImports=!0}}enterProgram(e){}programEnterVisitor(e,t){if(this.enter=this.fileAllowed(t),!this.enter)return;if(this.allImports=e.node.body.filter(s=>this.t.isImportDeclaration(s)),this.allImports.filter(s=>s.source.value===b).length===0){this.enter=!1;return}this.programNode=e.node,this.enterProgram(e)}exitProgram(e){}programExitVisitor(e){this.enter&&(this.didAlterImports=!1,this.allImports=[],this.programNode=void 0,this.exitProgram(e))}enterClass(e){}classEnter(e){this.enter&&(this.enterClassNode=this.isDLightClass(e),this.enterClass&&(this.initNode(e),this.enterClass(e)))}exitClass(e){}classExit(e){this.enter&&this.enterClassNode&&(this.transformDLightClass(),this.exitClass(e),this.clearNode(),this.enterClassNode=!1)}visitClassMethod(e){}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 s=e.node,r=this.findDecoratorByName(s.decorators,"Watch");if(this.t.isIdentifier(s.key,{name:"constructor"})||(this.autoBindMethods(s),!r))return;let a=[],d;if(this.t.isIdentifier(r))[a,d]=this.getDependencies(s);else{let o=r.arguments.filter(l=>this.t.isStringLiteral(l)).map(l=>l.value),n=this.t.classMethod("method",s.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:s,deps:a,depsNode:d,isWatcher:!0},s.decorators=this.removeDecorators(s.decorators,["Watch"]),this.visitClassMethod(e)}visitClassProperty(e){}classPropertyVisitor(e){if(!this.enterClassNode)return;let t=e.node;if(!this.t.isIdentifier(t.key))return;let i=t.key.name;if(i==="View")return;let s=t.decorators;if(this.findDecoratorByName(s,"View"))return;this.parseModel(e);let a=!!this.findDecoratorByName(s,"Prop"),d=!!this.findDecoratorByName(s,"Env"),o=!!this.findDecoratorByName(t.decorators,"Children"),[n,l]=o?[[]]:this.getDependencies(t);this.propertiesContainer[i]={node:t,deps:n,depsNode:l,isStatic:!!this.findDecoratorByName(s,"Static"),isContent:!!this.findDecoratorByName(s,"Content"),isChildren:o,isPropOrEnv:a?"Prop":d?"Env":void 0},t.decorators=this.removeDecorators(s,D),this.visitClassProperty(e)}resolveWatcherDecorator(e,t){if(!this.t.isIdentifier(e.key))return;let i=e.key.name,s=this.classBodyNode.body.indexOf(e),r=this.t.classProperty(this.t.identifier(`$w$${i}`));this.classBodyNode.body.splice(s,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(i),t]),this.t.blockStatement([this.t.returnStatement()])))}resolveChildrenDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let t=e.key.name,i=this.classBodyNode.body.indexOf(e),s=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(s)]));this.classBodyNode.body.splice(i,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,i=this.classBodyNode.body.indexOf(e),s=this.t.classProperty(this.t.identifier("_$contentKey"),this.t.stringLiteral(t));this.classBodyNode.body.splice(i,0,s)}resolvePropDecorator(e,t){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let i=e.key.name,s=this.classBodyNode.body.indexOf(e),r=t.toLowerCase()==="prop"?"p":"e",a=this.t.classProperty(this.t.identifier(`$${r}$${i}`));this.classBodyNode.body.splice(s,0,a)}resolveStateDecorator(e,t,i){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let s=e.key.name,r=this.classBodyNode.body.indexOf(e),a=this.dLightModel?[]:[this.t.classProperty(this.t.identifier(`$$${s}`),this.t.numericLiteral(1<<t))],d=i?[this.t.classProperty(this.t.identifier(`$s$${s}`),this.t.arrayExpression([...i].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(),i=this.dependencyMapReversed();this.addAutoUpdate(e);for(let[s,{node:r,deps:a,isStatic:d,isChildren:o,isPropOrEnv:n,isWatcher:l,isContent:c,depsNode:h}]of t){if(o){this.resolveChildrenDecorator(r);continue}a.length>0&&(e.push(...a),l?this.resolveWatcherDecorator(r,h):this.handleDerivedProperty(r,h)),n&&this.resolvePropDecorator(r,n),c&&(this.resolvePropDecorator(r,"Prop"),this.resolveContentDecorator(r)),!d&&e.includes(s)&&this.resolveStateDecorator(r,this.availableProperties.indexOf(s),i[s])}}addAutoUpdate(e){if(!this.classBodyNode)return;this.classBodyNode.body.filter(i=>!((this.t.isClassProperty(i)||this.t.isClassMethod(i))&&["View","constructor","_$compName"].includes(i.key.name)||this.t.isClassMethod(i,{kind:"method"})&&this.findDecoratorByName(i.decorators,"View"))).forEach(i=>{let s=this.t.isClassProperty(i)?i.value:this.t.isClassMethod(i)?i.body:null;s&&this.addAutoUpdateToNode(s,e)})}addAutoUpdateToNode(e,t){this.traverse(this.valueWrapper(e),{MemberExpression:i=>{if(!this.t.isThisExpression(i.node.object)||!this.t.isIdentifier(i.node.property))return;let s=i.node.property.name;if(!t.includes(s))return;let r=this.isAssignmentExpressionLeft(i);r&&this.addUpdate(r,s)},CallExpression:i=>{if(!this.t.isMemberExpression(i.node.callee))return;let s=i.node.callee.property;if(!this.t.isIdentifier(s)||!m.includes(s.name))return;let r=i.get("callee").get("object");for(;this.t.isMemberExpression(r.node);)r=r.get("object");if(!this.t.isThisExpression(r?.node))return;let a=r.parentPath.node.property.name;this.addUpdate(i,a)}})}addUpdate(e,t){let i=this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$updateView")),[this.t.stringLiteral(t)]),s=this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$updateDerived")),[this.t.stringLiteral(t)]),r=this.t.sequenceExpression([e.node,s]),a=e.parentPath;for(;a&&!(this.t.isBlockStatement(a.node)&&!this.t.isIfStatement(a.parentPath?.node)&&!this.t.isLoop(a.parentPath?.node));){if(this.t.isFunction(a.node)){a=a.get("body");break}a=a.parentPath}if(this.t.isBlockStatement(a?.node)){let d=a.node;this.getUpdatePropExp(d).has(t)||(this.getAllTopLevelReturnBlock(d).forEach(n=>{n.node.body.splice(-1,0,this.t.expressionStatement(i))}),this.t.isReturnStatement(d.body[d.body.length-1])||d.body.push(this.t.expressionStatement(i)))}else r=this.t.sequenceExpression([r,i]);e.replaceWith(r),e.skip()}getUpdatePropExp(e){let t=new Set;return e.body.forEach(i=>{if(!this.t.isExpressionStatement(i))return;let s=i.expression;if(!this.t.isCallExpression(s))return;let r=s.callee;if(!this.t.isMemberExpression(r))return;let a=r.object,d=r.property;if(!this.t.isThisExpression(a)||!this.t.isIdentifier(d,{name:"_$updateView"}))return;let o=s.arguments[0];this.t.isStringLiteral(o)&&t.add(o.value)}),t}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.addAutoUpdateToNode(t,this.availableProperties):this.addViewAutoUpdate(t))})}handleView(){if(!this.classBodyNode)return[];let e=new Set,t,i=[];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 h=this.arrowFunctionPropertyToMethod(o);if(!h)continue;o=h}n?(o.decorators=null,i.push(o)):t=o}}let s=i.map(o=>o.key.name),r=Object.fromEntries(i.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 h=c.key.name,p=this.getIdentifiers(this.t.assignmentExpression("=",this.t.objectPattern([this.t.objectProperty(this.t.numericLiteral(0),c.value)]),this.t.numericLiteral(0))).filter(f=>f!==h);return[h,p]}).filter(([c,h])=>h));return[o.key.name,l]}).filter(([o,n])=>n)),a=-1;if(t){let o;[o,a]=this.alterMainView(t,s,r),o.forEach(e.add.bind(e))}i.forEach(o=>{let n;[n,a]=this.alterSubView(o,s,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,i){let s=I(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});s.map(l=>this.addViewAutoUpdate(l));let[r,a]=E(s,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:m}),[d,o,n]=F(r,{babelApi:this.babelApi,className:this.className,importMap:g,subViewPropMap:Object.fromEntries(Object.entries(i).map(([l,c])=>[l,Object.keys(c)])),templateIdx:-1,attributeMap:this.attributeMap});return e.body=d,this.classBodyNode?.body.push(...o),[a,n]}alterSubView(e,t,i,s){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=I(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});r.map(y=>this.addViewAutoUpdate(y));let[a,d]=E(r,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:m}),o=i[e.key.name]??[],n={};Object.entries(o).forEach(([y,v])=>{v.forEach(V=>{n[V]=[y]})});let[l]=E(r,{babelApi:this.babelApi,availableProperties:Object.keys(o),dependencyMap:this.dependencyMap,dependencyParseType:"identifier",identifierDepMap:n,reactivityFuncNames:m}),c=Object.fromEntries(Object.entries(i).map(([y,v])=>[y,Object.keys(v)])),[h,p,f]=O(a,l,e.params[0],{babelApi:this.babelApi,className:this.className,importMap:g,subViewPropMap:c,templateIdx:s,attributeMap:this.attributeMap});return e.body=h,this.classBodyNode?.body.push(...p),[d,f]}fileAllowed(e){return this.includes.includes("*")?!0:!(!e||this.excludes.some(t=>w(e,t))||!this.includes.some(t=>w(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(r=>r.source.value===this.dlightPackageName&&r.specifiers.some(a=>{if(this.t.isImportSpecifier(a)&&this.t.isIdentifier(a.imported,{name:"use"}))return!0})))return;let i=e.node,s=i.key;this.t.isIdentifier(s)&&e.scope.traverse(i,{CallExpression:r=>{if(!this.t.isIdentifier(r.node.callee,{name:"use"}))return;let a=r.node.arguments,d=a[1],o=a[2],n=this.t.nullLiteral();if(d){let c=[],h=[];if(this.t.isObjectExpression(d))d.properties.forEach(p=>{if(this.t.isSpreadElement(p)){let[,f]=this.getDependenciesFromNode(p.argument);c.push([p.argument,f??this.t.nullLiteral()])}else if(this.t.isObjectProperty(p)){let[,f]=this.getDependenciesFromNode(p.value);h.push([!p.computed&&this.t.isIdentifier(p.key)?this.t.stringLiteral(p.key.name):p.key,p.value,f??this.t.nullLiteral()])}else h.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);c.push([d,p??this.t.nullLiteral()])}n=this.t.objectExpression([this.t.objectProperty(this.t.identifier("m"),this.t.arrayExpression(c.map(p=>this.t.arrayExpression(p)))),this.t.objectProperty(this.t.identifier("s"),this.t.arrayExpression(h.map(p=>this.t.arrayExpression(p))))])}let l=this.t.nullLiteral();if(o){let[,c]=this.getDependenciesFromNode(o);l=this.t.arrayExpression([o,c??this.t.nullLiteral()])}a[1]=n,a[2]=l,a[3]=this.t.stringLiteral(s.name),r.node.callee=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$injectModel"))}})}removeDecorators(e,t){return e?e.filter(i=>!(this.t.isIdentifier(i.expression)&&t.includes(i.expression.name)||this.t.isCallExpression(i.expression)&&this.t.isIdentifier(i.expression.callee)&&t.includes(i.expression.callee.name))):[]}findDecoratorByName(e,t){if(e)return e.find(i=>this.t.isIdentifier(i.expression,{name:t})||this.t.isCallExpression(i.expression)&&this.t.isIdentifier(i.expression.callee,{name:t}))?.expression}geneDependencyNode(e){let t=e;for(;t?.parentPath;){let i=t.parentPath;if(!(this.t.isBinaryExpression(i.node)||this.t.isMemberExpression(i.node)))return t.node;t=i}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 i=e.key.name,s=e.value,r=this.classBodyNode.body.indexOf(e),a=this.t.classMethod("get",this.t.identifier(`$f$${i}`),[],this.t.blockStatement([this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(i),t]),this.t.blockStatement([this.t.returnStatement(this.t.memberExpression(this.t.thisExpression(),this.t.identifier(i)))])),this.t.returnStatement(s)]));this.classBodyNode.body.splice(r+1,0,a),e.value=null}getDependenciesFromNode(e,t=!1){let i=new Set,s=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)?s.add(n):this.availableProperties.includes(n)&&!this.isMemberInEscapeFunction(o,this.classDeclarationNode)&&!this.isMemberInManualFunction(o,this.classDeclarationNode)&&(i.add(n),t&&this.dependencyMap[n]?.forEach(i.add.bind(i)),r[n]||(r[n]=[]),r[n].push(this.geneDependencyNode(o)))}}),s.forEach(o=>{i.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=[...i];if(t&&i.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,i])=>{i.forEach(s=>{e[s]||(e[s]=new Set),e[s].add(t)})}),e}arrowFunctionPropertyToMethod(e){if(!this.t.isArrowFunctionExpression(e.value))return;let t=e.value;if(!this.t.isBlockStatement(t.body))return;let i=this.classBodyNode.body.indexOf(e),s=this.t.classMethod("method",e.key,t.params,t.body);return this.classBodyNode.body.splice(i,1,s),s}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=[],i=!1;return this.traverse(this.valueWrapper(e),{Function:s=>{i||(i=!0,s.skip())},ReturnStatement:s=>{i||t.push(s.parentPath)},exit:s=>{this.t.isFunction(s.node)&&(i=!1)}}),t}valueWrapper(e){return this.t.file(this.t.program([this.t.isStatement(e)?e:this.t.expressionStatement(e)]))}isAttrFromFunction(e,t){let i=e.parentPath,s=r=>this.t.isIdentifier(r)?r.name===t:this.t.isAssignmentPattern(r)?s(r.left):this.t.isArrayPattern(r)?r.elements.filter(Boolean).map(a=>s(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)?s(r.argument):!1;for(;i;){let r=i.node;if(this.t.isArrowFunctionExpression(r)||this.t.isFunctionDeclaration(r)){for(let a of r.params)if(s(a))return!0}i=i.parentPath}return!1}isStandAloneIdentifier(e){let t=e.node,i=e.parentPath?.node;if(this.t.isMemberExpression(i)&&i.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:i=>{this.isStandAloneIdentifier(i)&&t.add(i.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 i=t.get("left");if(e.isDescendant(i))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)&&m.includes(t.node.callee.property.name):!1}isMemberInEscapeFunction(e,t){let i=!1,s=e.parentPath;for(;s&&s.node!==t;){let r=s.node;if(this.t.isCallExpression(r)&&this.t.isIdentifier(r.callee)&&P.escapeNamings.includes(r.callee.name)){i=!0;break}s=s.parentPath}return i}isMemberInManualFunction(e,t){let i=!1,s=e.parentPath;for(;s&&s.node!==t;){let r=s.node,a=s.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){i=!0;break}s=s.parentPath}return i}static uid(e=4){return Math.random().toString(32).slice(2,e+2)}},x=P;C(x,"escapeNamings",["escape","$"]);var S=x;function A(u,e){let{types:t}=u,{files:i="**/*.{js,ts}",excludeFiles:s="**/{dist,node_modules,lib}/*",enableDevTools:r=!1,htmlTags:a=n=>n,attributeMap:d=k}=e,o=new S(u,t,Array.isArray(i)?i:[i],Array.isArray(s)?s:[s],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 ee(u,e){return{plugins:[T,[L.default??L,{legacy:!0}],[A,e]]}}export{ee as default}; | ||
var B=Object.defineProperty;var j=(u,e,t)=>e in u?B(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var C=(u,e,t)=>(j(u,typeof e!="symbol"?e+"":e,t),t);import T from"babel-plugin-syntax-typescript-new";import L from"@babel/plugin-syntax-decorators";import{minimatch as w}from"minimatch";import{parseView as I}from"@dlightjs/view-parser";import{parseReactivity as E}from"@dlightjs/reactivity-parser";import{generateSubView as O,generateView as F}from"@dlightjs/view-generator";var M=process.env.NODE_ENV==="development",m=["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"],b="@dlightjs/dlight",g=Object.fromEntries(["createElement","setStyle","setDataset","setEvent","delegateEvent","setHTMLProp","setHTMLAttr","setHTMLProps","setHTMLAttrs","createTextNode","updateText","insertNode","ForNode","CondNode","ExpNode","EnvNode","SubViewNode","PropView"].map(u=>[u,u])),k={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"],class:["*"],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"],for:["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 P=class{dlightPackageName=b;babelApi;t;traverse;enableDevTools;includes;excludes;htmlTags;attributeMap;constructor(e,t,i,s,r,a,d){this.babelApi=e,this.t=t,this.traverse=e.traverse,this.includes=i,this.excludes=s,this.enableDevTools=M&&r,this.htmlTags=typeof a=="function"?a(N):a.includes("*")?[...new Set([...N,...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:i,isChildren:s}])=>e!=="_$compName"&&!t&&!i&&!s).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_${P.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 i=this.allImports.filter(s=>s.source.value===b);this.dlightPackageName!==b&&i.forEach(s=>{s.source.value=this.dlightPackageName}),this.programNode.body.unshift(this.t.importDeclaration(Object.entries(g).map(([s,r])=>this.t.importSpecifier(this.t.identifier(r),this.t.identifier(s))),this.t.stringLiteral(this.dlightPackageName))),this.didAlterImports=!0}}enterProgram(e){}programEnterVisitor(e,t){if(this.enter=this.fileAllowed(t),!this.enter)return;if(this.allImports=e.node.body.filter(s=>this.t.isImportDeclaration(s)),this.allImports.filter(s=>s.source.value===b).length===0){this.enter=!1;return}this.programNode=e.node,this.enterProgram(e)}exitProgram(e){}programExitVisitor(e){this.enter&&(this.didAlterImports=!1,this.allImports=[],this.programNode=void 0,this.exitProgram(e))}enterClass(e){}classEnter(e){this.enter&&(this.enterClassNode=this.isDLightClass(e),this.enterClass&&(this.initNode(e),this.enterClass(e)))}exitClass(e){}classExit(e){this.enter&&this.enterClassNode&&(this.transformDLightClass(),this.exitClass(e),this.clearNode(),this.enterClassNode=!1)}visitClassMethod(e){}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 s=e.node,r=this.findDecoratorByName(s.decorators,"Watch");if(this.t.isIdentifier(s.key,{name:"constructor"})||(this.autoBindMethods(s),!r))return;let a=[],d;if(this.t.isIdentifier(r))[a,d]=this.getDependencies(s);else{let o=r.arguments.filter(l=>this.t.isStringLiteral(l)).map(l=>l.value),n=this.t.classMethod("method",s.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:s,deps:a,depsNode:d,isWatcher:!0},s.decorators=this.removeDecorators(s.decorators,["Watch"]),this.visitClassMethod(e)}visitClassProperty(e){}classPropertyVisitor(e){if(!this.enterClassNode)return;let t=e.node;if(!this.t.isIdentifier(t.key))return;let i=t.key.name;if(i==="View")return;let s=t.decorators;if(this.findDecoratorByName(s,"View"))return;this.parseModel(e);let a=!!this.findDecoratorByName(s,"Prop"),d=!!this.findDecoratorByName(s,"Env"),o=!!this.findDecoratorByName(t.decorators,"Children"),[n,l]=o?[[]]:this.getDependencies(t);this.propertiesContainer[i]={node:t,deps:n,depsNode:l,isStatic:!!this.findDecoratorByName(s,"Static"),isContent:!!this.findDecoratorByName(s,"Content"),isChildren:o,isPropOrEnv:a?"Prop":d?"Env":void 0},t.decorators=this.removeDecorators(s,D),this.visitClassProperty(e)}resolveWatcherDecorator(e,t){if(!this.t.isIdentifier(e.key))return;let i=e.key.name,s=this.classBodyNode.body.indexOf(e),r=this.t.classProperty(this.t.identifier(`$w$${i}`));this.classBodyNode.body.splice(s,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(i),t]),this.t.blockStatement([this.t.returnStatement()])))}resolveChildrenDecorator(e){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let t=e.key.name,i=this.classBodyNode.body.indexOf(e),s=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(s)]));this.classBodyNode.body.splice(i,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,i=this.classBodyNode.body.indexOf(e),s=this.t.classProperty(this.t.identifier("_$contentKey"),this.t.stringLiteral(t));this.classBodyNode.body.splice(i,0,s)}resolvePropDecorator(e,t){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let i=e.key.name,s=this.classBodyNode.body.indexOf(e),r=t.toLowerCase()==="prop"?"p":"e",a=this.t.classProperty(this.t.identifier(`$${r}$${i}`));this.classBodyNode.body.splice(s,0,a)}resolveStateDecorator(e,t,i){if(!this.classBodyNode||!this.t.isIdentifier(e.key))return;let s=e.key.name,r=this.classBodyNode.body.indexOf(e),a=this.dLightModel?[]:[this.t.classProperty(this.t.identifier(`$$${s}`),this.t.numericLiteral(1<<t))],d=i?[this.t.classProperty(this.t.identifier(`$s$${s}`),this.t.arrayExpression([...i].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(),i=this.dependencyMapReversed();this.addAutoUpdate(e);for(let[s,{node:r,deps:a,isStatic:d,isChildren:o,isPropOrEnv:n,isWatcher:l,isContent:c,depsNode:h}]of t){if(o){this.resolveChildrenDecorator(r);continue}a.length>0&&(e.push(...a),l?this.resolveWatcherDecorator(r,h):this.handleDerivedProperty(r,h)),n&&this.resolvePropDecorator(r,n),c&&(this.resolvePropDecorator(r,"Prop"),this.resolveContentDecorator(r)),!d&&e.includes(s)&&this.resolveStateDecorator(r,this.availableProperties.indexOf(s),i[s])}}addAutoUpdate(e){if(!this.classBodyNode)return;this.classBodyNode.body.filter(i=>!((this.t.isClassProperty(i)||this.t.isClassMethod(i))&&["View","constructor","_$compName"].includes(i.key.name)||this.t.isClassMethod(i,{kind:"method"})&&this.findDecoratorByName(i.decorators,"View"))).forEach(i=>{let s=this.t.isClassProperty(i)?i.value:this.t.isClassMethod(i)?i.body:null;s&&this.addAutoUpdateToNode(s,e)})}addAutoUpdateToNode(e,t){this.traverse(this.valueWrapper(e),{MemberExpression:i=>{if(!this.t.isThisExpression(i.node.object)||!this.t.isIdentifier(i.node.property))return;let s=i.node.property.name;if(!t.includes(s))return;let r=this.isAssignmentExpressionLeft(i);r&&this.addUpdate(r,s)},CallExpression:i=>{if(!this.t.isMemberExpression(i.node.callee))return;let s=i.node.callee.property;if(!this.t.isIdentifier(s)||!m.includes(s.name))return;let r=i.get("callee").get("object");for(;this.t.isMemberExpression(r.node);)r=r.get("object");if(!this.t.isThisExpression(r?.node))return;let a=r.parentPath.node.property.name;this.addUpdate(i,a)}})}addUpdate(e,t){let i=this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$updateView")),[this.t.stringLiteral(t)]),s=this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$updateDerived")),[this.t.stringLiteral(t)]),r=this.t.sequenceExpression([e.node,s]),a=e.parentPath;for(;a&&!(this.t.isBlockStatement(a.node)&&!this.t.isIfStatement(a.parentPath?.node)&&!this.t.isLoop(a.parentPath?.node));){if(this.t.isFunction(a.node)){a=a.get("body");break}a=a.parentPath}if(this.t.isBlockStatement(a?.node)){let d=a.node;this.getUpdatePropExp(d).has(t)||(this.getAllTopLevelReturnBlock(d).forEach(n=>{n.body.splice(-1,0,this.t.expressionStatement(i))}),this.t.isReturnStatement(d.body[d.body.length-1])||d.body.push(this.t.expressionStatement(i)))}else r=this.t.sequenceExpression([r,i]);e.replaceWith(r),e.skip()}getUpdatePropExp(e){let t=new Set;return e.body.forEach(i=>{if(!this.t.isExpressionStatement(i))return;let s=i.expression;if(!this.t.isCallExpression(s))return;let r=s.callee;if(!this.t.isMemberExpression(r))return;let a=r.object,d=r.property;if(!this.t.isThisExpression(a)||!this.t.isIdentifier(d,{name:"_$updateView"}))return;let o=s.arguments[0];this.t.isStringLiteral(o)&&t.add(o.value)}),t}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.addAutoUpdateToNode(t,this.availableProperties):this.addViewAutoUpdate(t))})}handleView(){if(!this.classBodyNode)return[];let e=new Set,t,i=[];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 h=this.arrowFunctionPropertyToMethod(o);if(!h)continue;o=h}n?(o.decorators=null,i.push(o)):t=o}}let s=i.map(o=>o.key.name),r=Object.fromEntries(i.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 h=c.key.name,p=this.getIdentifiers(this.t.assignmentExpression("=",this.t.objectPattern([this.t.objectProperty(this.t.numericLiteral(0),c.value)]),this.t.numericLiteral(0))).filter(f=>f!==h);return[h,p]}).filter(([c,h])=>h));return[o.key.name,l]}).filter(([o,n])=>n)),a=-1;if(t){let o;[o,a]=this.alterMainView(t,s,r),o.forEach(e.add.bind(e))}i.forEach(o=>{let n;[n,a]=this.alterSubView(o,s,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,i){let s=I(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});s.map(l=>this.addViewAutoUpdate(l));let[r,a]=E(s,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:m}),[d,o,n]=F(r,{babelApi:this.babelApi,className:this.className,importMap:g,subViewPropMap:Object.fromEntries(Object.entries(i).map(([l,c])=>[l,Object.keys(c)])),templateIdx:-1,attributeMap:this.attributeMap});return e.body=d,this.classBodyNode?.body.push(...o),[a,n]}alterSubView(e,t,i,s){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=I(e.body,{babelApi:this.babelApi,subviewNames:t,htmlTags:this.htmlTags});r.map(y=>this.addViewAutoUpdate(y));let[a,d]=E(r,{babelApi:this.babelApi,availableProperties:this.availableProperties,dependencyMap:this.dependencyMap,reactivityFuncNames:m}),o=i[e.key.name]??[],n={};Object.entries(o).forEach(([y,v])=>{v.forEach(V=>{n[V]=[y]})});let[l]=E(r,{babelApi:this.babelApi,availableProperties:Object.keys(o),dependencyMap:this.dependencyMap,dependencyParseType:"identifier",identifierDepMap:n,reactivityFuncNames:m}),c=Object.fromEntries(Object.entries(i).map(([y,v])=>[y,Object.keys(v)])),[h,p,f]=O(a,l,e.params[0],{babelApi:this.babelApi,className:this.className,importMap:g,subViewPropMap:c,templateIdx:s,attributeMap:this.attributeMap});return e.body=h,this.classBodyNode?.body.push(...p),[d,f]}fileAllowed(e){return this.includes.includes("*")?!0:!(!e||this.excludes.some(t=>w(e,t))||!this.includes.some(t=>w(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(r=>r.source.value===this.dlightPackageName&&r.specifiers.some(a=>{if(this.t.isImportSpecifier(a)&&this.t.isIdentifier(a.imported,{name:"use"}))return!0})))return;let i=e.node,s=i.key;this.t.isIdentifier(s)&&e.scope.traverse(i,{CallExpression:r=>{if(!this.t.isIdentifier(r.node.callee,{name:"use"}))return;let a=r.node.arguments,d=a[1],o=a[2],n=this.t.nullLiteral();if(d){let c=[],h=[];if(this.t.isObjectExpression(d))d.properties.forEach(p=>{if(this.t.isSpreadElement(p)){let[,f]=this.getDependenciesFromNode(p.argument);c.push([p.argument,f??this.t.nullLiteral()])}else if(this.t.isObjectProperty(p)){let[,f]=this.getDependenciesFromNode(p.value);h.push([!p.computed&&this.t.isIdentifier(p.key)?this.t.stringLiteral(p.key.name):p.key,p.value,f??this.t.nullLiteral()])}else h.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);c.push([d,p??this.t.nullLiteral()])}n=this.t.objectExpression([this.t.objectProperty(this.t.identifier("m"),this.t.arrayExpression(c.map(p=>this.t.arrayExpression(p)))),this.t.objectProperty(this.t.identifier("s"),this.t.arrayExpression(h.map(p=>this.t.arrayExpression(p))))])}let l=this.t.nullLiteral();if(o){let[,c]=this.getDependenciesFromNode(o);l=this.t.arrayExpression([o,c??this.t.nullLiteral()])}a[1]=n,a[2]=l,a[3]=this.t.stringLiteral(s.name),r.node.callee=this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$injectModel"))}})}removeDecorators(e,t){return e?e.filter(i=>!(this.t.isIdentifier(i.expression)&&t.includes(i.expression.name)||this.t.isCallExpression(i.expression)&&this.t.isIdentifier(i.expression.callee)&&t.includes(i.expression.callee.name))):[]}findDecoratorByName(e,t){if(e)return e.find(i=>this.t.isIdentifier(i.expression,{name:t})||this.t.isCallExpression(i.expression)&&this.t.isIdentifier(i.expression.callee,{name:t}))?.expression}geneDependencyNode(e){let t=e;for(;t?.parentPath;){let i=t.parentPath;if(!(this.t.isBinaryExpression(i.node)||this.t.isMemberExpression(i.node)))return t.node;t=i}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 i=e.key.name,s=e.value,r=this.classBodyNode.body.indexOf(e),a=this.t.classMethod("get",this.t.identifier(`$f$${i}`),[],this.t.blockStatement([this.t.ifStatement(this.t.callExpression(this.t.memberExpression(this.t.thisExpression(),this.t.identifier("_$cache")),[this.t.stringLiteral(i),t]),this.t.blockStatement([this.t.returnStatement(this.t.memberExpression(this.t.thisExpression(),this.t.identifier(i)))])),this.t.returnStatement(s)]));this.classBodyNode.body.splice(r+1,0,a),e.value=null}getDependenciesFromNode(e,t=!1){let i=new Set,s=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)?s.add(n):this.availableProperties.includes(n)&&!this.isMemberInEscapeFunction(o,this.classDeclarationNode)&&!this.isMemberInManualFunction(o,this.classDeclarationNode)&&(i.add(n),t&&this.dependencyMap[n]?.forEach(i.add.bind(i)),r[n]||(r[n]=[]),r[n].push(this.geneDependencyNode(o)))}}),s.forEach(o=>{i.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=[...i];if(t&&i.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,i])=>{i.forEach(s=>{e[s]||(e[s]=new Set),e[s].add(t)})}),e}arrowFunctionPropertyToMethod(e){if(!this.t.isArrowFunctionExpression(e.value))return;let t=e.value;if(!this.t.isBlockStatement(t.body))return;let i=this.classBodyNode.body.indexOf(e),s=this.t.classMethod("method",e.key,t.params,t.body);return this.classBodyNode.body.splice(i,1,s),s}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=[],i=!1;return this.traverse(this.valueWrapper(e),{Function:s=>{i||(i=!0,s.skip())},ReturnStatement:s=>{if(i)return;let r=s.parentPath.node;if(this.t.isBlockStatement(r))t.push(r);else{let a=this.t.blockStatement([s.node]);s.replaceWith(a),t.push(a)}s.skip()},exit:s=>{this.t.isFunction(s.node)&&(i=!1)}}),t}valueWrapper(e){return this.t.file(this.t.program([this.t.isStatement(e)?e:this.t.expressionStatement(e)]))}isAttrFromFunction(e,t){let i=e.parentPath,s=r=>this.t.isIdentifier(r)?r.name===t:this.t.isAssignmentPattern(r)?s(r.left):this.t.isArrayPattern(r)?r.elements.filter(Boolean).map(a=>s(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)?s(r.argument):!1;for(;i;){let r=i.node;if(this.t.isArrowFunctionExpression(r)||this.t.isFunctionDeclaration(r)){for(let a of r.params)if(s(a))return!0}i=i.parentPath}return!1}isStandAloneIdentifier(e){let t=e.node,i=e.parentPath?.node;if(this.t.isMemberExpression(i)&&i.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:i=>{this.isStandAloneIdentifier(i)&&t.add(i.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 i=t.get("left");if(e.isDescendant(i))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)&&m.includes(t.node.callee.property.name):!1}isMemberInEscapeFunction(e,t){let i=!1,s=e.parentPath;for(;s&&s.node!==t;){let r=s.node;if(this.t.isCallExpression(r)&&this.t.isIdentifier(r.callee)&&P.escapeNamings.includes(r.callee.name)){i=!0;break}s=s.parentPath}return i}isMemberInManualFunction(e,t){let i=!1,s=e.parentPath;for(;s&&s.node!==t;){let r=s.node,a=s.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){i=!0;break}s=s.parentPath}return i}static uid(e=4){return Math.random().toString(32).slice(2,e+2)}},x=P;C(x,"escapeNamings",["escape","$"]);var S=x;function A(u,e){let{types:t}=u,{files:i="**/*.{js,ts}",excludeFiles:s="**/{dist,node_modules,lib}/*",enableDevTools:r=!1,htmlTags:a=n=>n,attributeMap:d=k}=e,o=new S(u,t,Array.isArray(i)?i:[i],Array.isArray(s)?s:[s],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 ee(u,e){return{plugins:[T,[L.default??L,{legacy:!0}],[A,e]]}}export{ee as default}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "babel-preset-dlight", | ||
"version": "1.0.0-beta.4", | ||
"version": "1.0.0-beta.5", | ||
"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
268952
264