@ivlev-dev/silent-validation-vite 0.0.0-stage → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js ADDED
@@ -0,0 +1,1286 @@
1
+ import { builtinModules } from "node:module";
2
+ import * as path from "node:path";
3
+ import MagicString from "magic-string";
4
+ import ts from "typescript";
5
+ import { generateValidationBlocks, schemaHasClassRef } from "./typegen.js";
6
+ const DEFAULT_INCLUDE = /\.(?:[cm]?ts|tsx)$/;
7
+ const DEFAULT_EXCLUDE = /node_modules/;
8
+ const PACKAGE_NAME = "@ivlev-dev/silent-validation";
9
+ const NAMESPACE_ALIAS_PREFIX = "__silent_validation_";
10
+ const ACCESSOR_PATTERN = /\baccessor\b/;
11
+ const EXTENDS_PATTERN = /\bextends\b/;
12
+ const SCHEMA_KEY = "silent.validation.schema";
13
+ const GENERATED_MARKER = /Symbol\s*\.\s*for\(\s*["']silent\.validation\.schema["']\s*\)/;
14
+ const DECLARATION_FILE_PATTERN = /\.d\.[cm]?ts$/i;
15
+ const RUNTIME_FILE_PATTERN = /\.(?:[cm]?js|jsx|[cm]?ts|tsx)$/i;
16
+ const SAFE_QUERY_KEYS = new Set(["import", "v", "t", "direct"]);
17
+ function moduleExport(checker, moduleSymbol, name) {
18
+ let exports;
19
+ try {
20
+ exports = checker.getExportsOfModule(moduleSymbol);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ for (const entry of exports) {
26
+ const resolved = resolveAlias(checker, entry);
27
+ if (entry.getName() === name || resolved.getName() === name) {
28
+ return resolved;
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+ function findBaseSymbols(program, checker, name) {
34
+ const symbols = new Set();
35
+ const addModule = (moduleSymbol) => {
36
+ if (moduleSymbol === undefined)
37
+ return;
38
+ const symbol = moduleExport(checker, moduleSymbol, name);
39
+ if (symbol === null)
40
+ return;
41
+ symbols.add(symbol);
42
+ symbols.add(resolveAlias(checker, symbol));
43
+ };
44
+ for (const sourceFile of program.getSourceFiles()) {
45
+ if (sourceFile.isDeclarationFile)
46
+ continue;
47
+ for (const statement of sourceFile.statements) {
48
+ if (!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement))
49
+ continue;
50
+ const specifier = statement.moduleSpecifier;
51
+ if (specifier === undefined)
52
+ continue;
53
+ if (!ts.isStringLiteral(specifier) || specifier.text !== PACKAGE_NAME)
54
+ continue;
55
+ addModule(checker.getSymbolAtLocation(specifier));
56
+ }
57
+ }
58
+ for (const root of program.getRootFileNames()) {
59
+ const resolved = ts.resolveModuleName(PACKAGE_NAME, root, program.getCompilerOptions(), ts.sys).resolvedModule;
60
+ if (resolved === undefined)
61
+ continue;
62
+ const sourceFile = program.getSourceFile(resolved.resolvedFileName);
63
+ if (sourceFile === undefined)
64
+ continue;
65
+ addModule(checker.getSymbolAtLocation(sourceFile));
66
+ }
67
+ return symbols;
68
+ }
69
+ function instanceTypeOf(checker, declaration) {
70
+ const type = checker.getTypeAtLocation(declaration);
71
+ if (ts.isClassExpression(declaration)) {
72
+ const signature = type.getConstructSignatures()[0];
73
+ if (signature !== undefined)
74
+ return signature.getReturnType();
75
+ }
76
+ return type;
77
+ }
78
+ function extendsTarget(type, checker, name, targets, seen) {
79
+ if (seen.has(type)) {
80
+ return false;
81
+ }
82
+ seen.add(type);
83
+ for (const base of type.getBaseTypes() ?? []) {
84
+ const symbol = base.getSymbol();
85
+ if (symbol !== undefined) {
86
+ const resolved = resolveAlias(checker, symbol);
87
+ const matches = targets.length > 0
88
+ ? targets.some((target) => symbolsEqual(checker, resolved, target))
89
+ : resolved.getName() === name;
90
+ if (matches) {
91
+ return true;
92
+ }
93
+ }
94
+ if (extendsTarget(base, checker, name, targets, seen)) {
95
+ return true;
96
+ }
97
+ }
98
+ return false;
99
+ }
100
+ const DEFAULT_COMPILER_OPTIONS = {
101
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
102
+ module: ts.ModuleKind.ESNext,
103
+ target: ts.ScriptTarget.ES2022,
104
+ jsx: ts.JsxEmit.Preserve,
105
+ strict: true,
106
+ experimentalDecorators: false,
107
+ useDefineForClassFields: true,
108
+ skipLibCheck: true,
109
+ noEmit: true,
110
+ };
111
+ function cleanModuleId(id) {
112
+ return id.split("?")[0]?.split("#")[0] ?? "";
113
+ }
114
+ function isVirtualModule(id) {
115
+ return id.includes("\0") || id.startsWith("virtual:");
116
+ }
117
+ function hasUnsafeQuery(id) {
118
+ const queryIndex = id.indexOf("?");
119
+ if (queryIndex < 0)
120
+ return false;
121
+ const hashIndex = id.indexOf("#", queryIndex);
122
+ const query = id.slice(queryIndex + 1, hashIndex < 0 ? undefined : hashIndex);
123
+ if (query.length === 0)
124
+ return false;
125
+ for (const key of new URLSearchParams(query).keys()) {
126
+ if (!SAFE_QUERY_KEYS.has(key))
127
+ return true;
128
+ }
129
+ return false;
130
+ }
131
+ function isDeclarationFile(file) {
132
+ return DECLARATION_FILE_PATTERN.test(file);
133
+ }
134
+ function hasGeneratedSchema(code) {
135
+ return code.includes("static {") && GENERATED_MARKER.test(code);
136
+ }
137
+ function matchesPattern(pattern, value) {
138
+ const flags = pattern.flags.replace(/[gy]/g, "");
139
+ return new RegExp(pattern.source, flags).test(value);
140
+ }
141
+ function resolveAlias(checker, symbol) {
142
+ let current = symbol;
143
+ const seen = new Set();
144
+ while ((current.flags & ts.SymbolFlags.Alias) !== 0 && !seen.has(current)) {
145
+ seen.add(current);
146
+ let next;
147
+ try {
148
+ next = checker.getAliasedSymbol(current);
149
+ }
150
+ catch {
151
+ break;
152
+ }
153
+ if (next === current)
154
+ break;
155
+ current = next;
156
+ }
157
+ return current;
158
+ }
159
+ function symbolsEqual(checker, left, right) {
160
+ return left === right || resolveAlias(checker, left) === resolveAlias(checker, right);
161
+ }
162
+ function declarationInfo(checker, symbol) {
163
+ const target = resolveAlias(checker, symbol);
164
+ for (const declaration of target.declarations ?? []) {
165
+ const sourceFile = declaration.getSourceFile();
166
+ if (sourceFile !== undefined)
167
+ return { file: sourceFile, declaration };
168
+ }
169
+ return null;
170
+ }
171
+ function ambientModuleName(declaration) {
172
+ let node = declaration;
173
+ while (node !== undefined && !ts.isSourceFile(node)) {
174
+ if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
175
+ return node.name.text;
176
+ }
177
+ node = node.parent;
178
+ }
179
+ return null;
180
+ }
181
+ function isGlobalModuleDeclaration(node) {
182
+ if ((node.flags & ts.NodeFlags.GlobalAugmentation) !== 0)
183
+ return true;
184
+ return ts.isIdentifier(node.name) && node.name.text === "global";
185
+ }
186
+ function isGlobalAugmentation(declaration) {
187
+ let node = declaration;
188
+ while (node !== undefined && !ts.isSourceFile(node)) {
189
+ if (ts.isModuleDeclaration(node)) {
190
+ if (isGlobalModuleDeclaration(node))
191
+ return true;
192
+ if (ts.isStringLiteral(node.name))
193
+ return false;
194
+ }
195
+ node = node.parent;
196
+ }
197
+ return false;
198
+ }
199
+ function declarationName(symbol) {
200
+ for (const declaration of symbol.declarations ?? []) {
201
+ if (ts.isClassDeclaration(declaration)
202
+ || ts.isClassExpression(declaration)
203
+ || ts.isEnumDeclaration(declaration)) {
204
+ if (declaration.name !== undefined)
205
+ return declaration.name.text;
206
+ }
207
+ }
208
+ for (const declaration of symbol.declarations ?? []) {
209
+ const name = ts.getNameOfDeclaration(declaration);
210
+ if (name !== undefined && ts.isIdentifier(name))
211
+ return name.text;
212
+ }
213
+ const name = symbol.getName();
214
+ return name.length > 0 ? name : null;
215
+ }
216
+ function localQualifiedName(checker, symbol) {
217
+ const target = resolveAlias(checker, symbol);
218
+ const declaration = target.valueDeclaration ?? target.declarations?.[0];
219
+ if (declaration === undefined)
220
+ return declarationName(target);
221
+ const parts = [];
222
+ let node = declaration;
223
+ while (node !== undefined && !ts.isSourceFile(node)) {
224
+ if (ts.isModuleDeclaration(node) && ts.isIdentifier(node.name)) {
225
+ if (!isGlobalModuleDeclaration(node))
226
+ parts.unshift(node.name.text);
227
+ }
228
+ else if ((ts.isClassDeclaration(node) || ts.isClassExpression(node))
229
+ && node.name !== undefined
230
+ && ts.isIdentifier(node.name)) {
231
+ parts.unshift(node.name.text);
232
+ }
233
+ else if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {
234
+ parts.unshift(node.name.text);
235
+ }
236
+ node = node.parent;
237
+ }
238
+ if (parts.length > 0)
239
+ return parts.join(".");
240
+ return declarationName(target);
241
+ }
242
+ function isGlobalDeclaration(sourceFile) {
243
+ return !ts.isExternalModule(sourceFile);
244
+ }
245
+ function isDefaultLibraryFile(sourceFile) {
246
+ const name = sourceFile.fileName;
247
+ const slash = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\"));
248
+ return /^lib(?:\.[^/\\]+)?\.d\.ts$/.test(name.slice(slash + 1));
249
+ }
250
+ function isNodeModulesFile(fileName) {
251
+ return fileName.split(/[\\/]/).includes("node_modules");
252
+ }
253
+ function programWatchFiles(entry) {
254
+ const files = new Set();
255
+ if (entry.project.configPath !== null) {
256
+ files.add(path.resolve(entry.project.configPath));
257
+ }
258
+ for (const rootName of entry.project.rootNames) {
259
+ files.add(path.resolve(rootName));
260
+ }
261
+ for (const sourceFile of entry.program.getSourceFiles()) {
262
+ if (isDefaultLibraryFile(sourceFile))
263
+ continue;
264
+ const fileName = path.resolve(sourceFile.fileName);
265
+ if (isNodeModulesFile(fileName))
266
+ continue;
267
+ files.add(fileName);
268
+ }
269
+ return [...files];
270
+ }
271
+ const BARE_BUILTIN_MODULES = new Set(builtinModules.filter((name) => !name.startsWith("node:")));
272
+ const PREFIXED_BUILTIN_MODULES = new Set(builtinModules.filter((name) => name.startsWith("node:")));
273
+ function isBuiltinModule(moduleName) {
274
+ if (moduleName.startsWith("node:")) {
275
+ return PREFIXED_BUILTIN_MODULES.has(moduleName)
276
+ || BARE_BUILTIN_MODULES.has(moduleName.slice(5));
277
+ }
278
+ return BARE_BUILTIN_MODULES.has(moduleName);
279
+ }
280
+ function isRelativeModule(moduleName) {
281
+ return moduleName.startsWith(".") || path.isAbsolute(moduleName);
282
+ }
283
+ function siblingRuntimeExists(fileName) {
284
+ const match = /^(.*)\.d\.([cm]?ts)$/i.exec(fileName);
285
+ if (match === null || match[1] === undefined)
286
+ return false;
287
+ const stem = match[1];
288
+ const extension = match[2] ?? "ts";
289
+ const candidates = extension === "mts"
290
+ ? [`${stem}.mjs`, `${stem}.js`]
291
+ : extension === "cts"
292
+ ? [`${stem}.cjs`, `${stem}.js`]
293
+ : [`${stem}.js`, `${stem}.mjs`, `${stem}.cjs`];
294
+ return candidates.some((candidate) => ts.sys.fileExists(candidate));
295
+ }
296
+ function isPlainRecord(value) {
297
+ return typeof value === "object" && value !== null && !Array.isArray(value);
298
+ }
299
+ function collectRuntimeTargets(value, key, targets) {
300
+ if (typeof value === "string") {
301
+ if (key !== "types" && key !== "typings")
302
+ targets.push(value);
303
+ return;
304
+ }
305
+ if (Array.isArray(value)) {
306
+ for (const item of value)
307
+ collectRuntimeTargets(item, key, targets);
308
+ return;
309
+ }
310
+ if (!isPlainRecord(value))
311
+ return;
312
+ for (const [entryKey, entryValue] of Object.entries(value)) {
313
+ if (entryKey === "types" || entryKey === "typings")
314
+ continue;
315
+ collectRuntimeTargets(entryValue, entryKey, targets);
316
+ }
317
+ }
318
+ function packageRuntimeExists(fileName) {
319
+ let directory = path.dirname(fileName);
320
+ for (;;) {
321
+ const packageFile = path.join(directory, "package.json");
322
+ if (ts.sys.fileExists(packageFile)) {
323
+ const text = ts.sys.readFile(packageFile);
324
+ if (text === undefined)
325
+ return false;
326
+ let data;
327
+ try {
328
+ data = JSON.parse(text);
329
+ }
330
+ catch {
331
+ return false;
332
+ }
333
+ if (!isPlainRecord(data))
334
+ return false;
335
+ const targets = [];
336
+ if (typeof data.main === "string")
337
+ targets.push(data.main);
338
+ if (typeof data.module === "string")
339
+ targets.push(data.module);
340
+ if (data.exports !== undefined)
341
+ collectRuntimeTargets(data.exports, "exports", targets);
342
+ for (const target of targets) {
343
+ const resolved = path.resolve(directory, target);
344
+ if (RUNTIME_FILE_PATTERN.test(resolved)
345
+ && !isDeclarationFile(resolved)
346
+ && ts.sys.fileExists(resolved)) {
347
+ return true;
348
+ }
349
+ }
350
+ return false;
351
+ }
352
+ const parent = path.dirname(directory);
353
+ if (parent === directory)
354
+ return false;
355
+ directory = parent;
356
+ }
357
+ }
358
+ function hasRuntimeModule(moduleName, containingFile, options) {
359
+ if (isBuiltinModule(moduleName))
360
+ return true;
361
+ const resolved = ts.resolveModuleName(moduleName, containingFile, options, ts.sys)
362
+ .resolvedModule;
363
+ if (resolved === undefined)
364
+ return false;
365
+ const fileName = resolved.resolvedFileName;
366
+ if (!isDeclarationFile(fileName)) {
367
+ return RUNTIME_FILE_PATTERN.test(fileName);
368
+ }
369
+ if (siblingRuntimeExists(fileName))
370
+ return true;
371
+ if (isRelativeModule(moduleName))
372
+ return false;
373
+ return packageRuntimeExists(fileName);
374
+ }
375
+ function rebaseModuleSpecifier(moduleName, importerFile, sourceFile, options) {
376
+ if (!isRelativeModule(moduleName))
377
+ return moduleName;
378
+ const resolved = ts.resolveModuleName(moduleName, importerFile, options, ts.sys)
379
+ .resolvedModule;
380
+ if (resolved === undefined)
381
+ return moduleName;
382
+ return relativeModuleSpecifier(sourceFile.fileName, resolved.resolvedFileName) ?? moduleName;
383
+ }
384
+ function exportedName(checker, symbol, sourceFile) {
385
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
386
+ if (moduleSymbol === undefined)
387
+ return null;
388
+ const targets = new Set([symbol, resolveAlias(checker, symbol)]);
389
+ let exports;
390
+ try {
391
+ exports = checker.getExportsOfModule(moduleSymbol);
392
+ }
393
+ catch {
394
+ return null;
395
+ }
396
+ for (const entry of exports) {
397
+ if (targets.has(entry) || targets.has(resolveAlias(checker, entry))) {
398
+ return entry.getName();
399
+ }
400
+ }
401
+ return null;
402
+ }
403
+ function typeOnlyExportSymbol(symbol) {
404
+ const declarations = symbol.declarations ?? [];
405
+ if (declarations.length === 0)
406
+ return false;
407
+ let sawSpecifier = false;
408
+ for (const declaration of declarations) {
409
+ if (!ts.isExportSpecifier(declaration))
410
+ return false;
411
+ sawSpecifier = true;
412
+ if (declaration.isTypeOnly)
413
+ continue;
414
+ const exportDeclaration = declaration.parent.parent;
415
+ if (!ts.isExportDeclaration(exportDeclaration) || !exportDeclaration.isTypeOnly) {
416
+ return false;
417
+ }
418
+ }
419
+ return sawSpecifier;
420
+ }
421
+ function moduleValueExportName(checker, moduleSymbol, targets, names) {
422
+ let exports;
423
+ try {
424
+ exports = checker.getExportsOfModule(moduleSymbol);
425
+ }
426
+ catch {
427
+ return null;
428
+ }
429
+ for (const name of names) {
430
+ for (const entry of exports) {
431
+ if (entry.getName() !== name)
432
+ continue;
433
+ if (typeOnlyExportSymbol(entry))
434
+ continue;
435
+ return entry.getName();
436
+ }
437
+ }
438
+ for (const entry of exports) {
439
+ if (typeOnlyExportSymbol(entry))
440
+ continue;
441
+ if (targets.has(entry) || targets.has(resolveAlias(checker, entry))) {
442
+ return entry.getName();
443
+ }
444
+ }
445
+ return null;
446
+ }
447
+ function typeOnlyReexport(checker, moduleSymbol, targets) {
448
+ let exports;
449
+ try {
450
+ exports = checker.getExportsOfModule(moduleSymbol);
451
+ }
452
+ catch {
453
+ return null;
454
+ }
455
+ for (const entry of exports) {
456
+ if (!typeOnlyExportSymbol(entry))
457
+ continue;
458
+ if (!targets.has(entry) && !targets.has(resolveAlias(checker, entry)))
459
+ continue;
460
+ for (const declaration of entry.declarations ?? []) {
461
+ if (!ts.isExportSpecifier(declaration))
462
+ continue;
463
+ const exportDeclaration = declaration.parent.parent;
464
+ if (!ts.isExportDeclaration(exportDeclaration))
465
+ continue;
466
+ const specifier = exportDeclaration.moduleSpecifier;
467
+ if (specifier === undefined || !ts.isStringLiteral(specifier))
468
+ continue;
469
+ return {
470
+ specifier: specifier.text,
471
+ moduleSymbol: checker.getSymbolAtLocation(specifier),
472
+ importerFile: exportDeclaration.getSourceFile().fileName,
473
+ name: entry.getName(),
474
+ };
475
+ }
476
+ }
477
+ return null;
478
+ }
479
+ function collectImportBindings(sourceFile, checker) {
480
+ const bindings = [];
481
+ for (const statement of sourceFile.statements) {
482
+ if (!ts.isImportDeclaration(statement))
483
+ continue;
484
+ if (!ts.isStringLiteral(statement.moduleSpecifier))
485
+ continue;
486
+ const clause = statement.importClause;
487
+ if (clause === undefined)
488
+ continue;
489
+ const moduleName = statement.moduleSpecifier.text;
490
+ const moduleSymbol = checker.getSymbolAtLocation(statement.moduleSpecifier);
491
+ if (clause.name !== undefined) {
492
+ const symbol = checker.getSymbolAtLocation(clause.name);
493
+ if (symbol !== undefined) {
494
+ bindings.push({
495
+ symbol,
496
+ localName: clause.name.text,
497
+ module: moduleName,
498
+ moduleSymbol,
499
+ typeOnly: clause.isTypeOnly,
500
+ kind: "default",
501
+ exportedName: "default",
502
+ });
503
+ }
504
+ }
505
+ const namedBindings = clause.namedBindings;
506
+ if (namedBindings === undefined)
507
+ continue;
508
+ if (ts.isNamespaceImport(namedBindings)) {
509
+ const symbol = checker.getSymbolAtLocation(namedBindings.name);
510
+ if (symbol !== undefined) {
511
+ bindings.push({
512
+ symbol,
513
+ localName: namedBindings.name.text,
514
+ module: moduleName,
515
+ moduleSymbol,
516
+ typeOnly: clause.isTypeOnly,
517
+ kind: "namespace",
518
+ });
519
+ }
520
+ continue;
521
+ }
522
+ for (const element of namedBindings.elements) {
523
+ const symbol = checker.getSymbolAtLocation(element.name);
524
+ if (symbol === undefined)
525
+ continue;
526
+ bindings.push({
527
+ symbol,
528
+ localName: element.name.text,
529
+ module: moduleName,
530
+ moduleSymbol,
531
+ typeOnly: clause.isTypeOnly || element.isTypeOnly,
532
+ kind: "named",
533
+ exportedName: element.propertyName?.text ?? element.name.text,
534
+ });
535
+ }
536
+ }
537
+ return bindings;
538
+ }
539
+ function moduleSpecifierFor(sourceFile, declarationFile, checker) {
540
+ const declarationModule = checker.getSymbolAtLocation(declarationFile);
541
+ for (const statement of sourceFile.statements) {
542
+ if (!ts.isImportDeclaration(statement))
543
+ continue;
544
+ if (!ts.isStringLiteral(statement.moduleSpecifier))
545
+ continue;
546
+ const moduleSymbol = checker.getSymbolAtLocation(statement.moduleSpecifier);
547
+ if (moduleSymbol !== undefined && moduleSymbol === declarationModule) {
548
+ return statement.moduleSpecifier.text;
549
+ }
550
+ }
551
+ return relativeModuleSpecifier(sourceFile.fileName, declarationFile.fileName);
552
+ }
553
+ function relativeModuleSpecifier(fromFile, toFile) {
554
+ let relative = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, "/");
555
+ if (relative.length === 0)
556
+ return null;
557
+ relative = relative.replace(/\.d\.[cm]?ts$/i, "").replace(/\.(?:[cm]?ts|tsx)$/i, "");
558
+ if (!relative.startsWith("."))
559
+ relative = `./${relative}`;
560
+ return relative;
561
+ }
562
+ function collectUsedNames(sourceFile) {
563
+ const names = new Set();
564
+ const visit = (node) => {
565
+ if (ts.isIdentifier(node))
566
+ names.add(node.text);
567
+ ts.forEachChild(node, visit);
568
+ };
569
+ visit(sourceFile);
570
+ return names;
571
+ }
572
+ function createRuntimeRefResolver(sourceFile, checker, options) {
573
+ const bindings = collectImportBindings(sourceFile, checker);
574
+ const usedNames = collectUsedNames(sourceFile);
575
+ const aliases = new Map();
576
+ const imports = [];
577
+ const runtimeModules = new Map();
578
+ const moduleHasRuntime = (moduleName) => {
579
+ const cached = runtimeModules.get(moduleName);
580
+ if (cached !== undefined)
581
+ return cached;
582
+ const result = hasRuntimeModule(moduleName, sourceFile.fileName, options);
583
+ runtimeModules.set(moduleName, result);
584
+ return result;
585
+ };
586
+ const valueTargetFor = (symbol, declarationFile) => {
587
+ const matching = bindings.filter((entry) => symbolsEqual(checker, entry.symbol, symbol));
588
+ const targets = new Set([symbol, resolveAlias(checker, symbol)]);
589
+ const names = new Set();
590
+ for (const entry of matching) {
591
+ if (entry.exportedName !== undefined)
592
+ names.add(entry.exportedName);
593
+ }
594
+ const ownName = declarationName(symbol);
595
+ if (ownName !== null)
596
+ names.add(ownName);
597
+ const primary = matching.find((entry) => entry.kind !== "namespace") ?? matching[0];
598
+ let moduleName = primary?.module
599
+ ?? (declarationFile === null
600
+ ? null
601
+ : moduleSpecifierFor(sourceFile, declarationFile, checker));
602
+ let moduleSymbol = primary?.moduleSymbol
603
+ ?? (declarationFile === null ? undefined : checker.getSymbolAtLocation(declarationFile));
604
+ let exportedNames = [...names];
605
+ const visited = new Set();
606
+ for (let depth = 0; depth < 16; depth += 1) {
607
+ if (moduleName === null)
608
+ return null;
609
+ const key = `${moduleName}\u0000${moduleSymbol?.getName() ?? ""}`;
610
+ if (visited.has(key))
611
+ return null;
612
+ visited.add(key);
613
+ if (moduleSymbol !== undefined) {
614
+ const valueName = moduleValueExportName(checker, moduleSymbol, targets, exportedNames);
615
+ if (valueName !== null)
616
+ return { module: moduleName, name: valueName };
617
+ const reexport = typeOnlyReexport(checker, moduleSymbol, targets);
618
+ if (reexport !== null) {
619
+ moduleName = rebaseModuleSpecifier(reexport.specifier, reexport.importerFile, sourceFile, options);
620
+ moduleSymbol = reexport.moduleSymbol;
621
+ exportedNames = [reexport.name, ...exportedNames];
622
+ continue;
623
+ }
624
+ }
625
+ return null;
626
+ }
627
+ return null;
628
+ };
629
+ const runtimeIssue = (symbol) => {
630
+ const info = declarationInfo(checker, symbol);
631
+ if (info === null)
632
+ return null;
633
+ if (isGlobalAugmentation(info.declaration)) {
634
+ return "глобальная декларация без рантайм-модуля";
635
+ }
636
+ if (info.file.fileName === sourceFile.fileName)
637
+ return null;
638
+ if (isGlobalDeclaration(info.file)) {
639
+ if (!isDeclarationFile(info.file.fileName))
640
+ return null;
641
+ if (isDefaultLibraryFile(info.file))
642
+ return null;
643
+ const ambient = ambientModuleName(info.declaration);
644
+ if (ambient === null)
645
+ return "глобальная декларация без рантайм-модуля";
646
+ return moduleHasRuntime(ambient) ? null : ambient;
647
+ }
648
+ const target = valueTargetFor(symbol, info.file);
649
+ if (target !== null && moduleHasRuntime(target.module))
650
+ return null;
651
+ const matching = bindings.filter((entry) => symbolsEqual(checker, entry.symbol, symbol));
652
+ const moduleName = target?.module
653
+ ?? matching[0]?.module
654
+ ?? moduleSpecifierFor(sourceFile, info.file, checker);
655
+ if (moduleName === null)
656
+ return null;
657
+ return moduleHasRuntime(moduleName) ? null : moduleName;
658
+ };
659
+ const aliasFor = (moduleName) => {
660
+ const existing = aliases.get(moduleName);
661
+ if (existing !== undefined)
662
+ return existing;
663
+ let counter = 1;
664
+ let alias = `${NAMESPACE_ALIAS_PREFIX}${counter}`;
665
+ while (usedNames.has(alias)) {
666
+ counter += 1;
667
+ alias = `${NAMESPACE_ALIAS_PREFIX}${counter}`;
668
+ }
669
+ usedNames.add(alias);
670
+ aliases.set(moduleName, alias);
671
+ imports.push({ module: moduleName, alias });
672
+ return alias;
673
+ };
674
+ const bindingReference = (symbol, moduleName, name) => {
675
+ const matching = bindings.filter((entry) => symbolsEqual(checker, entry.symbol, symbol));
676
+ const valueBinding = matching.find((entry) => !entry.typeOnly && entry.kind !== "namespace" && entry.module === moduleName);
677
+ if (valueBinding !== undefined)
678
+ return valueBinding.localName;
679
+ const namespaceBinding = bindings.find((entry) => entry.kind === "namespace"
680
+ && entry.module === moduleName
681
+ && !entry.typeOnly);
682
+ if (namespaceBinding !== undefined)
683
+ return `${namespaceBinding.localName}.${name}`;
684
+ return `${aliasFor(moduleName)}.${name}`;
685
+ };
686
+ const runtimeRef = (symbol) => {
687
+ const info = declarationInfo(checker, symbol);
688
+ if (info === null)
689
+ return "undefined";
690
+ if (isGlobalAugmentation(info.declaration))
691
+ return "undefined";
692
+ if (info.file.fileName === sourceFile.fileName) {
693
+ return localQualifiedName(checker, symbol) ?? "undefined";
694
+ }
695
+ if (isGlobalDeclaration(info.file)) {
696
+ if (!isDeclarationFile(info.file.fileName) || isDefaultLibraryFile(info.file)) {
697
+ return localQualifiedName(checker, symbol) ?? "undefined";
698
+ }
699
+ const ambient = ambientModuleName(info.declaration);
700
+ if (ambient === null)
701
+ return "undefined";
702
+ if (!moduleHasRuntime(ambient))
703
+ return "undefined";
704
+ const name = declarationName(symbol) ?? symbol.getName();
705
+ return bindingReference(symbol, ambient, name);
706
+ }
707
+ if (runtimeIssue(symbol) !== null) {
708
+ return "undefined";
709
+ }
710
+ const target = valueTargetFor(symbol, info.file);
711
+ if (target !== null && moduleHasRuntime(target.module)) {
712
+ return bindingReference(symbol, target.module, target.name);
713
+ }
714
+ const matching = bindings.filter((entry) => symbolsEqual(checker, entry.symbol, symbol));
715
+ const name = matching.find((entry) => entry.exportedName !== undefined)?.exportedName
716
+ ?? exportedName(checker, symbol, info.file);
717
+ if (name === null) {
718
+ return localQualifiedName(checker, symbol) ?? "undefined";
719
+ }
720
+ const moduleName = matching[0]?.module
721
+ ?? moduleSpecifierFor(sourceFile, info.file, checker);
722
+ if (moduleName === null)
723
+ return "undefined";
724
+ return bindingReference(symbol, moduleName, name);
725
+ };
726
+ return { runtimeRef, runtimeIssue, imports };
727
+ }
728
+ function closingPosition(sourceFile, declaration) {
729
+ const end = declaration.getEnd();
730
+ const position = end - 1;
731
+ if (sourceFile.text[position] === "}") {
732
+ return position;
733
+ }
734
+ const fallback = sourceFile.text.lastIndexOf("}", end);
735
+ return fallback >= 0 ? fallback : position;
736
+ }
737
+ function hasDefaultModifier(declaration) {
738
+ const modifiers = ts.getModifiers(declaration);
739
+ return modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) ?? false;
740
+ }
741
+ function classLikeName(declaration) {
742
+ if (declaration.name !== undefined)
743
+ return declaration.name.text;
744
+ const parent = declaration.parent;
745
+ if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) {
746
+ return parent.name.text;
747
+ }
748
+ if (ts.isPropertyDeclaration(parent) && ts.isIdentifier(parent.name)) {
749
+ return parent.name.text;
750
+ }
751
+ if (ts.isPropertyAssignment(parent)) {
752
+ if (ts.isIdentifier(parent.name) || ts.isStringLiteral(parent.name)) {
753
+ return parent.name.text;
754
+ }
755
+ }
756
+ if (ts.isArrayLiteralExpression(parent)) {
757
+ const index = parent.elements.indexOf(declaration);
758
+ const owner = parent.parent;
759
+ const ownerName = ts.isVariableDeclaration(owner) && ts.isIdentifier(owner.name)
760
+ ? owner.name.text
761
+ : ts.isPropertyAssignment(owner)
762
+ && (ts.isIdentifier(owner.name) || ts.isStringLiteral(owner.name))
763
+ ? owner.name.text
764
+ : null;
765
+ if (ownerName !== null && index >= 0)
766
+ return `${ownerName}[${index}]`;
767
+ }
768
+ if (ts.isClassDeclaration(declaration) && hasDefaultModifier(declaration)) {
769
+ return "default";
770
+ }
771
+ return undefined;
772
+ }
773
+ function unavailableFieldsOf(block) {
774
+ if (block.unavailableFields !== undefined)
775
+ return block.unavailableFields;
776
+ if (block.fields === undefined)
777
+ return [];
778
+ return [...block.fields]
779
+ .filter(([, schema]) => schemaHasClassRef(schema))
780
+ .map(([name]) => name);
781
+ }
782
+ function collectSkippedFields(sourceFile, checker, blocks, report) {
783
+ const skipped = new Map();
784
+ const declarations = new Map();
785
+ const collect = (node) => {
786
+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {
787
+ declarations.set(closingPosition(sourceFile, node), node);
788
+ }
789
+ ts.forEachChild(node, collect);
790
+ };
791
+ collect(sourceFile);
792
+ for (const block of blocks) {
793
+ const unavailable = unavailableFieldsOf(block);
794
+ if (unavailable.length === 0)
795
+ continue;
796
+ const declaration = declarations.get(block.position);
797
+ const className = block.className
798
+ ?? (declaration === undefined ? "class" : classLikeName(declaration) ?? "class");
799
+ const members = new Map();
800
+ for (const member of declaration?.members ?? []) {
801
+ if (ts.isAutoAccessorPropertyDeclaration(member) && ts.isIdentifier(member.name)) {
802
+ members.set(member.name.text, member);
803
+ }
804
+ }
805
+ for (const field of unavailable) {
806
+ const member = members.get(field);
807
+ const typeText = member?.type === undefined
808
+ ? field
809
+ : checker.typeToString(checker.getTypeFromTypeNode(member.type));
810
+ report(`${sourceFile.fileName}: ${className}.${field}: тип ${typeText} ссылается на класс, недоступный в рантайме`);
811
+ }
812
+ skipped.set(block.position, new Set(unavailable));
813
+ }
814
+ return skipped;
815
+ }
816
+ function findFieldsBounds(code) {
817
+ const marker = "fields: {";
818
+ const index = code.indexOf(marker);
819
+ if (index < 0)
820
+ return null;
821
+ const open = index + marker.length - 1;
822
+ let depth = 0;
823
+ let quote = null;
824
+ let escaped = false;
825
+ for (let position = open; position < code.length; position += 1) {
826
+ const char = code[position];
827
+ if (quote !== null) {
828
+ if (escaped) {
829
+ escaped = false;
830
+ }
831
+ else if (char === "\\") {
832
+ escaped = true;
833
+ }
834
+ else if (char === quote) {
835
+ quote = null;
836
+ }
837
+ continue;
838
+ }
839
+ if (char === '"' || char === "'" || char === "`") {
840
+ quote = char;
841
+ continue;
842
+ }
843
+ if (char === "{" || char === "[" || char === "(") {
844
+ depth += 1;
845
+ continue;
846
+ }
847
+ if (char === "}" || char === "]" || char === ")") {
848
+ depth -= 1;
849
+ if (depth === 0)
850
+ return { open, close: position };
851
+ }
852
+ }
853
+ return null;
854
+ }
855
+ function splitTopLevel(text) {
856
+ const parts = [];
857
+ let depth = 0;
858
+ let start = 0;
859
+ let quote = null;
860
+ let escaped = false;
861
+ for (let position = 0; position < text.length; position += 1) {
862
+ const char = text[position];
863
+ if (quote !== null) {
864
+ if (escaped) {
865
+ escaped = false;
866
+ }
867
+ else if (char === "\\") {
868
+ escaped = true;
869
+ }
870
+ else if (char === quote) {
871
+ quote = null;
872
+ }
873
+ continue;
874
+ }
875
+ if (char === '"' || char === "'" || char === "`") {
876
+ quote = char;
877
+ continue;
878
+ }
879
+ if (char === "{" || char === "[" || char === "(") {
880
+ depth += 1;
881
+ continue;
882
+ }
883
+ if (char === "}" || char === "]" || char === ")") {
884
+ depth -= 1;
885
+ continue;
886
+ }
887
+ if (char === "," && depth === 0) {
888
+ parts.push(text.slice(start, position));
889
+ start = position + 1;
890
+ }
891
+ }
892
+ parts.push(text.slice(start));
893
+ return parts.map((part) => part.trim()).filter((part) => part.length > 0);
894
+ }
895
+ function entryFieldName(entry) {
896
+ const match = /^("(?:[^"\\]|\\.)*")\s*:/.exec(entry);
897
+ if (match === null || match[1] === undefined)
898
+ return null;
899
+ try {
900
+ const parsed = JSON.parse(match[1]);
901
+ return typeof parsed === "string" ? parsed : null;
902
+ }
903
+ catch {
904
+ return null;
905
+ }
906
+ }
907
+ function stripUnusedLazyDefinitions(code, fieldsText) {
908
+ const definitionPattern = /^([ \t]*)const (lazy\d+) = (.*);\r?$/;
909
+ const definitions = new Map();
910
+ for (const line of code.split("\n")) {
911
+ const match = definitionPattern.exec(line);
912
+ if (match === null || match[2] === undefined || match[3] === undefined)
913
+ continue;
914
+ definitions.set(match[2], match[3]);
915
+ }
916
+ if (definitions.size === 0)
917
+ return code;
918
+ const needed = new Set();
919
+ const queue = [];
920
+ const scan = (text) => {
921
+ for (const match of text.matchAll(/\blazy\d+\b/g)) {
922
+ const name = match[0];
923
+ if (needed.has(name))
924
+ continue;
925
+ needed.add(name);
926
+ queue.push(name);
927
+ }
928
+ };
929
+ scan(fieldsText);
930
+ while (queue.length > 0) {
931
+ const name = queue.pop();
932
+ if (name === undefined)
933
+ continue;
934
+ const body = definitions.get(name);
935
+ if (body !== undefined)
936
+ scan(body);
937
+ }
938
+ const lines = code.split("\n").filter((line) => {
939
+ const match = definitionPattern.exec(line);
940
+ if (match === null || match[2] === undefined)
941
+ return true;
942
+ return needed.has(match[2]);
943
+ });
944
+ return lines.join("\n");
945
+ }
946
+ function stripSkippedFields(block, skipped) {
947
+ if (skipped === undefined || skipped.size === 0)
948
+ return block.code;
949
+ const bounds = findFieldsBounds(block.code);
950
+ if (bounds === null)
951
+ return block.code;
952
+ const entries = splitTopLevel(block.code.slice(bounds.open + 1, bounds.close));
953
+ const kept = entries.filter((entry) => {
954
+ const name = entryFieldName(entry);
955
+ return name === null || !skipped.has(name);
956
+ });
957
+ if (kept.length === 0)
958
+ return null;
959
+ const fieldsText = ` ${kept.join(", ")} `;
960
+ const updated = `${block.code.slice(0, bounds.open + 1)}${fieldsText}${block.code.slice(bounds.close)}`;
961
+ return stripUnusedLazyDefinitions(updated, fieldsText);
962
+ }
963
+ function importInsertionPosition(code) {
964
+ let position = code.charCodeAt(0) === 0xfeff ? 1 : 0;
965
+ if (code.startsWith("#!", position)) {
966
+ const newline = code.indexOf("\n", position);
967
+ position = newline < 0 ? code.length : newline + 1;
968
+ }
969
+ for (;;) {
970
+ const trivia = /^(?:\s+|\/\/[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/.exec(code.slice(position));
971
+ const cursor = position + (trivia?.[0].length ?? 0);
972
+ const directive = /^(?:"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*')/.exec(code.slice(cursor));
973
+ if (directive === null)
974
+ return cursor;
975
+ let end = cursor + directive[0].length;
976
+ const semicolon = /^\s*;/.exec(code.slice(end));
977
+ if (semicolon !== null)
978
+ end += semicolon[0].length;
979
+ position = end;
980
+ }
981
+ }
982
+ function readProject(configPath) {
983
+ const config = ts.readConfigFile(configPath, ts.sys.readFile);
984
+ if (config.error !== undefined) {
985
+ throw new Error(`@ivlev-dev/silent-validation: не удалось прочитать ${configPath}: ${ts.flattenDiagnosticMessageText(config.error.messageText, "\n")}`);
986
+ }
987
+ const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, path.dirname(configPath), undefined, configPath);
988
+ const errors = parsed.errors.filter((diagnostic) => diagnostic.code !== 18003);
989
+ if (errors.length > 0) {
990
+ const details = errors
991
+ .map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"))
992
+ .join("\n");
993
+ throw new Error(`@ivlev-dev/silent-validation: ошибка конфигурации ${configPath}:\n${details}`);
994
+ }
995
+ return {
996
+ configPath,
997
+ rootNames: parsed.fileNames,
998
+ options: { ...parsed.options, noEmit: true },
999
+ projectReferences: parsed.projectReferences,
1000
+ };
1001
+ }
1002
+ function fallbackProject() {
1003
+ return {
1004
+ configPath: null,
1005
+ rootNames: [],
1006
+ options: DEFAULT_COMPILER_OPTIONS,
1007
+ projectReferences: undefined,
1008
+ };
1009
+ }
1010
+ function createCompilerHost(options, cache, changedFiles) {
1011
+ const host = ts.createCompilerHost(options, true);
1012
+ const readSourceFile = host.getSourceFile.bind(host);
1013
+ const changed = new Set([...changedFiles].map((fileName) => path.resolve(fileName)));
1014
+ host.getSourceFile = (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
1015
+ const previous = cache.previous;
1016
+ if (previous !== undefined
1017
+ && shouldCreateNewSourceFile !== true
1018
+ && !changed.has(path.resolve(fileName))) {
1019
+ const cached = previous.getSourceFile(fileName);
1020
+ if (cached !== undefined)
1021
+ return cached;
1022
+ }
1023
+ return readSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
1024
+ };
1025
+ return host;
1026
+ }
1027
+ export function validation(options = {}) {
1028
+ const include = options.include ?? DEFAULT_INCLUDE;
1029
+ const exclude = options.exclude ?? DEFAULT_EXCLUDE;
1030
+ const baseName = options.base ?? "ValidationModel";
1031
+ const strict = options.strict === true;
1032
+ const programs = new Map();
1033
+ const baseSymbols = new WeakMap();
1034
+ const watchedFiles = new WeakMap();
1035
+ const registeredWatchFiles = new WeakMap();
1036
+ let root = process.cwd();
1037
+ const watchFilesFor = (entry) => {
1038
+ const cached = watchedFiles.get(entry.program);
1039
+ if (cached !== undefined)
1040
+ return cached;
1041
+ const files = programWatchFiles(entry);
1042
+ watchedFiles.set(entry.program, files);
1043
+ return files;
1044
+ };
1045
+ const registerWatchFiles = (entry, context) => {
1046
+ if (context?.addWatchFile === undefined)
1047
+ return;
1048
+ let registered = registeredWatchFiles.get(entry.program);
1049
+ if (registered === undefined) {
1050
+ registered = new Set();
1051
+ registeredWatchFiles.set(entry.program, registered);
1052
+ }
1053
+ for (const file of watchFilesFor(entry)) {
1054
+ if (registered.has(file))
1055
+ continue;
1056
+ registered.add(file);
1057
+ context.addWatchFile(file);
1058
+ }
1059
+ };
1060
+ const baseSymbolsFor = (program, checker) => {
1061
+ const cached = baseSymbols.get(program);
1062
+ if (cached !== undefined)
1063
+ return cached;
1064
+ const symbols = findBaseSymbols(program, checker, baseName);
1065
+ baseSymbols.set(program, symbols);
1066
+ return symbols;
1067
+ };
1068
+ const resolveConfigPath = (file) => {
1069
+ if (options.tsconfig !== undefined) {
1070
+ return path.isAbsolute(options.tsconfig)
1071
+ ? options.tsconfig
1072
+ : path.resolve(root, options.tsconfig);
1073
+ }
1074
+ return ts.findConfigFile(path.dirname(file), ts.sys.fileExists, "tsconfig.json") ?? null;
1075
+ };
1076
+ const invalidate = (file, reloadProject) => {
1077
+ const cleaned = cleanModuleId(file);
1078
+ if (cleaned.endsWith(".json")) {
1079
+ programs.clear();
1080
+ return;
1081
+ }
1082
+ for (const entry of programs.values()) {
1083
+ if (reloadProject) {
1084
+ entry.reloadProject = true;
1085
+ entry.dirty = true;
1086
+ entry.changedFiles.add(cleaned);
1087
+ continue;
1088
+ }
1089
+ if (entry.program.getSourceFile(cleaned) !== undefined) {
1090
+ entry.dirty = true;
1091
+ entry.changedFiles.add(cleaned);
1092
+ }
1093
+ }
1094
+ };
1095
+ const createProgramEntry = (file, project, previous) => {
1096
+ const rootNames = new Set();
1097
+ const addRoot = (name) => {
1098
+ if (name === file || ts.sys.fileExists(name))
1099
+ rootNames.add(name);
1100
+ };
1101
+ if (previous !== undefined && !previous.reloadProject) {
1102
+ for (const name of previous.rootNames)
1103
+ addRoot(name);
1104
+ }
1105
+ for (const name of project.rootNames)
1106
+ addRoot(name);
1107
+ addRoot(file);
1108
+ const changedFiles = previous?.changedFiles ?? new Set();
1109
+ const cache = { previous: previous?.program };
1110
+ let created;
1111
+ try {
1112
+ created = ts.createProgram({
1113
+ rootNames: [...rootNames],
1114
+ options: project.options,
1115
+ host: createCompilerHost(project.options, cache, changedFiles),
1116
+ ...(previous === undefined ? {} : { oldProgram: previous.program }),
1117
+ ...(project.projectReferences === undefined
1118
+ ? {}
1119
+ : { projectReferences: project.projectReferences }),
1120
+ });
1121
+ }
1122
+ finally {
1123
+ cache.previous = undefined;
1124
+ }
1125
+ return {
1126
+ program: created,
1127
+ rootNames,
1128
+ project,
1129
+ warnings: new Set(),
1130
+ decisions: new WeakMap(),
1131
+ changedFiles: new Set(),
1132
+ dirty: false,
1133
+ reloadProject: false,
1134
+ };
1135
+ };
1136
+ const programEntryFor = (file) => {
1137
+ const configPath = resolveConfigPath(file);
1138
+ const key = configPath ?? "<fallback>";
1139
+ const cached = programs.get(key);
1140
+ if (cached === undefined) {
1141
+ const project = configPath === null ? fallbackProject() : readProject(configPath);
1142
+ const created = createProgramEntry(file, project, undefined);
1143
+ programs.set(key, created);
1144
+ return created;
1145
+ }
1146
+ if (!cached.dirty && cached.program.getSourceFile(file) !== undefined) {
1147
+ return cached;
1148
+ }
1149
+ let project = cached.project;
1150
+ if (cached.reloadProject) {
1151
+ project = project.configPath === null ? fallbackProject() : readProject(project.configPath);
1152
+ }
1153
+ const created = createProgramEntry(file, project, cached);
1154
+ programs.set(key, created);
1155
+ return created;
1156
+ };
1157
+ const shouldTransform = (id, file) => {
1158
+ if (isVirtualModule(id) || isVirtualModule(file))
1159
+ return false;
1160
+ if (isDeclarationFile(file))
1161
+ return false;
1162
+ if (!matchesPattern(include, file))
1163
+ return false;
1164
+ if (matchesPattern(exclude, file))
1165
+ return false;
1166
+ return true;
1167
+ };
1168
+ return {
1169
+ name: "silent-validation",
1170
+ enforce: "pre",
1171
+ configResolved(config) {
1172
+ root = config.root;
1173
+ },
1174
+ configureServer(server) {
1175
+ server.watcher.on("change", (file) => {
1176
+ invalidate(file, false);
1177
+ });
1178
+ server.watcher.on("add", (file) => {
1179
+ invalidate(file, true);
1180
+ });
1181
+ server.watcher.on("unlink", (file) => {
1182
+ invalidate(file, true);
1183
+ });
1184
+ },
1185
+ watchChange(id) {
1186
+ invalidate(id, false);
1187
+ },
1188
+ transform: {
1189
+ order: "pre",
1190
+ handler(code, id) {
1191
+ if (hasUnsafeQuery(id))
1192
+ return null;
1193
+ const file = cleanModuleId(id);
1194
+ if (!shouldTransform(id, file))
1195
+ return null;
1196
+ if (!ACCESSOR_PATTERN.test(code) || !EXTENDS_PATTERN.test(code))
1197
+ return null;
1198
+ const context = this;
1199
+ const entry = programEntryFor(file);
1200
+ if (entry === null)
1201
+ return null;
1202
+ registerWatchFiles(entry, context);
1203
+ const sourceFile = entry.program.getSourceFile(file);
1204
+ if (sourceFile === undefined)
1205
+ return null;
1206
+ const transformedBefore = code !== sourceFile.text;
1207
+ if (transformedBefore && hasGeneratedSchema(code))
1208
+ return null;
1209
+ const warn = (message) => {
1210
+ if (entry.warnings.has(message))
1211
+ return;
1212
+ entry.warnings.add(message);
1213
+ context?.warn?.(message);
1214
+ };
1215
+ let offset = 0;
1216
+ if (transformedBefore) {
1217
+ const index = code.indexOf(sourceFile.text);
1218
+ if (index < 0) {
1219
+ warn(`${file}: код изменён до плагина silent-validation, схема не сгенерирована`);
1220
+ return null;
1221
+ }
1222
+ offset = index;
1223
+ }
1224
+ const checker = entry.program.getTypeChecker();
1225
+ const targets = baseSymbolsFor(entry.program, checker);
1226
+ const resolver = createRuntimeRefResolver(sourceFile, checker, entry.project.options);
1227
+ const shouldGenerate = (declaration) => {
1228
+ const cached = entry.decisions.get(declaration);
1229
+ if (cached !== undefined)
1230
+ return cached;
1231
+ const result = extendsTarget(instanceTypeOf(checker, declaration), checker, baseName, targets.size > 0 ? [...targets] : [], new Set());
1232
+ entry.decisions.set(declaration, result);
1233
+ return result;
1234
+ };
1235
+ const blocks = generateValidationBlocks({
1236
+ sourceFile,
1237
+ checker,
1238
+ runtimeRef: resolver.runtimeRef,
1239
+ shouldGenerate,
1240
+ diagnostics: warn,
1241
+ strict,
1242
+ });
1243
+ const skippedFields = collectSkippedFields(sourceFile, checker, blocks, (message) => {
1244
+ if (strict)
1245
+ throw new Error(message);
1246
+ warn(message);
1247
+ });
1248
+ if (blocks.length === 0)
1249
+ return null;
1250
+ const magic = new MagicString(code);
1251
+ let kept = 0;
1252
+ for (const block of blocks) {
1253
+ const rendered = stripSkippedFields(block, skippedFields.get(block.position));
1254
+ if (rendered === null)
1255
+ continue;
1256
+ magic.appendLeft(block.position + offset, rendered);
1257
+ kept += 1;
1258
+ }
1259
+ if (kept === 0)
1260
+ return null;
1261
+ const body = magic.toString();
1262
+ const usedImports = resolver.imports.filter((entry) => {
1263
+ const pattern = new RegExp(`\\b${entry.alias}\\b`);
1264
+ return pattern.test(body);
1265
+ });
1266
+ if (usedImports.length > 0) {
1267
+ const newline = sourceFile.text.includes("\r\n") ? "\r\n" : "\n";
1268
+ const statements = usedImports
1269
+ .map((entry) => `import * as ${entry.alias} from ${JSON.stringify(entry.module)};`)
1270
+ .join(newline);
1271
+ magic.appendLeft(importInsertionPosition(code), `${statements}${newline}`);
1272
+ }
1273
+ return {
1274
+ code: magic.toString(),
1275
+ map: magic.generateMap({
1276
+ hires: true,
1277
+ source: file,
1278
+ includeContent: true,
1279
+ }),
1280
+ };
1281
+ },
1282
+ },
1283
+ };
1284
+ }
1285
+ export default validation;
1286
+ //# sourceMappingURL=vite.js.map