ts-ref-kit 1.0.5 → 1.0.6

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.
@@ -0,0 +1,3 @@
1
+ var L=(e,n,s)=>new Promise((i,f)=>{var r=m=>{try{w(s.next(m))}catch(D){f(D)}},l=m=>{try{w(s.throw(m))}catch(D){f(D)}},w=m=>m.done?i(m.value):Promise.resolve(m.value).then(r,l);w((s=s.apply(e,n)).next())});import J from"typescript";import*as t from"typescript";import*as E from"fs";import*as C from"process";import*as x from"path";var fe=!0,O=new Map,K=new Map,j=new Map,A=new Map,q=new Map,v=new Set,B={[t.SyntaxKind.BooleanKeyword]:"boolean",[t.SyntaxKind.StringKeyword]:"string",[t.SyntaxKind.BigIntKeyword]:"bigint",[t.SyntaxKind.NumberKeyword]:"number",[t.SyntaxKind.SymbolKeyword]:"symbol",[t.SyntaxKind.VoidKeyword]:"void",[t.SyntaxKind.UndefinedKeyword]:"undefined",[t.SyntaxKind.UnknownKeyword]:"unknown",[t.SyntaxKind.AnyKeyword]:"any",[t.SyntaxKind.ObjectKeyword]:"object"},P="any",H=["string","number","boolean","bigint","symbol"],X=["any","Promise","Date","Error","undefined","unknown","object","Map","Set"],Y=["Mappable","EnableReflect"];[...H,...X,...Y].forEach(se);Y.forEach(e=>K.set(e,{name:e}));var k,G=!1,R=Reflect;function xe(i,f){return L(this,arguments,function*(e,n,s=C.cwd()){if(s=x.resolve(s),R.__classes===void 0){e=ae(e),U(e,n),R.__classes={};for(let[r,l]of O)R.__classes[r]=l;R.__interfaces={};for(let[r,l]of K)R.__interfaces[r]=l;R.__typeAliases={};for(let[r,l]of A)R.__typeAliases[r]=l;R.__constTypes={};for(let[r,l]of q)R.__constTypes[r]=l;yield Promise.all(e.map(r=>Z(r,s)))}})}function Z(e,n){return L(this,null,function*(){if(!E.existsSync(e))return;if(E.statSync(e).isDirectory()){E.readdirSync(e).forEach(r=>{Z(x.join(e,r),n)});return}let i=yield import(x.join(n,e).replace(/\.ts$/,".js"));R.__classDef={},Object.values(i).forEach(f=>{typeof f=="function"&&(R.__classDef[f.name]=f)})})}function U(e,n){if(e||(e=[C.cwd()]),e=ae(e),!G){let s=ee(e,n),i=t.createProgram(s,{});k=i.getTypeChecker(),s=s.map(r=>Q(r)),i.getSourceFiles().filter(r=>s.includes(Q(r.fileName))).forEach(r=>{b(`parse file: ${r.fileName}`),te(r)});for(let r of v.keys())!O.has(r)&&!K.has(r)&&!j.has(r)&&!A.has(r)&&!H.includes(r)&&!X.includes(r)&&(b(`remove unknown typeName: ${r}`),v.delete(r));Array.from(O.values()).forEach(ge),Array.from(K.values()).forEach(Te),[O,K,A].forEach(De),G=!0}return{classDefinitions:O,interfaceDefinitions:K,enumDefinitions:j,typeAliasDefinitions:A,constTypeDefinitions:q}}function ee(e,n){let s=[];return e.forEach(i=>{if(i=x.resolve(i),we(i,n)){b(`ignore excluded ${i}`);return}if(!E.existsSync(i)){console.error(`Path ${i} does not exist.`);return}if(E.statSync(i).isFile()){s.push(i);return}E.readdirSync(i).forEach(l=>s.push(...ee([x.join(i,l)],n)))}),s}function te(e){t.isClassDeclaration(e)?ce(e):t.isInterfaceDeclaration(e)?le(e):t.isEnumDeclaration(e)?pe(e):t.isTypeAliasDeclaration(e)?ue(e):t.isConstTypeReference(e)?me(e):e.forEachChild(te)}function ce(e){var w,m,D,S,u,T,M,$,y,a,d,h;let n=o(e.name);if(!n)return;let s=o((D=(m=(w=e.heritageClauses)==null?void 0:w.find(c=>c.token===t.SyntaxKind.ExtendsKeyword))==null?void 0:m.types)==null?void 0:D[0].expression),i=(u=(S=e.heritageClauses)==null?void 0:S.find(c=>c.token===t.SyntaxKind.ImplementsKeyword))==null?void 0:u.types.map(c=>o(c.expression)),f=[],r=[];for(let c of e.members)if(t.isPropertyDeclaration(c))f.push({name:o(c.name),isOptional:c.questionToken!==void 0,type:g(c),isPrivate:(T=c.modifiers)==null?void 0:T.some(p=>p.kind===t.SyntaxKind.PrivateKeyword),isStatic:(M=c.modifiers)==null?void 0:M.some(p=>p.kind===t.SyntaxKind.StaticKeyword)});else if(t.isMethodDeclaration(c))r.push({name:o(c.name),returnType:g(c),isPrivate:($=c.modifiers)==null?void 0:$.some(p=>p.kind===t.SyntaxKind.PrivateKeyword),isStatic:(y=c.modifiers)==null?void 0:y.some(p=>p.kind===t.SyntaxKind.StaticKeyword),isAsync:(a=c.modifiers)==null?void 0:a.some(p=>p.kind===t.SyntaxKind.AsyncKeyword),args:c.parameters.map(p=>({name:o(p.name),type:g(p),isOptional:p.questionToken!==void 0}))});else if(t.isGetAccessorDeclaration(c)){let p=f.find(N=>N.name===o(c.name));p||(p={name:o(c.name),isOptional:c.questionToken===void 0,type:g(c)},f.push(p)),p.accessor=p.accessor||{},p.accessor.getter={isPrivate:((d=c.modifiers)==null?void 0:d.some(N=>N.kind===t.SyntaxKind.PrivateKeyword))||!1},p.isPrivate=p.accessor.getter.isPrivate}else if(t.isSetAccessorDeclaration(c)){let p=f.find(N=>N.name===o(c.name));p||(p={name:o(c.name),isOptional:c.questionToken===void 0,type:g(c)},f.push(p)),p.accessor=p.accessor||{},p.accessor.setter={isPrivate:((h=c.modifiers)==null?void 0:h.some(N=>N.kind===t.SyntaxKind.PrivateKeyword))||!1}}let l={name:n,superClassName:s,implementations:i,properties:f,methods:r};b(`Define class: ${o(e.name)}`),O.set(n,l)}function le(e){var w,m,D,S;let n=o(e.name);if(!n)return;let s=((m=(w=e.heritageClauses)==null?void 0:w.find(u=>u.token===t.SyntaxKind.ExtendsKeyword))==null?void 0:m.types.map(u=>o(u.expression)))||[],i=[],f=[],r;for(let u of e.members)t.isPropertySignature(u)?i.push({name:o(u.name),isOptional:u.questionToken!==void 0,type:g(u),isPrivate:((D=u.modifiers)==null?void 0:D.some(T=>T.kind===t.SyntaxKind.PrivateKeyword))||!1}):t.isMethodSignature(u)?f.push({name:u.name.text,returnType:g(u),isPrivate:((S=u.modifiers)==null?void 0:S.some(T=>T.kind===t.SyntaxKind.PrivateKeyword))||!1,args:u.parameters.map(T=>({name:o(T.name),type:g(T),isOptional:T.questionToken!==void 0}))}):t.isIndexSignatureDeclaration(u)&&(r=g(u));let l=K.get(n);l?(l.implementations=I(l.implementations||[],s),l.methods=I(l.methods||[],f,(u,T)=>u.name===T.name),l.properties=I(l.properties||[],i,(u,T)=>u.name===T.name),l.indexElementType=r,b(`Merge interface ${o(e.name)}`)):(l={name:n,implementations:s,methods:f,properties:i,indexElementType:r},K.set(n,l),b(`Define interface ${o(e.name)}`))}function pe(e){let n=o(e.name);n&&(j.set(n,{name:n,members:e.members.map(s=>({name:o(s.name),initializer:o(s.initializer)}))}),b(`Define enum: ${o(e.name)}`))}function ue(e){b(`Define typeAlias: ${o(e.name)}`),A.set(o(e.name),g(e))}function me(e){let n=e.parent.parent;t.isVariableDeclaration(n)&&n.initializer&&t.isAsExpression(n.initializer)&&q.set(o(n.name),ne(n.initializer.expression))}function ne(e){return t.isArrayLiteralExpression(e)?ye(e):t.isObjectLiteralExpression(e)?de(e):t.isNumericLiteral(e)?"number":t.isStringLiteral(e)?"string":t.isBigIntLiteral(e)?"bigint":[t.SyntaxKind.TrueKeyword,t.SyntaxKind.FalseKeyword].includes(e.kind)?"boolean":P}function ye(e){let n=[];return e.elements.forEach(s=>{if(t.isStringLiteral(s))return n.push(o(s))}),n.length===0?P:n.length===1?n[0]:{unionMembers:n}}function de(e){let n=[];return e.properties.map(s=>{t.isPropertyAssignment(s)?n.push({name:o(s.name),type:ne(s.initializer)}):b(`unsupported property: ${s.name}`)}),{typeLiteralMembers:n}}function se(e){v.add(e)}function g(e,n=!1){if(e.type&&!n)return _(e.type);if(!k)return console.error("TypeChecker not initialized!"),P;let s=k.getTypeAtLocation(e),i=k.typeToTypeNode(s,void 0,void 0);return i?_("type"in i?i.type:i):P}function _(e){let n={};if(e===void 0)return P;if(t.isUnionTypeNode(e))n.unionMembers=e.types.map(_);else if(t.isIntersectionTypeNode(e))n.intersectionMembers=e.types.map(_);else if(t.isLiteralTypeNode(e))n.literalValue=o(e.literal);else if(t.isTypeLiteralNode(e)){let s=[];e.members.forEach(i=>{t.isPropertySignature(i)?s.push({name:o(i.name),isOptional:i.questionToken!==void 0,type:g(i)}):t.isIndexSignatureDeclaration(i)?n.indexElementType=g(i):s.push({name:o(i.name)||"",isOptional:i.questionToken!==void 0,type:_()})}),n.typeLiteralMembers=s}else if(t.isArrayTypeNode(e))n.arrayElementType=_(e.elementType);else if(t.isFunctionTypeNode(e))n.isFunction=!0;else if(t.isTypeReferenceNode(e))if(se(o(e.typeName)),e.typeArguments)n.generics=[o(e.typeName),...e.typeArguments.map(s=>_(s))];else return o(e.typeName);else{if(t.isIndexedAccessTypeNode(e))return g(e,!0);if(t.isThisTypeNode(e))return g(e);if(t.isParenthesizedTypeNode(e))return g(e);if(t.isConditionalTypeNode(e))return g(e);if(t.isTypeQueryNode(e))return g(e);if(t.isConstructorTypeNode(e))n.isConstructor=!0;else if(t.isTupleTypeNode(e))n.tupleMembers=e.elements.map(_);else{if(Object.keys(B).includes(String(e.kind)))return B[e.kind]||P;if(t.isOptionalTypeNode(e))Object.assign(n,g(e)),n.isOptionalInTuple=!0;else if(t.isNamedTupleMember(e))Object.assign(n,g(e));else return t.isTypeOperatorNode(e)&&e.operator===t.SyntaxKind.KeyOfKeyword,g(e,!0)}}return n}var I=(e,n,s)=>[...(e==null?void 0:e.filter(i=>!(n!=null&&n.some(f=>(s||(()=>f===i))(f,i)))))||[],...n||[]];function F(e){if(e!==void 0&&e!==P)return typeof e=="string"?v.has(e)?e:void 0:e}function ge(e){var n,s;(n=e.methods)==null||n.forEach(re),(s=e.properties)==null||s.forEach(ie)}function Te(e){var n,s;(n=e.methods)==null||n.forEach(re),(s=e.properties)==null||s.forEach(ie)}function ie(e){e.type=F(e.type)}function re(e){var n;(n=e.args)==null||n.forEach(s=>s.type=F(s.type)),e.returnType=F(e.returnType)}function o(e){if(!e)return e;if(e.end<0)return e.text;try{return t.isQualifiedName(e)?o(e.right):e.getText()}catch(n){return e.text}}function z(e){e&&Object.entries(e).forEach(n=>{let[s,i]=n;i instanceof Array&&i.length===0||i===!1||i===void 0?delete e[s]:i.constructor===Array?i.forEach(z):i.constructor===Object&&z(i)})}function De(e){for(let n of e.values())z(n)}function we(e,n){return n?(n=n instanceof Array?n:[n],n.some(s=>(s instanceof RegExp||(s=new RegExp(s.replace(/\./g,"\\.").replace(/\*/g,".*"))),e.match(s)))):!1}function Q(e,n=C.cwd()){return W(e).replace(W(n)+"/","")}function W(e){let n=x.sep;return e.split(n).join("/")}function ae(e){return e instanceof Array?e:[e]}function b(e){fe&&console.log(e)}function V(e,n){let s=f=>{let r=e.replace(/\\/g,"/"),l=f.replace(/\\/g,"/");l=l.replace(/\*\*/g,"<<double_star>>");let m=l.replace(/([.+^${}()|[\]\\])/g,"\\$1").replace(/<<double_star>>/g,".*").replace(/\*/g,"[^/]*");return!f.startsWith("/")&&!f.startsWith("*")&&(m=".*"+m),m="^"+m+"$",new RegExp(m).test(r)};return(n instanceof Array?n:[n]).some(s)}function oe(e){let{sourcePaths:n,exclude:s,forEnabledClassOnly:i}=e;if(!n)throw new Error("need provide source paths for reflect loader");let{classDefinitions:f,interfaceDefinitions:r,enumDefinitions:l,typeAliasDefinitions:w}=U(n,s),m=[],D=[];function S(y){let a=f.get(y),d=[];return a?(a.superClassName&&d.push(a.superClassName),d.push(...a.implementations||[])):(a=r.get(y),a?d.push(...a.implementations||[]):(a=w.get(y),a&&d.push(...a.implementations||[]))),d.flatMap(h=>[h,...S(h)])||[]}function u(y,a){return S(y.name).includes(a)}function T(y){if(J.isClassDeclaration(y)&&y.name!==void 0){let a=y.name.text,d=f.get(a);if(!a||!d||i&&!u(d,"EnableReflect"))return;D.push(`Reflect.__classDef = Object.assign(Reflect.__classDef || {}, { ${a} })`);return}y.forEachChild(T)}function M(){let y=[];return f.forEach((a,d)=>{i&&!u(a,"EnableReflect")||y.push(`Reflect.__classes = Object.assign(Reflect.__classes || {}, { ${d}: ${JSON.stringify(a)} })`)}),r.forEach((a,d)=>{i&&!u(a,"EnableReflect")||y.push(`Reflect.__interfaces = Object.assign(Reflect.__interfaces || {}, { ${d}: ${JSON.stringify(a)} })`)}),l.forEach((a,d)=>{y.push(`Reflect.__enums = Object.assign(Reflect.__enums || {}, { ${d}: ${JSON.stringify(a)} })`)}),w.forEach((a,d)=>{y.push(`Reflect.__typeAliases = Object.assign(Reflect.__typeAliases || {}, { ${d}: ${JSON.stringify(a)} })`)}),y.join(`
2
+ `)}return{outputAllMetas:M,transform:(y,a)=>{let d=(typeof n=="string"?[n]:n).map(h=>h+"/**.ts");if(V(a,d))try{let h=J.createSourceFile(a,y,J.ScriptTarget.Latest,!1);return m.length=0,D.length=0,T(h),`${m.join(";")};${y};${D.join(";")}`}catch(h){return console.error(`[reflect-parser-plugin] Error processing ${a}:`,h),null}}}}var he=process.cwd().replace(/\\/g,"/")+"/";function Ce(e){let n=oe(e);return{name:"reflect-parser-plugin",enforce:"pre",transform:(s,i)=>(i=i.replace(he,""),i===e.entry?`${n.outputAllMetas()}
3
+ ${s}`:n.transform(s,i))}}export{U as parseSource,oe as reflectLoader,Ce as reflectParserPlugin,xe as setupReflectTypes,Z as updateReflectModules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-ref-kit",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Type reflection and validation library for TypeScript",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -16,12 +16,12 @@
16
16
  "types": "./types/index.d.ts"
17
17
  },
18
18
  "./parser": {
19
- "import": "./dist/parser/reflect-parser.js",
19
+ "import": "./dist/parser/index.js",
20
20
  "types": "./types/parser/index.d.ts"
21
21
  }
22
22
  },
23
23
  "scripts": {
24
- "build-dts": "rm -rf types/* && tsc --emitDeclarationOnly --outDir types",
24
+ "build-types": "rm -rf types/* && tsc --emitDeclarationOnly --outDir types",
25
25
  "build": "node esbuild.config.js",
26
26
  "build-parser": "node esbuild.parser.config.js"
27
27
  },