Skip to content

Commit 037a7d9

Browse files
committed
Merge remote-tracking branch 'upstream/master' into 'origin/feat/inline-external-types'
2 parents 1978d31 + 6909fa8 commit 037a7d9

18 files changed

+306
-84
lines changed

packages/bson/src/bson-serializer.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1493,7 +1493,7 @@ export function createBSONSizer<T>(type?: ReceiveType<T>, serializer: BSONBinary
14931493
return compiler.build(code, 'data', 'state');
14941494
}
14951495

1496-
export function serializeWithoutOptimiser(data: any): Uint8Array {
1496+
export function serializeBSONWithoutOptimiser(data: any): Uint8Array {
14971497
const size = getValueSize(data);
14981498
const writer = new Writer(createBuffer(size));
14991499
writer.write(data);

packages/injector/src/provider.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,22 @@ export interface ProviderBase {
1919
transient?: true;
2020
}
2121

22+
/** @reflection never */
23+
export interface ProviderScope {
24+
scope?: 'module' | 'rpc' | 'http' | 'cli' | string;
25+
}
26+
2227
/** @reflection never */
2328
export type Token<T = any> = symbol | number | bigint | RegExp | boolean | string | AbstractClassType<T> | Type | T;
2429

2530
export function provide<T>(
2631
provider:
27-
| (ProviderBase &
32+
| (ProviderBase & ProviderScope &
2833
(
2934
| { useValue: T }
3035
| { useClass: ClassType }
3136
| { useExisting: any }
32-
| { useFactory: (...args: any[]) => T }
37+
| { useFactory: (...args: any[]) => T | undefined }
3338
))
3439
| ClassType
3540
| ((...args: any[]) => T)
@@ -86,7 +91,7 @@ export interface FactoryProvider<T> extends ProviderBase {
8691
/**
8792
* A function to invoke to create a value for this `token`.
8893
*/
89-
useFactory: (...args: any[]) => T;
94+
useFactory: (...args: any[]) => T | undefined;
9095
}
9196

9297
/** @reflection never */
@@ -154,11 +159,6 @@ export class Tag<T, TP extends TagProvider<T> = TagProvider<T>> {
154159
}
155160
}
156161

157-
/** @reflection never */
158-
export interface ProviderScope {
159-
scope?: 'module' | 'rpc' | 'http' | 'cli' | string;
160-
}
161-
162162
/** @reflection never */
163163
export type NormalizedProvider<T = any> = ProviderProvide<T> & ProviderScope;
164164

packages/rpc/src/decorators.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,19 @@ import {
1919
} from '@deepkit/type';
2020
import { ControllerDefinition } from './model.js';
2121

22-
class RpcController {
22+
export class RpcController {
2323
// Defaults to the name of the class
2424
name: string = '';
2525

26+
classType?: ClassType;
27+
2628
definition?: ControllerDefinition<any>;
2729

2830
actions = new Map<string, RpcAction>();
2931

3032
getPath(): string {
31-
return this.definition ? this.definition.path : this.name;
33+
const name = this.definition ? this.definition.path : this.name;
34+
return name || (this.classType ? reflect(this.classType).typeName || this.classType.name : '');
3235
}
3336
}
3437

@@ -59,7 +62,7 @@ class RpcClass {
5962
}
6063

6164
onDecorator(classType: ClassType) {
62-
this.t.name ||= reflect(classType).typeName || classType.name;
65+
this.t.classType = classType;
6366
}
6467
}
6568

packages/rpc/tests/controller.spec.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { assertType, entity, Positive, ReflectionClass, ReflectionKind } from '@deepkit/type';
22
import { expect, test } from '@jest/globals';
33
import { DirectClient } from '../src/client/client-direct.js';
4-
import { getActions, rpc, rpcClass } from '../src/decorators.js';
4+
import { getActions, rpc, rpcClass, RpcController } from '../src/decorators.js';
55
import { RpcKernel, RpcKernelConnection } from '../src/server/kernel.js';
66
import { Session, SessionState } from '../src/server/security.js';
77
import { BehaviorSubject } from 'rxjs';
@@ -12,9 +12,11 @@ test('default name', () => {
1212
@rpc.controller()
1313
class Controller {}
1414

15-
expect(rpcClass._fetch(Controller)).toMatchObject({
16-
name: 'Controller',
17-
});
15+
const controller = new RpcController();
16+
17+
controller.classType = Controller;
18+
19+
expect(controller.getPath()).toBe('Controller');
1820
});
1921

2022
test('decorator', async () => {

packages/sql/src/sql-adapter.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -565,7 +565,7 @@ export class RawQuery<T> implements FindQuery<T> {
565565
const connection = await this.connectionPool.getConnection(this.session.logger, this.session.assignedTransaction, this.session.stopwatch);
566566

567567
try {
568-
const caster = castFunction(undefined, undefined, undefined, this.type);
568+
const caster = castFunction(undefined, undefined, this.type);
569569
const res = await connection.execAndReturnAll(sql.sql, sql.params);
570570
return (isArray(res) ? [...res] : []).map(v => caster(v)) as T[];
571571
} finally {
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { deepkitType } from './src/plugin.js';
2+
import { readFileSync } from 'fs';
3+
4+
interface Arguments {
5+
file: string;
6+
config?: string;
7+
}
8+
9+
function parseArguments(args: string[]): Arguments {
10+
const result: Arguments = {
11+
file: '',
12+
};
13+
14+
for (let i = 0; i < args.length; i++) {
15+
const arg = args[i];
16+
if (arg === '--config') {
17+
result.config = args[i + 1];
18+
i++;
19+
} else {
20+
result.file = arg;
21+
}
22+
}
23+
24+
return result;
25+
}
26+
27+
const args = parseArguments(process.argv.slice(2));
28+
29+
30+
31+
const transformer = deepkitType({
32+
tsConfig: args.config,
33+
});
34+
35+
const code = readFileSync(args.file, 'utf8');
36+
const transformed = transformer(code, args.file);
37+
38+
console.log(transformed?.code);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#!/usr/bin/env node
2+
3+
try {
4+
require('./dist/cjs/compiler-debug.js');
5+
} catch (error) {}

packages/type-compiler/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { declarationTransformer, transformer } from './src/compiler.js';
1212
import type { Program } from 'typescript';
1313

1414
export * from './src/compiler.js';
15+
export * from './src/plugin.js';
1516
export * from './src/loader.js';
1617

1718
export default function myTransformerPlugin(program: Program, opts: {}) {

packages/type-compiler/package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414
}
1515
},
1616
"bin": {
17-
"deepkit-type-install": "./deepkit-type-install.js"
17+
"deepkit-type-install": "./deepkit-type-install.js",
18+
"deepkit-compiler-debug": "./deepkit-compiler-debug.js"
1819
},
1920
"sideEffects": false,
2021
"publishConfig": {

packages/type-compiler/src/compiler.ts

+30-43
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,14 @@ import ts from 'typescript';
7474

7575
import {
7676
ensureImportIsEmitted,
77-
extractJSDocAttribute, getEntityName,
77+
extractJSDocAttribute,
78+
getEntityName,
7879
getGlobalsOfSourceFile,
7980
getIdentifierName,
8081
getNameAsString,
8182
getPropertyName,
82-
hasModifier, isBuiltType,
83+
hasModifier,
84+
isBuiltType,
8385
isNodeWithLocals,
8486
NodeConverter,
8587
PackExpression,
@@ -90,9 +92,8 @@ import { existsSync, readFileSync } from 'fs';
9092
import { dirname, isAbsolute, join, resolve } from 'path';
9193
import stripJsonComments from 'strip-json-comments';
9294
import { MappedModifier, ReflectionOp, TypeNumberBrand } from '@deepkit/type-spec';
93-
import { Resolver } from './resolver.js';
95+
import { patternMatch, ReflectionMode, reflectionModeMatcher, reflectionModes, Resolver } from './resolver.js';
9496
import { knownLibFilesForCompilerOptions } from '@typescript/vfs';
95-
import * as micromatch from 'micromatch';
9697

9798
// don't use from @deepkit/core since we don't want to have a dependency to @deepkit/core
9899
export function isObject(obj: any): obj is { [key: string]: any } {
@@ -186,7 +187,6 @@ const serverEnv = 'undefined' !== typeof process;
186187
* It can't be more ops than this given number
187188
*/
188189
export const packSize: number = 2 ** packSizeByte; //64
189-
const reflectionModes = ['always', 'default', 'never'] as const;
190190

191191
export interface ReflectionOptions {
192192
/**
@@ -546,7 +546,7 @@ export class ReflectionTransformer implements CustomTransformer {
546546
'lib.es2017.typedarrays.d.ts',
547547
];
548548

549-
public embedAssignType: boolean = false;
549+
protected embedAssignType: boolean = false;
550550

551551
protected reflectionMode?: typeof reflectionModes[number];
552552
protected reflectionOptions?: ReflectionOptions;
@@ -726,7 +726,7 @@ export class ReflectionTransformer implements CustomTransformer {
726726
}
727727
}
728728

729-
debug(`Transform file ${sourceFile.fileName} via config ${this.compilerOptions.configFilePath || 'none'}, reflection=${this.reflectionMode}.`);
729+
debug(`Transform file ${sourceFile.fileName} via config ${this.compilerOptions.configFilePath || 'none'}, reflection=${this.reflectionMode} (${this.getModuleType()}).`);
730730

731731
if (this.reflectionMode === 'never') {
732732
return sourceFile;
@@ -1023,15 +1023,15 @@ export class ReflectionTransformer implements CustomTransformer {
10231023
this.sourceFile = visitNode(this.sourceFile, compileDeclarations);
10241024

10251025
if (this.addImports.length) {
1026-
const compilerOptions = this.compilerOptions;
10271026
const handledIdentifier: string[] = [];
10281027
for (const imp of this.addImports) {
10291028
if (handledIdentifier.includes(getIdentifierName(imp.identifier))) continue;
10301029
handledIdentifier.push(getIdentifierName(imp.identifier));
1031-
if (compilerOptions.module === ModuleKind.CommonJS) {
1030+
if (this.getModuleType() === 'cjs') {
10321031
//var {identifier} = require('./bar')
1032+
const test = this.f.createIdentifier(getIdentifierName(imp.identifier));
10331033
const variable = this.f.createVariableStatement(undefined, this.f.createVariableDeclarationList([this.f.createVariableDeclaration(
1034-
this.f.createObjectBindingPattern([this.f.createBindingElement(undefined, undefined, imp.identifier)]),
1034+
this.f.createObjectBindingPattern([this.f.createBindingElement(undefined, undefined, test)]),
10351035
undefined, undefined,
10361036
this.f.createCallExpression(this.f.createIdentifier('require'), undefined, [imp.from])
10371037
)], NodeFlags.Const));
@@ -1046,7 +1046,7 @@ export class ReflectionTransformer implements CustomTransformer {
10461046
//import {identifier} from './bar.js'
10471047
// import { identifier as identifier } is used to avoid automatic elision of imports (in angular builds for example)
10481048
// that's probably a bit unstable.
1049-
const specifier = this.f.createImportSpecifier(false, imp.identifier, imp.identifier);
1049+
const specifier = this.f.createImportSpecifier(false, undefined, imp.identifier);
10501050
const namedImports = this.f.createNamedImports([specifier]);
10511051
const importStatement = this.f.createImportDeclaration(undefined,
10521052
this.f.createImportClause(false, undefined, namedImports), imp.from
@@ -1142,6 +1142,10 @@ export class ReflectionTransformer implements CustomTransformer {
11421142
return this.sourceFile;
11431143
}
11441144

1145+
protected getModuleType(): 'cjs' | 'esm' {
1146+
return this.compilerOptions.module === ModuleKind.CommonJS ? 'cjs' : 'esm';
1147+
}
1148+
11451149
protected injectResetΩ<T extends FunctionDeclaration | FunctionExpression | MethodDeclaration | ConstructorDeclaration>(node: T): T {
11461150
let hasReceiveType = false;
11471151
for (const param of node.parameters) {
@@ -2039,12 +2043,7 @@ export class ReflectionTransformer implements CustomTransformer {
20392043

20402044
protected isExcluded(filePath: string): boolean {
20412045
if (!this.currentReflectionConfig.options.exclude) return false;
2042-
2043-
const excluded = micromatch.contains(filePath, this.currentReflectionConfig.options.exclude, {
2044-
basename: true,
2045-
cwd: this.currentReflectionConfig.baseDir
2046-
});
2047-
return excluded;
2046+
return patternMatch(filePath, this.currentReflectionConfig.options.exclude, this.currentReflectionConfig.baseDir);
20482047
}
20492048

20502049
protected extractPackStructOfTypeReference(type: TypeReferenceNode | ExpressionWithTypeArguments, program: CompilerProgram): void {
@@ -2186,6 +2185,8 @@ export class ReflectionTransformer implements CustomTransformer {
21862185
return;
21872186
}
21882187

2188+
const runtimeTypeName = this.getDeclarationVariableName(typeName);
2189+
21892190
//to break recursion, we track which declaration has already been compiled
21902191
if (!this.compiledDeclarations.has(declaration) && !this.compileDeclarations.has(declaration)) {
21912192
const declarationSourceFile = findSourceFile(declaration) || this.sourceFile;
@@ -2225,11 +2226,7 @@ export class ReflectionTransformer implements CustomTransformer {
22252226
return;
22262227
}
22272228

2228-
//check if the referenced file has reflection info emitted. if not, any is emitted for that reference
2229-
const typeVar = this.getDeclarationVariableName(typeName);
2230-
//check if typeVar is exported in referenced file
2231-
const builtType = isBuiltType(typeVar, found);
2232-
2229+
const builtType = isBuiltType(runtimeTypeName, found);
22332230
if (!builtType) {
22342231
if (!this.shouldInlineExternalImport(resolved.importDeclaration, typeName, declarationReflection)) return;
22352232
this.embedDeclarations.set(declaration, {
@@ -2244,7 +2241,7 @@ export class ReflectionTransformer implements CustomTransformer {
22442241
return;
22452242
}
22462243

2247-
this.addImports.push({ identifier: this.getDeclarationVariableName(typeName), from: resolved.importDeclaration.moduleSpecifier });
2244+
this.addImports.push({ identifier: runtimeTypeName, from: resolved.importDeclaration.moduleSpecifier });
22482245
}
22492246
}
22502247
} else {
@@ -2263,7 +2260,7 @@ export class ReflectionTransformer implements CustomTransformer {
22632260
}
22642261

22652262
const index = program.pushStack(
2266-
program.forNode === declaration ? 0 : this.f.createArrowFunction(undefined, undefined, [], undefined, undefined, this.getDeclarationVariableName(typeName))
2263+
program.forNode === declaration ? 0 : this.f.createArrowFunction(undefined, undefined, [], undefined, undefined, runtimeTypeName)
22672264
);
22682265
if (type.typeArguments) {
22692266
for (const argument of type.typeArguments) {
@@ -2696,7 +2693,7 @@ export class ReflectionTransformer implements CustomTransformer {
26962693
*
26972694
* where we embed assignType() at the beginning of the type.
26982695
*/
2699-
public wrapWithAssignType(fn: Expression, type: Expression) {
2696+
protected wrapWithAssignType(fn: Expression, type: Expression) {
27002697
this.embedAssignType = true;
27012698

27022699
return this.f.createCallExpression(
@@ -2709,18 +2706,8 @@ export class ReflectionTransformer implements CustomTransformer {
27092706
);
27102707
}
27112708

2712-
protected parseReflectionMode(mode: typeof reflectionModes[number] | '' | boolean | string | string[] | undefined, configPathDir: string): typeof reflectionModes[number] {
2713-
if (Array.isArray(mode)) {
2714-
if (!configPathDir) return 'never';
2715-
const matches = micromatch.contains(this.sourceFile.fileName, mode, {
2716-
cwd: configPathDir
2717-
});
2718-
2719-
return matches ? 'default' : 'never';
2720-
}
2721-
if ('boolean' === typeof mode) return mode ? 'default' : 'never';
2722-
if (mode === 'default' || mode === 'always') return mode;
2723-
return 'never';
2709+
protected parseReflectionMode(mode: ReflectionMode, configPathDir: string): typeof reflectionModes[number] {
2710+
return reflectionModeMatcher(this.sourceFile.fileName, mode, configPathDir);
27242711
}
27252712

27262713
protected resolvedTsConfig: { [path: string]: { data: Record<string, any>, exists: boolean } } = {};
@@ -2850,19 +2837,19 @@ export class ReflectionTransformer implements CustomTransformer {
28502837
}
28512838
}
28522839

2853-
if (reflection === undefined && packageJson.deepkitTypeCompilerOptions !== undefined) {
2840+
if (reflection === undefined && packageJson.reflection !== undefined) {
28542841
return {
2855-
mode: this.parseReflectionMode(packageJson.deepkitTypeCompilerOptions.reflection, currentDir),
2842+
mode: this.parseReflectionMode(packageJson.reflection, currentDir),
28562843
baseDir: currentDir,
2857-
options: this.parseReflectionOptionsDefaults(packageJson.deepkitTypeCompilerOptions || {})
2844+
options: this.parseReflectionOptionsDefaults(packageJson.reflectionOptions || {})
28582845
};
28592846
}
28602847

2861-
if (reflection === undefined && tsConfig.deepkitTypeCompilerOptions !== undefined) {
2848+
if (reflection === undefined && tsConfig.reflection !== undefined) {
28622849
return {
2863-
mode: this.parseReflectionMode(tsConfig.deepkitTypeCompilerOptions.reflection, currentDir),
2850+
mode: this.parseReflectionMode(tsConfig.reflection, currentDir),
28642851
baseDir: currentDir,
2865-
options: this.parseReflectionOptionsDefaults(tsConfig.deepkitTypeCompilerOptions || {})
2852+
options: this.parseReflectionOptionsDefaults(tsConfig.reflectionOptions || {})
28662853
};
28672854
}
28682855

0 commit comments

Comments
 (0)