@tslite/emit 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +4 -0
- package/dist/index.d.cts +78 -0
- package/dist/index.d.ts +78 -0
- package/dist/index.js +4 -0
- package/package.json +61 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var printer=require('@tslite/printer'),core=require('@tslite/core'),typeCore=require('@tslite/type-core');var r=e=>({t:"concat",parts:e}),h={t:"line"},g={t:"softline"},m={t:"hardline"},H={t:"breakParent"},y=e=>({t:"indent",doc:e}),D=e=>({t:"group",doc:e}),S=(e,t="")=>({t:"ifBreak",broken:e,flat:t}),Y=e=>({t:"fill",parts:e});function N(e,t){let n=[];return t.forEach((o,s)=>{s>0&&n.push(e),n.push(o);}),r(n)}var L=1,w=2;function J(e,t){if(typeof e=="string")return false;let n=t.get(e);if(n!==void 0)return n;let o=false;switch(e.t){case "hardline":case "breakParent":o=true;break;case "concat":case "fill":o=e.parts.some(s=>J(s,t));break;case "indent":case "group":o=J(e.doc,t);break;default:o=false;}return t.set(e,o),o}function Z(e,t,n,o){let s=n,a=[e],i=t.length-1;for(;s>=0;){if(a.length===0){if(i<0)return true;a.push(t[i--]);continue}let{indent:p,mode:u,doc:f}=a.pop();if(typeof f=="string"){s-=f.length;continue}switch(f.t){case "concat":case "fill":for(let l=f.parts.length-1;l>=0;l--)a.push({indent:p,mode:u,doc:f.parts[l]});break;case "indent":a.push({indent:p,mode:u,doc:f.doc});break;case "group":a.push({indent:p,mode:J(f.doc,o)?w:u,doc:f.doc});break;case "ifBreak":a.push({indent:p,mode:u,doc:u===w?f.broken:f.flat});break;case "line":if(u===w)return true;s-=1;break;case "softline":if(u===w)return true;break;case "hardline":return true;}}return false}function ee(e,t=80,n=2){let o=new Map,s=[],a=0,i=u=>{s.push(`
|
|
2
|
+
`+" ".repeat(u)),a=u;},p=[{indent:0,mode:w,doc:e}];for(;p.length>0;){let{indent:u,mode:f,doc:l}=p.pop();if(typeof l=="string"){s.push(l),a+=l.length;continue}switch(l.t){case "concat":for(let x=l.parts.length-1;x>=0;x--)p.push({indent:u,mode:f,doc:l.parts[x]});break;case "indent":p.push({indent:u+n,mode:f,doc:l.doc});break;case "group":{let x=J(l.doc,o)||!Z({indent:u,mode:L,doc:l.doc},p,t-a,o)?w:L;p.push({indent:u,mode:x,doc:l.doc});break}case "ifBreak":p.push({indent:u,mode:f,doc:f===w?l.broken:l.flat});break;case "fill":{let x=l.parts;if(x.length===0)break;let[T,k,...U]=x,W=t-a,j={indent:u,mode:L,doc:T},Q={indent:u,mode:w,doc:T},z=!J(T,o)&&Z(j,[],W,o);if(x.length===1){p.push(z?j:Q);break}let le={indent:u,mode:L,doc:k},_={indent:u,mode:w,doc:k};if(x.length===2){z?p.push(le,j):p.push(_,Q);break}let V={indent:u,mode:f,doc:Y(U)},fe=U[0];!J(T,o)&&!J(fe,o)&&Z({indent:u,mode:L,doc:r([T,k,fe])},[],W,o)?p.push(V,le,j):z?p.push(V,_,j):p.push(V,_,Q);break}case "line":f===L?(s.push(" "),a+=1):i(u);break;case "softline":f===w&&i(u);break;case "hardline":i(u);break;}}return s.join("").replace(/[ \t]+(\n|$)/g,"$1")}var ge=true;function De(e){ge=e;}var se=false;function be(e){se=e;}var xe="arrow";function Se(e){xe=e;}function $(e){let t=(e.match(/"/g)??[]).length,n=(e.match(/'/g)??[]).length;return (se?t<n:t<=n)?JSON.stringify(e):`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,'"').replace(/'/g,"\\'")}'`}function I(e){if(e?.type==="RestElement")return r(["...",I(e.argument)]);if(e?.type==="AssignmentPattern")return r([I(e.left)," = ",c(e.right)]);let t=e?.optional?r([printer.print(e),"?"]):printer.print(e);return e?.typeAnnotation?r([t,": ",v(e.typeAnnotationNode,e.typeAnnotation)]):t}function B(e){return e.type==="Line"?"//"+e.value:"/*"+e.value+"*/"}function E(e){let t=e?.leadingComments;if(!t||t.length===0)return "";let n=[];for(let o=0;o<t.length;o++){let s=t[o];n.push(B(s));let a=o<t.length-1?t[o+1].loc?.start?.line:e.loc?.start?.line,i=s.loc?.end?.line;a==null||i==null?n.push(m):s.type==="Line"||i<a?n.push(a-i>1?r([m,m]):m):n.push(" ");}return r(n)}function C(e){let t=e?.trailingComments;if(!t||t.length===0)return "";let n=[],o=e.loc?.end?.line;for(let s of t){let a=s.loc?.start?.line;a!=null&&o!=null&&a>o?(n.push(a-o>1?r([m,m]):m),n.push(B(s))):n.push(" ",B(s)),s.type==="Line"&&n.push(H),o=s.loc?.end?.line??o;}return r(n)}function M(e,t,n){let o=e?.innerComments;if(!o||o.length===0)return t+n;let s=N(m,o.map(B));return o.some(i=>i.type==="Line")?r([t,y(r([m,s])),m,n]):r([t," ",s," ",n])}function q(e,t,n){let o=C(e);return o===""?r([t,n]):e?.trailingComments?.some(a=>a.type==="Line")?r([t,n,o]):r([t,o,n])}function ae(e,t){let n=[];return e.forEach((o,s)=>{let a=s===e.length-1;if(o==null){a||n.push(",",h);return}let i=a?S(","):",";n.push(E(o),q(o,G(o),i)),a||n.push(h);}),r(n)}function Ne(e){if(e.length===0)return "()";let t=[];return e.forEach((n,o)=>{let s=o===e.length-1,a=s?n.type==="RestElement"?"":S(","):",";t.push(E(n),q(n,I(n),a)),s||t.push(h);}),D(r(["(",y(r([g,r(t)])),g,")"]))}var Oe=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function $e(e){return e?.type==="TSUnionType"||e?.type==="TSFunctionType"||e?.type==="TSConditionalType"}function Me(e){return r([e.name,e.optional?"?":"",": ",d(e.typeAnnotation)])}function Te(e){return e.length===0?"()":D(r(["(",y(r([g,N(r([",",h]),e.map(Me)),S(",")])),g,")"]))}function Xe(e){switch(e.type){case "TSPropertySignature":return r([e.readonly?"readonly ":"",Oe(e.key)?e.key:$(e.key),e.optional?"?":"",": ",d(e.typeAnnotation)]);case "TSIndexSignature":return r(["[k: ",e.keyType,"]: ",d(e.typeAnnotation)]);case "TSCallSignatureDeclaration":return r([Te(e.params),": ",d(e.returnType)]);default:return ""}}function Ge(e){if(e.members.length===0)return M(e,"{","}");let t=[];return e.members.forEach((n,o)=>{let s=o===e.members.length-1,a=s?S(";"):";";t.push(E(n),q(n,Xe(n),a)),s||t.push(h);}),D(r(["{",y(r([h,r(t)])),h,"}"]))}function Ue(e){let t=e.elementTypes.map((o,s)=>{let a=e.flags?.[s]??"req",i=e.labels?.[s],p=d(o),u=o.type==="TSUnionType"?r(["(",p,")"]):p;return i!==void 0?a==="rest"?r(["...",i,": ",u,"[]"]):a==="variadic"?r(["...",i,": ",p]):a==="optional"?r([i,"?: ",p]):r([i,": ",p]):a==="rest"?r(["...",u,"[]"]):a==="variadic"?r(["...",p]):a==="optional"?r([u,"?"]):p}),n=r(["[",N(", ",t),"]"]);return e.readonly?r(["readonly ",n]):n}function We(e){switch(e.type){case "TSKeywordType":return e.kind;case "TSLiteralType":return typeof e.literal=="string"?$(e.literal):String(e.literal);case "TSTypeReference":return r([e.typeName,e.typeArguments?.length?r(["<",N(", ",e.typeArguments.map(d)),">"]):""]);case "TSArrayType":{let t=$e(e.elementType)?r(["(",d(e.elementType),")"]):d(e.elementType),n=r([t,"[]"]);return e.readonly?r(["readonly ",n]):n}case "TSIndexedAccessType":return r([d(e.objectType),"[",d(e.indexType),"]"]);case "TSUnionType":return D(y(r([S(r([g,"| "])),N(r([h,"| "]),e.types.map(d))])));case "TSIntersectionType":return N(" & ",e.types.map(t=>t.type==="TSUnionType"?r(["(",d(t),")"]):d(t)));case "TSFunctionType":return r([e.typeParams?.length?r(["<",e.typeParams.join(", "),">"]):"",Te(e.params)," => ",d(e.returnType)]);case "TSTypeLiteral":return Ge(e);case "TSTupleType":return Ue(e);case "TSTypeOperator":return r([e.operator," ",d(e.typeAnnotation)]);case "TSInferType":return r(["infer ",e.name]);case "TSConditionalType":return r([d(e.checkType)," extends ",d(e.extendsType)," ? ",d(e.trueType)," : ",d(e.falseType)]);case "TSMappedType":return D(r(["{",y(r([h,"[",e.key," in ",d(e.constraint),"]",e.optional?"?":"",": ",d(e.typeAnnotation),S(";")])),h,"}"]));case "TSTypeQuery":return r(["typeof ",e.exprName.join(".")]);default:return ""}}function d(e){if(e==null)return "";let t=We(e),n=E(e),o=C(e);return n===""&&o===""?t:r([n,t,o])}function v(e,t){return e?d(e):typeCore.format(t)}function ce(e,t){if(!e?.length)return "";let n=[];e.forEach((s,a)=>{a>0&&n.push(", "),s.isConst&&n.push("const "),n.push(s.name),s.boundNode&&n.push(" extends ",d(s.boundNode)),s.defaultNode&&n.push(" = ",d(s.defaultNode));});let o=e.length===1&&!e[0].boundNode&&!e[0].defaultNode;return r(["<",...n,t&&o?",":"",">"])}function ie(e){let t=[],n,o=0;for(let s of e){let a=K(s),i=X(a);if(i!==""){if(o>0){let p=n?.loc?.end?.line,u=a?.leadingComments?.[0]?.loc?.start?.line??a?.loc?.start?.line,f=p!=null&&u!=null?u-p:1;t.push(f>1?r([m,m]):m);}t.push(i),n=a,o++;}}return {doc:r(t),count:o}}var qe=new Set(["FunctionDeclaration","IfStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","TryStatement","SwitchStatement","ClassDeclaration","BlockStatement","LabeledStatement"]);function X(e){let t=G(e);if(t==="")return "";let n=(e.type==="ExportNamedDeclaration"||e.type==="ExportDefaultDeclaration")&&K(e.declaration)?.type==="FunctionDeclaration",o=ge&&!qe.has(e.type)&&!n?";":"";return r([E(e),t,o,C(e)])}function Re(e){let{doc:t,count:n}=ie(e.body);return r([t,n?m:""])}function Ke(e){let{doc:t,count:n}=ie(e.body);return n===0?M(e,"{","}"):r(["{",y(r([m,t])),m,"}"])}function Qe(e){return e.properties.length===0?M(e,"{","}"):D(r(["{",y(r([h,ae(e.properties)])),h,"}"]))}function ze(e){return e.elements.length===0?M(e,"[","]"):D(r(["[",y(r([g,ae(e.elements)])),g,"]"]))}function _e(e){return e!=null&&(e.type==="ArrowFunctionExpression"||e.type==="FunctionExpression"||e.type==="ObjectExpression"||e.type==="JsonExpression"||e.type==="ArrayExpression")}function Ve(e){let t=c(e);return e.type!=="TSAsExpression"&&printer.isPrimaryOperand(e)?t:r(["(",t,")"])}function Ee(e){let t=e.typeArguments,n=r([t?.length?r(["<",N(", ",t.map(o=>typeCore.format(o))),">"]):"",e.optional?"?.":""]);if(e.arguments.length===0)return r([n,"()"]);if(_e(e.arguments[e.arguments.length-1])){let o=[n,"("],s=e.arguments.length-1;for(let a=0;a<s;a++){let i=e.arguments[a];o.push(E(i),q(i,G(i),",")," ");}return o.push(c(e.arguments[s]),")"),r(o)}return r([n,"(",D(r([y(r([g,ae(e.arguments)])),g])),")"])}function Ze(e){return ke(e)??r([Ve(e.callee),Ee(e)])}function te(e){let t=[];return e.optional&&t.push(e.computed?"?.":"?"),t.push(e.computed?"[":"."),t.push(e.computed?c(e.property):printer.print(e.property)),e.computed&&t.push("]"),r(t)}var He=e=>!!(e?.leadingComments?.length||e?.trailingComments?.length);function ne(e){switch(e?.type){case "Identifier":case "Literal":return true;case "TemplateLiteral":return e.expressions.length===0;case "MemberExpression":return !e.computed&&ne(e.object);case "UnaryExpression":return ne(e.argument);default:return false}}function ke(e){let t=[],n=e;for(;;)if(n.type==="CallExpression"&&n.callee?.type==="MemberExpression")t.unshift(n),n=n.callee;else if(n.type==="MemberExpression")t.unshift(n),n=n.object;else break;let o=n;if(t.some(He))return null;let s=[],a=0,i=false;for(let l of t)l.type==="CallExpression"?(a++,l.arguments.every(ne)||(i=true),(s[s.length-1]??(s[0]=[])).push(Ee(l))):l.computed?(s[s.length-1]??(s[0]=[])).push(te(l)):s.push([te(l)]);if(s.length<3)return null;let p=Ce(o),u=a>2&&i?m:g,f=s.map(l=>r([u,r(l)]));return D(r([p,y(r(f))]))}function Ye(e){return ke(e)??r([Ce(e.object),te(e)])}function A(e){if(!e||typeof e!="object")return false;switch(e.type){case "ObjectExpression":case "JsonExpression":return true;case "ConditionalExpression":return A(e.test);case "LogicalExpression":case "BinaryExpression":case "AssignmentExpression":return A(e.left);case "MemberExpression":return A(e.object);case "CallExpression":return A(e.callee);case "TaggedTemplateExpression":return A(e.tag);case "ChainExpression":case "TSAsExpression":return A(e.expression);case "SequenceExpression":return A(e.expressions?.[0]);default:return false}}function et(e){let t=e.async?"async ":"",n=ue(e.body)?pe(e.body):c(e.body);e.body.type!=="BlockStatement"&&A(e.body)&&(n=r(["(",n,")"]));let o=ce(e.typeParamNodes,true),s=Ne(e.params??[]),a=e.returnType?r([": ",v(e.returnTypeNode,e.returnType)]):"";return r([t,o,s,a," => ",n])}function tt(e){let t=printer.needsParens(e.test,core.Precedence.Conditional,false,true)?r(["(",c(e.test),")"]):c(e.test);return D(r([t,y(r([h,"? ",c(e.consequent),h,": ",c(e.alternate)]))]))}function nt(e){if(e.shorthand)return printer.print(e.value);let t=e.computed?r(["[",printer.print(e.key),"]"]):printer.print(e.key);return r([t,": ",R(e.value)])}function rt(e){let t=e.declarations.map(n=>n.init?r([I(n.id)," = ",R(n.init)]):I(n.id));return r([e.kind," ",N(r([","," "]),t)])}function ot(e){let t=printer.print(e.expression),n=t[0]==="{"||t.startsWith("function")||t.startsWith("class"),o=c(e.expression);return n?r(["(",o,")"]):o}function O(e){return e?.type==="BlockStatement"?r([" ",c(e)]):e?.type==="EmptyStatement"?";":y(r([m,X(e)]))}function we(e){let t=r(["if (",c(e.test),")",O(e.consequent)]);if(!e.alternate)return t;let n=e.alternate,o=e.consequent?.type==="BlockStatement"?" ":m,s=n.type==="IfStatement"?r([" ",E(n),we(n),C(n)]):O(n);return r([t,o,"else",s])}function st(e){return r(["while (",c(e.test),")",O(e.body)])}function at(e){let t=e.body?.type==="BlockStatement"?r([" ",c(e.body)," "]):r([y(r([m,X(e.body)])),m]);return r(["do",t,"while (",c(e.test),")"])}function ct(e){let t=e.init?c(e.init):"",n=e.test?r([" ",c(e.test)]):"",o=e.update?r([" ",c(e.update)]):"";return r(["for (",t,";",n,";",o,")",O(e.body)])}function me(e,t){let n=e.await?" await":"";return r(["for",n," (",c(e.left),` ${t} `,c(e.right),")",O(e.body)])}function it(e){let t=e.test?r(["case ",c(e.test),":"]):"default:",n=e.consequent??[],o="";return n.length===1&&n[0].type==="BlockStatement"?o=r([" ",X(n[0])]):n.length>0&&(o=y(r([m,ie(n).doc]))),r([E(e),t,o,C(e)])}function ut(e){let t=e.cases??[],n=t.length===0?M(e,"{","}"):r(["{",y(r([m,N(m,t.map(it))])),m,"}"]);return r(["switch (",c(e.discriminant),") ",n])}function pt(e){let t=["try ",c(e.block)],n=e.handler;if(n){let o=n.param?r([" (",I(n.param),")"]):"";t.push(" catch",o," ",c(n.body));}return e.finalizer&&t.push(" finally ",c(e.finalizer)),r(t)}function Ce(e){let t=c(e);return e.type!=="TSAsExpression"&&printer.isPrimaryOperand(e)?t:r(["(",t,")"])}function Ae(e,t){let n=c(e);return e.type==="TSAsExpression"||printer.needsParens(e,t,false)?r(["(",n,")"]):n}function lt(e){let t=e.operator,n=e.argument,o=(n.type==="UnaryExpression"||n.type==="UpdateExpression")&&String(n.operator)[0]===t,s=t.length>1||o?" ":"";return r([t,s,Ae(n,core.Precedence.Unary)])}function ft(e){let t=e.argument.type==="TSAsExpression"?r(["(",c(e.argument),")"]):c(e.argument);return e.prefix?r([e.operator,t]):r([t,e.operator])}function mt(e){let t=["`"];return e.quasis.forEach((n,o)=>{t.push(n.value.raw),n.tail||t.push("${",c(e.expressions[o]),"}");}),t.push("`"),r(t)}function yt(e){return r([c(e.left)," ",e.operator," ",R(e.right)])}function ye(e,t,n,o,s){let a=R(e),i=printer.needsParens(e,n,o,s)||printer.mixesCoalesce(t,e);return !i&&s&&!o&&(i=printer.unaryLike(e)||e.type==="Literal"&&typeof e.value=="number"&&(e.value<0||Object.is(e.value,-0))),i?r(["(",a,")"]):a}function dt(e){let t=e.operator,n=core.BinaryPrecedence[t]??1/0,o=t==="**",s=ye(e.left,t,n,false,o),a=ye(e.right,t,n,true,o);return D(r([s," ",t,y(r([h,a]))]))}function F(e){switch(e?.type){case "JSXIdentifier":return e.name;case "JSXMemberExpression":return `${F(e.object)}.${F(e.property)}`;case "JSXNamespacedName":return `${F(e.namespace)}:${F(e.name)}`;default:return ""}}function ht(e){return e.includes('"')?e.includes("'")?`"${e.replace(/"/g,""")}"`:`'${e}'`:`"${e}"`}function Je(e){let t=e.expression;if(t?.type==="JSXEmptyExpression"){let n=t.innerComments??[];return r(["{",N(" ",n.map(B)),"}"])}return r(["{",c(t),"}"])}function gt(e){if(e.type==="JSXSpreadAttribute")return r(["{...",c(e.argument),"}"]);let t=F(e.name);if(e.value==null)return t;let n=e.value,o=n.type==="Literal"?ht(String(n.value)):n.type==="JSXExpressionContainer"?Je(n):G(n);return r([t,"=",E(n),o,C(n)])}var P=()=>se?"{' '}":'{" "}';function Dt(e){let t=[],n=[],o="none",s="none",a=0,i=false,p=(f,l)=>{t.length===0?o=l:n.push(l),t.push(f);},u=f=>f===""?"none":f.includes(`
|
|
3
|
+
`)?"break":"space";for(let f of e)if(f.type==="JSXText"){let l=String(f.value);if(l.trim()===""){l!==""&&(s=u(l));continue}let x=/^\s*/.exec(l)[0],T=/\s*$/.exec(l)[0];l.trim().split(/\s+/).forEach((U,W)=>p({doc:U,word:true},W===0?u(x):"space")),s=u(T);}else f.type==="JSXExpressionContainer"||f.type==="JSXSpreadChild"?a++:i=true,p({doc:c(f),word:false},s),s="none";return a>1&&(i=true),{items:t,gaps:n,lead:o,trail:s,forced:i}}function bt(e,t,n){return e.word&&n.word?h:t==="space"?S(r([P(),g])," "):t==="break"?m:e.word||n.word?g:m}function Fe(e,t,n){let{items:o,gaps:s,lead:a,trail:i,forced:p}=Dt(t);if(o.length===0)return r([e,a==="space"||i==="space"?" ":"",n]);let u=[];o.forEach((T,k)=>{k>0&&u.push(bt(o[k-1],s[k-1],T)),u.push(T.doc);});let f=Y(u);if(p){let T=a==="space"?r([m,P(),m]):m,k=i==="space"?r([m,P()]):"";return D(r([e,y(r([T,f,k])),m,n]))}let l=a==="space"?S(P()," "):"",x=i==="space"?S(r([g,P()])," "):"";return D(r([e,y(r([l,g,f,x])),g,n]))}function xt(e,t,n){let o=r([E(e),F(e),C(e)]);if(t.length===0)return r(["<",o,n?" />":">"]);let s=t.map(a=>r([E(a),gt(a),C(a)]));return D(r(["<",o,y(r(s.flatMap(a=>[h,a]))),n?r([h,"/>"]):r([g,">"])]))}function St(e){let t=e.openingElement,n=F(t.name),o=xt(t.name,t.attributes??[],!!t.selfClosing);return t.selfClosing||!e.closingElement?o:Fe(o,e.children??[],r(["</",n,">"]))}function Nt(e){return Fe("<>",e.children??[],"</>")}var ue=e=>e?.type==="JSXElement"||e?.type==="JSXFragment";function pe(e){let t=c(e);return D(r([S("("),y(r([g,t])),g,S(")")]))}var R=e=>ue(e)?pe(e):c(e);function Le(e){if(e.type==="ImportDefaultSpecifier")return printer.print(e.local);if(e.type==="ImportNamespaceSpecifier")return r(["* as ",printer.print(e.local)]);let t=e.type==="ImportSpecifier"?e.imported:e.local,n=e.type==="ImportSpecifier"?e.local:e.exported,o=e.type==="ImportSpecifier"&&e.importKind==="type"?"type ":"";return r([o,t.name===n.name?printer.print(n):r([printer.print(t)," as ",printer.print(n)])])}function Ie(e){return D(r(["{",y(r([h,N(r([",",h]),e.map(Le)),S(",")])),h,"}"]))}function Tt(e){let t=$(String(e.source.value)),n=e.specifiers??[],o=e.importKind==="type"?"import type ":"import ";if(n.length===0)return r([o,t]);let s=[],a=n.filter(p=>p.type==="ImportSpecifier");for(let p of n)p.type!=="ImportSpecifier"&&s.push(Le(p));let i=[...s];return a.length&&i.push(Ie(a)),r([o,N(", ",i)," from ",t])}function Et(e){if(e.declaration)return r(["export ",c(K(e.declaration))]);let t=e.specifiers??[],n=e.source?r([" from ",$(String(e.source.value))]):"";return r(["export ",Ie(t),n])}function kt(e){let t=e.async?"async ":"",n=e.id?printer.print(e.id):"",o=ce(e.typeParamNodes,false),s=Ne(e.params??[]),a=e.returnType?r([": ",v(e.returnTypeNode,e.returnType)]):"";return r([t,"function ",n,o,s,a," ",c(e.body)])}function K(e){if(xe!=="declaration"||e?.type!=="VariableDeclaration"||e.kind!=="const"||e.declarations?.length!==1)return e;let t=e.declarations[0],n=t.init;if(n?.type!=="ArrowFunctionExpression"||t.id?.type!=="Identifier")return e;let o=n.body?.type==="BlockStatement"?n.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:n.body}]};return {type:"FunctionDeclaration",id:t.id,params:n.params,body:o,async:!!n.async,typeParamNodes:n.typeParamNodes,returnType:n.returnType,returnTypeNode:n.returnTypeNode,loc:e.loc,leadingComments:e.leadingComments,trailingComments:e.trailingComments}}function c(e){if(e==null)return "";let t=G(e),n=E(e),o=C(e);return n===""&&o===""?t:r([n,t,o])}function G(e){if(e==null)return "";switch(e.type){case "Program":return Re(e);case "BlockStatement":return Ke(e);case "VariableDeclaration":return rt(e);case "ReturnStatement":return e.argument?r(["return ",ue(e.argument)?pe(e.argument):c(e.argument)]):"return";case "ExpressionStatement":return ot(e);case "IfStatement":return we(e);case "WhileStatement":return st(e);case "DoWhileStatement":return at(e);case "ForStatement":return ct(e);case "ForInStatement":return me(e,"in");case "ForOfStatement":return me(e,"of");case "SwitchStatement":return ut(e);case "TryStatement":return pt(e);case "ThrowStatement":return r(["throw ",c(e.argument)]);case "LabeledStatement":return r([printer.print(e.label),": ",X(e.body)]);case "EmptyStatement":return "";case "ObjectExpression":return Qe(e);case "ArrayExpression":return ze(e);case "CallExpression":return Ze(e);case "ArrowFunctionExpression":return et(e);case "ConditionalExpression":return tt(e);case "BinaryExpression":case "LogicalExpression":return dt(e);case "MemberExpression":return Ye(e);case "ChainExpression":return c(e.expression);case "UnaryExpression":return lt(e);case "UpdateExpression":return ft(e);case "AwaitExpression":return r(["await ",Ae(e.argument,core.Precedence.Await)]);case "TemplateLiteral":return mt(e);case "AssignmentExpression":return yt(e);case "JSXElement":return St(e);case "JSXFragment":return Nt(e);case "JSXExpressionContainer":return Je(e);case "JSXSpreadChild":return r(["{...",c(e.expression),"}"]);case "ImportDeclaration":return Tt(e);case "ExportNamedDeclaration":return Et(e);case "ExportDefaultDeclaration":return r(["export default ",c(K(e.declaration))]);case "FunctionDeclaration":case "FunctionExpression":return kt(e);case "Property":return nt(e);case "SpreadElement":case "RestElement":return r(["...",c(e.argument)]);case "Literal":return typeof e.value=="string"&&!e.regex?$(e.value):printer.print(e);case "TSAsExpression":return r([c(e.expression)," as ",v(e.typeAnnotationNode,e.typeAnnotation)]);case "TSTypeAliasDeclaration":return r(["type ",e.id.name,ce(e.typeParamNodes,false)," = ",v(e.typeNode,e.typeAnnotation)]);default:return printer.print(e)}}function je(e,t={}){let{printWidth:n=80,semi:o=true,indent:s=2,singleQuote:a=false,functions:i="arrow"}=t;return De(o),be(a),Se(i),ee(c(e),n,s).replace(/\n+$/,"")+`
|
|
4
|
+
`}function wt(e,t={}){return je(e,{...t,semi:false}).replace(/\n$/,"")}exports.breakParent=H;exports.concat=r;exports.emit=je;exports.emitExpression=wt;exports.group=D;exports.hardline=m;exports.ifBreak=S;exports.indent=y;exports.join=N;exports.line=h;exports.nodeToDoc=c;exports.printDoc=ee;exports.softline=g;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
type Doc = string | {
|
|
2
|
+
readonly t: "concat";
|
|
3
|
+
readonly parts: readonly Doc[];
|
|
4
|
+
} | {
|
|
5
|
+
readonly t: "line";
|
|
6
|
+
} | {
|
|
7
|
+
readonly t: "softline";
|
|
8
|
+
} | {
|
|
9
|
+
readonly t: "hardline";
|
|
10
|
+
} | {
|
|
11
|
+
readonly t: "breakParent";
|
|
12
|
+
} | {
|
|
13
|
+
readonly t: "indent";
|
|
14
|
+
readonly doc: Doc;
|
|
15
|
+
} | {
|
|
16
|
+
readonly t: "group";
|
|
17
|
+
readonly doc: Doc;
|
|
18
|
+
} | {
|
|
19
|
+
readonly t: "ifBreak";
|
|
20
|
+
readonly broken: Doc;
|
|
21
|
+
readonly flat: Doc;
|
|
22
|
+
} | {
|
|
23
|
+
readonly t: "fill";
|
|
24
|
+
readonly parts: readonly Doc[];
|
|
25
|
+
};
|
|
26
|
+
declare const concat: (parts: Doc[]) => Doc;
|
|
27
|
+
declare const line: Doc;
|
|
28
|
+
declare const softline: Doc;
|
|
29
|
+
declare const hardline: Doc;
|
|
30
|
+
/** Propaga a quebra pros groups ancestrais (como `hardline`), mas não imprime
|
|
31
|
+
* nada — o que um comentário `//` trailing precisa: obriga a linha a abrir sem
|
|
32
|
+
* injetar um newline no ponto errado. */
|
|
33
|
+
declare const breakParent: Doc;
|
|
34
|
+
declare const indent: (doc: Doc) => Doc;
|
|
35
|
+
declare const group: (doc: Doc) => Doc;
|
|
36
|
+
/** `broken` quando o group quebra, `flat` quando cabe (ex.: vírgula final). */
|
|
37
|
+
declare const ifBreak: (broken: Doc, flat?: Doc) => Doc;
|
|
38
|
+
/** Intercala `sep` entre os docs. */
|
|
39
|
+
declare function join(sep: Doc, docs: Doc[]): Doc;
|
|
40
|
+
/** Renderiza um Doc em texto, quebrando os groups que não couberem em `width`. */
|
|
41
|
+
declare function printDoc(doc: Doc, width?: number, indentSize?: number): string;
|
|
42
|
+
|
|
43
|
+
type Node = any;
|
|
44
|
+
type FunctionsStyle = "arrow" | "declaration";
|
|
45
|
+
/**
|
|
46
|
+
* Wrapper público: embrulha o doc do nó com seus comentários LEADING (antes) e
|
|
47
|
+
* TRAILING (depois). Os statements NÃO passam por aqui — o `stmt` cuida deles
|
|
48
|
+
* (o trailing precisa vir depois do `;`). Nós dentro de expressões, sim.
|
|
49
|
+
*/
|
|
50
|
+
declare function nodeToDoc(node: Node): Doc;
|
|
51
|
+
|
|
52
|
+
interface EmitOptions {
|
|
53
|
+
/** Largura-alvo (o que cabe fica inline; o que passa, quebra). Default 80. */
|
|
54
|
+
readonly printWidth?: number;
|
|
55
|
+
/** Ponto-e-vírgula no fim dos statements. Default `true`. */
|
|
56
|
+
readonly semi?: boolean;
|
|
57
|
+
/** Espaços por nível de indentação. Default 2. */
|
|
58
|
+
readonly indent?: number;
|
|
59
|
+
/** Aspas simples em vez de duplas. Default `false` (double, padrão Prettier). */
|
|
60
|
+
readonly singleQuote?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Como escrever funções nomeadas no topo de um programa ou bloco. `"arrow"`
|
|
63
|
+
* (default) é fiel ao AST; `"declaration"` escreve `const f = (…) => …` como
|
|
64
|
+
* `function f(…) { … }` — a mesma lógica, na forma que se lê melhor num arquivo
|
|
65
|
+
* ejetado. Sempre seguro: a Linguagem não tem `this`.
|
|
66
|
+
*/
|
|
67
|
+
readonly functions?: FunctionsStyle;
|
|
68
|
+
}
|
|
69
|
+
/** Emite um nó (Program, statement ou expressão) como fonte, com quebra final. */
|
|
70
|
+
declare function emit(node: unknown, opts?: EmitOptions): string;
|
|
71
|
+
/**
|
|
72
|
+
* Emite uma **expressão**, e não um programa: sem ponto-e-vírgula e sem quebra
|
|
73
|
+
* final — para quem vai recompor o texto dentro de outro (uma interpolação, um
|
|
74
|
+
* campo, uma célula), onde `;` e `\n` seriam corrupção.
|
|
75
|
+
*/
|
|
76
|
+
declare function emitExpression(node: unknown, opts?: EmitOptions): string;
|
|
77
|
+
|
|
78
|
+
export { type Doc, type EmitOptions, type FunctionsStyle, breakParent, concat, emit, emitExpression, group, hardline, ifBreak, indent, join, line, nodeToDoc, printDoc, softline };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
type Doc = string | {
|
|
2
|
+
readonly t: "concat";
|
|
3
|
+
readonly parts: readonly Doc[];
|
|
4
|
+
} | {
|
|
5
|
+
readonly t: "line";
|
|
6
|
+
} | {
|
|
7
|
+
readonly t: "softline";
|
|
8
|
+
} | {
|
|
9
|
+
readonly t: "hardline";
|
|
10
|
+
} | {
|
|
11
|
+
readonly t: "breakParent";
|
|
12
|
+
} | {
|
|
13
|
+
readonly t: "indent";
|
|
14
|
+
readonly doc: Doc;
|
|
15
|
+
} | {
|
|
16
|
+
readonly t: "group";
|
|
17
|
+
readonly doc: Doc;
|
|
18
|
+
} | {
|
|
19
|
+
readonly t: "ifBreak";
|
|
20
|
+
readonly broken: Doc;
|
|
21
|
+
readonly flat: Doc;
|
|
22
|
+
} | {
|
|
23
|
+
readonly t: "fill";
|
|
24
|
+
readonly parts: readonly Doc[];
|
|
25
|
+
};
|
|
26
|
+
declare const concat: (parts: Doc[]) => Doc;
|
|
27
|
+
declare const line: Doc;
|
|
28
|
+
declare const softline: Doc;
|
|
29
|
+
declare const hardline: Doc;
|
|
30
|
+
/** Propaga a quebra pros groups ancestrais (como `hardline`), mas não imprime
|
|
31
|
+
* nada — o que um comentário `//` trailing precisa: obriga a linha a abrir sem
|
|
32
|
+
* injetar um newline no ponto errado. */
|
|
33
|
+
declare const breakParent: Doc;
|
|
34
|
+
declare const indent: (doc: Doc) => Doc;
|
|
35
|
+
declare const group: (doc: Doc) => Doc;
|
|
36
|
+
/** `broken` quando o group quebra, `flat` quando cabe (ex.: vírgula final). */
|
|
37
|
+
declare const ifBreak: (broken: Doc, flat?: Doc) => Doc;
|
|
38
|
+
/** Intercala `sep` entre os docs. */
|
|
39
|
+
declare function join(sep: Doc, docs: Doc[]): Doc;
|
|
40
|
+
/** Renderiza um Doc em texto, quebrando os groups que não couberem em `width`. */
|
|
41
|
+
declare function printDoc(doc: Doc, width?: number, indentSize?: number): string;
|
|
42
|
+
|
|
43
|
+
type Node = any;
|
|
44
|
+
type FunctionsStyle = "arrow" | "declaration";
|
|
45
|
+
/**
|
|
46
|
+
* Wrapper público: embrulha o doc do nó com seus comentários LEADING (antes) e
|
|
47
|
+
* TRAILING (depois). Os statements NÃO passam por aqui — o `stmt` cuida deles
|
|
48
|
+
* (o trailing precisa vir depois do `;`). Nós dentro de expressões, sim.
|
|
49
|
+
*/
|
|
50
|
+
declare function nodeToDoc(node: Node): Doc;
|
|
51
|
+
|
|
52
|
+
interface EmitOptions {
|
|
53
|
+
/** Largura-alvo (o que cabe fica inline; o que passa, quebra). Default 80. */
|
|
54
|
+
readonly printWidth?: number;
|
|
55
|
+
/** Ponto-e-vírgula no fim dos statements. Default `true`. */
|
|
56
|
+
readonly semi?: boolean;
|
|
57
|
+
/** Espaços por nível de indentação. Default 2. */
|
|
58
|
+
readonly indent?: number;
|
|
59
|
+
/** Aspas simples em vez de duplas. Default `false` (double, padrão Prettier). */
|
|
60
|
+
readonly singleQuote?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Como escrever funções nomeadas no topo de um programa ou bloco. `"arrow"`
|
|
63
|
+
* (default) é fiel ao AST; `"declaration"` escreve `const f = (…) => …` como
|
|
64
|
+
* `function f(…) { … }` — a mesma lógica, na forma que se lê melhor num arquivo
|
|
65
|
+
* ejetado. Sempre seguro: a Linguagem não tem `this`.
|
|
66
|
+
*/
|
|
67
|
+
readonly functions?: FunctionsStyle;
|
|
68
|
+
}
|
|
69
|
+
/** Emite um nó (Program, statement ou expressão) como fonte, com quebra final. */
|
|
70
|
+
declare function emit(node: unknown, opts?: EmitOptions): string;
|
|
71
|
+
/**
|
|
72
|
+
* Emite uma **expressão**, e não um programa: sem ponto-e-vírgula e sem quebra
|
|
73
|
+
* final — para quem vai recompor o texto dentro de outro (uma interpolação, um
|
|
74
|
+
* campo, uma célula), onde `;` e `\n` seriam corrupção.
|
|
75
|
+
*/
|
|
76
|
+
declare function emitExpression(node: unknown, opts?: EmitOptions): string;
|
|
77
|
+
|
|
78
|
+
export { type Doc, type EmitOptions, type FunctionsStyle, breakParent, concat, emit, emitExpression, group, hardline, ifBreak, indent, join, line, nodeToDoc, printDoc, softline };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {print,needsParens,isPrimaryOperand,mixesCoalesce,unaryLike}from'@tslite/printer';import {Precedence,BinaryPrecedence}from'@tslite/core';import {format}from'@tslite/type-core';var r=e=>({t:"concat",parts:e}),h={t:"line"},g={t:"softline"},m={t:"hardline"},H={t:"breakParent"},y=e=>({t:"indent",doc:e}),D=e=>({t:"group",doc:e}),S=(e,t="")=>({t:"ifBreak",broken:e,flat:t}),Y=e=>({t:"fill",parts:e});function N(e,t){let n=[];return t.forEach((o,s)=>{s>0&&n.push(e),n.push(o);}),r(n)}var L=1,w=2;function J(e,t){if(typeof e=="string")return false;let n=t.get(e);if(n!==void 0)return n;let o=false;switch(e.t){case "hardline":case "breakParent":o=true;break;case "concat":case "fill":o=e.parts.some(s=>J(s,t));break;case "indent":case "group":o=J(e.doc,t);break;default:o=false;}return t.set(e,o),o}function Z(e,t,n,o){let s=n,a=[e],i=t.length-1;for(;s>=0;){if(a.length===0){if(i<0)return true;a.push(t[i--]);continue}let{indent:p,mode:u,doc:f}=a.pop();if(typeof f=="string"){s-=f.length;continue}switch(f.t){case "concat":case "fill":for(let l=f.parts.length-1;l>=0;l--)a.push({indent:p,mode:u,doc:f.parts[l]});break;case "indent":a.push({indent:p,mode:u,doc:f.doc});break;case "group":a.push({indent:p,mode:J(f.doc,o)?w:u,doc:f.doc});break;case "ifBreak":a.push({indent:p,mode:u,doc:u===w?f.broken:f.flat});break;case "line":if(u===w)return true;s-=1;break;case "softline":if(u===w)return true;break;case "hardline":return true;}}return false}function ee(e,t=80,n=2){let o=new Map,s=[],a=0,i=u=>{s.push(`
|
|
2
|
+
`+" ".repeat(u)),a=u;},p=[{indent:0,mode:w,doc:e}];for(;p.length>0;){let{indent:u,mode:f,doc:l}=p.pop();if(typeof l=="string"){s.push(l),a+=l.length;continue}switch(l.t){case "concat":for(let x=l.parts.length-1;x>=0;x--)p.push({indent:u,mode:f,doc:l.parts[x]});break;case "indent":p.push({indent:u+n,mode:f,doc:l.doc});break;case "group":{let x=J(l.doc,o)||!Z({indent:u,mode:L,doc:l.doc},p,t-a,o)?w:L;p.push({indent:u,mode:x,doc:l.doc});break}case "ifBreak":p.push({indent:u,mode:f,doc:f===w?l.broken:l.flat});break;case "fill":{let x=l.parts;if(x.length===0)break;let[T,k,...U]=x,W=t-a,j={indent:u,mode:L,doc:T},Q={indent:u,mode:w,doc:T},z=!J(T,o)&&Z(j,[],W,o);if(x.length===1){p.push(z?j:Q);break}let le={indent:u,mode:L,doc:k},_={indent:u,mode:w,doc:k};if(x.length===2){z?p.push(le,j):p.push(_,Q);break}let V={indent:u,mode:f,doc:Y(U)},fe=U[0];!J(T,o)&&!J(fe,o)&&Z({indent:u,mode:L,doc:r([T,k,fe])},[],W,o)?p.push(V,le,j):z?p.push(V,_,j):p.push(V,_,Q);break}case "line":f===L?(s.push(" "),a+=1):i(u);break;case "softline":f===w&&i(u);break;case "hardline":i(u);break;}}return s.join("").replace(/[ \t]+(\n|$)/g,"$1")}var ge=true;function De(e){ge=e;}var se=false;function be(e){se=e;}var xe="arrow";function Se(e){xe=e;}function $(e){let t=(e.match(/"/g)??[]).length,n=(e.match(/'/g)??[]).length;return (se?t<n:t<=n)?JSON.stringify(e):`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,'"').replace(/'/g,"\\'")}'`}function I(e){if(e?.type==="RestElement")return r(["...",I(e.argument)]);if(e?.type==="AssignmentPattern")return r([I(e.left)," = ",c(e.right)]);let t=e?.optional?r([print(e),"?"]):print(e);return e?.typeAnnotation?r([t,": ",v(e.typeAnnotationNode,e.typeAnnotation)]):t}function B(e){return e.type==="Line"?"//"+e.value:"/*"+e.value+"*/"}function E(e){let t=e?.leadingComments;if(!t||t.length===0)return "";let n=[];for(let o=0;o<t.length;o++){let s=t[o];n.push(B(s));let a=o<t.length-1?t[o+1].loc?.start?.line:e.loc?.start?.line,i=s.loc?.end?.line;a==null||i==null?n.push(m):s.type==="Line"||i<a?n.push(a-i>1?r([m,m]):m):n.push(" ");}return r(n)}function C(e){let t=e?.trailingComments;if(!t||t.length===0)return "";let n=[],o=e.loc?.end?.line;for(let s of t){let a=s.loc?.start?.line;a!=null&&o!=null&&a>o?(n.push(a-o>1?r([m,m]):m),n.push(B(s))):n.push(" ",B(s)),s.type==="Line"&&n.push(H),o=s.loc?.end?.line??o;}return r(n)}function M(e,t,n){let o=e?.innerComments;if(!o||o.length===0)return t+n;let s=N(m,o.map(B));return o.some(i=>i.type==="Line")?r([t,y(r([m,s])),m,n]):r([t," ",s," ",n])}function q(e,t,n){let o=C(e);return o===""?r([t,n]):e?.trailingComments?.some(a=>a.type==="Line")?r([t,n,o]):r([t,o,n])}function ae(e,t){let n=[];return e.forEach((o,s)=>{let a=s===e.length-1;if(o==null){a||n.push(",",h);return}let i=a?S(","):",";n.push(E(o),q(o,G(o),i)),a||n.push(h);}),r(n)}function Ne(e){if(e.length===0)return "()";let t=[];return e.forEach((n,o)=>{let s=o===e.length-1,a=s?n.type==="RestElement"?"":S(","):",";t.push(E(n),q(n,I(n),a)),s||t.push(h);}),D(r(["(",y(r([g,r(t)])),g,")"]))}var Oe=e=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e);function $e(e){return e?.type==="TSUnionType"||e?.type==="TSFunctionType"||e?.type==="TSConditionalType"}function Me(e){return r([e.name,e.optional?"?":"",": ",d(e.typeAnnotation)])}function Te(e){return e.length===0?"()":D(r(["(",y(r([g,N(r([",",h]),e.map(Me)),S(",")])),g,")"]))}function Xe(e){switch(e.type){case "TSPropertySignature":return r([e.readonly?"readonly ":"",Oe(e.key)?e.key:$(e.key),e.optional?"?":"",": ",d(e.typeAnnotation)]);case "TSIndexSignature":return r(["[k: ",e.keyType,"]: ",d(e.typeAnnotation)]);case "TSCallSignatureDeclaration":return r([Te(e.params),": ",d(e.returnType)]);default:return ""}}function Ge(e){if(e.members.length===0)return M(e,"{","}");let t=[];return e.members.forEach((n,o)=>{let s=o===e.members.length-1,a=s?S(";"):";";t.push(E(n),q(n,Xe(n),a)),s||t.push(h);}),D(r(["{",y(r([h,r(t)])),h,"}"]))}function Ue(e){let t=e.elementTypes.map((o,s)=>{let a=e.flags?.[s]??"req",i=e.labels?.[s],p=d(o),u=o.type==="TSUnionType"?r(["(",p,")"]):p;return i!==void 0?a==="rest"?r(["...",i,": ",u,"[]"]):a==="variadic"?r(["...",i,": ",p]):a==="optional"?r([i,"?: ",p]):r([i,": ",p]):a==="rest"?r(["...",u,"[]"]):a==="variadic"?r(["...",p]):a==="optional"?r([u,"?"]):p}),n=r(["[",N(", ",t),"]"]);return e.readonly?r(["readonly ",n]):n}function We(e){switch(e.type){case "TSKeywordType":return e.kind;case "TSLiteralType":return typeof e.literal=="string"?$(e.literal):String(e.literal);case "TSTypeReference":return r([e.typeName,e.typeArguments?.length?r(["<",N(", ",e.typeArguments.map(d)),">"]):""]);case "TSArrayType":{let t=$e(e.elementType)?r(["(",d(e.elementType),")"]):d(e.elementType),n=r([t,"[]"]);return e.readonly?r(["readonly ",n]):n}case "TSIndexedAccessType":return r([d(e.objectType),"[",d(e.indexType),"]"]);case "TSUnionType":return D(y(r([S(r([g,"| "])),N(r([h,"| "]),e.types.map(d))])));case "TSIntersectionType":return N(" & ",e.types.map(t=>t.type==="TSUnionType"?r(["(",d(t),")"]):d(t)));case "TSFunctionType":return r([e.typeParams?.length?r(["<",e.typeParams.join(", "),">"]):"",Te(e.params)," => ",d(e.returnType)]);case "TSTypeLiteral":return Ge(e);case "TSTupleType":return Ue(e);case "TSTypeOperator":return r([e.operator," ",d(e.typeAnnotation)]);case "TSInferType":return r(["infer ",e.name]);case "TSConditionalType":return r([d(e.checkType)," extends ",d(e.extendsType)," ? ",d(e.trueType)," : ",d(e.falseType)]);case "TSMappedType":return D(r(["{",y(r([h,"[",e.key," in ",d(e.constraint),"]",e.optional?"?":"",": ",d(e.typeAnnotation),S(";")])),h,"}"]));case "TSTypeQuery":return r(["typeof ",e.exprName.join(".")]);default:return ""}}function d(e){if(e==null)return "";let t=We(e),n=E(e),o=C(e);return n===""&&o===""?t:r([n,t,o])}function v(e,t){return e?d(e):format(t)}function ce(e,t){if(!e?.length)return "";let n=[];e.forEach((s,a)=>{a>0&&n.push(", "),s.isConst&&n.push("const "),n.push(s.name),s.boundNode&&n.push(" extends ",d(s.boundNode)),s.defaultNode&&n.push(" = ",d(s.defaultNode));});let o=e.length===1&&!e[0].boundNode&&!e[0].defaultNode;return r(["<",...n,t&&o?",":"",">"])}function ie(e){let t=[],n,o=0;for(let s of e){let a=K(s),i=X(a);if(i!==""){if(o>0){let p=n?.loc?.end?.line,u=a?.leadingComments?.[0]?.loc?.start?.line??a?.loc?.start?.line,f=p!=null&&u!=null?u-p:1;t.push(f>1?r([m,m]):m);}t.push(i),n=a,o++;}}return {doc:r(t),count:o}}var qe=new Set(["FunctionDeclaration","IfStatement","ForStatement","ForInStatement","ForOfStatement","WhileStatement","TryStatement","SwitchStatement","ClassDeclaration","BlockStatement","LabeledStatement"]);function X(e){let t=G(e);if(t==="")return "";let n=(e.type==="ExportNamedDeclaration"||e.type==="ExportDefaultDeclaration")&&K(e.declaration)?.type==="FunctionDeclaration",o=ge&&!qe.has(e.type)&&!n?";":"";return r([E(e),t,o,C(e)])}function Re(e){let{doc:t,count:n}=ie(e.body);return r([t,n?m:""])}function Ke(e){let{doc:t,count:n}=ie(e.body);return n===0?M(e,"{","}"):r(["{",y(r([m,t])),m,"}"])}function Qe(e){return e.properties.length===0?M(e,"{","}"):D(r(["{",y(r([h,ae(e.properties)])),h,"}"]))}function ze(e){return e.elements.length===0?M(e,"[","]"):D(r(["[",y(r([g,ae(e.elements)])),g,"]"]))}function _e(e){return e!=null&&(e.type==="ArrowFunctionExpression"||e.type==="FunctionExpression"||e.type==="ObjectExpression"||e.type==="JsonExpression"||e.type==="ArrayExpression")}function Ve(e){let t=c(e);return e.type!=="TSAsExpression"&&isPrimaryOperand(e)?t:r(["(",t,")"])}function Ee(e){let t=e.typeArguments,n=r([t?.length?r(["<",N(", ",t.map(o=>format(o))),">"]):"",e.optional?"?.":""]);if(e.arguments.length===0)return r([n,"()"]);if(_e(e.arguments[e.arguments.length-1])){let o=[n,"("],s=e.arguments.length-1;for(let a=0;a<s;a++){let i=e.arguments[a];o.push(E(i),q(i,G(i),",")," ");}return o.push(c(e.arguments[s]),")"),r(o)}return r([n,"(",D(r([y(r([g,ae(e.arguments)])),g])),")"])}function Ze(e){return ke(e)??r([Ve(e.callee),Ee(e)])}function te(e){let t=[];return e.optional&&t.push(e.computed?"?.":"?"),t.push(e.computed?"[":"."),t.push(e.computed?c(e.property):print(e.property)),e.computed&&t.push("]"),r(t)}var He=e=>!!(e?.leadingComments?.length||e?.trailingComments?.length);function ne(e){switch(e?.type){case "Identifier":case "Literal":return true;case "TemplateLiteral":return e.expressions.length===0;case "MemberExpression":return !e.computed&&ne(e.object);case "UnaryExpression":return ne(e.argument);default:return false}}function ke(e){let t=[],n=e;for(;;)if(n.type==="CallExpression"&&n.callee?.type==="MemberExpression")t.unshift(n),n=n.callee;else if(n.type==="MemberExpression")t.unshift(n),n=n.object;else break;let o=n;if(t.some(He))return null;let s=[],a=0,i=false;for(let l of t)l.type==="CallExpression"?(a++,l.arguments.every(ne)||(i=true),(s[s.length-1]??(s[0]=[])).push(Ee(l))):l.computed?(s[s.length-1]??(s[0]=[])).push(te(l)):s.push([te(l)]);if(s.length<3)return null;let p=Ce(o),u=a>2&&i?m:g,f=s.map(l=>r([u,r(l)]));return D(r([p,y(r(f))]))}function Ye(e){return ke(e)??r([Ce(e.object),te(e)])}function A(e){if(!e||typeof e!="object")return false;switch(e.type){case "ObjectExpression":case "JsonExpression":return true;case "ConditionalExpression":return A(e.test);case "LogicalExpression":case "BinaryExpression":case "AssignmentExpression":return A(e.left);case "MemberExpression":return A(e.object);case "CallExpression":return A(e.callee);case "TaggedTemplateExpression":return A(e.tag);case "ChainExpression":case "TSAsExpression":return A(e.expression);case "SequenceExpression":return A(e.expressions?.[0]);default:return false}}function et(e){let t=e.async?"async ":"",n=ue(e.body)?pe(e.body):c(e.body);e.body.type!=="BlockStatement"&&A(e.body)&&(n=r(["(",n,")"]));let o=ce(e.typeParamNodes,true),s=Ne(e.params??[]),a=e.returnType?r([": ",v(e.returnTypeNode,e.returnType)]):"";return r([t,o,s,a," => ",n])}function tt(e){let t=needsParens(e.test,Precedence.Conditional,false,true)?r(["(",c(e.test),")"]):c(e.test);return D(r([t,y(r([h,"? ",c(e.consequent),h,": ",c(e.alternate)]))]))}function nt(e){if(e.shorthand)return print(e.value);let t=e.computed?r(["[",print(e.key),"]"]):print(e.key);return r([t,": ",R(e.value)])}function rt(e){let t=e.declarations.map(n=>n.init?r([I(n.id)," = ",R(n.init)]):I(n.id));return r([e.kind," ",N(r([","," "]),t)])}function ot(e){let t=print(e.expression),n=t[0]==="{"||t.startsWith("function")||t.startsWith("class"),o=c(e.expression);return n?r(["(",o,")"]):o}function O(e){return e?.type==="BlockStatement"?r([" ",c(e)]):e?.type==="EmptyStatement"?";":y(r([m,X(e)]))}function we(e){let t=r(["if (",c(e.test),")",O(e.consequent)]);if(!e.alternate)return t;let n=e.alternate,o=e.consequent?.type==="BlockStatement"?" ":m,s=n.type==="IfStatement"?r([" ",E(n),we(n),C(n)]):O(n);return r([t,o,"else",s])}function st(e){return r(["while (",c(e.test),")",O(e.body)])}function at(e){let t=e.body?.type==="BlockStatement"?r([" ",c(e.body)," "]):r([y(r([m,X(e.body)])),m]);return r(["do",t,"while (",c(e.test),")"])}function ct(e){let t=e.init?c(e.init):"",n=e.test?r([" ",c(e.test)]):"",o=e.update?r([" ",c(e.update)]):"";return r(["for (",t,";",n,";",o,")",O(e.body)])}function me(e,t){let n=e.await?" await":"";return r(["for",n," (",c(e.left),` ${t} `,c(e.right),")",O(e.body)])}function it(e){let t=e.test?r(["case ",c(e.test),":"]):"default:",n=e.consequent??[],o="";return n.length===1&&n[0].type==="BlockStatement"?o=r([" ",X(n[0])]):n.length>0&&(o=y(r([m,ie(n).doc]))),r([E(e),t,o,C(e)])}function ut(e){let t=e.cases??[],n=t.length===0?M(e,"{","}"):r(["{",y(r([m,N(m,t.map(it))])),m,"}"]);return r(["switch (",c(e.discriminant),") ",n])}function pt(e){let t=["try ",c(e.block)],n=e.handler;if(n){let o=n.param?r([" (",I(n.param),")"]):"";t.push(" catch",o," ",c(n.body));}return e.finalizer&&t.push(" finally ",c(e.finalizer)),r(t)}function Ce(e){let t=c(e);return e.type!=="TSAsExpression"&&isPrimaryOperand(e)?t:r(["(",t,")"])}function Ae(e,t){let n=c(e);return e.type==="TSAsExpression"||needsParens(e,t,false)?r(["(",n,")"]):n}function lt(e){let t=e.operator,n=e.argument,o=(n.type==="UnaryExpression"||n.type==="UpdateExpression")&&String(n.operator)[0]===t,s=t.length>1||o?" ":"";return r([t,s,Ae(n,Precedence.Unary)])}function ft(e){let t=e.argument.type==="TSAsExpression"?r(["(",c(e.argument),")"]):c(e.argument);return e.prefix?r([e.operator,t]):r([t,e.operator])}function mt(e){let t=["`"];return e.quasis.forEach((n,o)=>{t.push(n.value.raw),n.tail||t.push("${",c(e.expressions[o]),"}");}),t.push("`"),r(t)}function yt(e){return r([c(e.left)," ",e.operator," ",R(e.right)])}function ye(e,t,n,o,s){let a=R(e),i=needsParens(e,n,o,s)||mixesCoalesce(t,e);return !i&&s&&!o&&(i=unaryLike(e)||e.type==="Literal"&&typeof e.value=="number"&&(e.value<0||Object.is(e.value,-0))),i?r(["(",a,")"]):a}function dt(e){let t=e.operator,n=BinaryPrecedence[t]??1/0,o=t==="**",s=ye(e.left,t,n,false,o),a=ye(e.right,t,n,true,o);return D(r([s," ",t,y(r([h,a]))]))}function F(e){switch(e?.type){case "JSXIdentifier":return e.name;case "JSXMemberExpression":return `${F(e.object)}.${F(e.property)}`;case "JSXNamespacedName":return `${F(e.namespace)}:${F(e.name)}`;default:return ""}}function ht(e){return e.includes('"')?e.includes("'")?`"${e.replace(/"/g,""")}"`:`'${e}'`:`"${e}"`}function Je(e){let t=e.expression;if(t?.type==="JSXEmptyExpression"){let n=t.innerComments??[];return r(["{",N(" ",n.map(B)),"}"])}return r(["{",c(t),"}"])}function gt(e){if(e.type==="JSXSpreadAttribute")return r(["{...",c(e.argument),"}"]);let t=F(e.name);if(e.value==null)return t;let n=e.value,o=n.type==="Literal"?ht(String(n.value)):n.type==="JSXExpressionContainer"?Je(n):G(n);return r([t,"=",E(n),o,C(n)])}var P=()=>se?"{' '}":'{" "}';function Dt(e){let t=[],n=[],o="none",s="none",a=0,i=false,p=(f,l)=>{t.length===0?o=l:n.push(l),t.push(f);},u=f=>f===""?"none":f.includes(`
|
|
3
|
+
`)?"break":"space";for(let f of e)if(f.type==="JSXText"){let l=String(f.value);if(l.trim()===""){l!==""&&(s=u(l));continue}let x=/^\s*/.exec(l)[0],T=/\s*$/.exec(l)[0];l.trim().split(/\s+/).forEach((U,W)=>p({doc:U,word:true},W===0?u(x):"space")),s=u(T);}else f.type==="JSXExpressionContainer"||f.type==="JSXSpreadChild"?a++:i=true,p({doc:c(f),word:false},s),s="none";return a>1&&(i=true),{items:t,gaps:n,lead:o,trail:s,forced:i}}function bt(e,t,n){return e.word&&n.word?h:t==="space"?S(r([P(),g])," "):t==="break"?m:e.word||n.word?g:m}function Fe(e,t,n){let{items:o,gaps:s,lead:a,trail:i,forced:p}=Dt(t);if(o.length===0)return r([e,a==="space"||i==="space"?" ":"",n]);let u=[];o.forEach((T,k)=>{k>0&&u.push(bt(o[k-1],s[k-1],T)),u.push(T.doc);});let f=Y(u);if(p){let T=a==="space"?r([m,P(),m]):m,k=i==="space"?r([m,P()]):"";return D(r([e,y(r([T,f,k])),m,n]))}let l=a==="space"?S(P()," "):"",x=i==="space"?S(r([g,P()])," "):"";return D(r([e,y(r([l,g,f,x])),g,n]))}function xt(e,t,n){let o=r([E(e),F(e),C(e)]);if(t.length===0)return r(["<",o,n?" />":">"]);let s=t.map(a=>r([E(a),gt(a),C(a)]));return D(r(["<",o,y(r(s.flatMap(a=>[h,a]))),n?r([h,"/>"]):r([g,">"])]))}function St(e){let t=e.openingElement,n=F(t.name),o=xt(t.name,t.attributes??[],!!t.selfClosing);return t.selfClosing||!e.closingElement?o:Fe(o,e.children??[],r(["</",n,">"]))}function Nt(e){return Fe("<>",e.children??[],"</>")}var ue=e=>e?.type==="JSXElement"||e?.type==="JSXFragment";function pe(e){let t=c(e);return D(r([S("("),y(r([g,t])),g,S(")")]))}var R=e=>ue(e)?pe(e):c(e);function Le(e){if(e.type==="ImportDefaultSpecifier")return print(e.local);if(e.type==="ImportNamespaceSpecifier")return r(["* as ",print(e.local)]);let t=e.type==="ImportSpecifier"?e.imported:e.local,n=e.type==="ImportSpecifier"?e.local:e.exported,o=e.type==="ImportSpecifier"&&e.importKind==="type"?"type ":"";return r([o,t.name===n.name?print(n):r([print(t)," as ",print(n)])])}function Ie(e){return D(r(["{",y(r([h,N(r([",",h]),e.map(Le)),S(",")])),h,"}"]))}function Tt(e){let t=$(String(e.source.value)),n=e.specifiers??[],o=e.importKind==="type"?"import type ":"import ";if(n.length===0)return r([o,t]);let s=[],a=n.filter(p=>p.type==="ImportSpecifier");for(let p of n)p.type!=="ImportSpecifier"&&s.push(Le(p));let i=[...s];return a.length&&i.push(Ie(a)),r([o,N(", ",i)," from ",t])}function Et(e){if(e.declaration)return r(["export ",c(K(e.declaration))]);let t=e.specifiers??[],n=e.source?r([" from ",$(String(e.source.value))]):"";return r(["export ",Ie(t),n])}function kt(e){let t=e.async?"async ":"",n=e.id?print(e.id):"",o=ce(e.typeParamNodes,false),s=Ne(e.params??[]),a=e.returnType?r([": ",v(e.returnTypeNode,e.returnType)]):"";return r([t,"function ",n,o,s,a," ",c(e.body)])}function K(e){if(xe!=="declaration"||e?.type!=="VariableDeclaration"||e.kind!=="const"||e.declarations?.length!==1)return e;let t=e.declarations[0],n=t.init;if(n?.type!=="ArrowFunctionExpression"||t.id?.type!=="Identifier")return e;let o=n.body?.type==="BlockStatement"?n.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:n.body}]};return {type:"FunctionDeclaration",id:t.id,params:n.params,body:o,async:!!n.async,typeParamNodes:n.typeParamNodes,returnType:n.returnType,returnTypeNode:n.returnTypeNode,loc:e.loc,leadingComments:e.leadingComments,trailingComments:e.trailingComments}}function c(e){if(e==null)return "";let t=G(e),n=E(e),o=C(e);return n===""&&o===""?t:r([n,t,o])}function G(e){if(e==null)return "";switch(e.type){case "Program":return Re(e);case "BlockStatement":return Ke(e);case "VariableDeclaration":return rt(e);case "ReturnStatement":return e.argument?r(["return ",ue(e.argument)?pe(e.argument):c(e.argument)]):"return";case "ExpressionStatement":return ot(e);case "IfStatement":return we(e);case "WhileStatement":return st(e);case "DoWhileStatement":return at(e);case "ForStatement":return ct(e);case "ForInStatement":return me(e,"in");case "ForOfStatement":return me(e,"of");case "SwitchStatement":return ut(e);case "TryStatement":return pt(e);case "ThrowStatement":return r(["throw ",c(e.argument)]);case "LabeledStatement":return r([print(e.label),": ",X(e.body)]);case "EmptyStatement":return "";case "ObjectExpression":return Qe(e);case "ArrayExpression":return ze(e);case "CallExpression":return Ze(e);case "ArrowFunctionExpression":return et(e);case "ConditionalExpression":return tt(e);case "BinaryExpression":case "LogicalExpression":return dt(e);case "MemberExpression":return Ye(e);case "ChainExpression":return c(e.expression);case "UnaryExpression":return lt(e);case "UpdateExpression":return ft(e);case "AwaitExpression":return r(["await ",Ae(e.argument,Precedence.Await)]);case "TemplateLiteral":return mt(e);case "AssignmentExpression":return yt(e);case "JSXElement":return St(e);case "JSXFragment":return Nt(e);case "JSXExpressionContainer":return Je(e);case "JSXSpreadChild":return r(["{...",c(e.expression),"}"]);case "ImportDeclaration":return Tt(e);case "ExportNamedDeclaration":return Et(e);case "ExportDefaultDeclaration":return r(["export default ",c(K(e.declaration))]);case "FunctionDeclaration":case "FunctionExpression":return kt(e);case "Property":return nt(e);case "SpreadElement":case "RestElement":return r(["...",c(e.argument)]);case "Literal":return typeof e.value=="string"&&!e.regex?$(e.value):print(e);case "TSAsExpression":return r([c(e.expression)," as ",v(e.typeAnnotationNode,e.typeAnnotation)]);case "TSTypeAliasDeclaration":return r(["type ",e.id.name,ce(e.typeParamNodes,false)," = ",v(e.typeNode,e.typeAnnotation)]);default:return print(e)}}function je(e,t={}){let{printWidth:n=80,semi:o=true,indent:s=2,singleQuote:a=false,functions:i="arrow"}=t;return De(o),be(a),Se(i),ee(c(e),n,s).replace(/\n+$/,"")+`
|
|
4
|
+
`}function wt(e,t={}){return je(e,{...t,semi:false}).replace(/\n$/,"")}export{H as breakParent,r as concat,je as emit,wt as emitExpression,D as group,m as hardline,S as ifBreak,y as indent,N as join,h as line,c as nodeToDoc,ee as printDoc,g as softline};
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tslite/emit",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TSLite source emitter — AST to readable TypeScript/TSX source in one pass (Doc algebra, 80-col wrapping, types preserved, comments printed). The eject printer; the runtime printer is @tslite/printer.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/andersondrosa/tslite.git",
|
|
26
|
+
"directory": "packages/emit"
|
|
27
|
+
},
|
|
28
|
+
"keywords": [
|
|
29
|
+
"ast",
|
|
30
|
+
"emitter",
|
|
31
|
+
"pretty-printer",
|
|
32
|
+
"tsx",
|
|
33
|
+
"typescript",
|
|
34
|
+
"eject",
|
|
35
|
+
"codegen",
|
|
36
|
+
"tslite"
|
|
37
|
+
],
|
|
38
|
+
"author": "Anderson D. Rosa <andersondrosa@outlook.com>",
|
|
39
|
+
"license": "MIT",
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@tslite/core": "0.8.1",
|
|
42
|
+
"@tslite/type-core": "0.3.1",
|
|
43
|
+
"@tslite/printer": "0.5.2"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@tslite/parser": "1.2.0"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "tsup",
|
|
53
|
+
"dev": "tsup --watch",
|
|
54
|
+
"test": "vitest run",
|
|
55
|
+
"test:watch": "vitest",
|
|
56
|
+
"typecheck": "tsc --noEmit",
|
|
57
|
+
"lint": "eslint src tests",
|
|
58
|
+
"clean": "rm -rf dist",
|
|
59
|
+
"format": "prettier --write \"{src,tests}/**/*.ts\""
|
|
60
|
+
}
|
|
61
|
+
}
|