@lenne.tech/nest-server 12.8.5 → 12.8.7

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.
Files changed (35) hide show
  1. package/.claude/rules/architecture.md +1 -0
  2. package/.claude/rules/configurable-features.md +2 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/CLAUDE.md +4 -0
  5. package/FRAMEWORK-API.md +1 -1
  6. package/bin/check-unified-field-types.js +615 -0
  7. package/dist/core/common/decorators/unified-field.decorator.js +36 -1
  8. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  9. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  10. package/dist/core/modules/ai/core-ai-mcp.controller.d.ts +1 -0
  11. package/dist/core/modules/ai/core-ai-mcp.controller.js +11 -0
  12. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  13. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.d.ts +33 -0
  14. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js +74 -9
  15. package/dist/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.js.map +1 -1
  16. package/dist/core/modules/ai/index.d.ts +2 -2
  17. package/dist/core/modules/ai/index.js +1 -1
  18. package/dist/core/modules/ai/index.js.map +1 -1
  19. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +17 -1
  20. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +124 -8
  21. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  22. package/docs/REQUEST-LIFECYCLE.md +9 -1
  23. package/migration-guides/11.43.x-to-12.0.x.md +22 -2
  24. package/migration-guides/12.0.x-to-12.1.x.md +6 -0
  25. package/migration-guides/12.8.5-to-12.8.6.md +144 -0
  26. package/migration-guides/12.8.6-to-12.8.7.md +112 -0
  27. package/package.json +20 -18
  28. package/src/core/common/decorators/unified-field.decorator.ts +63 -1
  29. package/src/core/common/interfaces/server-options.interface.ts +18 -0
  30. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +8 -0
  31. package/src/core/modules/ai/README.md +66 -0
  32. package/src/core/modules/ai/core-ai-mcp.controller.ts +17 -0
  33. package/src/core/modules/ai/helpers/ai-mcp-oauth-consent.helper.ts +150 -11
  34. package/src/core/modules/ai/index.ts +5 -1
  35. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +222 -8
