@vue.ts/complex-types 1.0.0-beta.2 → 1.0.0-beta.3

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/README.md CHANGED
@@ -14,10 +14,6 @@ $ yarn add -D @vue.ts/complex-types
14
14
  $ pnpm add -D @vue.ts/complex-types
15
15
  ```
16
16
 
17
- ## TODOs
18
-
19
- - [ ] Add more tests
20
-
21
17
  ## 🚀 Usage
22
18
 
23
19
  <details>
package/dist/astro.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
 
3
3
  //#region src/astro.d.ts
4
4
  declare const _default: (options: Options) => {
package/dist/astro.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createVitePlugin } from "unplugin";
3
3
 
4
4
  //#region src/astro.ts
package/dist/esbuild.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as esbuild0 from "esbuild";
4
4
 
package/dist/esbuild.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createEsbuildPlugin } from "unplugin";
3
3
 
4
4
  //#region src/esbuild.ts
package/dist/farm.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as _farmfe_core0 from "@farmfe/core";
4
4
 
package/dist/farm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createFarmPlugin } from "unplugin";
3
3
 
4
4
  //#region src/farm.ts
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import * as unplugin0 from "unplugin";
3
3
  import { UnpluginFactory } from "unplugin";
4
4
 
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { src_default, unplugin, unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { src_default, unplugin, unpluginFactory } from "./src-C2cWUkxC.js";
2
2
 
3
3
  export { src_default as default, unplugin, unpluginFactory };
package/dist/nuxt.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as _nuxt_schema0 from "@nuxt/schema";
4
4
 
package/dist/nuxt.js CHANGED
@@ -1,6 +1,6 @@
1
- import "./src-k-9RVLWt.js";
2
- import { vite_default } from "./vite-D_E5rjeG.js";
3
- import { webpack_default } from "./webpack-BQtMUXaQ.js";
1
+ import "./src-C2cWUkxC.js";
2
+ import { vite_default } from "./vite-kxApzRU8.js";
3
+ import { webpack_default } from "./webpack-DB3Ln7vl.js";
4
4
  import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
5
5
 
6
6
  //#region src/nuxt.ts
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as rolldown0 from "rolldown";
4
4
 
package/dist/rolldown.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createRolldownPlugin } from "unplugin";
3
3
 
4
4
  //#region src/rolldown.ts
package/dist/rollup.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as rollup0 from "rollup";
4
4
 
package/dist/rollup.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createRollupPlugin } from "unplugin";
3
3
 
4
4
  //#region src/rollup.ts
package/dist/rspack.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
 
4
4
  //#region src/rspack.d.ts
package/dist/rspack.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createRspackPlugin } from "unplugin";
3
3
 
4
4
  //#region src/rspack.ts
@@ -0,0 +1,192 @@
1
+ import { createUnplugin } from "unplugin";
2
+ import { ensureLanguage, getLanguage } from "@vue.ts/language";
3
+ import { createFilter, normalizePath } from "@vue.ts/shared";
4
+ import MagicString from "magic-string";
5
+ import ts from "typescript";
6
+ import { join } from "node:path";
7
+
8
+ //#region src/core/utils.ts
9
+ const resolveOptions = (rawOptions) => ({
10
+ include: rawOptions.include ?? ["**/*.vue"],
11
+ exclude: rawOptions.exclude ?? ["node_modules/**"],
12
+ tsconfigPath: rawOptions.tsconfigPath ?? join(process.cwd(), "tsconfig.json"),
13
+ defineEmits: rawOptions.defineEmits ?? true,
14
+ defineProps: rawOptions.defineProps ?? true
15
+ });
16
+ const quotesReg = /"/g;
17
+ const escapeQuotes = (s) => s.replace(quotesReg, "\\\"");
18
+
19
+ //#endregion
20
+ //#region src/core/printer.ts
21
+ var Printer = class {
22
+ constructor(checker) {
23
+ this.checker = checker;
24
+ }
25
+ typeToString(type) {
26
+ return this.checker.typeToString(type, void 0, ts.TypeFormatFlags.NoTruncation);
27
+ }
28
+ printOuterUnionOrIntersection(type, separator, inner) {
29
+ return [...new Set(type.types.map((t) => this.printType(t, inner)).filter(Boolean))].join(separator);
30
+ }
31
+ isUnionUndefined(union) {
32
+ return union.types.some((t) => t.flags & ts.TypeFlags.Undefined);
33
+ }
34
+ printPrimitiveType(type) {
35
+ if (type.flags & ts.TypeFlags.BooleanLiteral) return "boolean";
36
+ else if (type.flags & ts.TypeFlags.String || type.isStringLiteral()) return "string";
37
+ else if (type.flags & ts.TypeFlags.Number || type.isNumberLiteral()) return "number";
38
+ else if (type.flags & ts.TypeFlags.BigInt) return "bigint";
39
+ else if (type.flags & ts.TypeFlags.Any) return "any";
40
+ else if (type.flags & ts.TypeFlags.Unknown) return "unknown";
41
+ else if (type.flags & ts.TypeFlags.Null) return "null";
42
+ return "";
43
+ }
44
+ printType(type, inner = false) {
45
+ if (type.isUnion()) return this.printOuterUnionOrIntersection(type, " | ", inner);
46
+ else if (type.isIntersection()) return this.printOuterUnionOrIntersection(type, " & ", inner);
47
+ if (this.typeToString(type).endsWith("[]")) return this.typeToString(type);
48
+ else if (type.flags & ts.TypeFlags.Object) {
49
+ const decl = type.getSymbol()?.declarations?.[0];
50
+ if (decl && ts.isFunctionTypeNode(decl)) return "Function";
51
+ if (inner) return "object";
52
+ const properties = type.getProperties();
53
+ const props = {};
54
+ for (const prop of properties) {
55
+ const propType = this.checker.getTypeOfSymbol(prop);
56
+ props[prop.getName()] = {
57
+ value: this.printType(this.checker.getTypeOfSymbol(prop), true),
58
+ isOptional: propType.isUnion() ? this.isUnionUndefined(propType) : !!(propType.flags & ts.TypeFlags.Undefined)
59
+ };
60
+ }
61
+ const parts = [];
62
+ for (const [propName, propData] of Object.entries(props)) {
63
+ const questionMark = propData.isOptional ? "?" : "";
64
+ parts.push(`"${propName}"${questionMark}: ${propData.value},`);
65
+ }
66
+ return Object.keys(props).length > 0 ? `{\n${parts.join("\n")}\n}` : "";
67
+ } else if (type.isLiteral() || type.flags & ts.TypeFlags.BooleanLiteral || type.flags & ts.TypeFlags.String || type.flags & ts.TypeFlags.Number || type.flags & ts.TypeFlags.BigInt || type.flags & ts.TypeFlags.Any || type.flags & ts.TypeFlags.Unknown || type.flags & ts.TypeFlags.Null) return this.printPrimitiveType(type);
68
+ else if (type.flags & ts.TypeFlags.Undefined) return "";
69
+ else if (type.flags & ts.TypeFlags.Conditional) return `${this.printType(type.resolvedTrueType)} | ${this.printType(type.resolvedFalseType)}`;
70
+ else if (type.isTypeParameter()) {
71
+ const symbol = type.getSymbol();
72
+ const decl = symbol?.declarations?.[0];
73
+ if (!decl || !ts.isTypeParameterDeclaration(decl)) return "";
74
+ const ref = ts.getEffectiveConstraintOfTypeParameter(decl);
75
+ if (!ref) return "";
76
+ const refType = this.checker.getTypeAtLocation(ref);
77
+ return this.printType(refType);
78
+ }
79
+ return this.typeToString(type);
80
+ }
81
+ printPropsTypeArg(node) {
82
+ const type = this.checker.getTypeAtLocation(node);
83
+ return this.printType(type);
84
+ }
85
+ printEventsByCallSignatures(callSignatures) {
86
+ return callSignatures.map((c) => {
87
+ const parameters = c.getParameters();
88
+ const event = parameters[0];
89
+ return this.typeToString(this.checker.getTypeOfSymbol(event));
90
+ });
91
+ }
92
+ printEventsByMembers(members) {
93
+ return members.map((m) => `"${escapeQuotes(m.getName())}"`);
94
+ }
95
+ printEventsRuntimeArg(node) {
96
+ const parts = [];
97
+ const type = this.checker.getTypeAtLocation(node);
98
+ const callSignatures = type.getCallSignatures();
99
+ const members = type.getProperties();
100
+ if (callSignatures.length > 0 && members.length > 0) throw new Error("[@vue.ts/complex-types] You may not use old style `defineEmits` and `defineEmits` shorthand together.");
101
+ if (members.length > 0) parts.push(...this.printEventsByMembers(members));
102
+ else parts.push(...this.printEventsByCallSignatures(callSignatures));
103
+ return `[${parts.join(", ")}]`;
104
+ }
105
+ };
106
+
107
+ //#endregion
108
+ //#region src/core/transformers/defineEmits.ts
109
+ const transformDefineEmits = (printer, s, id) => {
110
+ const normalizedFilepath = normalizePath(id);
111
+ const language = getLanguage();
112
+ const scriptSetupBlock = language.getScriptSetupBlock(normalizedFilepath);
113
+ const scriptSetupAst = language.getScriptSetupAst(normalizedFilepath);
114
+ const virtualFileAst = language.getVirtualFileOrTsAst(normalizedFilepath);
115
+ if (!scriptSetupBlock || !scriptSetupAst || !virtualFileAst) return;
116
+ const scriptSetupDefineEmitsNode = language.findNodeByRange(scriptSetupAst, (scriptSetupRanges) => scriptSetupRanges.defineEmits?.callExp);
117
+ const virtualFileDefineEmitsTypeNode = language.findNodeByName(virtualFileAst, "__VLS_Emit");
118
+ if (!scriptSetupDefineEmitsNode || !virtualFileDefineEmitsTypeNode) return;
119
+ const offset = scriptSetupBlock.startTagEnd;
120
+ const defineEmitsRuntimeArg = ts.isCallExpression(scriptSetupDefineEmitsNode) && scriptSetupDefineEmitsNode.arguments[0];
121
+ if (defineEmitsRuntimeArg) throw new Error("[@vue.ts/complex-types] `defineEmits` cannot accept both runtime argument and type argument.");
122
+ const tokens = scriptSetupDefineEmitsNode.getChildren(scriptSetupAst);
123
+ const lessThanToken = tokens.find((t) => t.kind === ts.SyntaxKind.LessThanToken);
124
+ const greaterThanToken = tokens.find((t) => t.kind === ts.SyntaxKind.GreaterThanToken);
125
+ const openParenToken = tokens.find((t) => t.kind === ts.SyntaxKind.OpenParenToken);
126
+ if (!lessThanToken || !greaterThanToken || !openParenToken) return;
127
+ const defineEmitsTypeArgRange = [offset + lessThanToken.pos, offset + greaterThanToken.end];
128
+ const runtimeArgPos = offset + openParenToken.end;
129
+ const printedRuntimeArg = printer.printEventsRuntimeArg(virtualFileDefineEmitsTypeNode);
130
+ s.remove(...defineEmitsTypeArgRange);
131
+ s.appendRight(runtimeArgPos, printedRuntimeArg);
132
+ };
133
+
134
+ //#endregion
135
+ //#region src/core/transformers/defineProps.ts
136
+ const transformDefineProps = (printer, s, id) => {
137
+ const normalizedFilepath = normalizePath(id);
138
+ const language = getLanguage();
139
+ const scriptSetupBlock = language.getScriptSetupBlock(normalizedFilepath);
140
+ const scriptSetupAst = language.getScriptSetupAst(normalizedFilepath);
141
+ const virtualFileAst = language.getVirtualFileOrTsAst(normalizedFilepath);
142
+ if (!scriptSetupBlock || !scriptSetupAst || !virtualFileAst) return;
143
+ const scriptSetupDefinePropsTypeRange = language.parseScriptSetupRanges(scriptSetupAst).defineProps?.typeArg;
144
+ const virtualFileDefinePropsTypeNode = language.findNodeByName(virtualFileAst, "__VLS_Props");
145
+ if (!scriptSetupDefinePropsTypeRange || !virtualFileDefinePropsTypeNode) return;
146
+ const printedType = printer.printPropsTypeArg(virtualFileDefinePropsTypeNode);
147
+ const offset = scriptSetupBlock.startTagEnd;
148
+ s.overwrite(offset + scriptSetupDefinePropsTypeRange.start, offset + scriptSetupDefinePropsTypeRange.end, printedType);
149
+ };
150
+
151
+ //#endregion
152
+ //#region src/core/transformers/index.ts
153
+ const transformers = [["defineEmits", transformDefineEmits], ["defineProps", transformDefineProps]];
154
+ const getTransformers = (options) => transformers.filter(([key]) => !!options[key]);
155
+
156
+ //#endregion
157
+ //#region src/core/transform.ts
158
+ function transform(code, id, options) {
159
+ const s = new MagicString(code);
160
+ const language = getLanguage();
161
+ const typeChecker = language.__internal__.typeChecker;
162
+ const printer = new Printer(typeChecker);
163
+ const transformers$1 = getTransformers(options);
164
+ for (const [, transform$1] of transformers$1) transform$1(printer, s, id);
165
+ return {
166
+ code: s.toString(),
167
+ map: s.generateMap({ hires: true })
168
+ };
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/index.ts
173
+ const unpluginFactory = (options = {}) => {
174
+ const resolvedOptions = resolveOptions(options);
175
+ const filter = createFilter(resolvedOptions.include, resolvedOptions.exclude);
176
+ return {
177
+ name: "@vue.ts/complex-types",
178
+ buildStart() {
179
+ const resolvedOptions$1 = resolveOptions(options);
180
+ ensureLanguage(resolvedOptions$1.tsconfigPath);
181
+ },
182
+ transform(code, id) {
183
+ if (!filter(id)) return;
184
+ return transform(code, id, resolvedOptions);
185
+ }
186
+ };
187
+ };
188
+ const unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
189
+ var src_default = unplugin;
190
+
191
+ //#endregion
192
+ export { src_default, unplugin, unpluginFactory };
@@ -2,7 +2,7 @@ import MagicString from "magic-string";
2
2
  import ts from "typescript";
3
3
  import { FilterPattern } from "@rollup/pluginutils";
4
4
 
5
- //#region ../common/src/types.d.ts
5
+ //#region ../shared/src/types.d.ts
6
6
  interface BaseOptions {
7
7
  include?: FilterPattern;
8
8
  exclude?: FilterPattern;
@@ -12,27 +12,12 @@ interface BaseOptions {
12
12
  declare class Printer {
13
13
  private checker;
14
14
  constructor(checker: ts.TypeChecker);
15
- private getBaseType;
16
15
  private typeToString;
17
- private printIntersectionTypeNode;
18
- private printUnionTypeNode;
19
- private printTypeLiteralNode;
20
- private printTypeByType;
21
- private printIdentifier;
22
- private printInterfaceDeclaration;
23
- private printEnumDeclaration;
24
- private printClassDeclaration;
25
- private printFunctionTypeNode;
26
- private printConstructorTypeNode;
27
- private printTypeQueryNode;
28
- private printArrayTypeNode;
29
- private printTupleTypeNode;
30
- private printConditionalTypeNode;
31
- private printIndexedAccessTypeNode;
32
- private printHeritageClause;
33
- private printImportSpecifier;
34
- private isKeywordTypeNode;
35
- print(node: ts.Node): string;
16
+ private printOuterUnionOrIntersection;
17
+ private isUnionUndefined;
18
+ private printPrimitiveType;
19
+ private printType;
20
+ printPropsTypeArg(node: ts.Node): string;
36
21
  private printEventsByCallSignatures;
37
22
  private printEventsByMembers;
38
23
  printEventsRuntimeArg(node: ts.Node): string;
package/dist/types.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { Options, ResolvedOptions, TransformOptions, Transformer, Transformers, ValidTransforms } from "./types-CFmCIAvs.js";
1
+ import { Options, ResolvedOptions, TransformOptions, Transformer, Transformers, ValidTransforms } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  export { Options, ResolvedOptions, TransformOptions, Transformer, Transformers, ValidTransforms };
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createVitePlugin } from "unplugin";
3
3
 
4
4
  //#region src/vite.ts
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as vite0 from "vite";
4
4
 
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./src-k-9RVLWt.js";
2
- import { vite_default } from "./vite-D_E5rjeG.js";
1
+ import "./src-C2cWUkxC.js";
2
+ import { vite_default } from "./vite-kxApzRU8.js";
3
3
 
4
4
  export { vite_default as default };
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./src-k-9RVLWt.js";
1
+ import { unpluginFactory } from "./src-C2cWUkxC.js";
2
2
  import { createWebpackPlugin } from "unplugin";
3
3
 
4
4
  //#region src/webpack.ts
package/dist/webpack.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Options } from "./types-CFmCIAvs.js";
1
+ import { Options } from "./types-afZXKowK.js";
2
2
  import "./types-u_Hr5uXA.js";
3
3
  import * as webpack0 from "webpack";
4
4
 
package/dist/webpack.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./src-k-9RVLWt.js";
2
- import { webpack_default } from "./webpack-BQtMUXaQ.js";
1
+ import "./src-C2cWUkxC.js";
2
+ import { webpack_default } from "./webpack-DB3Ln7vl.js";
3
3
 
4
4
  export { webpack_default as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vue.ts/complex-types",
3
- "version": "1.0.0-beta.2",
3
+ "version": "1.0.0-beta.3",
4
4
  "author": "Ray <i@mk1.io> (@so1ve)",
5
5
  "type": "module",
6
6
  "description": "Resolve complex types in Vue SFCs.",
@@ -65,8 +65,8 @@
65
65
  "@nuxt/kit": "^3.17.6",
66
66
  "magic-string": "^0.30.17",
67
67
  "unplugin": "^2.3.5",
68
- "@vue.ts/common": "1.0.0-beta.2",
69
- "@vue.ts/language": "1.0.0-beta.2"
68
+ "@vue.ts/language": "1.0.0-beta.3",
69
+ "@vue.ts/shared": "1.0.0-beta.3"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@nuxt/schema": "^3.17.6",
@@ -83,9 +83,9 @@
83
83
  "esbuild": "*",
84
84
  "rolldown": "*",
85
85
  "rollup": "^3",
86
- "typescript": "^5.2.2",
86
+ "typescript": ">=5.5",
87
87
  "vite": ">=3",
88
- "vue": "^3.3.7",
88
+ "vue": ">=3",
89
89
  "webpack": "^4 || ^5"
90
90
  },
91
91
  "peerDependenciesMeta": {
@@ -1,360 +0,0 @@
1
- import { createUnplugin } from "unplugin";
2
- import { createFilter, normalizePath } from "@vue.ts/common";
3
- import { ensureLanguage, getLanguage } from "@vue.ts/language";
4
- import MagicString from "magic-string";
5
- import ts from "typescript";
6
- import { join } from "node:path";
7
-
8
- //#region src/core/utils.ts
9
- const resolveOptions = (rawOptions) => ({
10
- include: rawOptions.include ?? ["**/*.vue"],
11
- exclude: rawOptions.exclude ?? ["node_modules/**"],
12
- tsconfigPath: rawOptions.tsconfigPath ?? join(process.cwd(), "tsconfig.json"),
13
- defineEmits: rawOptions.defineEmits ?? true,
14
- defineProps: rawOptions.defineProps ?? true
15
- });
16
- const quotesReg = /"/g;
17
- const escapeQuotes = (s) => s.replace(quotesReg, "\\\"");
18
-
19
- //#endregion
20
- //#region src/core/printer.ts
21
- var Printer = class {
22
- constructor(checker) {
23
- this.checker = checker;
24
- }
25
- getBaseType(nodeOrType) {
26
- if ("kind" in nodeOrType) nodeOrType = this.checker.getTypeAtLocation(nodeOrType);
27
- return this.checker.getBaseConstraintOfType(nodeOrType) ?? this.checker.getBaseTypeOfLiteralType(nodeOrType);
28
- }
29
- typeToString(type) {
30
- return this.checker.typeToString(type, void 0, ts.TypeFormatFlags.NoTruncation);
31
- }
32
- printIntersectionTypeNode(node) {
33
- return node.types.map((t) => this.print(t)).join(" & ");
34
- }
35
- printUnionTypeNode(node) {
36
- return node.types.map((t) => this.print(t)).join(" | ");
37
- }
38
- printTypeLiteralNode(node) {
39
- const parts = ["{"];
40
- for (const member of node.members) if (ts.isPropertySignature(member)) {
41
- const stringBaseType = member.type ? this.typeToString(this.getBaseType(member.type)) : "any";
42
- parts.push([
43
- member.name.getText(),
44
- member.questionToken?.getText(),
45
- ": ",
46
- stringBaseType
47
- ].filter(Boolean).join(""));
48
- }
49
- parts.push("}");
50
- return parts.join("\n");
51
- }
52
- printTypeByType(node) {
53
- const type = this.checker.getTypeAtLocation(node);
54
- const properties = type.getProperties();
55
- const parts = ["{"];
56
- const isMapped = ts.isMappedTypeNode(node);
57
- for (const property of properties) {
58
- const isOptional = property.flags & ts.SymbolFlags.Optional;
59
- const questionToken = isMapped ? node.questionToken?.getText() ?? "" : isOptional ? "?" : "";
60
- const valueType = this.checker.getTypeOfSymbol(property);
61
- const stringValueType = this.typeToString(this.getBaseType(valueType));
62
- parts.push(`${this.checker.symbolToString(property)}${questionToken}: ${stringValueType}`);
63
- }
64
- parts.push("}");
65
- return parts.join("\n");
66
- }
67
- printIdentifier(node) {
68
- const symbol = this.checker.getSymbolAtLocation(node);
69
- if (!symbol) return node.getText();
70
- const declarations = symbol.getDeclarations();
71
- if (!declarations || declarations.length === 0) return node.getText();
72
- return this.print(declarations[0]);
73
- }
74
- printInterfaceDeclaration(node) {
75
- const parts = ["{"];
76
- for (const member of node.members) if (ts.isPropertySignature(member)) {
77
- const stringBaseType = member.type ? this.print(member.type) : "any";
78
- parts.push([
79
- member.name?.getText(),
80
- member.questionToken?.getText(),
81
- ": ",
82
- stringBaseType
83
- ].filter(Boolean).join(""));
84
- } else if (ts.isMethodSignature(member)) {
85
- const signature = this.checker.getSignatureFromDeclaration(member);
86
- const returnType = signature ? this.typeToString(signature.getReturnType()) : "any";
87
- const parameters = member.parameters.map((param) => {
88
- const paramType = param.type ? this.typeToString(this.getBaseType(param.type)) : "any";
89
- return `${param.name.getText()}: ${paramType}`;
90
- }).join(", ");
91
- parts.push(`${member.name?.getText()}(${parameters}): ${returnType}`);
92
- }
93
- parts.push("}");
94
- let result = parts.join("\n");
95
- if (node.heritageClauses && node.heritageClauses.length > 0) result = node.heritageClauses.map((clause) => this.print(clause)).join(" & ");
96
- return result;
97
- }
98
- printEnumDeclaration(node) {
99
- const parts = ["{"];
100
- for (const member of node.members) {
101
- const name = member.name.getText();
102
- if (member.initializer) {
103
- const value = member.initializer.getText();
104
- parts.push(`${name}: ${value}`);
105
- } else parts.push(`${name}: number`);
106
- }
107
- parts.push("}");
108
- return parts.join("\n");
109
- }
110
- printClassDeclaration(node) {
111
- const parts = ["{"];
112
- for (const member of node.members) if (ts.isPropertyDeclaration(member)) {
113
- const name = member.name?.getText();
114
- const typeAnnotation = member.type ? this.typeToString(this.getBaseType(member.type)) : "any";
115
- const optional = member.questionToken ? "?" : "";
116
- parts.push(`${name}${optional}: ${typeAnnotation}`);
117
- } else if (ts.isMethodDeclaration(member)) {
118
- const name = member.name?.getText();
119
- const signature = this.checker.getSignatureFromDeclaration(member);
120
- const returnType = signature ? this.typeToString(signature.getReturnType()) : "any";
121
- const parameters = member.parameters.map((param) => {
122
- const paramType = param.type ? this.typeToString(this.getBaseType(param.type)) : "any";
123
- return `${param.name.getText()}: ${paramType}`;
124
- }).join(", ");
125
- parts.push(`${name}(${parameters}): ${returnType}`);
126
- } else if (ts.isConstructorDeclaration(member)) {
127
- const parameters = member.parameters.map((param) => {
128
- const paramType = param.type ? this.typeToString(this.getBaseType(param.type)) : "any";
129
- return `${param.name.getText()}: ${paramType}`;
130
- }).join(", ");
131
- parts.push(`constructor(${parameters}): void`);
132
- }
133
- parts.push("}");
134
- return parts.join("\n");
135
- }
136
- printFunctionTypeNode(node) {
137
- const parameters = node.parameters.map((param) => {
138
- const paramType = param.type ? this.print(param.type) : "any";
139
- const optional = param.questionToken ? "?" : "";
140
- const rest = param.dotDotDotToken ? "..." : "";
141
- return `${rest}${param.name.getText()}${optional}: ${paramType}`;
142
- }).join(", ");
143
- const returnType = node.type ? this.print(node.type) : "any";
144
- return `(${parameters}) => ${returnType}`;
145
- }
146
- printConstructorTypeNode(node) {
147
- const parameters = node.parameters.map((param) => {
148
- const paramType = param.type ? this.print(param.type) : "any";
149
- const optional = param.questionToken ? "?" : "";
150
- const rest = param.dotDotDotToken ? "..." : "";
151
- return `${rest}${param.name.getText()}${optional}: ${paramType}`;
152
- }).join(", ");
153
- const returnType = node.type ? this.print(node.type) : "any";
154
- return `new (${parameters}) => ${returnType}`;
155
- }
156
- printTypeQueryNode(node) {
157
- const exprName = node.exprName.getText();
158
- return `typeof ${exprName}`;
159
- }
160
- printArrayTypeNode(node) {
161
- return `${this.print(node.elementType)}[]`;
162
- }
163
- printTupleTypeNode(node) {
164
- const elements = node.elements.map((element) => {
165
- if (ts.isRestTypeNode(element)) return `...${this.print(element.type)}`;
166
- if (ts.isOptionalTypeNode(element)) return `${this.print(element.type)}?`;
167
- if (ts.isNamedTupleMember(element)) {
168
- const type = this.print(element.type);
169
- const optional = element.questionToken ? "?" : "";
170
- const rest = element.dotDotDotToken ? "..." : "";
171
- return `${rest}${element.name.getText()}${optional}: ${type}`;
172
- }
173
- return this.print(element);
174
- });
175
- return `[${elements.join(", ")}]`;
176
- }
177
- printConditionalTypeNode(node) {
178
- const conditionalType = this.checker.getTypeAtLocation(node);
179
- if (conditionalType && !(conditionalType.flags & ts.TypeFlags.Conditional)) {
180
- const resolvedTypeString = this.typeToString(conditionalType);
181
- if (resolvedTypeString !== node.getText()) return resolvedTypeString;
182
- }
183
- const checkType = this.print(node.checkType);
184
- const extendsType = this.print(node.extendsType);
185
- const trueType = this.print(node.trueType);
186
- const falseType = this.print(node.falseType);
187
- return `${checkType} extends ${extendsType} ? ${trueType} : ${falseType}`;
188
- }
189
- printIndexedAccessTypeNode(node) {
190
- const objectType = this.print(node.objectType);
191
- const indexType = this.print(node.indexType);
192
- return `${objectType}[${indexType}]`;
193
- }
194
- printHeritageClause(node) {
195
- if (node.token === ts.SyntaxKind.ExtendsKeyword) {
196
- const parts = [];
197
- for (const type of node.types) if (ts.isExpressionWithTypeArguments(type)) if (type.expression && type.typeArguments) parts.push(this.print(type));
198
- else parts.push(this.print(type.expression));
199
- return parts.join(" & ");
200
- }
201
- return "";
202
- }
203
- printImportSpecifier(node) {
204
- const name = node.propertyName ? node.propertyName.getText() : node.name.getText();
205
- const symbol = this.checker.getSymbolAtLocation(node.name);
206
- if (!symbol) return name;
207
- const aliasedSymbol = this.checker.getAliasedSymbol(symbol);
208
- const targetSymbol = aliasedSymbol || symbol;
209
- const declarations = targetSymbol.getDeclarations();
210
- if (!declarations || declarations.length === 0) return name;
211
- const declaration = declarations.find((decl) => ts.isTypeAliasDeclaration(decl) || ts.isInterfaceDeclaration(decl) || ts.isClassDeclaration(decl) || ts.isEnumDeclaration(decl) || ts.isVariableDeclaration(decl));
212
- if (declaration) return this.print(declaration);
213
- return name;
214
- }
215
- isKeywordTypeNode(node) {
216
- return node.kind === ts.SyntaxKind.StringKeyword || node.kind === ts.SyntaxKind.NumberKeyword || node.kind === ts.SyntaxKind.BooleanKeyword || node.kind === ts.SyntaxKind.ObjectKeyword || node.kind === ts.SyntaxKind.UndefinedKeyword || node.kind === ts.SyntaxKind.NullKeyword || node.kind === ts.SyntaxKind.VoidKeyword || node.kind === ts.SyntaxKind.AnyKeyword || node.kind === ts.SyntaxKind.UnknownKeyword || node.kind === ts.SyntaxKind.NeverKeyword || node.kind === ts.SyntaxKind.SymbolKeyword || node.kind === ts.SyntaxKind.BigIntKeyword;
217
- }
218
- print(node) {
219
- if (ts.isIdentifier(node)) return this.printIdentifier(node);
220
- else if (ts.isIntersectionTypeNode(node)) return this.printIntersectionTypeNode(node);
221
- else if (ts.isUnionTypeNode(node)) return this.printUnionTypeNode(node);
222
- else if (ts.isTypeLiteralNode(node)) return this.printTypeLiteralNode(node);
223
- else if (ts.isTypeReferenceNode(node)) return this.print(node.typeName);
224
- else if (ts.isInterfaceDeclaration(node)) return this.printInterfaceDeclaration(node);
225
- else if (ts.isTypeAliasDeclaration(node)) return node.type ? this.print(node.type) : "any";
226
- else if (ts.isEnumDeclaration(node)) return this.printEnumDeclaration(node);
227
- else if (ts.isClassDeclaration(node)) return this.printClassDeclaration(node);
228
- else if (ts.isFunctionTypeNode(node)) return this.printFunctionTypeNode(node);
229
- else if (ts.isConstructorTypeNode(node)) return this.printConstructorTypeNode(node);
230
- else if (ts.isTypeQueryNode(node)) return this.printTypeQueryNode(node);
231
- else if (ts.isArrayTypeNode(node)) return this.printArrayTypeNode(node);
232
- else if (ts.isTupleTypeNode(node)) return this.printTupleTypeNode(node);
233
- else if (ts.isConditionalTypeNode(node)) return this.printConditionalTypeNode(node);
234
- else if (ts.isIndexedAccessTypeNode(node)) return this.printIndexedAccessTypeNode(node);
235
- else if (ts.isParenthesizedTypeNode(node)) return this.print(node.type);
236
- else if (ts.isHeritageClause(node)) return this.printHeritageClause(node);
237
- else if (ts.isTypeAliasDeclaration(node) && node.type) return this.print(node.type);
238
- else if (ts.isInterfaceDeclaration(node)) return this.printInterfaceDeclaration(node);
239
- else if (ts.isVariableDeclaration(node) && node.type) return this.print(node.type);
240
- else if (ts.isImportSpecifier(node)) return this.printImportSpecifier(node);
241
- else if (ts.isTypeParameterDeclaration(node)) {
242
- if (node.constraint) return this.print(node.constraint);
243
- else if (node.default) return this.print(node.default);
244
- return "{}";
245
- } else if (ts.isParameter(node) && node.type) return this.print(node.type);
246
- else if (ts.isLiteralTypeNode(node) || ts.isThisTypeNode(node) || ts.isPropertyAccessExpression(node) || this.isKeywordTypeNode(node)) return node.getText();
247
- else if (ts.isMappedTypeNode(node) || ts.isExpressionWithTypeArguments(node)) return this.printTypeByType(node);
248
- else {
249
- console.error(`[@vue.ts/complex-types] \`${ts.SyntaxKind[node.kind]}\` is not supported.`);
250
- return node.getText();
251
- }
252
- }
253
- printEventsByCallSignatures(callSignatures) {
254
- return callSignatures.map((c) => {
255
- const parameters = c.getParameters();
256
- const event = parameters[0];
257
- return this.typeToString(this.checker.getTypeOfSymbol(event));
258
- });
259
- }
260
- printEventsByMembers(members) {
261
- return members.map((m) => `"${escapeQuotes(m.getName())}"`);
262
- }
263
- printEventsRuntimeArg(node) {
264
- const parts = [];
265
- const type = this.checker.getTypeAtLocation(node);
266
- const callSignatures = type.getCallSignatures();
267
- const members = type.getProperties();
268
- if (callSignatures.length > 0 && members.length > 0) throw new Error("[@vue.ts/complex-types] You may not use old style `defineEmits` and `defineEmits` shorthand together.");
269
- if (members.length > 0) parts.push(...this.printEventsByMembers(members));
270
- else parts.push(...this.printEventsByCallSignatures(callSignatures));
271
- return `[${parts.join(", ")}]`;
272
- }
273
- };
274
-
275
- //#endregion
276
- //#region src/core/transformers/defineEmits.ts
277
- const transformDefineEmits = (printer, s, id) => {
278
- const normalizedFilepath = normalizePath(id);
279
- const language = getLanguage();
280
- const scriptSetupBlock = language.getScriptSetupBlock(normalizedFilepath);
281
- const scriptSetupAst = language.getScriptSetupAst(normalizedFilepath);
282
- const virtualFileAst = language.getVirtualFileOrTsAst(normalizedFilepath);
283
- if (!scriptSetupBlock || !scriptSetupAst || !virtualFileAst) return;
284
- const scriptSetupDefineEmitsNode = language.findNodeByRange(scriptSetupAst, (scriptSetupRanges) => scriptSetupRanges.defineEmits?.callExp);
285
- const virtualFileDefineEmitsTypeNode = language.findNodeByName(virtualFileAst, "__VLS_Emit");
286
- if (!scriptSetupDefineEmitsNode || !virtualFileDefineEmitsTypeNode) return;
287
- const offset = scriptSetupBlock.startTagEnd;
288
- const defineEmitsRuntimeArg = ts.isCallExpression(scriptSetupDefineEmitsNode) && scriptSetupDefineEmitsNode.arguments[0];
289
- if (defineEmitsRuntimeArg) throw new Error("[@vue.ts/complex-types] `defineEmits` cannot accept both runtime argument and type argument.");
290
- const tokens = scriptSetupDefineEmitsNode.getChildren(scriptSetupAst);
291
- const lessThanToken = tokens.find((t) => t.kind === ts.SyntaxKind.LessThanToken);
292
- const greaterThanToken = tokens.find((t) => t.kind === ts.SyntaxKind.GreaterThanToken);
293
- const openParenToken = tokens.find((t) => t.kind === ts.SyntaxKind.OpenParenToken);
294
- if (!lessThanToken || !greaterThanToken || !openParenToken) return;
295
- const defineEmitsTypeArgRange = [offset + lessThanToken.pos, offset + greaterThanToken.end];
296
- const runtimeArgPos = offset + openParenToken.end;
297
- const printedRuntimeArg = printer.printEventsRuntimeArg(virtualFileDefineEmitsTypeNode);
298
- s.remove(...defineEmitsTypeArgRange);
299
- s.appendRight(runtimeArgPos, printedRuntimeArg);
300
- };
301
-
302
- //#endregion
303
- //#region src/core/transformers/defineProps.ts
304
- const transformDefineProps = (printer, s, id) => {
305
- const normalizedFilepath = normalizePath(id);
306
- const language = getLanguage();
307
- const scriptSetupBlock = language.getScriptSetupBlock(normalizedFilepath);
308
- const scriptSetupAst = language.getScriptSetupAst(normalizedFilepath);
309
- const virtualFileAst = language.getVirtualFileOrTsAst(normalizedFilepath);
310
- if (!scriptSetupBlock || !scriptSetupAst || !virtualFileAst) return;
311
- const scriptSetupDefinePropsTypeRange = language.parseScriptSetupRanges(scriptSetupAst).defineProps?.typeArg;
312
- const virtualFileDefinePropsTypeNode = language.findNodeByName(virtualFileAst, "__VLS_Props");
313
- if (!scriptSetupDefinePropsTypeRange || !virtualFileDefinePropsTypeNode) return;
314
- const printedType = printer.print(virtualFileDefinePropsTypeNode);
315
- const offset = scriptSetupBlock.startTagEnd;
316
- s.overwrite(offset + scriptSetupDefinePropsTypeRange.start, offset + scriptSetupDefinePropsTypeRange.end, printedType);
317
- };
318
-
319
- //#endregion
320
- //#region src/core/transformers/index.ts
321
- const transformers = [["defineEmits", transformDefineEmits], ["defineProps", transformDefineProps]];
322
- const getTransformers = (options) => transformers.filter(([key]) => !!options[key]);
323
-
324
- //#endregion
325
- //#region src/core/transform.ts
326
- function transform(code, id, options) {
327
- const s = new MagicString(code);
328
- const language = getLanguage();
329
- const typeChecker = language.__internal__.typeChecker;
330
- const printer = new Printer(typeChecker);
331
- const transformers$1 = getTransformers(options);
332
- for (const [, transform$1] of transformers$1) transform$1(printer, s, id);
333
- return {
334
- code: s.toString(),
335
- map: s.generateMap({ hires: true })
336
- };
337
- }
338
-
339
- //#endregion
340
- //#region src/index.ts
341
- const unpluginFactory = (options = {}) => {
342
- const resolvedOptions = resolveOptions(options);
343
- const filter = createFilter(resolvedOptions.include, resolvedOptions.exclude);
344
- return {
345
- name: "@vue.ts/complex-types",
346
- buildStart() {
347
- const resolvedOptions$1 = resolveOptions(options);
348
- ensureLanguage(resolvedOptions$1.tsconfigPath);
349
- },
350
- transform(code, id) {
351
- if (!filter(id)) return;
352
- return transform(code, id, resolvedOptions);
353
- }
354
- };
355
- };
356
- const unplugin = /* @__PURE__ */ createUnplugin(unpluginFactory);
357
- var src_default = unplugin;
358
-
359
- //#endregion
360
- export { src_default, unplugin, unpluginFactory };