@travetto/compiler 3.0.0-rc.4 → 3.0.0-rc.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.
- package/README.md +8 -5
- package/__index__.ts +3 -0
- package/bin/transpile.d.ts +32 -0
- package/bin/transpile.js +227 -0
- package/bin/trv.js +81 -0
- package/package.json +30 -15
- package/src/compiler.ts +147 -147
- package/src/state.ts +225 -0
- package/src/util.ts +202 -0
- package/support/bin/compiler-bootstrap.ts +151 -0
- package/support/bin/utils.ts +116 -0
- package/support/main.output.ts +11 -0
- package/tsconfig.trv.json +22 -0
- package/LICENSE +0 -21
- package/index.ts +0 -3
- package/src/host.ts +0 -142
- package/src/transformer.ts +0 -75
- package/support/dynamic.compiler.ts +0 -72
- package/support/phase.init.ts +0 -13
- package/support/phase.reset.ts +0 -10
package/src/util.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import ts from 'typescript';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import { readdirSync } from 'fs';
|
|
4
|
+
|
|
5
|
+
import { ManifestModule, ManifestRoot, Package, PackageUtil, path } from '@travetto/manifest';
|
|
6
|
+
|
|
7
|
+
type InputToSource = (inputFile: string) => ({ source: string, module: ManifestModule } | undefined);
|
|
8
|
+
export type FileWatchEvent = { type: 'create' | 'delete' | 'update', path: string };
|
|
9
|
+
|
|
10
|
+
const nativeCwd = process.cwd();
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Standard utilities for compiler
|
|
14
|
+
*/
|
|
15
|
+
export class CompilerUtil {
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Determines if write callback data has sourcemap information
|
|
19
|
+
* @param data
|
|
20
|
+
* @returns
|
|
21
|
+
*/
|
|
22
|
+
static isSourceMapUrlPosData(data?: ts.WriteFileCallbackData): data is { sourceMapUrlPos: number } {
|
|
23
|
+
return data !== undefined && data !== null && typeof data === 'object' && ('sourceMapUrlPos' in data);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Rewrite's sourcemap locations to real folders
|
|
28
|
+
* @returns
|
|
29
|
+
*/
|
|
30
|
+
static rewriteSourceMap(text: string, inputToSource: InputToSource): string {
|
|
31
|
+
const data: { sourceRoot: string, sources: string[] } = JSON.parse(text);
|
|
32
|
+
const [src] = data.sources;
|
|
33
|
+
|
|
34
|
+
const { source: file, module } = inputToSource(src) ?? {};
|
|
35
|
+
if (file && module) {
|
|
36
|
+
data.sourceRoot = module.source;
|
|
37
|
+
data.sources = [file.replace(`${module.source}/`, '')];
|
|
38
|
+
text = JSON.stringify(data);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return text;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Rewrite's inline sourcemap locations to real folders
|
|
46
|
+
* @param text
|
|
47
|
+
* @param inputToSource
|
|
48
|
+
* @param writeData
|
|
49
|
+
* @returns
|
|
50
|
+
*/
|
|
51
|
+
static rewriteInlineSourceMap(
|
|
52
|
+
text: string,
|
|
53
|
+
inputToSource: InputToSource,
|
|
54
|
+
{ sourceMapUrlPos }: ts.WriteFileCallbackData & { sourceMapUrlPos: number }
|
|
55
|
+
): string {
|
|
56
|
+
const sourceMapUrl = text.substring(sourceMapUrlPos);
|
|
57
|
+
const [prefix, sourceMapData] = sourceMapUrl.split('base64,');
|
|
58
|
+
const rewritten = this.rewriteSourceMap(Buffer.from(sourceMapData, 'base64url').toString('utf8'), inputToSource);
|
|
59
|
+
return [
|
|
60
|
+
text.substring(0, sourceMapUrlPos),
|
|
61
|
+
prefix,
|
|
62
|
+
'base64,',
|
|
63
|
+
Buffer.from(rewritten, 'utf8').toString('base64url')
|
|
64
|
+
].join('');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Rewrites the package.json to target .js files instead of .ts files, and pins versions
|
|
69
|
+
* @param manifest
|
|
70
|
+
* @param file
|
|
71
|
+
* @param text
|
|
72
|
+
* @returns
|
|
73
|
+
*/
|
|
74
|
+
static rewritePackageJSON(manifest: ManifestRoot, text: string, opts: ts.CompilerOptions): string {
|
|
75
|
+
const pkg: Package = JSON.parse(text);
|
|
76
|
+
if (pkg.files) {
|
|
77
|
+
pkg.files = pkg.files.map(x => x.replace(/[.]ts$/, '.js'));
|
|
78
|
+
}
|
|
79
|
+
if (pkg.main) {
|
|
80
|
+
pkg.main = pkg.main.replace(/[.]ts$/, '.js');
|
|
81
|
+
}
|
|
82
|
+
pkg.type = opts.module !== ts.ModuleKind.CommonJS ? 'module' : 'commonjs';
|
|
83
|
+
for (const key of ['devDependencies', 'dependencies', 'peerDependencies'] as const) {
|
|
84
|
+
if (key in pkg) {
|
|
85
|
+
for (const dep of Object.keys(pkg[key] ?? {})) {
|
|
86
|
+
if (dep in manifest.modules) {
|
|
87
|
+
pkg[key]![dep] = manifest.modules[dep].version;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return JSON.stringify(pkg, null, 2);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Read the given tsconfig.json values for the project
|
|
97
|
+
* @param path
|
|
98
|
+
* @returns
|
|
99
|
+
*/
|
|
100
|
+
static async readTsConfigOptions(file: string): Promise<ts.CompilerOptions> {
|
|
101
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
102
|
+
const { options } = ts.parseJsonSourceFileConfigFileContent(
|
|
103
|
+
ts.readJsonConfigFile(file, ts.sys.readFile), ts.sys, nativeCwd
|
|
104
|
+
);
|
|
105
|
+
options.target = ts.ScriptTarget.ESNext;
|
|
106
|
+
return options;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Build transpilation error
|
|
111
|
+
* @param filename The name of the file
|
|
112
|
+
* @param diagnostics The diagnostic errors
|
|
113
|
+
*/
|
|
114
|
+
static buildTranspileError(filename: string, diagnostics: Error | readonly ts.Diagnostic[]): Error {
|
|
115
|
+
if (diagnostics instanceof Error) {
|
|
116
|
+
return diagnostics;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const errors: string[] = diagnostics.slice(0, 5).map(diag => {
|
|
120
|
+
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
121
|
+
const message = ts.flattenDiagnosticMessageText(diag.messageText, '\n');
|
|
122
|
+
if (diag.file) {
|
|
123
|
+
const { line, character } = diag.file.getLineAndCharacterOfPosition(diag.start!);
|
|
124
|
+
return ` @ ${diag.file.fileName.replace(nativeCwd, '.')}(${line + 1}, ${character + 1}): ${message}`;
|
|
125
|
+
} else {
|
|
126
|
+
return ` ${message}`;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
if (diagnostics.length > 5) {
|
|
131
|
+
errors.push(`${diagnostics.length - 5} more ...`);
|
|
132
|
+
}
|
|
133
|
+
return new Error(`Transpiling ${filename.replace(nativeCwd, '.')} failed: \n${errors.join('\n')}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Allows for watching of explicit folders
|
|
138
|
+
*
|
|
139
|
+
* @param onEvent
|
|
140
|
+
* @returns
|
|
141
|
+
*/
|
|
142
|
+
static async fileWatcher(
|
|
143
|
+
folders: string[],
|
|
144
|
+
onEvent: (ev: FileWatchEvent, folder: string) => void
|
|
145
|
+
): Promise<() => Promise<void>> {
|
|
146
|
+
const watcher = await import('@parcel/watcher');
|
|
147
|
+
const subs: (() => Promise<void>)[] = [];
|
|
148
|
+
for (const folder of folders) {
|
|
149
|
+
const sub = await watcher.subscribe(folder, (err, events) => {
|
|
150
|
+
for (const ev of events) {
|
|
151
|
+
onEvent(ev, folder);
|
|
152
|
+
}
|
|
153
|
+
}, { ignore: ['node_modules', ...readdirSync(folder).filter(x => x.startsWith('.') && x.length > 2)] });
|
|
154
|
+
subs.push(() => sub.unsubscribe());
|
|
155
|
+
}
|
|
156
|
+
const readiedSubs = await Promise.all(subs);
|
|
157
|
+
return () => Promise.all(readiedSubs.map(s => s())).then(() => { });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Get loaded compiler options
|
|
162
|
+
*/
|
|
163
|
+
static async getCompilerOptions(outputFolder: string, bootTsConfig: string, workspace: string): Promise<ts.CompilerOptions> {
|
|
164
|
+
const opts: Partial<ts.CompilerOptions> = {};
|
|
165
|
+
const rootDir = nativeCwd;
|
|
166
|
+
const projTsconfig = path.resolve('tsconfig.json');
|
|
167
|
+
// Fallback to base tsconfig if not found in local folder
|
|
168
|
+
const config = (await fs.stat(projTsconfig).catch(() => false)) ? projTsconfig : bootTsConfig;
|
|
169
|
+
const base = await this.readTsConfigOptions(config);
|
|
170
|
+
|
|
171
|
+
const { type } = PackageUtil.readPackage(workspace);
|
|
172
|
+
|
|
173
|
+
if (type !== undefined) {
|
|
174
|
+
base.module = `${type}`.toLowerCase() === 'commonjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
...base,
|
|
179
|
+
resolveJsonModule: true,
|
|
180
|
+
allowJs: true,
|
|
181
|
+
outDir: outputFolder,
|
|
182
|
+
sourceRoot: rootDir,
|
|
183
|
+
...opts,
|
|
184
|
+
rootDir,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Naive hashing
|
|
191
|
+
*/
|
|
192
|
+
static naiveHash(text: string): number {
|
|
193
|
+
let hash = 5381;
|
|
194
|
+
|
|
195
|
+
for (let i = 0; i < text.length; i++) {
|
|
196
|
+
// eslint-disable-next-line no-bitwise
|
|
197
|
+
hash = (hash * 33) ^ text.charCodeAt(i);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return Math.abs(hash);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import cp from 'child_process';
|
|
4
|
+
|
|
5
|
+
import type { ManifestState, ManifestContext, ManifestRoot } from '@travetto/manifest';
|
|
6
|
+
|
|
7
|
+
import { log, compileIfStale, getProjectSources, addNodePath, importManifest } from './utils';
|
|
8
|
+
|
|
9
|
+
const PRECOMPILE_MODS = [
|
|
10
|
+
'@travetto/terminal',
|
|
11
|
+
'@travetto/manifest',
|
|
12
|
+
'@travetto/transformer',
|
|
13
|
+
'@travetto/compiler'
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
let manifestTemp;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Step 0
|
|
20
|
+
*/
|
|
21
|
+
export async function precompile(ctx: ManifestContext): Promise<void> {
|
|
22
|
+
for (const mod of PRECOMPILE_MODS) {
|
|
23
|
+
await compileIfStale(ctx, `[0] Compiling ${mod}`, await getProjectSources(ctx, mod),);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function writeManifest(ctx: ManifestContext, manifest: ManifestRoot): Promise<void> {
|
|
28
|
+
const { ManifestUtil } = await importManifest(ctx);
|
|
29
|
+
return ManifestUtil.writeManifest(ctx, manifest);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function rewriteManifests(ctx: ManifestContext, state: ManifestState): Promise<void> {
|
|
33
|
+
const { ManifestUtil } = await importManifest(ctx);
|
|
34
|
+
|
|
35
|
+
// Write out all changed manifests
|
|
36
|
+
const { getContext } = await import('../../bin/transpile');
|
|
37
|
+
|
|
38
|
+
const dirtyModules = [...Object.entries(state.delta)].filter(x => x[1].length > 0).map(([mod]) => mod);
|
|
39
|
+
for (const module of dirtyModules) {
|
|
40
|
+
const subCtx = await getContext(state.manifest.modules[module].source);
|
|
41
|
+
await ManifestUtil.createAndWriteManifest(subCtx);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Step 1
|
|
47
|
+
*/
|
|
48
|
+
export async function buildManifest(ctx: ManifestContext): Promise<ManifestState> {
|
|
49
|
+
log('[1] Manifest Generation');
|
|
50
|
+
const { ManifestUtil } = await importManifest(ctx);
|
|
51
|
+
return ManifestUtil.produceState(ctx);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function shouldRebuildCompiler({ delta }: ManifestState): { total: boolean, transformers: [string, string][] } {
|
|
55
|
+
// Did enough things change to re-stage and build the compiler
|
|
56
|
+
const transformersChanged = Object.entries(delta)
|
|
57
|
+
.flatMap(([mod, files]) => files.map(x => [mod, x.file]))
|
|
58
|
+
.filter((ev): ev is [string, string] => ev[1].startsWith('support/transform'));
|
|
59
|
+
const transformerChanged = (delta['@travetto/transformer'] ?? []);
|
|
60
|
+
const compilerChanged = delta['@travetto/compiler'] ?? [];
|
|
61
|
+
|
|
62
|
+
const changed = transformerChanged.length || transformersChanged.length || compilerChanged.length;
|
|
63
|
+
if (changed) {
|
|
64
|
+
if (compilerChanged.length) {
|
|
65
|
+
log('[2] Compiler source changed @travetto/compiler', compilerChanged);
|
|
66
|
+
}
|
|
67
|
+
if (transformerChanged.length) {
|
|
68
|
+
log('[2] Compiler source changed @travetto/transformer', transformerChanged);
|
|
69
|
+
}
|
|
70
|
+
if (transformersChanged.length) {
|
|
71
|
+
log('[2] Compiler source changed */support/transform', transformersChanged);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { total: changed > 0, transformers: transformersChanged };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Step 2
|
|
79
|
+
*/
|
|
80
|
+
async function buildCompiler(state: ManifestState, ctx: ManifestContext): Promise<void> {
|
|
81
|
+
const changed = shouldRebuildCompiler(state);
|
|
82
|
+
|
|
83
|
+
if (changed.transformers.length) {
|
|
84
|
+
state = await buildManifest(ctx);
|
|
85
|
+
let x = 0;
|
|
86
|
+
for (const [mod, file] of changed.transformers) {
|
|
87
|
+
await compileIfStale(
|
|
88
|
+
ctx,
|
|
89
|
+
`[2.${x += 1}] ${file} Bootstrapping`,
|
|
90
|
+
await getProjectSources(ctx, mod, ['package.json', file])
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
log('[2] Compiler Ready');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Step 4
|
|
100
|
+
*/
|
|
101
|
+
async function compileOutput(state: ManifestState, ctx: ManifestContext, watch?: boolean): Promise<void> {
|
|
102
|
+
let changes = Object.values(state.delta).flat();
|
|
103
|
+
|
|
104
|
+
// Remove files that should go away
|
|
105
|
+
await Promise.all(changes.filter(x => x.type === 'removed')
|
|
106
|
+
.map(x => fs.unlink(path.resolve(ctx.workspacePath, ctx.outputFolder, x.file)).catch(() => { })));
|
|
107
|
+
|
|
108
|
+
changes = changes.filter(x => x.type !== 'removed');
|
|
109
|
+
|
|
110
|
+
const { ManifestUtil } = await importManifest(ctx);
|
|
111
|
+
const resolve = ManifestUtil.resolveFile.bind(null, ctx, state.manifest, '@travetto/compiler');
|
|
112
|
+
|
|
113
|
+
manifestTemp ??= await ManifestUtil.writeState(state);
|
|
114
|
+
const cwd = path.resolve(ctx.workspacePath, ctx.compilerFolder);
|
|
115
|
+
|
|
116
|
+
if (changes.length) {
|
|
117
|
+
log('[3] Changed Sources', changes);
|
|
118
|
+
|
|
119
|
+
// Blocking call, compile only
|
|
120
|
+
const res = cp.spawnSync(process.argv0,
|
|
121
|
+
[resolve('support/main.output'), manifestTemp],
|
|
122
|
+
{ cwd, stdio: 'inherit', encoding: 'utf8' }
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
if (res.status) {
|
|
126
|
+
throw new Error(res.stderr);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
await rewriteManifests(ctx, state);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (watch) {
|
|
133
|
+
// Rewrite state with updated manifest
|
|
134
|
+
const newState = await ManifestUtil.produceState(ctx);
|
|
135
|
+
manifestTemp = await ManifestUtil.writeState(newState);
|
|
136
|
+
|
|
137
|
+
// Run with watching
|
|
138
|
+
cp.spawnSync(process.argv0,
|
|
139
|
+
[resolve('support/main.output'), manifestTemp, 'true'], { cwd, stdio: 'inherit' }
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export async function compile(ctx: ManifestContext, watch?: boolean): Promise<ManifestState> {
|
|
145
|
+
await precompile(ctx); // Step 0
|
|
146
|
+
const state = await buildManifest(ctx); // Step 1
|
|
147
|
+
await buildCompiler(state, ctx); // Step 2
|
|
148
|
+
await compileOutput(state, ctx, watch); // Step 3
|
|
149
|
+
await addNodePath(path.resolve(ctx.workspacePath, ctx.outputFolder));
|
|
150
|
+
return state;
|
|
151
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import fs from 'fs/promises';
|
|
2
|
+
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { type Stats } from 'fs';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
|
|
7
|
+
import type { ManifestContext, ManifestUtil } from '@travetto/manifest';
|
|
8
|
+
|
|
9
|
+
import { transpileFile, writePackageJson } from '../../bin/transpile';
|
|
10
|
+
|
|
11
|
+
const req = createRequire(`${process.cwd()}/node_modules`);
|
|
12
|
+
|
|
13
|
+
type ModFile = { input: string, output: string, stale: boolean };
|
|
14
|
+
|
|
15
|
+
const SOURCE_SEED = ['package.json', 'index.ts', '__index__.ts', 'src', 'support', 'bin'];
|
|
16
|
+
|
|
17
|
+
export const IS_DEBUG = /\b([*]|build)\b/.test(process.env.DEBUG ?? '');
|
|
18
|
+
|
|
19
|
+
const resolveImport = (lib: string): string => req.resolve(lib);
|
|
20
|
+
const recentStat = (stat: Stats): number => Math.max(stat.ctimeMs, stat.mtimeMs);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Common logging support
|
|
24
|
+
*/
|
|
25
|
+
export const log = IS_DEBUG ?
|
|
26
|
+
(...args: unknown[]): void => console.debug(new Date().toISOString(), ...args) :
|
|
27
|
+
(): void => { };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Scan directory to find all project sources for comparison
|
|
31
|
+
*/
|
|
32
|
+
export async function getProjectSources(
|
|
33
|
+
ctx: ManifestContext, module: string, seed: string[] = SOURCE_SEED
|
|
34
|
+
): Promise<ModFile[]> {
|
|
35
|
+
const inputFolder = (ctx.mainModule === module) ?
|
|
36
|
+
process.cwd() :
|
|
37
|
+
path.dirname(resolveImport(`${module}/package.json`));
|
|
38
|
+
|
|
39
|
+
const folders = seed.filter(x => !/[.]/.test(x)).map(x => path.resolve(inputFolder, x));
|
|
40
|
+
const files = seed.filter(x => /[.]/.test(x)).map(x => path.resolve(inputFolder, x));
|
|
41
|
+
|
|
42
|
+
while (folders.length) {
|
|
43
|
+
const sub = folders.pop();
|
|
44
|
+
if (!sub) {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
for (const file of await fs.readdir(sub).catch(() => [])) {
|
|
49
|
+
if (file.startsWith('.')) {
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const resolvedInput = path.resolve(sub, file);
|
|
53
|
+
const stat = await fs.stat(resolvedInput);
|
|
54
|
+
|
|
55
|
+
if (stat.isDirectory()) {
|
|
56
|
+
folders.push(resolvedInput);
|
|
57
|
+
} else if (file.endsWith('.d.ts')) {
|
|
58
|
+
// Do nothing
|
|
59
|
+
} else if (file.endsWith('.ts') || file.endsWith('.js')) {
|
|
60
|
+
files.push(resolvedInput);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const outputFolder = path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules', module);
|
|
66
|
+
const out: ModFile[] = [];
|
|
67
|
+
for (const input of files) {
|
|
68
|
+
const output = input.replace(inputFolder, outputFolder).replace(/[.]ts$/, '.js');
|
|
69
|
+
const inputTs = await fs.stat(input).then(recentStat, () => 0);
|
|
70
|
+
if (inputTs) {
|
|
71
|
+
const outputTs = await fs.stat(output).then(recentStat, () => 0);
|
|
72
|
+
await fs.mkdir(path.dirname(output), { recursive: true, });
|
|
73
|
+
out.push({ input, output, stale: inputTs > outputTs });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Recompile folder if stale
|
|
82
|
+
*/
|
|
83
|
+
export async function compileIfStale(ctx: ManifestContext, prefix: string, files: ModFile[]): Promise<void> {
|
|
84
|
+
try {
|
|
85
|
+
if (files.some(f => f.stale)) {
|
|
86
|
+
log(`${prefix} Starting`);
|
|
87
|
+
for (const file of files.filter(x => x.stale)) {
|
|
88
|
+
if (file.input.endsWith('package.json')) {
|
|
89
|
+
await writePackageJson(ctx, file.input, file.output);
|
|
90
|
+
} else {
|
|
91
|
+
await transpileFile(ctx, file.input, file.output);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
} else {
|
|
95
|
+
log(`${prefix} Skipped`);
|
|
96
|
+
}
|
|
97
|
+
} catch (err) {
|
|
98
|
+
console.error(err);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Add node path at runtime
|
|
104
|
+
*/
|
|
105
|
+
export async function addNodePath(folder: string): Promise<void> {
|
|
106
|
+
process.env.NODE_PATH = [`${folder}/node_modules`, process.env.NODE_PATH].join(path.delimiter);
|
|
107
|
+
const { Module } = await import('module');
|
|
108
|
+
// @ts-expect-error
|
|
109
|
+
Module._initPaths();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Import the manifest utils once compiled
|
|
114
|
+
*/
|
|
115
|
+
export const importManifest = (ctx: ManifestContext): Promise<{ ManifestUtil: typeof ManifestUtil }> =>
|
|
116
|
+
import(path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules', '@travetto', 'manifest', '__index__.js'));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { readFileSync } from 'fs';
|
|
2
|
+
import { install } from 'source-map-support';
|
|
3
|
+
|
|
4
|
+
import { ManifestState } from '@travetto/manifest';
|
|
5
|
+
|
|
6
|
+
import { Compiler } from '../src/compiler';
|
|
7
|
+
|
|
8
|
+
install();
|
|
9
|
+
const [manifestState, watch] = process.argv.slice(2);
|
|
10
|
+
const state: ManifestState = JSON.parse(readFileSync(manifestState, 'utf8'));
|
|
11
|
+
new Compiler().init(state).run(watch === 'true');
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"module": "CommonJS",
|
|
4
|
+
"target": "esnext",
|
|
5
|
+
"moduleResolution": "node",
|
|
6
|
+
"lib": [
|
|
7
|
+
"es2022"
|
|
8
|
+
],
|
|
9
|
+
"strict": true,
|
|
10
|
+
"esModuleInterop": true,
|
|
11
|
+
"strictPropertyInitialization": false,
|
|
12
|
+
"experimentalDecorators": true,
|
|
13
|
+
"noEmitOnError": false,
|
|
14
|
+
"noErrorTruncation": true,
|
|
15
|
+
"resolveJsonModule": true,
|
|
16
|
+
"sourceMap": true,
|
|
17
|
+
"inlineSourceMap": false,
|
|
18
|
+
"removeComments": true,
|
|
19
|
+
"importHelpers": true,
|
|
20
|
+
"outDir": "build/"
|
|
21
|
+
},
|
|
22
|
+
}
|
package/LICENSE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2020 ArcSine Technologies
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
package/index.ts
DELETED
package/src/host.ts
DELETED
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import * as ts from 'typescript';
|
|
2
|
-
import { readFileSync } from 'fs';
|
|
3
|
-
import * as path from 'path';
|
|
4
|
-
|
|
5
|
-
import { PathUtil, AppCache } from '@travetto/boot';
|
|
6
|
-
import { SourceUtil } from '@travetto/boot/src/internal/source-util';
|
|
7
|
-
import { SystemUtil } from '@travetto/boot/src/internal/system';
|
|
8
|
-
import { TranspileUtil } from '@travetto/boot/src/internal/transpile-util';
|
|
9
|
-
import { SourceIndex } from '@travetto/boot/src/internal/source';
|
|
10
|
-
import { AppManifest } from '@travetto/base';
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Manages the source code and typescript relationship.
|
|
14
|
-
*/
|
|
15
|
-
export class SourceHost implements ts.CompilerHost {
|
|
16
|
-
|
|
17
|
-
#rootFiles = new Set<string>();
|
|
18
|
-
#hashes = new Map<string, number>();
|
|
19
|
-
#sources = new Map<string, ts.SourceFile>();
|
|
20
|
-
readonly contents = new Map<string, string>();
|
|
21
|
-
|
|
22
|
-
#trackFile(filename: string, content: string): void {
|
|
23
|
-
this.contents.set(filename, content);
|
|
24
|
-
this.#hashes.set(filename, SystemUtil.naiveHash(readFileSync(filename, 'utf8'))); // Get og content for hashing
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
getCanonicalFileName: (file: string) => string = (f: string) => f;
|
|
28
|
-
getCurrentDirectory: () => string = () => PathUtil.cwd;
|
|
29
|
-
getDefaultLibFileName: (opts: ts.CompilerOptions) => string = (opts: ts.CompilerOptions) => ts.getDefaultLibFileName(opts);
|
|
30
|
-
getNewLine: () => string = () => ts.sys.newLine;
|
|
31
|
-
useCaseSensitiveFileNames: () => boolean = () => ts.sys.useCaseSensitiveFileNames;
|
|
32
|
-
getDefaultLibLocation(): string {
|
|
33
|
-
return path.dirname(ts.getDefaultLibFilePath(TranspileUtil.compilerOptions));
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Get root files
|
|
38
|
-
*/
|
|
39
|
-
getRootFiles(): Set<string> {
|
|
40
|
-
if (!this.#rootFiles.size) {
|
|
41
|
-
// Only needed for compilation
|
|
42
|
-
this.#rootFiles = new Set(SourceIndex.findByFolders(AppManifest.source, 'required').map(x => x.file));
|
|
43
|
-
}
|
|
44
|
-
return this.#rootFiles;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Read file from disk, using the transpile pre-processor on .ts files
|
|
49
|
-
*/
|
|
50
|
-
readFile(filename: string): string {
|
|
51
|
-
filename = PathUtil.toUnixTs(filename);
|
|
52
|
-
let content = ts.sys.readFile(filename);
|
|
53
|
-
if (content === undefined) {
|
|
54
|
-
throw new Error(`Unable to read file ${filename}`);
|
|
55
|
-
}
|
|
56
|
-
if (filename.endsWith(SourceUtil.EXT) && !filename.endsWith('.d.ts')) {
|
|
57
|
-
content = SourceUtil.preProcess(filename, content);
|
|
58
|
-
}
|
|
59
|
-
return content;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* Write file to disk, and set value in cache as well
|
|
64
|
-
*/
|
|
65
|
-
writeFile(filename: string, content: string): void {
|
|
66
|
-
filename = PathUtil.toUnixTs(filename);
|
|
67
|
-
this.#trackFile(filename, content);
|
|
68
|
-
AppCache.writeEntry(filename, content);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Fetch file
|
|
73
|
-
*/
|
|
74
|
-
fetchFile(filename: string): void {
|
|
75
|
-
filename = PathUtil.toUnixTs(filename);
|
|
76
|
-
const cached = AppCache.readEntry(filename);
|
|
77
|
-
this.#trackFile(filename, cached);
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Get a source file on demand
|
|
82
|
-
* @returns
|
|
83
|
-
*/
|
|
84
|
-
getSourceFile(filename: string, __tgt: unknown, __onErr: unknown, force?: boolean): ts.SourceFile {
|
|
85
|
-
if (!this.#sources.has(filename) || force) {
|
|
86
|
-
const content = this.readFile(filename)!;
|
|
87
|
-
this.#sources.set(filename, ts.createSourceFile(filename, content ?? '',
|
|
88
|
-
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
|
89
|
-
(TranspileUtil.compilerOptions as ts.CompilerOptions).target!
|
|
90
|
-
));
|
|
91
|
-
}
|
|
92
|
-
return this.#sources.get(filename)!;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* See if a file exists
|
|
97
|
-
*/
|
|
98
|
-
fileExists(filename: string): boolean {
|
|
99
|
-
filename = PathUtil.toUnixTs(filename);
|
|
100
|
-
return this.contents.has(filename) || ts.sys.fileExists(filename);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* See if a file's hash code has changed
|
|
105
|
-
*/
|
|
106
|
-
hashChanged(filename: string, content?: string): boolean {
|
|
107
|
-
content ??= readFileSync(filename, 'utf8');
|
|
108
|
-
// Let's see if they are really different
|
|
109
|
-
const hash = SystemUtil.naiveHash(content);
|
|
110
|
-
if (hash === this.#hashes.get(filename)) {
|
|
111
|
-
console.debug('Contents Unchanged', { filename });
|
|
112
|
-
return false;
|
|
113
|
-
}
|
|
114
|
-
return true;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Unload a file from the transpiler
|
|
119
|
-
*/
|
|
120
|
-
unload(filename: string, unlink = true): void {
|
|
121
|
-
if (this.contents.has(filename)) {
|
|
122
|
-
AppCache.removeExpiredEntry(filename, unlink);
|
|
123
|
-
|
|
124
|
-
if (unlink && this.#hashes.has(filename)) {
|
|
125
|
-
this.#hashes.delete(filename);
|
|
126
|
-
}
|
|
127
|
-
this.#rootFiles.delete(filename);
|
|
128
|
-
this.contents.delete(filename);
|
|
129
|
-
this.#sources.delete(filename);
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Reset the transpiler
|
|
135
|
-
*/
|
|
136
|
-
reset(): void {
|
|
137
|
-
this.contents.clear();
|
|
138
|
-
this.#rootFiles.clear();
|
|
139
|
-
this.#hashes.clear();
|
|
140
|
-
this.#sources.clear();
|
|
141
|
-
}
|
|
142
|
-
}
|