@@ -0,0 +1,615 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-unified-field-types — every `@UnifiedField` gets a runtime type both compilers agree on.
4
+ *
5
+ * `@UnifiedField` reads a field's type from the `design:type` metadata when no `type` is given. tsc
6
+ * (the build) writes that metadata with the type checker; the SWC loader of the dev start writes it
7
+ * syntactically, file by file. Where the two disagree, the dev API validates, documents and
8
+ * generates client types differently from the deployed one:
9
+ *
10
+ * field SWC (dev start) tsc (build, strict: false)
11
+ * max?: null | number Object Number
12
+ * kind?: Kind (type alias) Object String
13
+ * status?: Status | null (enum) Object String / Number
14
+ * flag?: boolean | null Object Boolean
15
+ * meta?: Record<string, unknown> Object Object
16
+ * state?: 'ok' | 'error' (in place) String String
17
+ *
18
+ * A plain enum (`status?: Status`) is no finding: SWC writes the enum object there, and @UnifiedField reads it as
19
+ * String / Number like tsc since 12.8.7.
20
+ *
21
+ * `Object` makes `@UnifiedField` validate the field as a nested object, so the dev API refuses
22
+ * `max: 5` while the build accepts it. This script finds every `@UnifiedField` without `type`,
23
+ * `isAny` or `enum` whose declared type is not one both compilers emit the same way (`number`,
24
+ * `string`, `boolean`, `Date`, a class imported as a value, an enum, a union of string literals
25
+ * written in place), and resolves with the type checker the runtime type the tsc build uses.
26
+ * `--fix` writes exactly that as `type: () => X`, so the deployed behaviour stays as it is and the
27
+ * dev start matches it. Where the tsc build writes something else today — Object for a union with
28
+ * null / undefined under strictNullChecks, for a generic alias, for a field without a type
29
+ * annotation — the field is marked "[changes the deployed build]": the type written for it (the one
30
+ * the field declares) changes its deployed validation. The comparison reads tsc's own emit. A field whose type has no
31
+ * runtime class (an interface, a `Record`, a mixed union, `any`) is reported with what to declare
32
+ * instead.
33
+ *
34
+ * Usage:
35
+ * node <nest-server>/bin/check-unified-field-types.js [--fix] [--project tsconfig.json] [--include src]
36
+ * (npm mode: the package bin `nest-check-unified-field-types`)
37
+ *
38
+ * Exit codes: 0 nothing to do, 1 findings left (without --fix: any; with --fix: the ones it cannot
39
+ * fix), 2 usage or configuration error.
40
+ */
41
+ 'use strict';
42
+
43
+ const fs = require('node:fs');
44
+ const path = require('node:path');
45
+ const { createRequire } = require('node:module');
46
+
47
+ const PREFIX = '[unified-field-types]';
48
+
49
+ function usage() {
50
+ return [
51
+ 'Usage: check-unified-field-types [--fix] [--project <tsconfig>] [--include <dir>]...',
52
+ '',
53
+ ' --fix write `type: () => X` into every field the checker can resolve',
54
+ ' --project, -p tsconfig to build the program from (default: tsconfig.json)',
55
+ ' --include directory to check, repeatable (default: src)',
56
+ ].join('\n');
57
+ }
58
+
59
+ function parseArgs(argv) {
60
+ const args = { fix: false, help: false, include: [], project: 'tsconfig.json' };
61
+ for (let i = 0; i < argv.length; i++) {
62
+ const arg = argv[i];
63
+ if (arg === '--') {
64
+ // `pnpm run <script> -- --fix` passes the separator through (npm and yarn drop it)
65
+ continue;
66
+ }
67
+ if (arg === '--fix') {
68
+ args.fix = true;
69
+ } else if (arg === '--help' || arg === '-h') {
70
+ args.help = true;
71
+ } else if (arg === '--project' || arg === '-p') {
72
+ args.project = argv[++i];
73
+ } else if (arg.startsWith('--project=')) {
74
+ args.project = arg.slice('--project='.length);
75
+ } else if (arg === '--include') {
76
+ args.include.push(argv[++i]);
77
+ } else if (arg.startsWith('--include=')) {
78
+ args.include.push(arg.slice('--include='.length));
79
+ } else {
80
+ throw new UsageError(`Unknown argument: ${arg}`);
81
+ }
82
+ }
83
+ if (!args.project) {
84
+ throw new UsageError('--project needs a path');
85
+ }
86
+ if (args.include.length === 0) {
87
+ args.include.push('src');
88
+ }
89
+ return args;
90
+ }
91
+
92
+ class UsageError extends Error {}
93
+
94
+ /** The project's own TypeScript, so the checker resolves types exactly as its build does. */
95
+ function loadTypeScript(cwd) {
96
+ try {
97
+ return createRequire(path.join(cwd, 'package.json'))('typescript');
98
+ } catch {
99
+ return require('typescript');
100
+ }
101
+ }
102
+
103
+ function createProgram(ts, cwd, project) {
104
+ const configPath = path.resolve(cwd, project);
105
+ if (!fs.existsSync(configPath)) {
106
+ throw new UsageError(`tsconfig not found: ${configPath}`);
107
+ }
108
+ const host = {
109
+ ...ts.sys,
110
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
111
+ throw new UsageError(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
112
+ },
113
+ };
114
+ const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, host);
115
+ // Emit is only ever called with a writeFile callback (see emittedDesignTypes), so nothing reaches the disk
116
+ const options = {
117
+ ...parsed.options,
118
+ composite: false,
119
+ declaration: false,
120
+ declarationMap: false,
121
+ emitDeclarationOnly: false,
122
+ incremental: false,
123
+ inlineSourceMap: false,
124
+ noEmit: false,
125
+ noEmitOnError: false,
126
+ sourceMap: false,
127
+ };
128
+ return ts.createProgram({ options, rootNames: parsed.fileNames });
129
+ }
130
+
131
+ /** `UnifiedField` as `@UnifiedField(...)` or `@ns.UnifiedField(...)`. */
132
+ function unifiedFieldCall(ts, decorator) {
133
+ const expression = decorator.expression;
134
+ if (!ts.isCallExpression(expression)) {
135
+ return undefined;
136
+ }
137
+ const callee = expression.expression;
138
+ const name = ts.isIdentifier(callee)
139
+ ? callee.text
140
+ : ts.isPropertyAccessExpression(callee)
141
+ ? callee.name.text
142
+ : undefined;
143
+ return name === 'UnifiedField' ? expression : undefined;
144
+ }
145
+
146
+ function propertyName(ts, property) {
147
+ const name = property.name;
148
+ return name && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? name.text : undefined;
149
+ }
150
+
151
+ /**
152
+ * Whether the options already decide the type: `type`, `enum`, `isAny: true`. Options the script
153
+ * cannot read (a variable, a spread, `isAny: someFlag`) count as deciding — it never guesses.
154
+ */
155
+ function optionsDecideType(ts, options) {
156
+ if (!options) {
157
+ return false;
158
+ }
159
+ if (!ts.isObjectLiteralExpression(options)) {
160
+ return true;
161
+ }
162
+ for (const property of options.properties) {
163
+ if (ts.isSpreadAssignment(property)) {
164
+ return true;
165
+ }
166
+ const name = propertyName(ts, property);
167
+ if (name === 'type' || name === 'enum') {
168
+ return true;
169
+ }
170
+ if (
171
+ name === 'isAny' &&
172
+ !(ts.isPropertyAssignment(property) && property.initializer.kind === ts.SyntaxKind.FalseKeyword)
173
+ ) {
174
+ return true;
175
+ }
176
+ }
177
+ return false;
178
+ }
179
+
180
+ function isArrayTypeNode(ts, node) {
181
+ if (ts.isArrayTypeNode(node) || ts.isTupleTypeNode(node)) {
182
+ return true;
183
+ }
184
+ if (ts.isTypeOperatorNode(node)) {
185
+ return isArrayTypeNode(ts, node.type);
186
+ }
187
+ return (
188
+ ts.isTypeReferenceNode(node) &&
189
+ ts.isIdentifier(node.typeName) &&
190
+ (node.typeName.text === 'Array' || node.typeName.text === 'ReadonlyArray')
191
+ );
192
+ }
193
+
194
+ /** The import declaration that brings `symbol` into the file, or undefined for a local declaration. */
195
+ function importOf(ts, symbol) {
196
+ const declaration = symbol.declarations?.[0];
197
+ if (!declaration) {
198
+ return undefined;
199
+ }
200
+ if (ts.isImportSpecifier(declaration)) {
201
+ return { typeOnly: declaration.isTypeOnly || declaration.parent.parent.isTypeOnly };
202
+ }
203
+ if (ts.isImportClause(declaration)) {
204
+ return { typeOnly: declaration.isTypeOnly };
205
+ }
206
+ if (ts.isNamespaceImport(declaration)) {
207
+ return { typeOnly: declaration.parent.isTypeOnly };
208
+ }
209
+ return undefined;
210
+ }
211
+
212
+ function isLibDate(symbol) {
213
+ return (
214
+ symbol?.getName() === 'Date' &&
215
+ (symbol.declarations ?? []).some((d) => /[\\/]typescript[\\/]lib[\\/]lib\./.test(d.getSourceFile().fileName))
216
+ );
217
+ }
218
+
219
+ /**
220
+ * Whether both compilers emit the same runtime type for this annotation: a primitive keyword,
221
+ * `Date`, or a class the file has as a value (declared here, or imported without `type`).
222
+ */
223
+ function emitsTheSameType(ts, checker, node) {
224
+ if (
225
+ node.kind === ts.SyntaxKind.NumberKeyword ||
226
+ node.kind === ts.SyntaxKind.StringKeyword ||
227
+ node.kind === ts.SyntaxKind.BooleanKeyword
228
+ ) {
229
+ return true;
230
+ }
231
+ // `'a' | 'b'` written out in place: SWC emits String like tsc (measured). Not so with null/undefined in the union
232
+ if (
233
+ ts.isUnionTypeNode(node) &&
234
+ node.types.every((member) => ts.isLiteralTypeNode(member) && ts.isStringLiteral(member.literal))
235
+ ) {
236
+ return true;
237
+ }
238
+ if (!ts.isTypeReferenceNode(node) || node.typeArguments || !ts.isIdentifier(node.typeName)) {
239
+ return false;
240
+ }
241
+ const symbol = checker.getSymbolAtLocation(node.typeName);
242
+ if (!symbol) {
243
+ return false;
244
+ }
245
+ const imported = importOf(ts, symbol);
246
+ if (imported?.typeOnly) {
247
+ return false;
248
+ }
249
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
250
+ // An enum: SWC writes the enum object, which @UnifiedField reads as String / Number like tsc does (12.8.7)
251
+ if (target.flags & ts.SymbolFlags.Enum) {
252
+ return true;
253
+ }
254
+ return isLibDate(target) || (target.flags & ts.SymbolFlags.Class) !== 0;
255
+ }
256
+
257
+ function everyMember(type, predicate) {
258
+ return type.isUnion() ? type.types.every(predicate) : predicate(type);
259
+ }
260
+
261
+ /**
262
+ * The runtime type the tsc build emits for this field (null and undefined dropped), as the name to
263
+ * put into `type: () => X` — or a reason why there is no such class.
264
+ */
265
+ function resolveRuntimeType(ts, checker, property) {
266
+ const declared = checker.getTypeAtLocation(property);
267
+ const type = checker.getNonNullableType(declared);
268
+ const flags = ts.TypeFlags;
269
+ if (type.flags & (flags.Any | flags.Unknown)) {
270
+ return { reason: 'any / unknown' };
271
+ }
272
+ if (everyMember(type, (t) => (t.flags & flags.NumberLike) !== 0)) {
273
+ return { name: 'Number' };
274
+ }
275
+ if (everyMember(type, (t) => (t.flags & flags.StringLike) !== 0)) {
276
+ return { name: 'String' };
277
+ }
278
+ if (everyMember(type, (t) => (t.flags & flags.BooleanLike) !== 0)) {
279
+ return { name: 'Boolean' };
280
+ }
281
+ if (type.isUnion()) {
282
+ return { reason: 'a union of different types' };
283
+ }
284
+ const symbol = type.getSymbol();
285
+ if (isLibDate(symbol)) {
286
+ return { name: 'Date' };
287
+ }
288
+ if (symbol && symbol.flags & ts.SymbolFlags.Class) {
289
+ const reference = classValueReference(ts, checker, property, symbol);
290
+ return reference
291
+ ? { name: reference }
292
+ : {
293
+ reason:
294
+ `no value in this file refers to class ${symbol.getName()} (imported only as a type, or its name means ` +
295
+ 'something else here): import it as a value, then write type: () => <that name> yourself',
296
+ };
297
+ }
298
+ if (symbol && symbol.flags & ts.SymbolFlags.Interface) {
299
+ return { reason: `interface ${symbol.getName()}` };
300
+ }
301
+ return { reason: 'an object type without a runtime class (Record, object literal type, …)' };
302
+ }
303
+
304
+ /**
305
+ * The text that refers to `classSymbol` as a value at this field — what `--fix` may write into `type: () => …` — or
306
+ * undefined. Matched by symbol, never by name: a class imported under another name (`import { Settings as Tenant }`,
307
+ * `import * as tenant`) next to a local class of the original name must get `Tenant` / `tenant.Settings`, not the local
308
+ * class — writing that would change which class the deployed build validates and restricts the field with.
309
+ *
310
+ * 1. The reference the annotation itself writes (`Foo`, `Alias`, `ns.Foo`), when it resolves to the class and is not
311
+ * a type-only import.
312
+ * 2. Otherwise the class's own name, when it resolves to that very class as a value here (`resolveName`).
313
+ */
314
+ function classValueReference(ts, checker, property, classSymbol) {
315
+ const target = (symbol) =>
316
+ symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
317
+ const typeOnly = (symbol) => importOf(ts, symbol)?.typeOnly === true;
318
+ const names = [];
319
+ const collect = (node) => {
320
+ if (ts.isTypeReferenceNode(node)) {
321
+ names.push(node.typeName);
322
+ }
323
+ ts.forEachChild(node, collect);
324
+ };
325
+ if (property.type) {
326
+ collect(property.type);
327
+ }
328
+ for (const name of names) {
329
+ if (target(checker.getSymbolAtLocation(name)) !== classSymbol) {
330
+ continue;
331
+ }
332
+ let head = name;
333
+ while (ts.isQualifiedName(head)) {
334
+ head = head.left;
335
+ }
336
+ const headSymbol = checker.getSymbolAtLocation(head);
337
+ if (headSymbol && typeOnly(headSymbol)) {
338
+ continue;
339
+ }
340
+ return name.getText();
341
+ }
342
+ if (typeof checker.resolveName === 'function') {
343
+ const own = checker.resolveName(classSymbol.getName(), property, ts.SymbolFlags.Value, false);
344
+ if (own && !typeOnly(own) && target(own) === classSymbol) {
345
+ return classSymbol.getName();
346
+ }
347
+ }
348
+ return undefined;
349
+ }
350
+
351
+ /** Why the SWC dev start cannot read this annotation like tsc does — for the report. */
352
+ function describeAnnotation(ts, checker, node) {
353
+ if (!node) {
354
+ return 'no type annotation';
355
+ }
356
+ if (ts.isUnionTypeNode(node)) {
357
+ return 'a union';
358
+ }
359
+ if (ts.isLiteralTypeNode(node)) {
360
+ return 'a literal type';
361
+ }
362
+ if (ts.isTypeReferenceNode(node)) {
363
+ const symbol = ts.isIdentifier(node.typeName) ? checker.getSymbolAtLocation(node.typeName) : undefined;
364
+ if (symbol && importOf(ts, symbol)?.typeOnly) {
365
+ return 'a type-only import';
366
+ }
367
+ const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
368
+ if (target && target.flags & ts.SymbolFlags.Enum) {
369
+ return 'an enum';
370
+ }
371
+ if (target && target.flags & ts.SymbolFlags.TypeAlias) {
372
+ return 'a type alias';
373
+ }
374
+ if (target && target.flags & ts.SymbolFlags.Interface) {
375
+ return 'an interface';
376
+ }
377
+ return node.typeArguments ? 'a generic type' : 'a type reference';
378
+ }
379
+ return 'a type expression';
380
+ }
381
+
382
+ /** The edit that adds `type: () => <name>` to the decorator call's options. */
383
+ function typeOptionEdit(ts, sourceFile, call, name) {
384
+ const insertion = `type: () => ${name}`;
385
+ const text = sourceFile.text;
386
+ const options = call.arguments[0];
387
+ if (!options) {
388
+ return { end: call.arguments.pos, start: call.arguments.pos, text: `{ ${insertion} }` };
389
+ }
390
+ const properties = options.properties;
391
+ if (properties.length === 0) {
392
+ return { end: options.end, start: options.getStart(sourceFile), text: `{ ${insertion} }` };
393
+ }
394
+ // What precedes a property on its line: only its indentation when it starts the line, code otherwise
395
+ const linePrefix = (node) => {
396
+ const start = node.getStart(sourceFile);
397
+ return text.slice(text.lastIndexOf('\n', start - 1) + 1, start);
398
+ };
399
+ const ownLine = (node) => /^[ \t]*$/.test(linePrefix(node));
400
+ // Keys are kept in alphabetical order in the stack's code; insert before the first one after `type`
401
+ const next = properties.find((property) => (propertyName(ts, property) ?? '') > 'type');
402
+ if (next) {
403
+ const start = next.getStart(sourceFile);
404
+ return { end: start, start, text: ownLine(next) ? `${insertion},\n${linePrefix(next)}` : `${insertion}, ` };
405
+ }
406
+ const last = properties[properties.length - 1];
407
+ const between = text.slice(last.end, options.end - 1);
408
+ const comma = between.trimStart().startsWith(',') ? last.end + between.indexOf(',') + 1 : undefined;
409
+ if (ownLine(last)) {
410
+ const indentOf = linePrefix;
411
+ return comma === undefined
412
+ ? { end: last.end, start: last.end, text: `,\n${indentOf(last)}${insertion}` }
413
+ : { end: comma, start: comma, text: `\n${indentOf(last)}${insertion},` };
414
+ }
415
+ return comma === undefined
416
+ ? { end: last.end, start: last.end, text: `, ${insertion}` }
417
+ : { end: comma, start: comma, text: ` ${insertion}` };
418
+ }
419
+
420
+ /**
421
+ * The `design:type` expression tsc writes for each decorated property of these files, read from an in-memory emit
422
+ * (the writeFile callback keeps it off the disk): Map<sourceFile, Map<"Class.property", expression>>.
423
+ */
424
+ function emittedDesignTypes(program, sourceFiles) {
425
+ const result = new Map();
426
+ for (const sourceFile of sourceFiles) {
427
+ let js = '';
428
+ program.emit(sourceFile, (name, text) => {
429
+ if (/\.[cm]?js$/.test(name)) {
430
+ js = text;
431
+ }
432
+ });
433
+ const types = new Map();
434
+ // `__decorate([` / `(0, tslib_1.__decorate)([` (importHelpers), the same for `__metadata`
435
+ for (const match of js.matchAll(/__decorate\)?\(\[([\s\S]*?)\],\s*([\w$]+)\.prototype,\s*"([^"]+)"/g)) {
436
+ const metadata = /__metadata\)?\("design:type",\s*([\s\S]*?)\)\s*(?:,|$)/.exec(match[1]);
437
+ if (metadata) {
438
+ types.set(`${match[2]}.${match[3]}`, metadata[1].trim());
439
+ }
440
+ }
441
+ result.set(sourceFile, types);
442
+ }
443
+ return result;
444
+ }
445
+
446
+ /** A design:type as a comparable kind: the primitive constructor's name, `class` for a class reference, or undefined. */
447
+ function designTypeKind(expression) {
448
+ if (!expression) {
449
+ return undefined;
450
+ }
451
+ const primitive = /^(Number|String|Boolean|Date|Object|Array|Function)$/.exec(expression);
452
+ return primitive ? primitive[1] : 'class';
453
+ }
454
+
455
+ function analyze(ts, program, cwd, include) {
456
+ const checker = program.getTypeChecker();
457
+ const roots = include.map((dir) => path.resolve(cwd, dir) + path.sep);
458
+ const findings = [];
459
+ for (const sourceFile of program.getSourceFiles()) {
460
+ const fileName = path.resolve(sourceFile.fileName);
461
+ if (
462
+ sourceFile.isDeclarationFile ||
463
+ fileName.includes(`${path.sep}node_modules${path.sep}`) ||
464
+ /\.(spec|test)\.[cm]?tsx?$/.test(fileName) ||
465
+ !roots.some((root) => fileName.startsWith(root))
466
+ ) {
467
+ continue;
468
+ }
469
+ const visit = (node) => {
470
+ if (ts.isPropertyDeclaration(node) && ts.canHaveDecorators(node)) {
471
+ for (const decorator of ts.getDecorators(node) ?? []) {
472
+ const call = unifiedFieldCall(ts, decorator);
473
+ if (!call || optionsDecideType(ts, call.arguments[0])) {
474
+ continue;
475
+ }
476
+ if (node.type && (isArrayTypeNode(ts, node.type) || emitsTheSameType(ts, checker, node.type))) {
477
+ continue;
478
+ }
479
+ const owner = node.parent && ts.isClassLike(node.parent) && node.parent.name ? node.parent.name.text : '?';
480
+ const resolved = resolveRuntimeType(ts, checker, node);
481
+ findings.push({
482
+ call,
483
+ field: `${owner}.${propertyName(ts, node) ?? '?'}`,
484
+ owner,
485
+ property: propertyName(ts, node),
486
+ fileName,
487
+ line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
488
+ hint: resolved.reason,
489
+ name: resolved.name,
490
+ reason: describeAnnotation(ts, checker, node.type),
491
+ sourceFile,
492
+ });
493
+ }
494
+ }
495
+ ts.forEachChild(node, visit);
496
+ };
497
+ visit(sourceFile);
498
+ }
499
+ // Whether a written type changes the deployed build: compare it with what tsc's own emit writes for the field
500
+ const files = [...new Set(findings.filter((f) => f.name).map((f) => f.sourceFile))];
501
+ const emitted = emittedDesignTypes(program, files);
502
+ for (const finding of findings.filter((f) => f.name)) {
503
+ const deployed = emitted.get(finding.sourceFile)?.get(`${finding.owner}.${finding.property}`);
504
+ finding.changesDeployed = designTypeKind(deployed) !== designTypeKind(finding.name);
505
+ }
506
+ return findings;
507
+ }
508
+
509
+ /**
510
+ * Writes the edits. Their positions refer to the text TypeScript parsed, which has a leading UTF-8 BOM stripped — so
511
+ * they are shifted by the BOM, which stays in the file. A file whose text no longer matches what was parsed (changed
512
+ * since) is left untouched and returned in `skipped`.
513
+ */
514
+ function applyFixes(ts, findings) {
515
+ const byFile = new Map();
516
+ for (const finding of findings.filter((f) => f.name)) {
517
+ const entry = byFile.get(finding.fileName) ?? { edits: [], sourceFile: finding.sourceFile };
518
+ entry.edits.push(typeOptionEdit(ts, finding.sourceFile, finding.call, finding.name));
519
+ byFile.set(finding.fileName, entry);
520
+ }
521
+ const written = [];
522
+ const skipped = [];
523
+ for (const [fileName, { edits, sourceFile }] of byFile) {
524
+ let text = fs.readFileSync(fileName, 'utf8');
525
+ const offset = text.charCodeAt(0) === 0xfeff ? 1 : 0;
526
+ if (text.slice(offset) !== sourceFile.text) {
527
+ skipped.push(fileName);
528
+ continue;
529
+ }
530
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
531
+ text = text.slice(0, edit.start + offset) + edit.text + text.slice(edit.end + offset);
532
+ }
533
+ fs.writeFileSync(fileName, text);
534
+ written.push(fileName);
535
+ }
536
+ return { skipped, written };
537
+ }
538
+
539
+ function main(argv, cwd = process.cwd(), out = console) {
540
+ let args;
541
+ try {
542
+ args = parseArgs(argv);
543
+ } catch (error) {
544
+ out.error(`${PREFIX} ${error.message}\n${usage()}`);
545
+ return 2;
546
+ }
547
+ if (args.help) {
548
+ out.log(usage());
549
+ return 0;
550
+ }
551
+ let findings;
552
+ const ts = loadTypeScript(cwd);
553
+ try {
554
+ findings = analyze(ts, createProgram(ts, cwd, args.project), cwd, args.include);
555
+ } catch (error) {
556
+ if (error instanceof UsageError) {
557
+ out.error(`${PREFIX} ${error.message}`);
558
+ return 2;
559
+ }
560
+ throw error;
561
+ }
562
+ if (findings.length === 0) {
563
+ out.log(`${PREFIX} OK — every @UnifiedField has a runtime type both compilers agree on.`);
564
+ return 0;
565
+ }
566
+ const fixable = findings.filter((f) => f.name);
567
+ const manual = findings.filter((f) => !f.name);
568
+ if (args.fix && fixable.length > 0) {
569
+ const { skipped, written } = applyFixes(ts, fixable);
570
+ if (skipped.length > 0) {
571
+ for (const fileName of skipped) {
572
+ out.error(`${PREFIX} ${path.relative(cwd, fileName)} changed while the check ran — left untouched, run again`);
573
+ }
574
+ return 1;
575
+ }
576
+ out.log(`${PREFIX} fixed ${fixable.length} field(s) in ${written.length} file(s):`);
577
+ } else if (fixable.length > 0) {
578
+ out.log(`${PREFIX} ${fixable.length} field(s) need an explicit type (\`--fix\` writes it):`);
579
+ }
580
+ for (const f of fixable) {
581
+ const marker = f.changesDeployed ? ' [changes the deployed build]' : '';
582
+ out.log(` ${path.relative(cwd, f.fileName)}:${f.line} ${f.field} (${f.reason}) → type: () => ${f.name}${marker}`);
583
+ }
584
+ if (fixable.some((f) => f.changesDeployed)) {
585
+ out.log(
586
+ ' [changes the deployed build]: the tsc build writes a different type for this field today — Object for a ' +
587
+ 'union with null / undefined under strictNullChecks (the default without a `strict` key since TypeScript 6), ' +
588
+ 'for a generic alias, for a field without a type annotation. The written type is the one the field declares, ' +
589
+ 'so the deployed API validates it differently from now on. Review those fields.',
590
+ );
591
+ }
592
+ if (manual.length > 0) {
593
+ out.log(`${PREFIX} ${manual.length} field(s) to declare by hand — no runtime class to write automatically:`);
594
+ for (const f of manual) {
595
+ out.log(` ${path.relative(cwd, f.fileName)}:${f.line} ${f.field} (${f.reason}) — ${f.hint}`);
596
+ }
597
+ out.log(
598
+ ' Declare `type: () => Object` for a free-form object, `isAny: true` for any value, or a class for a nested ' +
599
+ 'structure (its @UnifiedField fields are then validated and @Restricted is enforced on them).',
600
+ );
601
+ }
602
+ out.log(
603
+ `${PREFIX} Why: without \`type\`, @UnifiedField reads the compiler's design:type, which the SWC dev start writes ` +
604
+ 'as Object for a union with null / undefined, a type alias or an interface — the dev API then validates such a ' +
605
+ 'field as a nested object. For every field not marked, --fix writes exactly the type the tsc build writes ' +
606
+ '(read from its emit), so the deployed API keeps its behaviour.',
607
+ );
608
+ return args.fix ? (manual.length > 0 ? 1 : 0) : 1;
609
+ }
610
+
611
+ if (require.main === module) {
612
+ process.exitCode = main(process.argv.slice(2));
613
+ }
614
+
615
+ module.exports = { main };
@@ -74,6 +74,38 @@ function warnIfLikelyMisconfiguredEnumOptions(value, propertyHint) {
74
74
  `The object will be treated as the enum itself (shortcut form), which is likely wrong.`);
