@travetto/transformer 3.0.0-rc.1 → 3.0.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <!-- This file was generated by @travetto/doc and should not be modified directly -->
2
- <!-- Please modify https://github.com/travetto/travetto/tree/main/module/transformer/doc.ts and execute "npx trv doc" to rebuild -->
2
+ <!-- Please modify https://github.com/travetto/travetto/tree/main/module/transformer/DOC.ts and execute "npx trv doc" to rebuild -->
3
3
  # Transformation
4
4
  ## Functionality for AST transformations, with transformer registration, and general utils
5
5
 
@@ -10,7 +10,7 @@ npm install @travetto/transformer
10
10
 
11
11
  This module provides support for enhanced AST transformations, and declarative transformer registration, with common patterns to support all the transformers used throughout the framework. Transformations are located by `support/transformer.<name>.ts` as the filename.
12
12
 
13
- The module is primarily aimed at extremely advanced usages for things that cannot be detected at runtime. The [Registry](https://github.com/travetto/travetto/tree/main/module/registry#readme "Patterns and utilities for handling registration of metadata and functionality for run-time use") module already has knowledge of all `class`es and `field`s, and is able to listen to changes there. Many of the modules build upon work by some of the foundational transformers defined in [Registry](https://github.com/travetto/travetto/tree/main/module/registry#readme "Patterns and utilities for handling registration of metadata and functionality for run-time use"), [Schema](https://github.com/travetto/travetto/tree/main/module/schema#readme "Data type registry for runtime validation, reflection and binding. ") and [Dependency Injection](https://github.com/travetto/travetto/tree/main/module/di#readme "Dependency registration/management and injection support."). These all center around defining a registry of classes, and associated type information.
13
+ The module is primarily aimed at extremely advanced usages for things that cannot be detected at runtime. The [Registry](https://github.com/travetto/travetto/tree/main/module/registry#readme "Patterns and utilities for handling registration of metadata and functionality for run-time use") module already has knowledge of all `class`es and `field`s, and is able to listen to changes there. Many of the modules build upon work by some of the foundational transformers defined in [Registry](https://github.com/travetto/travetto/tree/main/module/registry#readme "Patterns and utilities for handling registration of metadata and functionality for run-time use"), [Schema](https://github.com/travetto/travetto/tree/main/module/schema#readme "Data type registry for runtime validation, reflection and binding.") and [Dependency Injection](https://github.com/travetto/travetto/tree/main/module/di#readme "Dependency registration/management and injection support."). These all center around defining a registry of classes, and associated type information.
14
14
 
15
15
  Because working with the [Typescript](https://typescriptlang.org) API can be delicate (and open to breaking changes), creating new transformers should be done cautiously.
16
16
 
@@ -20,22 +20,19 @@ Below is an example of a transformer that upper cases all `class`, `method` and
20
20
 
21
21
  **Code: Sample Transformer - Upper case all declarations**
22
22
  ```typescript
23
- import * as ts from 'typescript';
23
+ import ts from 'typescript';
24
24
 
25
- import { OnProperty, TransformerState, OnMethod, OnClass, TransformerId } from '@travetto/transformer';
25
+ import { OnProperty, TransformerState, OnMethod, OnClass } from '@travetto/transformer';
26
26
 
27
27
  export class MakeUpper {
28
28
 
29
- static [TransformerId] = '@trv:transformer-test';
30
-
31
29
  @OnProperty()
32
30
  static handleProperty(state: TransformerState, node: ts.PropertyDeclaration): ts.PropertyDeclaration {
33
- if (!state.source.fileName.includes('doc/src')) {
31
+ if (!state.file.includes('doc/src')) {
34
32
  return node;
35
33
  }
36
34
  return state.factory.updatePropertyDeclaration(
37
35
  node,
38
- [],
39
36
  node.modifiers,
40
37
  node.name.getText().toUpperCase(),
41
38
  undefined,
@@ -46,12 +43,11 @@ export class MakeUpper {
46
43
 
47
44
  @OnClass()
48
45
  static handleClass(state: TransformerState, node: ts.ClassDeclaration): ts.ClassDeclaration {
49
- if (!state.source.fileName.includes('doc/src')) {
46
+ if (!state.file.includes('doc/src')) {
50
47
  return node;
51
48
  }
52
49
  return state.factory.updateClassDeclaration(
53
50
  node,
54
- [],
55
51
  node.modifiers,
56
52
  state.createIdentifier(node.name!.getText().toUpperCase()),
57
53
  node.typeParameters,
@@ -62,12 +58,11 @@ export class MakeUpper {
62
58
 
63
59
  @OnMethod()
64
60
  static handleMethod(state: TransformerState, node: ts.MethodDeclaration): ts.MethodDeclaration {
65
- if (!state.source.fileName.includes('doc/src')) {
61
+ if (!state.file.includes('doc/src')) {
66
62
  return node;
67
63
  }
68
64
  return state.factory.updateMethodDeclaration(
69
65
  node,
70
- [],
71
66
  node.modifiers,
72
67
  undefined,
73
68
  state.createIdentifier(node.name.getText().toUpperCase()),
package/__index__.ts ADDED
@@ -0,0 +1,15 @@
1
+ export * from './src/state';
2
+ export * from './src/visitor';
3
+ export * from './src/register';
4
+ export * from './src/types/visitor';
5
+ export * from './src/types/shared';
6
+ export type { AnyType } from './src/resolver/types';
7
+ export * from './src/manager';
8
+
9
+ export * from './src/util/core';
10
+ export * from './src/util/declaration';
11
+ export * from './src/util/decorator';
12
+ export * from './src/util/doc';
13
+ export * from './src/util/literal';
14
+ export * from './src/util/log';
15
+ export * from './src/util/system';
package/package.json CHANGED
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "name": "@travetto/transformer",
3
- "displayName": "Transformation",
4
- "version": "3.0.0-rc.1",
3
+ "version": "3.0.0-rc.10",
5
4
  "description": "Functionality for AST transformations, with transformer registration, and general utils",
6
5
  "keywords": [
7
6
  "typescript",
@@ -15,17 +14,25 @@
15
14
  "name": "Travetto Framework"
16
15
  },
17
16
  "files": [
18
- "index.ts",
17
+ "__index__.ts",
19
18
  "src",
20
- "test-support"
19
+ "support"
21
20
  ],
22
- "main": "index.ts",
21
+ "main": "__index__.ts",
23
22
  "repository": {
24
23
  "url": "https://github.com/travetto/travetto.git",
25
24
  "directory": "module/transformer"
26
25
  },
27
26
  "dependencies": {
28
- "@travetto/base": "^3.0.0-rc.0"
27
+ "@travetto/manifest": "^3.0.0-rc.7",
28
+ "tslib": "^2.5.0",
29
+ "typescript": "^4.9.5"
30
+ },
31
+ "travetto": {
32
+ "displayName": "Transformation",
33
+ "profiles": [
34
+ "compile"
35
+ ]
29
36
  },
30
37
  "publishConfig": {
31
38
  "access": "public"
package/src/importer.ts CHANGED
@@ -1,13 +1,16 @@
1
- import * as ts from 'typescript';
2
- import { basename, dirname, relative } from 'path';
1
+ import ts from 'typescript';
3
2
 
4
- import { PathUtil } from '@travetto/boot';
5
- import { ModuleUtil } from '@travetto/boot/src/internal/module-util';
3
+ import { PackageUtil, path } from '@travetto/manifest';
6
4
 
7
5
  import { AnyType, ExternalType } from './resolver/types';
8
6
  import { ImportUtil } from './util/import';
9
7
  import { CoreUtil } from './util/core';
10
8
  import { Import } from './types/shared';
9
+ import { LiteralUtil } from './util/literal';
10
+ import { DeclarationUtil } from './util/declaration';
11
+ import { TransformerIndex } from './manifest-index';
12
+
13
+ const D_OR_D_TS_EXT_RE = /[.]d([.]ts)?$/;
11
14
 
12
15
  /**
13
16
  * Manages imports within a ts.SourceFile
@@ -18,18 +21,81 @@ export class ImportManager {
18
21
  #imports: Map<string, Import>;
19
22
  #idx: Record<string, number> = {};
20
23
  #ids = new Map<string, string>();
24
+ #importName: string;
21
25
 
22
26
  constructor(public source: ts.SourceFile, public factory: ts.NodeFactory) {
23
27
  this.#imports = ImportUtil.collectImports(source);
28
+ this.#importName = TransformerIndex.getImportName(source.fileName);
29
+ }
30
+
31
+ #getImportFile(spec?: ts.Expression): string | undefined {
32
+ if (spec && ts.isStringLiteral(spec)) {
33
+ return spec.text.replace(/^['"]|["']$/g, '');
34
+ }
35
+ }
36
+
37
+ #rewriteModuleSpecifier(spec: ts.Expression | undefined): ts.Expression | undefined {
38
+ const fileOrImport = this.#getImportFile(spec);
39
+ if (
40
+ fileOrImport &&
41
+ (fileOrImport.startsWith('.') || TransformerIndex.isKnown(fileOrImport)) &&
42
+ !/[.]([mc]?js|ts|json)$/.test(fileOrImport)
43
+ ) {
44
+ return LiteralUtil.fromLiteral(this.factory, `${fileOrImport}.js`);
45
+ }
46
+ return spec;
47
+ }
48
+
49
+ #rewriteImportClause(
50
+ spec: ts.Expression | undefined,
51
+ clause: ts.ImportClause | undefined,
52
+ checker: ts.TypeChecker
53
+ ): ts.ImportClause | undefined {
54
+ if (!(spec && clause?.namedBindings && ts.isNamedImports(clause.namedBindings))) {
55
+ return clause;
56
+ }
57
+
58
+ const fileOrImport = this.#getImportFile(spec);
59
+ if (!(fileOrImport && (fileOrImport.startsWith('.') || TransformerIndex.isKnown(fileOrImport)))) {
60
+ return clause;
61
+ }
62
+
63
+ const bindings = clause.namedBindings;
64
+ const newBindings: ts.ImportSpecifier[] = [];
65
+ // Remove all type only imports
66
+ for (const el of bindings.elements) {
67
+ if (!el.isTypeOnly) {
68
+ const type = checker.getTypeAtLocation(el.name);
69
+ const objFlags = DeclarationUtil.getObjectFlags(type);
70
+ const typeFlags = type.getFlags();
71
+ if (objFlags || typeFlags !== 1) {
72
+ newBindings.push(el);
73
+ }
74
+ }
75
+ }
76
+ if (newBindings.length !== bindings.elements.length) {
77
+ return this.factory.updateImportClause(
78
+ clause,
79
+ clause.isTypeOnly,
80
+ clause.name,
81
+ this.factory.createNamedImports(newBindings)
82
+ );
83
+ } else {
84
+ return clause;
85
+ }
24
86
  }
25
87
 
26
88
  /**
27
89
  * Produces a unique ID for a given file, importing if needed
28
90
  */
29
- getId(file: string): string {
91
+ getId(file: string, name?: string): string {
30
92
  if (!this.#ids.has(file)) {
31
- const key = basename(file).replace(/[.][^.]*$/, '').replace(/[^A-Za-z0-9]+/g, '_');
32
- this.#ids.set(file, `ᚕ_${key}_${this.#idx[key] = (this.#idx[key] || 0) + 1}`);
93
+ if (name) {
94
+ this.#ids.set(file, name);
95
+ } else {
96
+ const key = path.basename(file).replace(/[.][^.]*$/, '').replace(/[^A-Za-z0-9]+/g, '_');
97
+ this.#ids.set(file, `Ⲑ_${key}_${this.#idx[key] = (this.#idx[key] || 0) + 1}`);
98
+ }
33
99
  }
34
100
  return this.#ids.get(file)!;
35
101
  }
@@ -37,28 +103,16 @@ export class ImportManager {
37
103
  /**
38
104
  * Import a file if needed, and record it's identifier
39
105
  */
40
- importFile(file: string, base?: string): Import {
41
- file = ModuleUtil.normalizePath(file);
106
+ importFile(file: string, name?: string): Import {
107
+ file = TransformerIndex.getImportName(file);
42
108
 
43
109
  // Allow for node classes to be imported directly
44
110
  if (/@types\/node/.test(file)) {
45
- file = require.resolve(file.replace(/.*@types\/node\//, '').replace(/[.]d([.]ts)?$/, ''));
46
- }
47
-
48
- // Handle relative imports
49
- if (file.startsWith('.') && base &&
50
- !base.startsWith('@travetto') && !base.includes('node_modules')
51
- ) { // Relative path
52
- const fileDir = dirname(PathUtil.resolveUnix(file));
53
- const baseDir = dirname(PathUtil.resolveUnix(base));
54
- file = `${relative(baseDir, fileDir) || '.'}/${basename(file)}`;
55
- if (/^[A-Za-z]/.test(file)) {
56
- file = `./${file}`;
57
- }
111
+ file = PackageUtil.resolveImport(file.replace(/.*@types\/node\//, '').replace(D_OR_D_TS_EXT_RE, ''));
58
112
  }
59
113
 
60
- if (!/[.]d([.]ts)?$/.test(file) && !this.#newImports.has(file)) {
61
- const id = this.getId(file);
114
+ if (!D_OR_D_TS_EXT_RE.test(file) && !this.#newImports.has(file)) {
115
+ const id = this.getId(file, name);
62
116
 
63
117
  if (this.#imports.has(id)) { // Already imported, be cool
64
118
  return this.#imports.get(id)!;
@@ -77,8 +131,8 @@ export class ImportManager {
77
131
  */
78
132
  importFromResolved(...types: AnyType[]): void {
79
133
  for (const type of types) {
80
- if (type.key === 'external' && type.source && type.source !== this.source.fileName) {
81
- this.importFile(type.source, this.source.fileName);
134
+ if (type.key === 'external' && type.importName && type.importName !== this.#importName) {
135
+ this.importFile(type.importName);
82
136
  }
83
137
  switch (type.key) {
84
138
  case 'external':
@@ -99,11 +153,11 @@ export class ImportManager {
99
153
  }
100
154
 
101
155
  try {
102
- const importStmts = [...this.#newImports.values()].map(({ path, ident }) => {
156
+ const importStmts = [...this.#newImports.values()].map(({ path: resolved, ident }) => {
103
157
  const importStmt = this.factory.createImportDeclaration(
104
- undefined, undefined,
158
+ undefined,
105
159
  this.factory.createImportClause(false, undefined, this.factory.createNamespaceImport(ident)),
106
- this.factory.createStringLiteral(path)
160
+ this.factory.createStringLiteral(resolved)
107
161
  );
108
162
  return importStmt;
109
163
  });
@@ -116,27 +170,61 @@ export class ImportManager {
116
170
  if (!(err instanceof Error)) {
117
171
  throw err;
118
172
  }
119
- const out = new Error(`${err.message} in ${file.fileName.replace(PathUtil.cwd, '.')}`);
173
+ const out = new Error(`${err.message} in ${file.fileName.replace(process.cwd(), '.')}`);
120
174
  out.stack = err.stack;
121
175
  throw out;
122
176
  }
123
177
  }
124
178
 
179
+ finalizeImportExportExtension(ret: ts.SourceFile, checker: ts.TypeChecker): ts.SourceFile {
180
+ const toAdd: ts.Statement[] = [];
181
+
182
+ for (const stmt of ret.statements) {
183
+ if (ts.isExportDeclaration(stmt)) {
184
+ if (!stmt.isTypeOnly) {
185
+ toAdd.push(this.factory.updateExportDeclaration(
186
+ stmt,
187
+ stmt.modifiers,
188
+ stmt.isTypeOnly,
189
+ stmt.exportClause,
190
+ this.#rewriteModuleSpecifier(stmt.moduleSpecifier),
191
+ stmt.assertClause
192
+ ));
193
+ }
194
+ } else if (ts.isImportDeclaration(stmt)) {
195
+ if (!stmt.importClause?.isTypeOnly) {
196
+ toAdd.push(this.factory.updateImportDeclaration(
197
+ stmt,
198
+ stmt.modifiers,
199
+ this.#rewriteImportClause(stmt.moduleSpecifier, stmt.importClause, checker)!,
200
+ this.#rewriteModuleSpecifier(stmt.moduleSpecifier)!,
201
+ stmt.assertClause
202
+ ));
203
+ }
204
+ } else {
205
+ toAdd.push(stmt);
206
+ }
207
+ }
208
+ return CoreUtil.updateSource(this.factory, ret, toAdd);
209
+ }
210
+
125
211
  /**
126
212
  * Reset the imports into the source file
127
213
  */
128
- finalize(ret: ts.SourceFile): ts.SourceFile {
129
- return this.finalizeNewImports(ret) ?? ret;
214
+ finalize(ret: ts.SourceFile, checker: ts.TypeChecker): ts.SourceFile {
215
+ ret = this.finalizeNewImports(ret) ?? ret;
216
+ ret = this.finalizeImportExportExtension(ret, checker) ?? ret;
217
+ return ret;
130
218
  }
131
219
 
132
220
  /**
133
221
  * Get the identifier and import if needed
134
222
  */
135
223
  getOrImport(factory: ts.NodeFactory, type: ExternalType): ts.Identifier | ts.PropertyAccessExpression {
136
- if (type.source === this.source.fileName) {
224
+ if (type.importName === this.#importName) {
137
225
  return factory.createIdentifier(type.name!);
138
226
  } else {
139
- const { ident } = this.#imports.get(type.source) ?? this.importFile(type.source, this.source.fileName);
227
+ const { ident } = this.#imports.get(type.importName) ?? this.importFile(type.importName);
140
228
  return factory.createPropertyAccessExpression(ident, type.name!);
141
229
  }
142
230
  }
package/src/manager.ts ADDED
@@ -0,0 +1,62 @@
1
+ import ts from 'typescript';
2
+
3
+ import { RootIndex } from '@travetto/manifest';
4
+
5
+ import { NodeTransformer } from './types/visitor';
6
+ import { VisitorFactory } from './visitor';
7
+ import { TransformerState } from './state';
8
+ import { getAllTransformers } from './register';
9
+
10
+ /**
11
+ * Manages the typescript transformers
12
+ */
13
+ export class TransformerManager {
14
+
15
+ /**
16
+ * Create transformer manager
17
+ * @param transformerFiles
18
+ * @param manifest
19
+ * @returns
20
+ */
21
+ static async create(transformerFiles: string[]): Promise<TransformerManager> {
22
+ const transformers: NodeTransformer<TransformerState>[] = [];
23
+
24
+ for (const file of transformerFiles) { // Exclude based on blacklist
25
+ const entry = RootIndex.getEntry(file)!;
26
+ transformers.push(...getAllTransformers(await import(entry.import), entry.module));
27
+ }
28
+
29
+ // Prepare a new visitor factory with a given type checker
30
+ return new TransformerManager(transformers);
31
+ }
32
+
33
+ #cached: ts.CustomTransformers | undefined;
34
+ #transformers: NodeTransformer<TransformerState>[];
35
+
36
+ constructor(transformers: NodeTransformer<TransformerState>[]) {
37
+ this.#transformers = transformers;
38
+ }
39
+
40
+ /**
41
+ * Initialize with type checker
42
+ * @param checker
43
+ */
44
+ init(checker: ts.TypeChecker): void {
45
+ const visitor = new VisitorFactory(
46
+ (ctx, src) => new TransformerState(src, ctx.factory, checker),
47
+ this.#transformers
48
+ );
49
+
50
+ // Define transformers for the compiler
51
+ this.#cached = {
52
+ before: [visitor.visitor()]
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Get typescript transformer object
58
+ */
59
+ get(): ts.CustomTransformers | undefined {
60
+ return this.#cached!;
61
+ }
62
+ }
@@ -0,0 +1,36 @@
1
+ import ts from 'typescript';
2
+
3
+ import { RootIndex, IndexedFile, path } from '@travetto/manifest';
4
+ import { DeclarationUtil } from './util/declaration';
5
+
6
+ /**
7
+ * Specific logic for the transformer
8
+ */
9
+ export class TransformerIndex {
10
+ /**
11
+ * Resolve import name for a given type
12
+ */
13
+ static getImportName(type: ts.Type | string, removeExt = false): string {
14
+ const ogSource = typeof type === 'string' ? type : DeclarationUtil.getPrimaryDeclarationNode(type).getSourceFile().fileName;
15
+ let sourceFile = path.toPosix(ogSource);
16
+
17
+ if (!sourceFile.endsWith('.js') && !sourceFile.endsWith('.ts')) {
18
+ sourceFile = `${sourceFile}.ts`;
19
+ }
20
+
21
+ const imp =
22
+ RootIndex.getEntry(/[.]ts$/.test(sourceFile) ? sourceFile : `${sourceFile}.js`)?.import ??
23
+ RootIndex.getFromImport(sourceFile.replace(/^.*node_modules\//, '').replace(/[.]ts$/, ''))?.import ??
24
+ ogSource;
25
+
26
+ return removeExt ? imp.replace(/[.]js$/, '') : imp;
27
+ }
28
+
29
+ static isKnown(fileOrImport: string): boolean {
30
+ return (RootIndex.getFromSource(fileOrImport) !== undefined) || (RootIndex.getFromImport(fileOrImport) !== undefined);
31
+ }
32
+
33
+ static getFromImport(imp: string): IndexedFile | undefined {
34
+ return RootIndex.getFromImport(imp);
35
+ }
36
+ }
package/src/register.ts CHANGED
@@ -1,26 +1,55 @@
1
- import * as ts from 'typescript';
2
- import { DecoratorMeta, NodeTransformer, State, TransformPhase, TransformerType, Transformer, TransformerId } from './types/visitor';
1
+ import ts from 'typescript';
3
2
 
4
- const HandlersProp = Symbol.for('@trv:transformer/handlers');
3
+ import { DecoratorMeta, NodeTransformer, State, TransformPhase, TransformerType, Transformer, ModuleNameⲐ } from './types/visitor';
4
+
5
+ const HandlersProp = Symbol.for('@travetto/transformer:handlers');
5
6
 
6
7
  type TransformerWithHandlers = Transformer & { [HandlersProp]?: NodeTransformer[] };
7
8
 
9
+ function isTransformer(x: unknown): x is Transformer {
10
+ return x !== null && x !== undefined && typeof x === 'function';
11
+ }
12
+
8
13
  /**
9
14
  * Get all transformers
10
15
  * @param obj Object to search for transformers
11
16
  */
12
- export function getAllTransformers(obj: Record<string, { [HandlersProp]?: NodeTransformer[] }>): NodeTransformer[] {
13
- return Object.values(obj).flatMap(x => x[HandlersProp] ?? []);
17
+ export function getAllTransformers(obj: Record<string, { [HandlersProp]?: NodeTransformer[] }>, module: string): NodeTransformer[] {
18
+ return Object.values(obj)
19
+ .flatMap(x => {
20
+ if (isTransformer(x)) {
21
+ x[ModuleNameⲐ] = module;
22
+ }
23
+ return (x[HandlersProp] ?? []);
24
+ })
25
+ .map(handler => ({
26
+ ...handler,
27
+ key: `${module}:${handler.key}`,
28
+ target: handler.target?.map(t => `${module}:${t}`)
29
+ }));
14
30
  }
15
31
 
16
32
  // Store handlers in class
17
33
  function storeHandler(cls: TransformerWithHandlers, fn: Function, phase: TransformPhase, type: TransformerType, target?: string[]): void {
18
- if (target) {
19
- const ns = cls[TransformerId].split('/')[0]; // Everything before the '/'
20
- target = target.map(x => x.startsWith('@') ? x : `${ns}/${x}`);
21
- }
22
- cls[HandlersProp] = cls[HandlersProp] ?? [];
23
- cls[HandlersProp]!.push({ key: `${cls[TransformerId]}/${fn.name}`, [phase]: fn.bind(cls), type, target });
34
+ (cls[HandlersProp] ??= []).push({ key: fn.name, [phase]: fn.bind(cls), type, target });
35
+ }
36
+
37
+ /**
38
+ * Wraps entire file before transforming
39
+ */
40
+ export function OnFile(...target: string[]) {
41
+ return <S extends State = State, R extends ts.Node = ts.Node>(
42
+ inst: Transformer, __: unknown, d: TypedPropertyDescriptor<(state: S, node: ts.SourceFile) => R>
43
+ ): void => storeHandler(inst, d.value!, 'before', 'file', target);
44
+ }
45
+
46
+ /**
47
+ * Wraps entire file after transforming
48
+ */
49
+ export function AfterFile(...target: string[]) {
50
+ return <S extends State = State, R extends ts.Node = ts.Node>(
51
+ inst: Transformer, __: unknown, d: TypedPropertyDescriptor<(state: S, node: ts.SourceFile) => R>
52
+ ): void => storeHandler(inst, d.value!, 'before', 'file', target);
24
53
  }
25
54
 
26
55
  /**
@@ -1,12 +1,17 @@
1
1
  /* eslint-disable no-bitwise */
2
- import * as ts from 'typescript';
3
- import { dirname } from 'path';
2
+ import ts from 'typescript';
4
3
 
5
- import { PathUtil } from '@travetto/boot';
6
- import { Util } from '@travetto/base';
4
+ import { path } from '@travetto/manifest';
5
+
6
+ import { DocUtil } from '../util/doc';
7
+ import { CoreUtil } from '../util/core';
8
+ import { DeclarationUtil } from '../util/declaration';
9
+ import { LiteralUtil } from '../util/literal';
7
10
 
8
11
  import { Type, AnyType, UnionType, Checker } from './types';
9
- import { DocUtil, CoreUtil, DeclarationUtil, LiteralUtil } from '../util';
12
+ import { CoerceUtil } from './coerce';
13
+
14
+ import { TransformerIndex } from '../manifest-index';
10
15
 
11
16
  /**
12
17
  * List of global types that can be parameterized
@@ -62,9 +67,10 @@ export function TypeCategorize(checker: ts.TypeChecker, type: ts.Type): { catego
62
67
  }
63
68
 
64
69
  const source = DeclarationUtil.getPrimaryDeclarationNode(resolvedType).getSourceFile();
65
- if (source?.fileName.includes('@types/node/globals') || source?.fileName.includes('typescript/lib')) {
70
+ const sourceFile = source.fileName;
71
+ if (sourceFile?.includes('@types/node/globals') || sourceFile?.includes('typescript/lib')) {
66
72
  return { category: 'literal', type };
67
- } else if (!source?.fileName.includes('@travetto') && source?.fileName.endsWith('.d.ts')) {
73
+ } else if (sourceFile?.endsWith('.d.ts') && !TransformerIndex.isKnown(sourceFile)) {
68
74
  return { category: 'unknown', type };
69
75
  } else if (!resolvedType.isClass()) { // Not a real type
70
76
  return { category: 'shape', type: resolvedType };
@@ -118,7 +124,7 @@ export const TypeBuilder: {
118
124
  if (name in GLOBAL_SIMPLE) {
119
125
  const cons = GLOBAL_SIMPLE[name];
120
126
  // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
121
- const ret = LiteralUtil.isLiteralType(type) ? Util.coerceType(type.value, cons as typeof String, false) :
127
+ const ret = LiteralUtil.isLiteralType(type) ? CoerceUtil.coerce(type.value, cons as typeof String, false) :
122
128
  undefined;
123
129
 
124
130
  return {
@@ -140,12 +146,10 @@ export const TypeBuilder: {
140
146
  },
141
147
  external: {
142
148
  build: (checker, type) => {
143
- const source = DeclarationUtil.getPrimaryDeclarationNode(type).getSourceFile();
144
149
  const name = CoreUtil.getSymbol(type)?.getName();
145
- return {
146
- key: 'external', name, source: source.fileName,
147
- tsTypeArguments: checker.getAllTypeArguments(type)
148
- };
150
+ const importName = TransformerIndex.getImportName(type);
151
+ const tsTypeArguments = checker.getAllTypeArguments(type);
152
+ return { key: 'external', name, importName, tsTypeArguments };
149
153
  }
150
154
  },
151
155
  union: {
@@ -176,25 +180,23 @@ export const TypeBuilder: {
176
180
  },
177
181
  shape: {
178
182
  build: (checker, type, alias?) => {
179
- const fieldNodes: Record<string, ts.Type> = {};
180
- const name = CoreUtil.getSymbol(alias ?? type);
181
- const source = DeclarationUtil.getPrimaryDeclarationNode(type)?.getSourceFile();
183
+ const tsFieldTypes: Record<string, ts.Type> = {};
184
+ const name = CoreUtil.getSymbol(alias ?? type)?.getName();
185
+ const importName = TransformerIndex.getImportName(type);
186
+ const tsTypeArguments = checker.getAllTypeArguments(type);
182
187
  for (const member of checker.getPropertiesOfType(type)) {
183
188
  const dec = DeclarationUtil.getPrimaryDeclarationNode(member);
184
189
  if (DeclarationUtil.isPublic(dec)) { // If public
185
190
  const memberType = checker.getType(dec);
186
- if (!memberType.getCallSignatures().length) { // if not a function
187
- fieldNodes[member.getName()] = memberType;
191
+ if (
192
+ !member.getName().includes('@') && // if not a symbol
193
+ !memberType.getCallSignatures().length // if not a function
194
+ ) {
195
+ tsFieldTypes[member.getName()] = memberType;
188
196
  }
189
197
  }
190
198
  }
191
- return {
192
- key: 'shape', name: name?.getName(),
193
- source: source?.fileName,
194
- tsFieldTypes: fieldNodes,
195
- tsTypeArguments: checker.getAllTypeArguments(type),
196
- fieldTypes: {}
197
- };
199
+ return { key: 'shape', name, importName, tsFieldTypes, tsTypeArguments, fieldTypes: {} };
198
200
  }
199
201
  },
200
202
  concrete: {
@@ -202,23 +204,26 @@ export const TypeBuilder: {
202
204
  const [tag] = DocUtil.readDocTag(type, 'concrete');
203
205
  if (tag) {
204
206
  // eslint-disable-next-line prefer-const
205
- let [source, name, ext] = tag.split(':');
207
+ let [importName, name] = tag.split(':');
206
208
  if (!name) {
207
- name = source;
208
- source = '.';
209
+ name = importName;
210
+ importName = '.';
209
211
  }
210
212
 
211
- const sourceFile: string = DeclarationUtil.getDeclarations(type)
212
- ?.find(x => ts.getAllJSDocTags(x, (t): t is ts.JSDocTag => t.tagName.getText() === 'concrete').length)
213
- ?.getSourceFile().fileName ?? '';
213
+ // Resolving relative to source file
214
+ if (importName.startsWith('.')) {
215
+ const rawSourceFile: string = DeclarationUtil.getDeclarations(type)
216
+ ?.find(x => ts.getAllJSDocTags(x, (t): t is ts.JSDocTag => t.tagName.getText() === 'concrete').length)
217
+ ?.getSourceFile().fileName ?? '';
214
218
 
215
- if (source === '.') {
216
- source = sourceFile;
217
- } else if (source.startsWith('.')) {
218
- source = PathUtil.resolveUnix(dirname(sourceFile), source);
219
+ if (importName === '.') {
220
+ importName = TransformerIndex.getImportName(rawSourceFile);
221
+ } else {
222
+ const base = path.dirname(rawSourceFile);
223
+ importName = TransformerIndex.getImportName(path.resolve(base, importName));
224
+ }
219
225
  }
220
-
221
- return { key: 'external', name, source: ext === 'node' ? source : PathUtil.resolveUnix(sourceFile, source) };
226
+ return { key: 'external', name, importName };
222
227
  }
223
228
  }
224
229
  }
@@ -1,5 +1,5 @@
1
- import * as ts from 'typescript';
2
- import { AnyType } from './types';
1
+ import ts from 'typescript';
2
+ import type { AnyType } from './types';
3
3
 
4
4
  /**
5
5
  * Cache for handling recursive checks