@elliots/typical 0.1.9 → 0.2.0-beta.1
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 +232 -96
- package/dist/src/cli.js +14 -60
- package/dist/src/cli.js.map +1 -1
- package/dist/src/cli.typical.ts +136 -0
- package/dist/src/config.d.ts +56 -0
- package/dist/src/config.js +124 -32
- package/dist/src/config.js.map +1 -1
- package/dist/src/config.typical.ts +287 -0
- package/dist/src/esm-loader-register.js.map +1 -1
- package/dist/src/esm-loader.d.ts +1 -0
- package/dist/src/esm-loader.js +31 -8
- package/dist/src/esm-loader.js.map +1 -1
- package/dist/src/file-filter.d.ts +1 -1
- package/dist/src/file-filter.js.map +1 -1
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.js +2 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/program-manager.d.ts +27 -0
- package/dist/src/program-manager.js +121 -0
- package/dist/src/program-manager.js.map +1 -0
- package/dist/src/regex-hoister.d.ts +1 -1
- package/dist/src/regex-hoister.js +13 -19
- package/dist/src/regex-hoister.js.map +1 -1
- package/dist/src/setup.d.ts +1 -1
- package/dist/src/setup.js +3 -3
- package/dist/src/setup.js.map +1 -1
- package/dist/src/source-map.d.ts +78 -0
- package/dist/src/source-map.js +133 -0
- package/dist/src/source-map.js.map +1 -0
- package/dist/src/source-map.typical.ts +216 -0
- package/dist/src/timing.d.ts +19 -0
- package/dist/src/timing.js +65 -0
- package/dist/src/timing.js.map +1 -0
- package/dist/src/transformer.d.ts +28 -126
- package/dist/src/transformer.js +44 -1477
- package/dist/src/transformer.js.map +1 -1
- package/dist/src/transformer.typical.ts +2552 -0
- package/dist/src/tsc-plugin.d.ts +8 -1
- package/dist/src/tsc-plugin.js +11 -7
- package/dist/src/tsc-plugin.js.map +1 -1
- package/package.json +54 -44
- package/src/cli.ts +45 -98
- package/src/config.ts +200 -57
- package/src/esm-loader-register.ts +2 -2
- package/src/esm-loader.ts +46 -19
- package/src/index.ts +5 -2
- package/src/patch-fs.cjs +14 -14
- package/src/timing.ts +74 -0
- package/src/transformer.ts +52 -1969
- package/bin/ttsc +0 -12
- package/src/file-filter.ts +0 -49
- package/src/patch-tsconfig.cjs +0 -52
- package/src/regex-hoister.ts +0 -203
- package/src/setup.ts +0 -39
- package/src/tsc-plugin.ts +0 -12
package/dist/src/transformer.js
CHANGED
|
@@ -1,1497 +1,64 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
/**
|
|
2
|
+
* TypicalTransformer - Thin wrapper around the Go compiler.
|
|
3
|
+
*
|
|
4
|
+
* The Go compiler (compiler) handles all TypeScript analysis
|
|
5
|
+
* and validation code generation. This class just manages the lifecycle
|
|
6
|
+
* and communication with the Go process.
|
|
7
|
+
*/
|
|
8
|
+
import { resolve } from 'path';
|
|
9
|
+
import { TypicalCompiler } from '@elliots/typical-compiler';
|
|
10
|
+
import { loadConfig } from './config.js';
|
|
11
11
|
export class TypicalTransformer {
|
|
12
12
|
config;
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
constructor(config, program, tsInstance) {
|
|
13
|
+
compiler;
|
|
14
|
+
projectHandle = null;
|
|
15
|
+
initPromise = null;
|
|
16
|
+
configFile;
|
|
17
|
+
constructor(config, configFile = 'tsconfig.json') {
|
|
19
18
|
this.config = config ?? loadConfig();
|
|
20
|
-
this.
|
|
21
|
-
this.
|
|
22
|
-
}
|
|
23
|
-
createSourceFile(fileName, content) {
|
|
24
|
-
return this.ts.createSourceFile(fileName, content, this.ts.ScriptTarget.ES2020, true);
|
|
25
|
-
}
|
|
26
|
-
transform(sourceFile, mode, skippedTypes = new Set()) {
|
|
27
|
-
if (typeof sourceFile === "string") {
|
|
28
|
-
const file = this.program.getSourceFile(sourceFile);
|
|
29
|
-
if (!file) {
|
|
30
|
-
throw new Error(`Source file not found in program: ${sourceFile}`);
|
|
31
|
-
}
|
|
32
|
-
sourceFile = file;
|
|
33
|
-
}
|
|
34
|
-
const printer = this.ts.createPrinter();
|
|
35
|
-
// Phase 1: typical's own transformations only (no typia)
|
|
36
|
-
const typicalTransformer = this.getTypicalOnlyTransformer(skippedTypes);
|
|
37
|
-
const phase1Result = this.ts.transform(sourceFile, [typicalTransformer]);
|
|
38
|
-
let transformedCode = printer.printFile(phase1Result.transformed[0]);
|
|
39
|
-
phase1Result.dispose();
|
|
40
|
-
if (mode === "basic") {
|
|
41
|
-
return transformedCode;
|
|
42
|
-
}
|
|
43
|
-
// Phase 2: if code has typia calls, run typia transformer in its own context
|
|
44
|
-
if (transformedCode.includes("typia.")) {
|
|
45
|
-
const result = this.applyTypiaTransform(sourceFile.fileName, transformedCode, printer);
|
|
46
|
-
if (typeof result === 'object' && result.retry) {
|
|
47
|
-
// Typia failed on a type - add to skipped and retry the whole transform
|
|
48
|
-
skippedTypes.add(result.failedType);
|
|
49
|
-
// Clear validator caches since we're retrying
|
|
50
|
-
this.typeValidators.clear();
|
|
51
|
-
this.typeStringifiers.clear();
|
|
52
|
-
this.typeParsers.clear();
|
|
53
|
-
return this.transform(sourceFile, mode, skippedTypes);
|
|
54
|
-
}
|
|
55
|
-
transformedCode = result;
|
|
56
|
-
}
|
|
57
|
-
if (mode === "typia") {
|
|
58
|
-
return transformedCode;
|
|
59
|
-
}
|
|
60
|
-
// Mode "js" - transpile to JavaScript
|
|
61
|
-
const compileResult = ts.transpileModule(transformedCode, {
|
|
62
|
-
compilerOptions: this.program.getCompilerOptions(),
|
|
63
|
-
});
|
|
64
|
-
return compileResult.outputText;
|
|
19
|
+
this.configFile = configFile;
|
|
20
|
+
this.compiler = new TypicalCompiler({ cwd: process.cwd() });
|
|
65
21
|
}
|
|
66
22
|
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
* Returns either the transformed code string, or a retry signal with the failed type.
|
|
23
|
+
* Ensure the Go compiler is started and project is loaded.
|
|
24
|
+
* Uses lazy initialization - only starts on first transform.
|
|
70
25
|
*/
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const relativePath = path.relative(rootDir, fileName);
|
|
78
|
-
const intermediateFileName = relativePath.replace(/\.(tsx?)$/, ".typical.$1");
|
|
79
|
-
const intermediateFilePath = path.join(outDir, intermediateFileName);
|
|
80
|
-
const dir = path.dirname(intermediateFilePath);
|
|
81
|
-
if (!fs.existsSync(dir)) {
|
|
82
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
83
|
-
}
|
|
84
|
-
fs.writeFileSync(intermediateFilePath, code);
|
|
85
|
-
console.log(`TYPICAL: Wrote intermediate file: ${intermediateFilePath}`);
|
|
86
|
-
}
|
|
87
|
-
if (process.env.DEBUG) {
|
|
88
|
-
console.log("TYPICAL: Before typia transform (first 500 chars):", code.substring(0, 500));
|
|
89
|
-
}
|
|
90
|
-
// Create a new source file from the transformed code
|
|
91
|
-
const newSourceFile = this.ts.createSourceFile(fileName, code, this.ts.ScriptTarget.ES2020, true);
|
|
92
|
-
// Create a new program with the transformed source file so typia can resolve types.
|
|
93
|
-
// Pass oldProgram to reuse parsed/bound data from unchanged dependency files.
|
|
94
|
-
const compilerOptions = this.program.getCompilerOptions();
|
|
95
|
-
const originalSourceFiles = new Map();
|
|
96
|
-
for (const sf of this.program.getSourceFiles()) {
|
|
97
|
-
originalSourceFiles.set(sf.fileName, sf);
|
|
26
|
+
async ensureInitialized() {
|
|
27
|
+
if (!this.initPromise) {
|
|
28
|
+
this.initPromise = (async () => {
|
|
29
|
+
await this.compiler.start();
|
|
30
|
+
this.projectHandle = await this.compiler.loadProject(this.configFile);
|
|
31
|
+
})();
|
|
98
32
|
}
|
|
99
|
-
|
|
100
|
-
originalSourceFiles.set(fileName, newSourceFile);
|
|
101
|
-
const customHost = {
|
|
102
|
-
getSourceFile: (hostFileName, languageVersion) => {
|
|
103
|
-
if (originalSourceFiles.has(hostFileName)) {
|
|
104
|
-
return originalSourceFiles.get(hostFileName);
|
|
105
|
-
}
|
|
106
|
-
return this.ts.createSourceFile(hostFileName, this.ts.sys.readFile(hostFileName) || "", languageVersion, true);
|
|
107
|
-
},
|
|
108
|
-
getDefaultLibFileName: (opts) => this.ts.getDefaultLibFilePath(opts),
|
|
109
|
-
writeFile: () => { },
|
|
110
|
-
getCurrentDirectory: () => this.ts.sys.getCurrentDirectory(),
|
|
111
|
-
getCanonicalFileName: (fn) => this.ts.sys.useCaseSensitiveFileNames ? fn : fn.toLowerCase(),
|
|
112
|
-
useCaseSensitiveFileNames: () => this.ts.sys.useCaseSensitiveFileNames,
|
|
113
|
-
getNewLine: () => this.ts.sys.newLine,
|
|
114
|
-
fileExists: (fn) => originalSourceFiles.has(fn) || this.ts.sys.fileExists(fn),
|
|
115
|
-
readFile: (fn) => this.ts.sys.readFile(fn),
|
|
116
|
-
};
|
|
117
|
-
// Create new program, passing oldProgram to reuse dependency context
|
|
118
|
-
const newProgram = this.ts.createProgram(Array.from(originalSourceFiles.keys()), compilerOptions, customHost, this.program // Reuse old program's structure for unchanged files
|
|
119
|
-
);
|
|
120
|
-
// Get the bound source file from the new program (has proper symbol tables)
|
|
121
|
-
const boundSourceFile = newProgram.getSourceFile(fileName);
|
|
122
|
-
if (!boundSourceFile) {
|
|
123
|
-
throw new Error(`Failed to get bound source file: ${fileName}`);
|
|
124
|
-
}
|
|
125
|
-
// Collect typia diagnostics to detect transformation failures
|
|
126
|
-
const diagnostics = [];
|
|
127
|
-
// Create typia transformer with the new program
|
|
128
|
-
const typiaTransformerFactory = typiaTransform(newProgram, {}, {
|
|
129
|
-
addDiagnostic(diag) {
|
|
130
|
-
diagnostics.push(diag);
|
|
131
|
-
if (process.env.DEBUG) {
|
|
132
|
-
console.warn("Typia diagnostic:", diag);
|
|
133
|
-
}
|
|
134
|
-
return diagnostics.length - 1;
|
|
135
|
-
},
|
|
136
|
-
});
|
|
137
|
-
// Run typia's transformer in its own ts.transform() call
|
|
138
|
-
const typiaResult = this.ts.transform(boundSourceFile, [typiaTransformerFactory]);
|
|
139
|
-
let typiaTransformed = typiaResult.transformed[0];
|
|
140
|
-
typiaResult.dispose();
|
|
141
|
-
if (process.env.DEBUG) {
|
|
142
|
-
const afterTypia = printer.printFile(typiaTransformed);
|
|
143
|
-
console.log("TYPICAL: After typia transform (first 500 chars):", afterTypia.substring(0, 500));
|
|
144
|
-
}
|
|
145
|
-
// Check for typia errors via diagnostics
|
|
146
|
-
const errors = diagnostics.filter(d => d.category === this.ts.DiagnosticCategory.Error);
|
|
147
|
-
if (errors.length > 0) {
|
|
148
|
-
// Check if any error is due to Window/globalThis intersection (DOM types)
|
|
149
|
-
for (const d of errors) {
|
|
150
|
-
const fullMessage = typeof d.messageText === 'string' ? d.messageText : d.messageText.messageText;
|
|
151
|
-
if (fullMessage.includes('Window & typeof globalThis') || fullMessage.includes('typeof globalThis')) {
|
|
152
|
-
// Find the validator that failed - look for the type in the error
|
|
153
|
-
// Error format: "Code: typia.createAssert<{ value: number; table: Table; }>()"
|
|
154
|
-
if (d.file && d.start !== undefined && d.length !== undefined) {
|
|
155
|
-
const sourceSnippet = d.file.text.substring(d.start, d.start + d.length);
|
|
156
|
-
// Extract the type from typia.createAssert<TYPE>()
|
|
157
|
-
const typeMatch = sourceSnippet.match(/typia\.\w+<([^>]+(?:<[^>]*>)*)>\(\)/);
|
|
158
|
-
if (typeMatch) {
|
|
159
|
-
const failedType = typeMatch[1].trim();
|
|
160
|
-
console.warn(`TYPICAL: Skipping validation for type due to Window/globalThis (typia cannot process DOM types): ${failedType.substring(0, 100)}...`);
|
|
161
|
-
// Add to ignored types and signal retry needed
|
|
162
|
-
return { retry: true, failedType };
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
// No retryable errors, throw the original error
|
|
168
|
-
const errorMessages = errors.map(d => {
|
|
169
|
-
const fullMessage = typeof d.messageText === 'string' ? d.messageText : d.messageText.messageText;
|
|
170
|
-
if (d.file && d.start !== undefined && d.length !== undefined) {
|
|
171
|
-
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
172
|
-
// Extract the actual source code that caused the error
|
|
173
|
-
const sourceSnippet = d.file.text.substring(d.start, d.start + d.length);
|
|
174
|
-
// Truncate long snippets
|
|
175
|
-
const snippet = sourceSnippet.length > 100
|
|
176
|
-
? sourceSnippet.substring(0, 100) + '...'
|
|
177
|
-
: sourceSnippet;
|
|
178
|
-
// Format the error message - extract type issues from typia's verbose output
|
|
179
|
-
const formattedIssues = this.formatTypiaError(fullMessage);
|
|
180
|
-
return `${d.file.fileName}:${line + 1}:${character + 1}\n` +
|
|
181
|
-
` Code: ${snippet}\n` +
|
|
182
|
-
formattedIssues;
|
|
183
|
-
}
|
|
184
|
-
return this.formatTypiaError(fullMessage);
|
|
185
|
-
});
|
|
186
|
-
throw new Error(`TYPICAL: Typia transformation failed:\n\n${errorMessages.join('\n\n')}`);
|
|
187
|
-
}
|
|
188
|
-
// Hoist RegExp constructors to top-level constants for performance
|
|
189
|
-
if (this.config.hoistRegex !== false) {
|
|
190
|
-
// Need to run hoisting in a transform context
|
|
191
|
-
const hoistResult = this.ts.transform(typiaTransformed, [
|
|
192
|
-
(context) => (sf) => hoistRegexConstructors(sf, this.ts, context.factory)
|
|
193
|
-
]);
|
|
194
|
-
typiaTransformed = hoistResult.transformed[0];
|
|
195
|
-
hoistResult.dispose();
|
|
196
|
-
}
|
|
197
|
-
const finalCode = printer.printFile(typiaTransformed);
|
|
198
|
-
// Also check for untransformed typia calls as a fallback
|
|
199
|
-
// (in case typia silently fails without reporting a diagnostic)
|
|
200
|
-
const untransformedCalls = this.findUntransformedTypiaCalls(finalCode);
|
|
201
|
-
if (untransformedCalls.length > 0) {
|
|
202
|
-
const failedTypes = untransformedCalls.map(c => c.type).filter((v, i, a) => a.indexOf(v) === i);
|
|
203
|
-
throw new Error(`TYPICAL: Failed to transform the following types (typia cannot process them):\n` +
|
|
204
|
-
failedTypes.map(t => ` - ${t}`).join('\n') +
|
|
205
|
-
`\n\nTo skip validation for these types, add to ignoreTypes in typical.json:\n` +
|
|
206
|
-
` "ignoreTypes": [${failedTypes.map(t => `"${t}"`).join(', ')}]` +
|
|
207
|
-
`\n\nFile: ${fileName}`);
|
|
208
|
-
}
|
|
209
|
-
return finalCode;
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Get a transformer that only applies typical's transformations (no typia).
|
|
213
|
-
* @param skippedTypes Set of type strings to skip validation for (used for retry after typia errors)
|
|
214
|
-
*/
|
|
215
|
-
getTypicalOnlyTransformer(skippedTypes = new Set()) {
|
|
216
|
-
return (context) => {
|
|
217
|
-
const factory = context.factory;
|
|
218
|
-
const typeChecker = this.program.getTypeChecker();
|
|
219
|
-
const transformContext = {
|
|
220
|
-
ts: this.ts,
|
|
221
|
-
factory,
|
|
222
|
-
context,
|
|
223
|
-
};
|
|
224
|
-
return (sourceFile) => {
|
|
225
|
-
// Check if this file should be transformed based on include/exclude patterns
|
|
226
|
-
if (!this.shouldTransformFile(sourceFile.fileName)) {
|
|
227
|
-
return sourceFile;
|
|
228
|
-
}
|
|
229
|
-
if (process.env.DEBUG) {
|
|
230
|
-
console.log("TYPICAL: processing ", sourceFile.fileName);
|
|
231
|
-
}
|
|
232
|
-
return this.transformSourceFile(sourceFile, transformContext, typeChecker, skippedTypes);
|
|
233
|
-
};
|
|
234
|
-
};
|
|
33
|
+
await this.initPromise;
|
|
235
34
|
}
|
|
236
35
|
/**
|
|
237
|
-
*
|
|
238
|
-
* This is used by the TSC plugin where we need a single transformer factory.
|
|
36
|
+
* Transform a TypeScript file by adding runtime validation.
|
|
239
37
|
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
|
|
243
|
-
getTransformer(withTypia) {
|
|
244
|
-
return (context) => {
|
|
245
|
-
const factory = context.factory;
|
|
246
|
-
const typeChecker = this.program.getTypeChecker();
|
|
247
|
-
const transformContext = {
|
|
248
|
-
ts: this.ts,
|
|
249
|
-
factory,
|
|
250
|
-
context,
|
|
251
|
-
};
|
|
252
|
-
return (sourceFile) => {
|
|
253
|
-
// Check if this file should be transformed based on include/exclude patterns
|
|
254
|
-
if (!this.shouldTransformFile(sourceFile.fileName)) {
|
|
255
|
-
return sourceFile;
|
|
256
|
-
}
|
|
257
|
-
if (process.env.DEBUG) {
|
|
258
|
-
console.log("TYPICAL: processing ", sourceFile.fileName);
|
|
259
|
-
}
|
|
260
|
-
// Apply typical's transformations
|
|
261
|
-
let transformedSourceFile = this.transformSourceFile(sourceFile, transformContext, typeChecker);
|
|
262
|
-
if (!withTypia) {
|
|
263
|
-
return transformedSourceFile;
|
|
264
|
-
}
|
|
265
|
-
// Print the transformed code to check for typia calls
|
|
266
|
-
const printer = this.ts.createPrinter();
|
|
267
|
-
const transformedCode = printer.printFile(transformedSourceFile);
|
|
268
|
-
if (!transformedCode.includes("typia.")) {
|
|
269
|
-
return transformedSourceFile;
|
|
270
|
-
}
|
|
271
|
-
// Write intermediate file if debug option is enabled
|
|
272
|
-
if (this.config.debug?.writeIntermediateFiles) {
|
|
273
|
-
const compilerOptions = this.program.getCompilerOptions();
|
|
274
|
-
const outDir = compilerOptions.outDir || ".";
|
|
275
|
-
const rootDir = compilerOptions.rootDir || ".";
|
|
276
|
-
const relativePath = path.relative(rootDir, sourceFile.fileName);
|
|
277
|
-
const intermediateFileName = relativePath.replace(/\.(tsx?)$/, ".typical.$1");
|
|
278
|
-
const intermediateFilePath = path.join(outDir, intermediateFileName);
|
|
279
|
-
const dir = path.dirname(intermediateFilePath);
|
|
280
|
-
if (!fs.existsSync(dir)) {
|
|
281
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
282
|
-
}
|
|
283
|
-
fs.writeFileSync(intermediateFilePath, transformedCode);
|
|
284
|
-
console.log(`TYPICAL: Wrote intermediate file: ${intermediateFilePath}`);
|
|
285
|
-
}
|
|
286
|
-
if (process.env.DEBUG) {
|
|
287
|
-
console.log("TYPICAL: Before typia transform (first 500 chars):", transformedCode.substring(0, 500));
|
|
288
|
-
}
|
|
289
|
-
// Create a new source file from the transformed code
|
|
290
|
-
const newSourceFile = this.ts.createSourceFile(sourceFile.fileName, transformedCode, sourceFile.languageVersion, true);
|
|
291
|
-
// Create a new program with the transformed source file so typia can resolve types.
|
|
292
|
-
// Pass oldProgram to reuse parsed/bound data from unchanged dependency files.
|
|
293
|
-
const compilerOptions = this.program.getCompilerOptions();
|
|
294
|
-
const originalSourceFiles = new Map();
|
|
295
|
-
for (const sf of this.program.getSourceFiles()) {
|
|
296
|
-
originalSourceFiles.set(sf.fileName, sf);
|
|
297
|
-
}
|
|
298
|
-
// Replace the original source file with our transformed one
|
|
299
|
-
originalSourceFiles.set(sourceFile.fileName, newSourceFile);
|
|
300
|
-
const customHost = {
|
|
301
|
-
getSourceFile: (hostFileName, languageVersion) => {
|
|
302
|
-
if (originalSourceFiles.has(hostFileName)) {
|
|
303
|
-
return originalSourceFiles.get(hostFileName);
|
|
304
|
-
}
|
|
305
|
-
return this.ts.createSourceFile(hostFileName, this.ts.sys.readFile(hostFileName) || "", languageVersion, true);
|
|
306
|
-
},
|
|
307
|
-
getDefaultLibFileName: (opts) => this.ts.getDefaultLibFilePath(opts),
|
|
308
|
-
writeFile: () => { },
|
|
309
|
-
getCurrentDirectory: () => this.ts.sys.getCurrentDirectory(),
|
|
310
|
-
getCanonicalFileName: (fn) => this.ts.sys.useCaseSensitiveFileNames ? fn : fn.toLowerCase(),
|
|
311
|
-
useCaseSensitiveFileNames: () => this.ts.sys.useCaseSensitiveFileNames,
|
|
312
|
-
getNewLine: () => this.ts.sys.newLine,
|
|
313
|
-
fileExists: (fn) => originalSourceFiles.has(fn) || this.ts.sys.fileExists(fn),
|
|
314
|
-
readFile: (fn) => this.ts.sys.readFile(fn),
|
|
315
|
-
};
|
|
316
|
-
// Create new program, passing oldProgram to reuse dependency context
|
|
317
|
-
const newProgram = this.ts.createProgram(Array.from(originalSourceFiles.keys()), compilerOptions, customHost, this.program // Reuse old program's structure for unchanged files
|
|
318
|
-
);
|
|
319
|
-
// Get the bound source file from the new program (has proper symbol tables)
|
|
320
|
-
const boundSourceFile = newProgram.getSourceFile(sourceFile.fileName);
|
|
321
|
-
if (!boundSourceFile) {
|
|
322
|
-
throw new Error(`Failed to get bound source file: ${sourceFile.fileName}`);
|
|
323
|
-
}
|
|
324
|
-
// Collect typia diagnostics to detect transformation failures
|
|
325
|
-
const diagnostics = [];
|
|
326
|
-
// Create typia transformer with the new program
|
|
327
|
-
const typiaTransformerFactory = typiaTransform(newProgram, {}, {
|
|
328
|
-
addDiagnostic(diag) {
|
|
329
|
-
diagnostics.push(diag);
|
|
330
|
-
if (process.env.DEBUG) {
|
|
331
|
-
console.warn("Typia diagnostic:", diag);
|
|
332
|
-
}
|
|
333
|
-
return diagnostics.length - 1;
|
|
334
|
-
},
|
|
335
|
-
});
|
|
336
|
-
// Apply typia's transformer to the bound source file
|
|
337
|
-
const typiaNodeTransformer = typiaTransformerFactory(context);
|
|
338
|
-
transformedSourceFile = typiaNodeTransformer(boundSourceFile);
|
|
339
|
-
if (process.env.DEBUG) {
|
|
340
|
-
const afterTypia = printer.printFile(transformedSourceFile);
|
|
341
|
-
console.log("TYPICAL: After typia transform (first 500 chars):", afterTypia.substring(0, 500));
|
|
342
|
-
}
|
|
343
|
-
// Check for typia errors via diagnostics
|
|
344
|
-
const errors = diagnostics.filter(d => d.category === this.ts.DiagnosticCategory.Error);
|
|
345
|
-
if (errors.length > 0) {
|
|
346
|
-
const errorMessages = errors.map(d => {
|
|
347
|
-
const fullMessage = typeof d.messageText === 'string' ? d.messageText : d.messageText.messageText;
|
|
348
|
-
if (d.file && d.start !== undefined && d.length !== undefined) {
|
|
349
|
-
const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
|
|
350
|
-
// Extract the actual source code that caused the error
|
|
351
|
-
const sourceSnippet = d.file.text.substring(d.start, d.start + d.length);
|
|
352
|
-
// Truncate long snippets
|
|
353
|
-
const snippet = sourceSnippet.length > 100
|
|
354
|
-
? sourceSnippet.substring(0, 100) + '...'
|
|
355
|
-
: sourceSnippet;
|
|
356
|
-
// Format the error message - extract type issues from typia's verbose output
|
|
357
|
-
const formattedIssues = this.formatTypiaError(fullMessage);
|
|
358
|
-
return `${d.file.fileName}:${line + 1}:${character + 1}\n` +
|
|
359
|
-
` Code: ${snippet}\n` +
|
|
360
|
-
formattedIssues;
|
|
361
|
-
}
|
|
362
|
-
return this.formatTypiaError(fullMessage);
|
|
363
|
-
});
|
|
364
|
-
throw new Error(`TYPICAL: Typia transformation failed:\n\n${errorMessages.join('\n\n')}`);
|
|
365
|
-
}
|
|
366
|
-
// Hoist RegExp constructors to top-level constants for performance
|
|
367
|
-
if (this.config.hoistRegex !== false) {
|
|
368
|
-
transformedSourceFile = hoistRegexConstructors(transformedSourceFile, this.ts, factory);
|
|
369
|
-
}
|
|
370
|
-
// Also check for untransformed typia calls as a fallback
|
|
371
|
-
const finalCode = printer.printFile(transformedSourceFile);
|
|
372
|
-
const untransformedCalls = this.findUntransformedTypiaCalls(finalCode);
|
|
373
|
-
if (untransformedCalls.length > 0) {
|
|
374
|
-
const failedTypes = untransformedCalls.map(c => c.type).filter((v, i, a) => a.indexOf(v) === i);
|
|
375
|
-
throw new Error(`TYPICAL: Failed to transform the following types (typia cannot process them):\n` +
|
|
376
|
-
failedTypes.map(t => ` - ${t}`).join('\n') +
|
|
377
|
-
`\n\nTo skip validation for these types, add to ignoreTypes in typical.json:\n` +
|
|
378
|
-
` "ignoreTypes": [${failedTypes.map(t => `"${t}"`).join(', ')}]` +
|
|
379
|
-
`\n\nFile: ${sourceFile.fileName}`);
|
|
380
|
-
}
|
|
381
|
-
return transformedSourceFile;
|
|
382
|
-
};
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
/**
|
|
386
|
-
* Transform a single source file with TypeScript AST
|
|
387
|
-
*/
|
|
388
|
-
transformSourceFile(sourceFile, ctx, typeChecker, skippedTypes = new Set()) {
|
|
389
|
-
const { ts } = ctx;
|
|
390
|
-
// Helper to check if a type should be skipped (failed in typia on previous attempt)
|
|
391
|
-
const shouldSkipType = (typeText) => {
|
|
392
|
-
if (skippedTypes.size === 0)
|
|
393
|
-
return false;
|
|
394
|
-
// Normalize: remove all whitespace and semicolons for comparison
|
|
395
|
-
const normalize = (s) => s.replace(/[\s;]+/g, '').toLowerCase();
|
|
396
|
-
const normalized = normalize(typeText);
|
|
397
|
-
for (const skipped of skippedTypes) {
|
|
398
|
-
const skippedNormalized = normalize(skipped);
|
|
399
|
-
if (normalized === skippedNormalized || normalized.includes(skippedNormalized) || skippedNormalized.includes(normalized)) {
|
|
400
|
-
if (process.env.DEBUG) {
|
|
401
|
-
console.log(`TYPICAL: Matched skipped type: "${typeText.substring(0, 50)}..." matches "${skipped.substring(0, 50)}..."`);
|
|
402
|
-
}
|
|
403
|
-
return true;
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
return false;
|
|
407
|
-
};
|
|
408
|
-
if (!sourceFile.fileName.includes('transformer.test.ts')) {
|
|
409
|
-
// Check if this file has already been transformed by us
|
|
410
|
-
const sourceText = sourceFile.getFullText();
|
|
411
|
-
if (sourceText.includes('__typical_' + 'assert_') || sourceText.includes('__typical_' + 'stringify_') || sourceText.includes('__typical_' + 'parse_')) {
|
|
412
|
-
throw new Error(`File ${sourceFile.fileName} has already been transformed by Typical! Double transformation detected.`);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
// Reset caches for each file
|
|
416
|
-
this.typeValidators.clear();
|
|
417
|
-
this.typeStringifiers.clear();
|
|
418
|
-
this.typeParsers.clear();
|
|
419
|
-
let needsTypiaImport = false;
|
|
420
|
-
const visit = (node) => {
|
|
421
|
-
// Transform JSON calls first (before they get wrapped in functions)
|
|
422
|
-
if (ts.isCallExpression(node) &&
|
|
423
|
-
ts.isPropertyAccessExpression(node.expression)) {
|
|
424
|
-
const propertyAccess = node.expression;
|
|
425
|
-
if (ts.isIdentifier(propertyAccess.expression) &&
|
|
426
|
-
propertyAccess.expression.text === "JSON") {
|
|
427
|
-
needsTypiaImport = true;
|
|
428
|
-
if (propertyAccess.name.text === "stringify") {
|
|
429
|
-
// For stringify, we need to infer the type from the argument
|
|
430
|
-
// First check if the argument type is 'any' - if so, skip transformation
|
|
431
|
-
if (node.arguments.length > 0) {
|
|
432
|
-
const arg = node.arguments[0];
|
|
433
|
-
const argType = typeChecker.getTypeAtLocation(arg);
|
|
434
|
-
if (this.isAnyOrUnknownTypeFlags(argType)) {
|
|
435
|
-
return node; // Don't transform JSON.stringify for any/unknown types
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
if (this.config.reusableValidators) {
|
|
439
|
-
// Infer type from argument
|
|
440
|
-
const arg = node.arguments[0];
|
|
441
|
-
const { typeText, typeNode } = this.inferStringifyType(arg, typeChecker, ctx);
|
|
442
|
-
const stringifierName = this.getOrCreateStringifier(typeText, typeNode);
|
|
443
|
-
return ctx.factory.createCallExpression(ctx.factory.createIdentifier(stringifierName), undefined, node.arguments);
|
|
444
|
-
}
|
|
445
|
-
else {
|
|
446
|
-
// Use inline typia.json.stringify
|
|
447
|
-
return ctx.factory.updateCallExpression(node, ctx.factory.createPropertyAccessExpression(ctx.factory.createPropertyAccessExpression(ctx.factory.createIdentifier("typia"), "json"), "stringify"), node.typeArguments, node.arguments);
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
else if (propertyAccess.name.text === "parse") {
|
|
451
|
-
// For JSON.parse, we need to infer the expected type from context
|
|
452
|
-
// Check if this is part of a variable declaration or type assertion
|
|
453
|
-
let targetType;
|
|
454
|
-
// Look for type annotations in parent nodes
|
|
455
|
-
let parent = node.parent;
|
|
456
|
-
while (parent) {
|
|
457
|
-
if (ts.isVariableDeclaration(parent) && parent.type) {
|
|
458
|
-
targetType = parent.type;
|
|
459
|
-
break;
|
|
460
|
-
}
|
|
461
|
-
else if (ts.isAsExpression(parent)) {
|
|
462
|
-
targetType = parent.type;
|
|
463
|
-
break;
|
|
464
|
-
}
|
|
465
|
-
else if (ts.isReturnStatement(parent)) {
|
|
466
|
-
// Look for function return type
|
|
467
|
-
let funcParent = parent.parent;
|
|
468
|
-
while (funcParent) {
|
|
469
|
-
if ((ts.isFunctionDeclaration(funcParent) ||
|
|
470
|
-
ts.isArrowFunction(funcParent) ||
|
|
471
|
-
ts.isMethodDeclaration(funcParent)) &&
|
|
472
|
-
funcParent.type) {
|
|
473
|
-
targetType = funcParent.type;
|
|
474
|
-
break;
|
|
475
|
-
}
|
|
476
|
-
funcParent = funcParent.parent;
|
|
477
|
-
}
|
|
478
|
-
break;
|
|
479
|
-
}
|
|
480
|
-
else if (ts.isArrowFunction(parent) && parent.type) {
|
|
481
|
-
// Arrow function with expression body (not block)
|
|
482
|
-
// e.g., (s: string): User => JSON.parse(s)
|
|
483
|
-
targetType = parent.type;
|
|
484
|
-
break;
|
|
485
|
-
}
|
|
486
|
-
parent = parent.parent;
|
|
487
|
-
}
|
|
488
|
-
if (targetType && this.isAnyOrUnknownType(targetType)) {
|
|
489
|
-
// Don't transform JSON.parse for any/unknown types
|
|
490
|
-
return node;
|
|
491
|
-
}
|
|
492
|
-
// If we can't determine the target type and there's no explicit type argument,
|
|
493
|
-
// don't transform - we can't validate against an unknown type
|
|
494
|
-
if (!targetType && !node.typeArguments) {
|
|
495
|
-
return node;
|
|
496
|
-
}
|
|
497
|
-
if (this.config.reusableValidators && targetType) {
|
|
498
|
-
// Use reusable parser - use typeNode text to preserve local aliases
|
|
499
|
-
const typeText = this.getTypeKey(targetType, typeChecker);
|
|
500
|
-
const parserName = this.getOrCreateParser(typeText, targetType);
|
|
501
|
-
const newCall = ctx.factory.createCallExpression(ctx.factory.createIdentifier(parserName), undefined, node.arguments);
|
|
502
|
-
return newCall;
|
|
503
|
-
}
|
|
504
|
-
else {
|
|
505
|
-
// Use inline typia.json.assertParse
|
|
506
|
-
const typeArguments = targetType
|
|
507
|
-
? [targetType]
|
|
508
|
-
: node.typeArguments;
|
|
509
|
-
return ctx.factory.updateCallExpression(node, ctx.factory.createPropertyAccessExpression(ctx.factory.createPropertyAccessExpression(ctx.factory.createIdentifier("typia"), "json"), "assertParse"), typeArguments, node.arguments);
|
|
510
|
-
}
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
// Transform type assertions (as expressions) when validateCasts is enabled
|
|
515
|
-
// e.g., `obj as User` becomes `__typical_assert_N(obj)`
|
|
516
|
-
if (this.config.validateCasts && ts.isAsExpression(node)) {
|
|
517
|
-
const targetType = node.type;
|
|
518
|
-
// Skip 'as any' and 'as unknown' casts - these are intentional escapes
|
|
519
|
-
if (this.isAnyOrUnknownType(targetType)) {
|
|
520
|
-
return ctx.ts.visitEachChild(node, visit, ctx.context);
|
|
521
|
-
}
|
|
522
|
-
// Skip primitive types - no runtime validation needed
|
|
523
|
-
if (targetType.kind === ts.SyntaxKind.StringKeyword ||
|
|
524
|
-
targetType.kind === ts.SyntaxKind.NumberKeyword ||
|
|
525
|
-
targetType.kind === ts.SyntaxKind.BooleanKeyword) {
|
|
526
|
-
return ctx.ts.visitEachChild(node, visit, ctx.context);
|
|
527
|
-
}
|
|
528
|
-
// Skip types matching ignoreTypes patterns (including classes extending DOM types)
|
|
529
|
-
const typeText = this.getTypeKey(targetType, typeChecker);
|
|
530
|
-
const targetTypeObj = typeChecker.getTypeFromTypeNode(targetType);
|
|
531
|
-
if (this.isIgnoredType(typeText, typeChecker, targetTypeObj)) {
|
|
532
|
-
if (process.env.DEBUG) {
|
|
533
|
-
console.log(`TYPICAL: Skipping ignored type for cast: ${typeText}`);
|
|
534
|
-
}
|
|
535
|
-
return ctx.ts.visitEachChild(node, visit, ctx.context);
|
|
536
|
-
}
|
|
537
|
-
// Skip types that failed in typia (retry mechanism)
|
|
538
|
-
if (shouldSkipType(typeText)) {
|
|
539
|
-
if (process.env.DEBUG) {
|
|
540
|
-
console.log(`TYPICAL: Skipping previously failed type for cast: ${typeText}`);
|
|
541
|
-
}
|
|
542
|
-
return ctx.ts.visitEachChild(node, visit, ctx.context);
|
|
543
|
-
}
|
|
544
|
-
needsTypiaImport = true;
|
|
545
|
-
// Visit the expression first to transform any nested casts
|
|
546
|
-
const visitedExpression = ctx.ts.visitNode(node.expression, visit);
|
|
547
|
-
if (this.config.reusableValidators) {
|
|
548
|
-
// Use typeNode text to preserve local aliases
|
|
549
|
-
const typeText = this.getTypeKey(targetType, typeChecker);
|
|
550
|
-
const validatorName = this.getOrCreateValidator(typeText, targetType);
|
|
551
|
-
// Replace `expr as Type` with `__typical_assert_N(expr)`
|
|
552
|
-
return ctx.factory.createCallExpression(ctx.factory.createIdentifier(validatorName), undefined, [visitedExpression]);
|
|
553
|
-
}
|
|
554
|
-
else {
|
|
555
|
-
// Inline validator: typia.assert<Type>(expr)
|
|
556
|
-
return ctx.factory.createCallExpression(ctx.factory.createPropertyAccessExpression(ctx.factory.createIdentifier("typia"), "assert"), [targetType], [visitedExpression]);
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
// Transform function declarations
|
|
560
|
-
if (ts.isFunctionDeclaration(node)) {
|
|
561
|
-
needsTypiaImport = true;
|
|
562
|
-
return transformFunction(node);
|
|
563
|
-
}
|
|
564
|
-
// Transform arrow functions
|
|
565
|
-
if (ts.isArrowFunction(node)) {
|
|
566
|
-
needsTypiaImport = true;
|
|
567
|
-
return transformFunction(node);
|
|
568
|
-
}
|
|
569
|
-
// Transform method declarations
|
|
570
|
-
if (ts.isMethodDeclaration(node)) {
|
|
571
|
-
needsTypiaImport = true;
|
|
572
|
-
return transformFunction(node);
|
|
573
|
-
}
|
|
574
|
-
return ctx.ts.visitEachChild(node, visit, ctx.context);
|
|
575
|
-
};
|
|
576
|
-
const transformFunction = (func) => {
|
|
577
|
-
const body = func.body;
|
|
578
|
-
// For arrow functions with expression bodies (not blocks),
|
|
579
|
-
// still visit the expression to transform JSON calls etc.
|
|
580
|
-
// Also handle Promise return types with .then() validation
|
|
581
|
-
if (body && !ts.isBlock(body) && ts.isArrowFunction(func)) {
|
|
582
|
-
let visitedBody = ctx.ts.visitNode(body, visit);
|
|
583
|
-
// Check if this is a non-async function with Promise return type
|
|
584
|
-
let returnType = func.type;
|
|
585
|
-
let returnTypeForString;
|
|
586
|
-
if (returnType) {
|
|
587
|
-
returnTypeForString = typeChecker.getTypeFromTypeNode(returnType);
|
|
588
|
-
}
|
|
589
|
-
else {
|
|
590
|
-
// Try to infer the return type from the signature
|
|
591
|
-
try {
|
|
592
|
-
const signature = typeChecker.getSignatureFromDeclaration(func);
|
|
593
|
-
if (signature) {
|
|
594
|
-
const inferredReturnType = typeChecker.getReturnTypeOfSignature(signature);
|
|
595
|
-
returnType = typeChecker.typeToTypeNode(inferredReturnType, func, TYPE_NODE_FLAGS);
|
|
596
|
-
returnTypeForString = inferredReturnType;
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
catch {
|
|
600
|
-
// Skip inference
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
// Check for Promise<T> return type
|
|
604
|
-
if (returnType && returnTypeForString) {
|
|
605
|
-
const promiseSymbol = returnTypeForString.getSymbol();
|
|
606
|
-
if (promiseSymbol && promiseSymbol.getName() === "Promise") {
|
|
607
|
-
const typeArgs = returnTypeForString.typeArguments;
|
|
608
|
-
if (typeArgs && typeArgs.length > 0) {
|
|
609
|
-
const innerType = typeArgs[0];
|
|
610
|
-
let innerTypeNode;
|
|
611
|
-
if (ts.isTypeReferenceNode(returnType) && returnType.typeArguments && returnType.typeArguments.length > 0) {
|
|
612
|
-
innerTypeNode = returnType.typeArguments[0];
|
|
613
|
-
}
|
|
614
|
-
else {
|
|
615
|
-
innerTypeNode = typeChecker.typeToTypeNode(innerType, func, TYPE_NODE_FLAGS);
|
|
616
|
-
}
|
|
617
|
-
// Only add validation if validateFunctions is enabled
|
|
618
|
-
if (this.config.validateFunctions !== false && innerTypeNode && !this.isAnyOrUnknownType(innerTypeNode)) {
|
|
619
|
-
const innerTypeText = this.getTypeKey(innerTypeNode, typeChecker, innerType);
|
|
620
|
-
if (!this.isIgnoredType(innerTypeText, typeChecker, innerType) && !shouldSkipType(innerTypeText)) {
|
|
621
|
-
// Wrap expression with .then(validator)
|
|
622
|
-
const validatorName = this.config.reusableValidators
|
|
623
|
-
? this.getOrCreateValidator(innerTypeText, innerTypeNode)
|
|
624
|
-
: null;
|
|
625
|
-
if (validatorName) {
|
|
626
|
-
needsTypiaImport = true;
|
|
627
|
-
visitedBody = ctx.factory.createCallExpression(ctx.factory.createPropertyAccessExpression(visitedBody, ctx.factory.createIdentifier("then")), undefined, [ctx.factory.createIdentifier(validatorName)]);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
}
|
|
634
|
-
if (visitedBody !== body) {
|
|
635
|
-
return ctx.factory.updateArrowFunction(func, func.modifiers, func.typeParameters, func.parameters, func.type, func.equalsGreaterThanToken, visitedBody);
|
|
636
|
-
}
|
|
637
|
-
return func;
|
|
638
|
-
}
|
|
639
|
-
if (!body || !ts.isBlock(body))
|
|
640
|
-
return func;
|
|
641
|
-
// Track validated variables (params and consts with type annotations)
|
|
642
|
-
const validatedVariables = new Map();
|
|
643
|
-
// Add parameter validation (only if validateFunctions is enabled)
|
|
644
|
-
const validationStatements = [];
|
|
645
|
-
// Skip parameter validation if validateFunctions is disabled
|
|
646
|
-
const shouldValidateFunctions = this.config.validateFunctions !== false;
|
|
647
|
-
func.parameters.forEach((param) => {
|
|
648
|
-
if (shouldValidateFunctions && param.type) {
|
|
649
|
-
// Skip 'any' and 'unknown' types - no point validating them
|
|
650
|
-
if (this.isAnyOrUnknownType(param.type)) {
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
// Skip types matching ignoreTypes patterns (including classes extending DOM types)
|
|
654
|
-
const typeText = this.getTypeKey(param.type, typeChecker);
|
|
655
|
-
const paramType = typeChecker.getTypeFromTypeNode(param.type);
|
|
656
|
-
// Skip type parameters (generics) - can't be validated at runtime
|
|
657
|
-
if (this.isAnyOrUnknownTypeFlags(paramType)) {
|
|
658
|
-
if (process.env.DEBUG) {
|
|
659
|
-
console.log(`TYPICAL: Skipping type parameter/any for parameter: ${typeText}`);
|
|
660
|
-
}
|
|
661
|
-
return;
|
|
662
|
-
}
|
|
663
|
-
if (process.env.DEBUG) {
|
|
664
|
-
console.log(`TYPICAL: Processing parameter type: ${typeText}`);
|
|
665
|
-
}
|
|
666
|
-
if (this.isIgnoredType(typeText, typeChecker, paramType)) {
|
|
667
|
-
if (process.env.DEBUG) {
|
|
668
|
-
console.log(`TYPICAL: Skipping ignored type for parameter: ${typeText}`);
|
|
669
|
-
}
|
|
670
|
-
return;
|
|
671
|
-
}
|
|
672
|
-
// Skip types that failed in typia (retry mechanism)
|
|
673
|
-
if (shouldSkipType(typeText)) {
|
|
674
|
-
if (process.env.DEBUG) {
|
|
675
|
-
console.log(`TYPICAL: Skipping previously failed type for parameter: ${typeText}`);
|
|
676
|
-
}
|
|
677
|
-
return;
|
|
678
|
-
}
|
|
679
|
-
const paramName = ts.isIdentifier(param.name)
|
|
680
|
-
? param.name.text
|
|
681
|
-
: "param";
|
|
682
|
-
const paramIdentifier = ctx.factory.createIdentifier(paramName);
|
|
683
|
-
// Track this parameter as validated for flow analysis
|
|
684
|
-
validatedVariables.set(paramName, paramType);
|
|
685
|
-
if (this.config.reusableValidators) {
|
|
686
|
-
// Use reusable validators - use typeNode text to preserve local aliases
|
|
687
|
-
const validatorName = this.getOrCreateValidator(typeText, param.type);
|
|
688
|
-
const validatorCall = ctx.factory.createCallExpression(ctx.factory.createIdentifier(validatorName), undefined, [paramIdentifier]);
|
|
689
|
-
const assertCall = ctx.factory.createExpressionStatement(validatorCall);
|
|
690
|
-
validationStatements.push(assertCall);
|
|
691
|
-
}
|
|
692
|
-
else {
|
|
693
|
-
// Use inline typia.assert calls
|
|
694
|
-
const typiaIdentifier = ctx.factory.createIdentifier("typia");
|
|
695
|
-
const assertIdentifier = ctx.factory.createIdentifier("assert");
|
|
696
|
-
const propertyAccess = ctx.factory.createPropertyAccessExpression(typiaIdentifier, assertIdentifier);
|
|
697
|
-
const callExpression = ctx.factory.createCallExpression(propertyAccess, [param.type], [paramIdentifier]);
|
|
698
|
-
const assertCall = ctx.factory.createExpressionStatement(callExpression);
|
|
699
|
-
validationStatements.push(assertCall);
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
});
|
|
703
|
-
// First visit all child nodes (including JSON calls) before adding validation
|
|
704
|
-
const visitedBody = ctx.ts.visitNode(body, visit);
|
|
705
|
-
// Also track const declarations with type annotations as validated
|
|
706
|
-
// (the assignment will be validated, and const can't be reassigned)
|
|
707
|
-
const collectConstDeclarations = (node) => {
|
|
708
|
-
if (ts.isVariableStatement(node)) {
|
|
709
|
-
const isConst = (node.declarationList.flags & ts.NodeFlags.Const) !== 0;
|
|
710
|
-
if (isConst) {
|
|
711
|
-
for (const decl of node.declarationList.declarations) {
|
|
712
|
-
if (decl.type && ts.isIdentifier(decl.name)) {
|
|
713
|
-
// Skip any/unknown types
|
|
714
|
-
if (!this.isAnyOrUnknownType(decl.type)) {
|
|
715
|
-
const constType = typeChecker.getTypeFromTypeNode(decl.type);
|
|
716
|
-
validatedVariables.set(decl.name.text, constType);
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
ts.forEachChild(node, collectConstDeclarations);
|
|
723
|
-
};
|
|
724
|
-
collectConstDeclarations(visitedBody);
|
|
725
|
-
// Transform return statements - use explicit type or infer from type checker
|
|
726
|
-
let transformedStatements = visitedBody.statements;
|
|
727
|
-
let returnType = func.type;
|
|
728
|
-
// Check if this is an async function
|
|
729
|
-
const isAsync = func.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.AsyncKeyword);
|
|
730
|
-
// If no explicit return type, try to infer it from the type checker
|
|
731
|
-
let returnTypeForString;
|
|
732
|
-
if (!returnType) {
|
|
733
|
-
try {
|
|
734
|
-
const signature = typeChecker.getSignatureFromDeclaration(func);
|
|
735
|
-
if (signature) {
|
|
736
|
-
const inferredReturnType = typeChecker.getReturnTypeOfSignature(signature);
|
|
737
|
-
returnType = typeChecker.typeToTypeNode(inferredReturnType, func, TYPE_NODE_FLAGS);
|
|
738
|
-
returnTypeForString = inferredReturnType;
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
catch {
|
|
742
|
-
// Could not infer signature (e.g., untyped arrow function callback)
|
|
743
|
-
// Skip return type validation for this function
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
else {
|
|
747
|
-
// For explicit return types, get the Type from the TypeNode
|
|
748
|
-
returnTypeForString = typeChecker.getTypeFromTypeNode(returnType);
|
|
749
|
-
}
|
|
750
|
-
// Handle Promise return types
|
|
751
|
-
// Track whether this is a non-async function returning Promise (needs .then() wrapper)
|
|
752
|
-
let isNonAsyncPromiseReturn = false;
|
|
753
|
-
if (returnType && returnTypeForString) {
|
|
754
|
-
const promiseSymbol = returnTypeForString.getSymbol();
|
|
755
|
-
if (promiseSymbol && promiseSymbol.getName() === "Promise") {
|
|
756
|
-
// Unwrap Promise<T> to get T for validation
|
|
757
|
-
const typeArgs = returnTypeForString.typeArguments;
|
|
758
|
-
if (typeArgs && typeArgs.length > 0) {
|
|
759
|
-
returnTypeForString = typeArgs[0];
|
|
760
|
-
// Also update the TypeNode to match
|
|
761
|
-
if (ts.isTypeReferenceNode(returnType) && returnType.typeArguments && returnType.typeArguments.length > 0) {
|
|
762
|
-
returnType = returnType.typeArguments[0];
|
|
763
|
-
}
|
|
764
|
-
else {
|
|
765
|
-
// Create a new type node from the unwrapped type
|
|
766
|
-
returnType = typeChecker.typeToTypeNode(returnTypeForString, func, TYPE_NODE_FLAGS);
|
|
767
|
-
}
|
|
768
|
-
if (!isAsync) {
|
|
769
|
-
// For non-async functions returning Promise, we'll use .then(validator)
|
|
770
|
-
isNonAsyncPromiseReturn = true;
|
|
771
|
-
if (process.env.DEBUG) {
|
|
772
|
-
console.log(`TYPICAL: Non-async Promise return type - will use .then() for validation`);
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
}
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
// Skip 'any' and 'unknown' return types - no point validating them
|
|
779
|
-
// Also skip types matching ignoreTypes patterns (including classes extending DOM types)
|
|
780
|
-
// Also skip types containing type parameters or constructor types
|
|
781
|
-
const returnTypeText = returnType && returnTypeForString
|
|
782
|
-
? this.getTypeKey(returnType, typeChecker, returnTypeForString)
|
|
783
|
-
: null;
|
|
784
|
-
if (process.env.DEBUG && returnTypeText) {
|
|
785
|
-
console.log(`TYPICAL: Checking return type: "${returnTypeText}" (isAsync: ${isAsync})`);
|
|
786
|
-
}
|
|
787
|
-
// Skip if return type contains type parameters, constructor types, or is otherwise unvalidatable
|
|
788
|
-
const shouldSkipReturnType = returnTypeForString && this.containsUnvalidatableType(returnTypeForString);
|
|
789
|
-
if (shouldSkipReturnType && process.env.DEBUG) {
|
|
790
|
-
console.log(`TYPICAL: Skipping unvalidatable return type: ${returnTypeText}`);
|
|
791
|
-
}
|
|
792
|
-
const isIgnoredReturnType = returnTypeText && this.isIgnoredType(returnTypeText, typeChecker, returnTypeForString);
|
|
793
|
-
if (isIgnoredReturnType && process.env.DEBUG) {
|
|
794
|
-
console.log(`TYPICAL: Skipping ignored type for return: ${returnTypeText}`);
|
|
795
|
-
}
|
|
796
|
-
const isSkippedReturnType = returnTypeText && shouldSkipType(returnTypeText);
|
|
797
|
-
if (isSkippedReturnType && process.env.DEBUG) {
|
|
798
|
-
console.log(`TYPICAL: Skipping previously failed type for return: ${returnTypeText}`);
|
|
799
|
-
}
|
|
800
|
-
if (shouldValidateFunctions && returnType && returnTypeForString && !this.isAnyOrUnknownType(returnType) && !isIgnoredReturnType && !shouldSkipReturnType && !isSkippedReturnType) {
|
|
801
|
-
const returnTransformer = (node) => {
|
|
802
|
-
// Don't recurse into nested functions - they have their own return types
|
|
803
|
-
if (ts.isFunctionDeclaration(node) || ts.isArrowFunction(node) ||
|
|
804
|
-
ts.isFunctionExpression(node) || ts.isMethodDeclaration(node)) {
|
|
805
|
-
return node;
|
|
806
|
-
}
|
|
807
|
-
if (ts.isReturnStatement(node) && node.expression) {
|
|
808
|
-
// Skip return validation if the expression already contains a __typical _parse_* call
|
|
809
|
-
// since typia.assertParse already validates the parsed data
|
|
810
|
-
const containsTypicalParse = (n) => {
|
|
811
|
-
if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
|
|
812
|
-
const name = n.expression.text;
|
|
813
|
-
if (name.startsWith("__typical" + "_parse_")) {
|
|
814
|
-
return true;
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
return ts.forEachChild(n, containsTypicalParse) || false;
|
|
818
|
-
};
|
|
819
|
-
if (containsTypicalParse(node.expression)) {
|
|
820
|
-
return node; // Already validated by parse, skip return validation
|
|
821
|
-
}
|
|
822
|
-
// Flow analysis: Skip return validation if returning a validated variable
|
|
823
|
-
// (or property of one) that hasn't been tainted
|
|
824
|
-
const rootVar = this.getRootIdentifier(node.expression);
|
|
825
|
-
if (rootVar && validatedVariables.has(rootVar)) {
|
|
826
|
-
// Check if the variable has been tainted (mutated, passed to function, etc.)
|
|
827
|
-
if (!this.isTainted(rootVar, visitedBody)) {
|
|
828
|
-
// Return expression is rooted at a validated, untainted variable
|
|
829
|
-
// For direct returns (identifier) or property access, we can skip validation
|
|
830
|
-
if (ts.isIdentifier(node.expression) || ts.isPropertyAccessExpression(node.expression)) {
|
|
831
|
-
return node; // Skip validation - already validated and untainted
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
// For non-async functions returning Promise, use .then(validator)
|
|
836
|
-
// For async functions, await the expression before validating
|
|
837
|
-
if (isNonAsyncPromiseReturn) {
|
|
838
|
-
// return expr.then(validator)
|
|
839
|
-
const returnTypeText = this.getTypeKey(returnType, typeChecker, returnTypeForString);
|
|
840
|
-
const validatorName = this.config.reusableValidators
|
|
841
|
-
? this.getOrCreateValidator(returnTypeText, returnType)
|
|
842
|
-
: null;
|
|
843
|
-
// Create the validator reference (either reusable or inline)
|
|
844
|
-
let validatorExpr;
|
|
845
|
-
if (validatorName) {
|
|
846
|
-
validatorExpr = ctx.factory.createIdentifier(validatorName);
|
|
847
|
-
}
|
|
848
|
-
else {
|
|
849
|
-
// Inline: typia.assert<T>
|
|
850
|
-
validatorExpr = ctx.factory.createPropertyAccessExpression(ctx.factory.createIdentifier("typia"), ctx.factory.createIdentifier("assert"));
|
|
851
|
-
// Note: For inline mode, we'd need to create a wrapper arrow function
|
|
852
|
-
// to pass the type argument. For simplicity, just use the property access
|
|
853
|
-
// and let typia handle it (though this won't work without type args)
|
|
854
|
-
// In practice, reusableValidators should be true for this to work well
|
|
855
|
-
}
|
|
856
|
-
// expr.then(validator)
|
|
857
|
-
const thenCall = ctx.factory.createCallExpression(ctx.factory.createPropertyAccessExpression(node.expression, ctx.factory.createIdentifier("then")), undefined, [validatorExpr]);
|
|
858
|
-
return ctx.factory.updateReturnStatement(node, thenCall);
|
|
859
|
-
}
|
|
860
|
-
// For async functions, we need to await the expression before validating
|
|
861
|
-
// because the return expression might be a Promise
|
|
862
|
-
let expressionToValidate = node.expression;
|
|
863
|
-
if (isAsync) {
|
|
864
|
-
// Check if the expression is already an await expression
|
|
865
|
-
const isAlreadyAwaited = ts.isAwaitExpression(node.expression);
|
|
866
|
-
if (!isAlreadyAwaited) {
|
|
867
|
-
// Wrap in await: return validate(await expr)
|
|
868
|
-
expressionToValidate = ctx.factory.createAwaitExpression(node.expression);
|
|
869
|
-
}
|
|
870
|
-
}
|
|
871
|
-
if (this.config.reusableValidators) {
|
|
872
|
-
// Use reusable validators - use typeNode text to preserve local aliases
|
|
873
|
-
// Pass returnTypeForString for synthesized nodes (inferred return types)
|
|
874
|
-
const returnTypeText = this.getTypeKey(returnType, typeChecker, returnTypeForString);
|
|
875
|
-
const validatorName = this.getOrCreateValidator(returnTypeText, returnType);
|
|
876
|
-
const validatorCall = ctx.factory.createCallExpression(ctx.factory.createIdentifier(validatorName), undefined, [expressionToValidate]);
|
|
877
|
-
return ctx.factory.updateReturnStatement(node, validatorCall);
|
|
878
|
-
}
|
|
879
|
-
else {
|
|
880
|
-
// Use inline typia.assert calls
|
|
881
|
-
const typiaIdentifier = ctx.factory.createIdentifier("typia");
|
|
882
|
-
const assertIdentifier = ctx.factory.createIdentifier("assert");
|
|
883
|
-
const propertyAccess = ctx.factory.createPropertyAccessExpression(typiaIdentifier, assertIdentifier);
|
|
884
|
-
const callExpression = ctx.factory.createCallExpression(propertyAccess, [returnType], [expressionToValidate]);
|
|
885
|
-
return ctx.factory.updateReturnStatement(node, callExpression);
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
return ctx.ts.visitEachChild(node, returnTransformer, ctx.context);
|
|
889
|
-
};
|
|
890
|
-
transformedStatements = ctx.ts.visitNodes(visitedBody.statements, returnTransformer);
|
|
891
|
-
}
|
|
892
|
-
// Insert validation statements at the beginning
|
|
893
|
-
const newStatements = ctx.factory.createNodeArray([
|
|
894
|
-
...validationStatements,
|
|
895
|
-
...transformedStatements,
|
|
896
|
-
]);
|
|
897
|
-
const newBody = ctx.factory.updateBlock(visitedBody, newStatements);
|
|
898
|
-
if (ts.isFunctionDeclaration(func)) {
|
|
899
|
-
return ctx.factory.updateFunctionDeclaration(func, func.modifiers, func.asteriskToken, func.name, func.typeParameters, func.parameters, func.type, newBody);
|
|
900
|
-
}
|
|
901
|
-
else if (ts.isArrowFunction(func)) {
|
|
902
|
-
return ctx.factory.updateArrowFunction(func, func.modifiers, func.typeParameters, func.parameters, func.type, func.equalsGreaterThanToken, newBody);
|
|
903
|
-
}
|
|
904
|
-
else if (ts.isMethodDeclaration(func)) {
|
|
905
|
-
return ctx.factory.updateMethodDeclaration(func, func.modifiers, func.asteriskToken, func.name, func.questionToken, func.typeParameters, func.parameters, func.type, newBody);
|
|
906
|
-
}
|
|
907
|
-
return func;
|
|
908
|
-
};
|
|
909
|
-
let transformedSourceFile = ctx.ts.visitNode(sourceFile, visit);
|
|
910
|
-
// Add typia import and validator statements if needed
|
|
911
|
-
if (needsTypiaImport) {
|
|
912
|
-
transformedSourceFile = this.addTypiaImport(transformedSourceFile, ctx);
|
|
913
|
-
// Add validator statements after imports (only if using reusable validators)
|
|
914
|
-
if (this.config.reusableValidators) {
|
|
915
|
-
const validatorStmts = this.createValidatorStatements(ctx);
|
|
916
|
-
if (validatorStmts.length > 0) {
|
|
917
|
-
const importStatements = transformedSourceFile.statements.filter(ctx.ts.isImportDeclaration);
|
|
918
|
-
const otherStatements = transformedSourceFile.statements.filter((stmt) => !ctx.ts.isImportDeclaration(stmt));
|
|
919
|
-
const newStatements = ctx.factory.createNodeArray([
|
|
920
|
-
...importStatements,
|
|
921
|
-
...validatorStmts,
|
|
922
|
-
...otherStatements,
|
|
923
|
-
]);
|
|
924
|
-
transformedSourceFile = ctx.factory.updateSourceFile(transformedSourceFile, newStatements);
|
|
925
|
-
}
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
return transformedSourceFile;
|
|
929
|
-
}
|
|
930
|
-
shouldTransformFile(fileName) {
|
|
931
|
-
return shouldTransformFile(fileName, this.config);
|
|
932
|
-
}
|
|
933
|
-
/**
|
|
934
|
-
* Check if a TypeNode represents a type that shouldn't be validated.
|
|
935
|
-
* This includes:
|
|
936
|
-
* - any/unknown (intentional escape hatches)
|
|
937
|
-
* - Type parameters (generics like T)
|
|
938
|
-
* - Constructor types (new (...args: any[]) => T)
|
|
939
|
-
* - Function types ((...args) => T)
|
|
940
|
-
*/
|
|
941
|
-
isAnyOrUnknownType(typeNode) {
|
|
942
|
-
// any/unknown are escape hatches
|
|
943
|
-
if (typeNode.kind === this.ts.SyntaxKind.AnyKeyword ||
|
|
944
|
-
typeNode.kind === this.ts.SyntaxKind.UnknownKeyword) {
|
|
945
|
-
return true;
|
|
946
|
-
}
|
|
947
|
-
// Type parameters (generics) can't be validated at runtime
|
|
948
|
-
if (typeNode.kind === this.ts.SyntaxKind.TypeReference) {
|
|
949
|
-
const typeRef = typeNode;
|
|
950
|
-
// Single identifier that's a type parameter
|
|
951
|
-
if (ts.isIdentifier(typeRef.typeName)) {
|
|
952
|
-
// Check if it's a type parameter by looking for it in enclosing type parameter lists
|
|
953
|
-
// For now, we'll check if it's a single uppercase letter or common generic names
|
|
954
|
-
const name = typeRef.typeName.text;
|
|
955
|
-
// Common type parameter names - single letters or common conventions
|
|
956
|
-
if (/^[A-Z]$/.test(name) || /^T[A-Z]?[a-z]*$/.test(name)) {
|
|
957
|
-
return true;
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
// Constructor types can't be validated by typia
|
|
962
|
-
if (typeNode.kind === this.ts.SyntaxKind.ConstructorType) {
|
|
963
|
-
return true;
|
|
964
|
-
}
|
|
965
|
-
// Function types generally shouldn't be validated
|
|
966
|
-
if (typeNode.kind === this.ts.SyntaxKind.FunctionType) {
|
|
967
|
-
return true;
|
|
968
|
-
}
|
|
969
|
-
return false;
|
|
970
|
-
}
|
|
971
|
-
/**
|
|
972
|
-
* Check if a type contains any unvalidatable parts (type parameters, constructor types, etc.)
|
|
973
|
-
* This recursively checks intersection and union types.
|
|
974
|
-
*/
|
|
975
|
-
containsUnvalidatableType(type) {
|
|
976
|
-
// Type parameters can't be validated at runtime
|
|
977
|
-
if ((type.flags & this.ts.TypeFlags.TypeParameter) !== 0) {
|
|
978
|
-
return true;
|
|
979
|
-
}
|
|
980
|
-
// Check intersection types - if any part is unvalidatable, the whole thing is
|
|
981
|
-
if (type.isIntersection()) {
|
|
982
|
-
return type.types.some(t => this.containsUnvalidatableType(t));
|
|
983
|
-
}
|
|
984
|
-
// Check union types
|
|
985
|
-
if (type.isUnion()) {
|
|
986
|
-
return type.types.some(t => this.containsUnvalidatableType(t));
|
|
987
|
-
}
|
|
988
|
-
// Check for constructor signatures (like `new (...args) => T`)
|
|
989
|
-
const callSignatures = type.getConstructSignatures?.() ?? [];
|
|
990
|
-
if (callSignatures.length > 0) {
|
|
991
|
-
return true;
|
|
992
|
-
}
|
|
993
|
-
return false;
|
|
994
|
-
}
|
|
995
|
-
/**
|
|
996
|
-
* Check if a Type has any or unknown flags, or is a type parameter or function/constructor.
|
|
997
|
-
*/
|
|
998
|
-
isAnyOrUnknownTypeFlags(type) {
|
|
999
|
-
// any/unknown
|
|
1000
|
-
if ((type.flags & this.ts.TypeFlags.Any) !== 0 ||
|
|
1001
|
-
(type.flags & this.ts.TypeFlags.Unknown) !== 0) {
|
|
1002
|
-
return true;
|
|
1003
|
-
}
|
|
1004
|
-
// Type parameters (generics) - can't be validated at runtime
|
|
1005
|
-
if ((type.flags & this.ts.TypeFlags.TypeParameter) !== 0) {
|
|
1006
|
-
return true;
|
|
1007
|
-
}
|
|
1008
|
-
return false;
|
|
1009
|
-
}
|
|
1010
|
-
/**
|
|
1011
|
-
* Check if a type name matches any of the ignoreTypes patterns.
|
|
1012
|
-
* Supports wildcards: "React.*" matches "React.FormEvent", "React.ChangeEvent", etc.
|
|
1013
|
-
* Also handles union types: "Document | Element" is ignored if "Document" or "Element" is in ignoreTypes.
|
|
1014
|
-
*/
|
|
1015
|
-
isIgnoredType(typeName, typeChecker, type) {
|
|
1016
|
-
// Combine user patterns with DOM types if ignoreDOMTypes is enabled (default: true)
|
|
1017
|
-
const userPatterns = this.config.ignoreTypes ?? [];
|
|
1018
|
-
const domPatterns = this.config.ignoreDOMTypes !== false ? DOM_TYPES_TO_IGNORE : [];
|
|
1019
|
-
const patterns = [...userPatterns, ...domPatterns];
|
|
1020
|
-
if (patterns.length === 0)
|
|
1021
|
-
return false;
|
|
1022
|
-
// For union types, check each constituent
|
|
1023
|
-
if (type && type.isUnion()) {
|
|
1024
|
-
const nonNullTypes = type.types.filter(t => !(t.flags & this.ts.TypeFlags.Null) && !(t.flags & this.ts.TypeFlags.Undefined));
|
|
1025
|
-
if (nonNullTypes.length === 0)
|
|
1026
|
-
return false;
|
|
1027
|
-
// All non-null types must be ignored
|
|
1028
|
-
return nonNullTypes.every(t => this.isIgnoredSingleType(t, patterns, typeChecker));
|
|
1029
|
-
}
|
|
1030
|
-
// For non-union types, check directly
|
|
1031
|
-
if (type && typeChecker) {
|
|
1032
|
-
return this.isIgnoredSingleType(type, patterns, typeChecker);
|
|
1033
|
-
}
|
|
1034
|
-
// Fallback: string-based matching for union types like "Document | Element | null"
|
|
1035
|
-
const typeParts = typeName.split(' | ').map(t => t.trim());
|
|
1036
|
-
const nonNullParts = typeParts.filter(t => t !== 'null' && t !== 'undefined');
|
|
1037
|
-
if (nonNullParts.length === 0)
|
|
1038
|
-
return false;
|
|
1039
|
-
return nonNullParts.every(part => this.matchesIgnorePattern(part, patterns));
|
|
1040
|
-
}
|
|
1041
|
-
/**
|
|
1042
|
-
* Check if a single type (not a union) should be ignored.
|
|
1043
|
-
* Checks both the type name and its base classes.
|
|
1044
|
-
*/
|
|
1045
|
-
isIgnoredSingleType(type, patterns, typeChecker, depth = 0) {
|
|
1046
|
-
// Prevent infinite recursion
|
|
1047
|
-
if (depth > 20)
|
|
1048
|
-
return false;
|
|
1049
|
-
const typeName = type.symbol?.name || '';
|
|
1050
|
-
if (process.env.DEBUG) {
|
|
1051
|
-
console.log(`TYPICAL: isIgnoredSingleType checking type: "${typeName}" (depth: ${depth})`);
|
|
1052
|
-
}
|
|
1053
|
-
// Check direct name match
|
|
1054
|
-
if (this.matchesIgnorePattern(typeName, patterns)) {
|
|
1055
|
-
if (process.env.DEBUG) {
|
|
1056
|
-
console.log(`TYPICAL: Type "${typeName}" matched ignore pattern directly`);
|
|
1057
|
-
}
|
|
1058
|
-
return true;
|
|
1059
|
-
}
|
|
1060
|
-
// Check base classes (for classes extending DOM types like HTMLElement)
|
|
1061
|
-
// This works for class types that have getBaseTypes available
|
|
1062
|
-
const baseTypes = type.getBaseTypes?.() ?? [];
|
|
1063
|
-
if (process.env.DEBUG && baseTypes.length > 0) {
|
|
1064
|
-
console.log(`TYPICAL: Type "${typeName}" has ${baseTypes.length} base types: ${baseTypes.map(t => t.symbol?.name || '?').join(', ')}`);
|
|
1065
|
-
}
|
|
1066
|
-
for (const baseType of baseTypes) {
|
|
1067
|
-
if (this.isIgnoredSingleType(baseType, patterns, typeChecker, depth + 1)) {
|
|
1068
|
-
if (process.env.DEBUG) {
|
|
1069
|
-
console.log(`TYPICAL: Type "${typeName}" ignored because base type "${baseType.symbol?.name}" is ignored`);
|
|
1070
|
-
}
|
|
1071
|
-
return true;
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
// Also check the declared type's symbol for heritage clauses (alternative approach)
|
|
1075
|
-
// This handles cases where getBaseTypes doesn't return what we expect
|
|
1076
|
-
if (type.symbol?.declarations) {
|
|
1077
|
-
for (const decl of type.symbol.declarations) {
|
|
1078
|
-
if (this.ts.isClassDeclaration(decl) && decl.heritageClauses) {
|
|
1079
|
-
for (const heritage of decl.heritageClauses) {
|
|
1080
|
-
if (heritage.token === this.ts.SyntaxKind.ExtendsKeyword) {
|
|
1081
|
-
for (const heritageType of heritage.types) {
|
|
1082
|
-
const baseTypeName = heritageType.expression.getText();
|
|
1083
|
-
if (process.env.DEBUG) {
|
|
1084
|
-
console.log(`TYPICAL: Type "${typeName}" extends "${baseTypeName}" (from heritage clause)`);
|
|
1085
|
-
}
|
|
1086
|
-
if (this.matchesIgnorePattern(baseTypeName, patterns)) {
|
|
1087
|
-
if (process.env.DEBUG) {
|
|
1088
|
-
console.log(`TYPICAL: Type "${typeName}" ignored because it extends "${baseTypeName}"`);
|
|
1089
|
-
}
|
|
1090
|
-
return true;
|
|
1091
|
-
}
|
|
1092
|
-
// Recursively check the heritage type
|
|
1093
|
-
if (typeChecker) {
|
|
1094
|
-
const heritageTypeObj = typeChecker.getTypeAtLocation(heritageType);
|
|
1095
|
-
if (this.isIgnoredSingleType(heritageTypeObj, patterns, typeChecker, depth + 1)) {
|
|
1096
|
-
return true;
|
|
1097
|
-
}
|
|
1098
|
-
// For mixin patterns like `extends VueWatcher(BaseElement)`, the expression is a CallExpression.
|
|
1099
|
-
// We need to check the return type of the mixin function AND the arguments passed to it.
|
|
1100
|
-
if (this.ts.isCallExpression(heritageType.expression)) {
|
|
1101
|
-
// Check arguments to the mixin (e.g., BaseElement in VueWatcher(BaseElement))
|
|
1102
|
-
for (const arg of heritageType.expression.arguments) {
|
|
1103
|
-
const argType = typeChecker.getTypeAtLocation(arg);
|
|
1104
|
-
if (process.env.DEBUG) {
|
|
1105
|
-
console.log(`TYPICAL: Type "${typeName}" mixin arg: "${argType.symbol?.name}" (from call expression)`);
|
|
1106
|
-
}
|
|
1107
|
-
if (this.isIgnoredSingleType(argType, patterns, typeChecker, depth + 1)) {
|
|
1108
|
-
if (process.env.DEBUG) {
|
|
1109
|
-
console.log(`TYPICAL: Type "${typeName}" ignored because mixin argument "${argType.symbol?.name}" is ignored`);
|
|
1110
|
-
}
|
|
1111
|
-
return true;
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
}
|
|
1122
|
-
return false;
|
|
1123
|
-
}
|
|
1124
|
-
/**
|
|
1125
|
-
* Check if a single type name matches any ignore pattern.
|
|
38
|
+
* @param fileName - Path to the TypeScript file
|
|
39
|
+
* @param mode - Output mode: 'ts' returns TypeScript, 'js' would transpile (not yet supported)
|
|
40
|
+
* @returns Transformed code with validation
|
|
1126
41
|
*/
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
const regexStr = '^' + pattern
|
|
1131
|
-
.replace(/[.+^${}()|[\]\\]/g, '\\$&') // Escape special regex chars except *
|
|
1132
|
-
.replace(/\*/g, '.*') + '$';
|
|
1133
|
-
return new RegExp(regexStr).test(typeName);
|
|
1134
|
-
});
|
|
1135
|
-
}
|
|
1136
|
-
/**
|
|
1137
|
-
* Find untransformed typia calls in the output code.
|
|
1138
|
-
* These indicate types that typia could not process.
|
|
1139
|
-
*/
|
|
1140
|
-
findUntransformedTypiaCalls(code) {
|
|
1141
|
-
const results = [];
|
|
1142
|
-
// Match patterns like: typia.createAssert<Type>() or typia.json.createAssertParse<Type>()
|
|
1143
|
-
// The type argument can contain nested generics like React.FormEvent<HTMLElement>
|
|
1144
|
-
const patterns = [
|
|
1145
|
-
/typia\.createAssert<([^>]+(?:<[^>]*>)?)>\s*\(\)/g,
|
|
1146
|
-
/typia\.json\.createAssertParse<([^>]+(?:<[^>]*>)?)>\s*\(\)/g,
|
|
1147
|
-
/typia\.json\.createStringify<([^>]+(?:<[^>]*>)?)>\s*\(\)/g,
|
|
1148
|
-
];
|
|
1149
|
-
for (const pattern of patterns) {
|
|
1150
|
-
let match;
|
|
1151
|
-
while ((match = pattern.exec(code)) !== null) {
|
|
1152
|
-
const methodMatch = match[0].match(/typia\.([\w.]+)</);
|
|
1153
|
-
results.push({
|
|
1154
|
-
method: methodMatch ? methodMatch[1] : 'unknown',
|
|
1155
|
-
type: match[1]
|
|
1156
|
-
});
|
|
1157
|
-
}
|
|
42
|
+
async transform(fileName, mode = 'ts') {
|
|
43
|
+
if (mode === 'js') {
|
|
44
|
+
throw new Error('Mode "js" not yet supported - use "ts" and transpile separately');
|
|
1158
45
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
* Infer type information from a JSON.stringify argument for creating a reusable stringifier.
|
|
1163
|
-
*/
|
|
1164
|
-
inferStringifyType(arg, typeChecker, ctx) {
|
|
1165
|
-
const ts = this.ts;
|
|
1166
|
-
// Type assertion: use the asserted type directly
|
|
1167
|
-
if (ts.isAsExpression(arg)) {
|
|
1168
|
-
const typeNode = arg.type;
|
|
1169
|
-
const typeKey = this.getTypeKey(typeNode, typeChecker);
|
|
1170
|
-
return { typeText: typeKey, typeNode };
|
|
1171
|
-
}
|
|
1172
|
-
// Object literal: infer type from type checker
|
|
1173
|
-
if (ts.isObjectLiteralExpression(arg)) {
|
|
1174
|
-
const objectType = typeChecker.getTypeAtLocation(arg);
|
|
1175
|
-
const typeNode = typeChecker.typeToTypeNode(objectType, arg, TYPE_NODE_FLAGS);
|
|
1176
|
-
if (!typeNode) {
|
|
1177
|
-
throw new Error('unknown type node for object literal: ' + arg.getText());
|
|
1178
|
-
}
|
|
1179
|
-
const typeKey = this.getTypeKey(typeNode, typeChecker, objectType);
|
|
1180
|
-
return { typeText: typeKey, typeNode };
|
|
1181
|
-
}
|
|
1182
|
-
// Other expressions: infer from type checker
|
|
1183
|
-
const argType = typeChecker.getTypeAtLocation(arg);
|
|
1184
|
-
const typeNode = typeChecker.typeToTypeNode(argType, arg, TYPE_NODE_FLAGS);
|
|
1185
|
-
if (typeNode) {
|
|
1186
|
-
const typeKey = this.getTypeKey(typeNode, typeChecker, argType);
|
|
1187
|
-
return { typeText: typeKey, typeNode };
|
|
1188
|
-
}
|
|
1189
|
-
// Fallback to unknown
|
|
46
|
+
await this.ensureInitialized();
|
|
47
|
+
const resolvedPath = resolve(fileName);
|
|
48
|
+
const result = await this.compiler.transformFile(this.projectHandle, resolvedPath);
|
|
1190
49
|
return {
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
};
|
|
1194
|
-
}
|
|
1195
|
-
// ============================================
|
|
1196
|
-
// Flow Analysis Helpers
|
|
1197
|
-
// ============================================
|
|
1198
|
-
/**
|
|
1199
|
-
* Gets the root identifier from an expression.
|
|
1200
|
-
* e.g., `user.address.city` -> "user"
|
|
1201
|
-
*/
|
|
1202
|
-
getRootIdentifier(expr) {
|
|
1203
|
-
if (this.ts.isIdentifier(expr)) {
|
|
1204
|
-
return expr.text;
|
|
1205
|
-
}
|
|
1206
|
-
if (this.ts.isPropertyAccessExpression(expr)) {
|
|
1207
|
-
return this.getRootIdentifier(expr.expression);
|
|
1208
|
-
}
|
|
1209
|
-
return undefined;
|
|
1210
|
-
}
|
|
1211
|
-
/**
|
|
1212
|
-
* Check if a validated variable has been tainted (mutated) in the function body.
|
|
1213
|
-
* A variable is tainted if it's reassigned, has properties modified, is passed
|
|
1214
|
-
* to a function, has methods called on it, or if an await occurs.
|
|
1215
|
-
*/
|
|
1216
|
-
isTainted(varName, body) {
|
|
1217
|
-
let tainted = false;
|
|
1218
|
-
const ts = this.ts;
|
|
1219
|
-
// Collect aliases (variables that reference properties of varName)
|
|
1220
|
-
// e.g., const addr = user.address; -> addr is an alias
|
|
1221
|
-
const aliases = new Set([varName]);
|
|
1222
|
-
const collectAliases = (node) => {
|
|
1223
|
-
if (ts.isVariableStatement(node)) {
|
|
1224
|
-
for (const decl of node.declarationList.declarations) {
|
|
1225
|
-
if (ts.isIdentifier(decl.name) && decl.initializer) {
|
|
1226
|
-
const initRoot = this.getRootIdentifier(decl.initializer);
|
|
1227
|
-
if (initRoot && aliases.has(initRoot)) {
|
|
1228
|
-
aliases.add(decl.name.text);
|
|
1229
|
-
}
|
|
1230
|
-
}
|
|
1231
|
-
}
|
|
1232
|
-
}
|
|
1233
|
-
ts.forEachChild(node, collectAliases);
|
|
1234
|
-
};
|
|
1235
|
-
collectAliases(body);
|
|
1236
|
-
// Helper to check if any alias is involved
|
|
1237
|
-
const involvesTrackedVar = (expr) => {
|
|
1238
|
-
const root = this.getRootIdentifier(expr);
|
|
1239
|
-
return root !== undefined && aliases.has(root);
|
|
50
|
+
code: result.code,
|
|
51
|
+
map: result.sourceMap ?? null,
|
|
1240
52
|
};
|
|
1241
|
-
const checkTainting = (node) => {
|
|
1242
|
-
if (tainted)
|
|
1243
|
-
return;
|
|
1244
|
-
// Reassignment: trackedVar = ...
|
|
1245
|
-
if (ts.isBinaryExpression(node) &&
|
|
1246
|
-
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
1247
|
-
ts.isIdentifier(node.left) &&
|
|
1248
|
-
aliases.has(node.left.text)) {
|
|
1249
|
-
tainted = true;
|
|
1250
|
-
return;
|
|
1251
|
-
}
|
|
1252
|
-
// Property assignment: trackedVar.x = ... or alias.x = ...
|
|
1253
|
-
if (ts.isBinaryExpression(node) &&
|
|
1254
|
-
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
1255
|
-
ts.isPropertyAccessExpression(node.left) &&
|
|
1256
|
-
involvesTrackedVar(node.left)) {
|
|
1257
|
-
tainted = true;
|
|
1258
|
-
return;
|
|
1259
|
-
}
|
|
1260
|
-
// Element assignment: trackedVar[x] = ... or alias[x] = ...
|
|
1261
|
-
if (ts.isBinaryExpression(node) &&
|
|
1262
|
-
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
1263
|
-
ts.isElementAccessExpression(node.left) &&
|
|
1264
|
-
involvesTrackedVar(node.left.expression)) {
|
|
1265
|
-
tainted = true;
|
|
1266
|
-
return;
|
|
1267
|
-
}
|
|
1268
|
-
// Passed as argument to a function: fn(trackedVar) or fn(alias)
|
|
1269
|
-
if (ts.isCallExpression(node)) {
|
|
1270
|
-
for (const arg of node.arguments) {
|
|
1271
|
-
let hasTrackedRef = false;
|
|
1272
|
-
const checkRef = (n) => {
|
|
1273
|
-
if (ts.isIdentifier(n) && aliases.has(n.text)) {
|
|
1274
|
-
hasTrackedRef = true;
|
|
1275
|
-
}
|
|
1276
|
-
ts.forEachChild(n, checkRef);
|
|
1277
|
-
};
|
|
1278
|
-
checkRef(arg);
|
|
1279
|
-
if (hasTrackedRef) {
|
|
1280
|
-
tainted = true;
|
|
1281
|
-
return;
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
// Method call on the variable: trackedVar.method() or alias.method()
|
|
1286
|
-
if (ts.isCallExpression(node) &&
|
|
1287
|
-
ts.isPropertyAccessExpression(node.expression) &&
|
|
1288
|
-
involvesTrackedVar(node.expression.expression)) {
|
|
1289
|
-
tainted = true;
|
|
1290
|
-
return;
|
|
1291
|
-
}
|
|
1292
|
-
// Await expression (async boundary - external code could run)
|
|
1293
|
-
if (ts.isAwaitExpression(node)) {
|
|
1294
|
-
tainted = true;
|
|
1295
|
-
return;
|
|
1296
|
-
}
|
|
1297
|
-
ts.forEachChild(node, checkTainting);
|
|
1298
|
-
};
|
|
1299
|
-
checkTainting(body);
|
|
1300
|
-
return tainted;
|
|
1301
|
-
}
|
|
1302
|
-
addTypiaImport(sourceFile, ctx) {
|
|
1303
|
-
const { factory } = ctx;
|
|
1304
|
-
const existingImports = sourceFile.statements.filter(ctx.ts.isImportDeclaration);
|
|
1305
|
-
const hasTypiaImport = existingImports.some((imp) => imp.moduleSpecifier &&
|
|
1306
|
-
ctx.ts.isStringLiteral(imp.moduleSpecifier) &&
|
|
1307
|
-
imp.moduleSpecifier.text === "typia");
|
|
1308
|
-
if (!hasTypiaImport) {
|
|
1309
|
-
const typiaImport = factory.createImportDeclaration(undefined, factory.createImportClause(false, factory.createIdentifier("typia"), undefined), factory.createStringLiteral("typia"));
|
|
1310
|
-
const newSourceFile = factory.updateSourceFile(sourceFile, factory.createNodeArray([typiaImport, ...sourceFile.statements]));
|
|
1311
|
-
return newSourceFile;
|
|
1312
|
-
}
|
|
1313
|
-
return sourceFile;
|
|
1314
53
|
}
|
|
1315
54
|
/**
|
|
1316
|
-
*
|
|
1317
|
-
*
|
|
1318
|
-
* but falls back to typeToString() for synthesized nodes without source positions.
|
|
1319
|
-
*
|
|
1320
|
-
* @param typeNode The TypeNode to get a key for
|
|
1321
|
-
* @param typeChecker The TypeChecker to use
|
|
1322
|
-
* @param typeObj Optional Type object - use this for synthesized nodes since
|
|
1323
|
-
* getTypeFromTypeNode doesn't work correctly on them
|
|
55
|
+
* Close the Go compiler process and release resources.
|
|
56
|
+
* This immediately kills the process without waiting for pending operations.
|
|
1324
57
|
*/
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
const text = typeNode.getText();
|
|
1330
|
-
// Check for truncation patterns in source text (shouldn't happen but be safe)
|
|
1331
|
-
if (!text.includes('...') || !text.match(/\.\.\.\d+\s+more/)) {
|
|
1332
|
-
return text;
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
|
-
catch {
|
|
1336
|
-
// Fall through to typeToString
|
|
1337
|
-
}
|
|
1338
|
-
}
|
|
1339
|
-
// Fallback for synthesized nodes - use the provided Type object if available,
|
|
1340
|
-
// otherwise try to get it from the node (which may not work correctly)
|
|
1341
|
-
const type = typeObj ?? typeChecker.getTypeFromTypeNode(typeNode);
|
|
1342
|
-
const typeString = typeChecker.typeToString(type, undefined, this.ts.TypeFormatFlags.NoTruncation);
|
|
1343
|
-
// TypeScript may still truncate very large types even with NoTruncation flag.
|
|
1344
|
-
// Detect truncation patterns like "...19 more..." and use a hash-based key instead.
|
|
1345
|
-
if (typeString.match(/\.\.\.\d+\s+more/)) {
|
|
1346
|
-
const hash = this.hashString(typeString);
|
|
1347
|
-
return `__complex_type_${hash}`;
|
|
1348
|
-
}
|
|
1349
|
-
return typeString;
|
|
1350
|
-
}
|
|
1351
|
-
/**
|
|
1352
|
-
* Simple string hash for creating unique identifiers from type strings.
|
|
1353
|
-
*/
|
|
1354
|
-
hashString(str) {
|
|
1355
|
-
let hash = 0;
|
|
1356
|
-
for (let i = 0; i < str.length; i++) {
|
|
1357
|
-
const char = str.charCodeAt(i);
|
|
1358
|
-
hash = ((hash << 5) - hash) + char;
|
|
1359
|
-
hash = hash & hash; // Convert to 32bit integer
|
|
1360
|
-
}
|
|
1361
|
-
return Math.abs(hash).toString(36);
|
|
1362
|
-
}
|
|
1363
|
-
/**
|
|
1364
|
-
* Format typia's error message into a cleaner list format.
|
|
1365
|
-
* Typia outputs verbose messages like:
|
|
1366
|
-
* "unsupported type detected\n\n- Window.ondevicemotion: unknown\n - nonsensible intersection\n\n- Window.ondeviceorientation..."
|
|
1367
|
-
* We want to extract just the problematic types and their issues.
|
|
1368
|
-
*/
|
|
1369
|
-
formatTypiaError(message) {
|
|
1370
|
-
const lines = message.split('\n');
|
|
1371
|
-
const firstLine = lines[0]; // e.g., "unsupported type detected"
|
|
1372
|
-
// Parse the error entries - each starts with "- " at the beginning of a line
|
|
1373
|
-
const issues = [];
|
|
1374
|
-
let currentIssue = null;
|
|
1375
|
-
for (const line of lines.slice(1)) {
|
|
1376
|
-
if (line.startsWith('- ')) {
|
|
1377
|
-
// New type entry
|
|
1378
|
-
if (currentIssue) {
|
|
1379
|
-
issues.push(currentIssue);
|
|
1380
|
-
}
|
|
1381
|
-
currentIssue = { type: line.slice(2), reasons: [] };
|
|
1382
|
-
}
|
|
1383
|
-
else if (line.startsWith(' - ') && currentIssue) {
|
|
1384
|
-
// Reason for current type
|
|
1385
|
-
currentIssue.reasons.push(line.slice(4));
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
if (currentIssue) {
|
|
1389
|
-
issues.push(currentIssue);
|
|
1390
|
-
}
|
|
1391
|
-
if (issues.length === 0) {
|
|
1392
|
-
return ` ${firstLine}`;
|
|
1393
|
-
}
|
|
1394
|
-
// Limit to 5 issues, show count of remaining
|
|
1395
|
-
const maxIssues = 5;
|
|
1396
|
-
const displayIssues = issues.slice(0, maxIssues);
|
|
1397
|
-
const remainingCount = issues.length - maxIssues;
|
|
1398
|
-
const formatted = displayIssues.map(issue => {
|
|
1399
|
-
const reasons = issue.reasons.map(r => ` - ${r}`).join('\n');
|
|
1400
|
-
return ` - ${issue.type}\n${reasons}`;
|
|
1401
|
-
}).join('\n');
|
|
1402
|
-
const suffix = remainingCount > 0 ? `\n (and ${remainingCount} more errors)` : '';
|
|
1403
|
-
return ` ${firstLine}\n${formatted}${suffix}`;
|
|
1404
|
-
}
|
|
1405
|
-
/**
|
|
1406
|
-
* Creates a readable name suffix from a type string.
|
|
1407
|
-
* For simple identifiers like "User" or "string", returns the name directly.
|
|
1408
|
-
* For complex types, returns a numeric index.
|
|
1409
|
-
*/
|
|
1410
|
-
getTypeNameSuffix(typeText, existingNames, fallbackIndex) {
|
|
1411
|
-
// Complex types from getTypeKey() - use numeric index
|
|
1412
|
-
if (typeText.startsWith('__complex_type_')) {
|
|
1413
|
-
return String(fallbackIndex);
|
|
1414
|
-
}
|
|
1415
|
-
// Check if it's a simple identifier (letters, numbers, underscore, starting with letter/underscore)
|
|
1416
|
-
if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(typeText)) {
|
|
1417
|
-
// It's a simple type name like "User", "string", "MyType"
|
|
1418
|
-
let name = typeText;
|
|
1419
|
-
// Handle collisions by appending a number
|
|
1420
|
-
if (existingNames.has(name)) {
|
|
1421
|
-
let i = 2;
|
|
1422
|
-
while (existingNames.has(`${typeText}${i}`)) {
|
|
1423
|
-
i++;
|
|
1424
|
-
}
|
|
1425
|
-
name = `${typeText}${i}`;
|
|
1426
|
-
}
|
|
1427
|
-
return name;
|
|
1428
|
-
}
|
|
1429
|
-
// Complex type - use numeric index
|
|
1430
|
-
return String(fallbackIndex);
|
|
1431
|
-
}
|
|
1432
|
-
/**
|
|
1433
|
-
* Generic method to get or create a typed function (validator, stringifier, or parser).
|
|
1434
|
-
*/
|
|
1435
|
-
getOrCreateTypedFunction(kind, typeText, typeNode) {
|
|
1436
|
-
const maps = {
|
|
1437
|
-
assert: this.typeValidators,
|
|
1438
|
-
stringify: this.typeStringifiers,
|
|
1439
|
-
parse: this.typeParsers,
|
|
1440
|
-
};
|
|
1441
|
-
const prefixes = {
|
|
1442
|
-
assert: '__typical_assert_',
|
|
1443
|
-
stringify: '__typical_stringify_',
|
|
1444
|
-
parse: '__typical_parse_',
|
|
1445
|
-
};
|
|
1446
|
-
const map = maps[kind];
|
|
1447
|
-
const prefix = prefixes[kind];
|
|
1448
|
-
if (map.has(typeText)) {
|
|
1449
|
-
return map.get(typeText).name;
|
|
1450
|
-
}
|
|
1451
|
-
const existingSuffixes = [...map.values()].map(v => v.name.slice(prefix.length));
|
|
1452
|
-
const existingNames = new Set(existingSuffixes);
|
|
1453
|
-
const numericCount = existingSuffixes.filter(s => /^\d+$/.test(s)).length;
|
|
1454
|
-
const suffix = this.getTypeNameSuffix(typeText, existingNames, numericCount);
|
|
1455
|
-
const name = `${prefix}${suffix}`;
|
|
1456
|
-
map.set(typeText, { name, typeNode });
|
|
1457
|
-
return name;
|
|
1458
|
-
}
|
|
1459
|
-
getOrCreateValidator(typeText, typeNode) {
|
|
1460
|
-
return this.getOrCreateTypedFunction('assert', typeText, typeNode);
|
|
1461
|
-
}
|
|
1462
|
-
getOrCreateStringifier(typeText, typeNode) {
|
|
1463
|
-
return this.getOrCreateTypedFunction('stringify', typeText, typeNode);
|
|
1464
|
-
}
|
|
1465
|
-
getOrCreateParser(typeText, typeNode) {
|
|
1466
|
-
return this.getOrCreateTypedFunction('parse', typeText, typeNode);
|
|
1467
|
-
}
|
|
1468
|
-
/**
|
|
1469
|
-
* Creates a nested property access expression from an array of identifiers.
|
|
1470
|
-
* e.g., ['typia', 'json', 'createStringify'] -> typia.json.createStringify
|
|
1471
|
-
*/
|
|
1472
|
-
createPropertyAccessChain(factory, parts) {
|
|
1473
|
-
let expr = factory.createIdentifier(parts[0]);
|
|
1474
|
-
for (let i = 1; i < parts.length; i++) {
|
|
1475
|
-
expr = factory.createPropertyAccessExpression(expr, parts[i]);
|
|
1476
|
-
}
|
|
1477
|
-
return expr;
|
|
1478
|
-
}
|
|
1479
|
-
createValidatorStatements(ctx) {
|
|
1480
|
-
const { factory } = ctx;
|
|
1481
|
-
const statements = [];
|
|
1482
|
-
const configs = [
|
|
1483
|
-
{ map: this.typeValidators, methodPath: ['typia', 'createAssert'] },
|
|
1484
|
-
{ map: this.typeStringifiers, methodPath: ['typia', 'json', 'createStringify'] },
|
|
1485
|
-
{ map: this.typeParsers, methodPath: ['typia', 'json', 'createAssertParse'] },
|
|
1486
|
-
];
|
|
1487
|
-
for (const { map, methodPath } of configs) {
|
|
1488
|
-
for (const [, { name, typeNode }] of map) {
|
|
1489
|
-
const createCall = factory.createCallExpression(this.createPropertyAccessChain(factory, methodPath), [typeNode], []);
|
|
1490
|
-
const declaration = factory.createVariableStatement(undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(name, undefined, undefined, createCall)], ctx.ts.NodeFlags.Const));
|
|
1491
|
-
statements.push(declaration);
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1494
|
-
return statements;
|
|
58
|
+
async close() {
|
|
59
|
+
this.projectHandle = null;
|
|
60
|
+
this.initPromise = null;
|
|
61
|
+
await this.compiler.close();
|
|
1495
62
|
}
|
|
1496
63
|
}
|
|
1497
64
|
//# sourceMappingURL=transformer.js.map
|