75
75
  }
76
76
  }
77
+ function designTypeOf(metadataType) {
78
+ if (typeof metadataType !== 'object' || metadataType === null || Array.isArray(metadataType)) {
79
+ return metadataType;
80
+ }
81
+ const values = Object.values(metadataType);
82
+ if (values.length === 0) {
83
+ return metadataType;
84
+ }
85
+ const numbers = values.filter((value) => typeof value === 'number');
86
+ const strings = values.filter((value) => typeof value === 'string');
87
+ if (numbers.length === 0 && strings.length === values.length) {
88
+ return String;
89
+ }
90
+ if (numbers.length > 0 &&
91
+ strings.every((name) => typeof metadataType[name] === 'number')) {
92
+ return Number;
93
+ }
94
+ return metadataType;
95
+ }
96
+ const ambiguousTypeWarned = new Set();
97
+ function warnIfAmbiguousMetadataType(metadataType, propertyHint) {
98
+ const ambiguous = metadataType === Object || (typeof metadataType === 'object' && metadataType !== null);
99
+ if (!ambiguous || ambiguousTypeWarned.has(propertyHint))
100
+ return;
101
+ ambiguousTypeWarned.add(propertyHint);
102
+ console.warn(`[@UnifiedField] "${propertyHint}" has no explicit type, and the compiler metadata says only "Object". The SWC ` +
103
+ 'dev start and the tsc build can disagree here (a union with null/undefined, a type alias, an interface), so ' +
104
+ 'the dev API may validate it as a nested object. Declare it: type: () => Number / String / Boolean / ' +
105
+ 'Date / <Class>, type: () => Object for a free-form object, or isAny: true. `nest-check-unified-field-types ' +
106
+ '--fix` (vendor mode: `node ./bin/check-unified-field-types.js --fix`) writes the declared type; a later ' +
107
+ 'release refuses such a field at boot.');
108
+ }
77
109
  export function UnifiedField(opts = {}) {
78
110
  const isLongForm = opts.enum ? isEnumOptionsObject(opts.enum) : false;
79
111
  const normalizedEnum = opts.enum
@@ -133,12 +165,15 @@ export function UnifiedField(opts = {}) {
133
165
  if (!existingKeys.includes(key)) {
134
166
  Reflect.defineMetadata(UNIFIED_FIELD_KEYS, [...existingKeys, key], target);
135
167
  }
136
- const metadataType = Reflect.getMetadata('design:type', target, propertyKey);
168
+ const metadataType = designTypeOf(Reflect.getMetadata('design:type', target, propertyKey));
137
169
  const userType = opts.type;
138
170
  const isArrayField = opts.isArray === true || metadataType === Array;
139
171
  if (metadataType === Array && !userType) {
140
172
  throw new Error(`Array field '${String(propertyKey)}' of '${String(target)}' must have an explicit type`);
141
173
  }
174
+ if (!userType && !opts.isAny && !normalizedEnum) {
175
+ warnIfAmbiguousMetadataType(metadataType, `${target.constructor?.name || '?'}.${key}`);
176
+ }
142
177
  const resolvedTypeFn = () => {
143
178
  if (userType) {
144
179
  if (userType instanceof GraphQLScalarType) {