@travetto/compiler 3.0.0-rc.3 → 3.0.0-rc.31

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.
@@ -0,0 +1,25 @@
1
+ import { workerData, parentPort } from 'worker_threads';
2
+ import { utimesSync } from 'fs';
3
+
4
+ const data: { files: string[], interval: number } = workerData;
5
+ const files = data.files;
6
+
7
+ const interval = setInterval(() => {
8
+ const now = Date.now() / 1000;
9
+ for (const file of files) {
10
+ try {
11
+ utimesSync(file, now, now);
12
+ } catch { }
13
+ }
14
+ }, data.interval);
15
+
16
+
17
+ parentPort?.on('message', val => {
18
+ if (val === 'stop') {
19
+ files.splice(0, files.length);
20
+ clearInterval(interval);
21
+ } else if (val && typeof val === 'object' && 'files' in val && Array.isArray(val.files)) {
22
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
23
+ files.splice(0, files.length, ...val.files as string[]);
24
+ }
25
+ });
@@ -0,0 +1,234 @@
1
+ import { Stats, watchFile, unwatchFile, rmSync, mkdirSync, writeFileSync, existsSync } from 'fs';
2
+ import fs from 'fs/promises';
3
+ import { Worker } from 'worker_threads';
4
+ import path from 'path';
5
+
6
+ import type { ManifestContext } from '@travetto/manifest';
7
+
8
+ import { CompilerLogger, LogUtil } from './log';
9
+
10
+ type LockStatus = 'complete' | 'stale';
11
+ type LockDetails = {
12
+ pid: number | undefined;
13
+ file: string;
14
+ };
15
+
16
+ export type LockType = 'build' | 'watch';
17
+ export type LockCompileAction = 'skip' | 'build';
18
+ type LockAction = LockCompileAction | 'retry';
19
+
20
+ const STALE_THRESHOLD = 1000;
21
+
22
+ /**
23
+ * Manager for all lock activity
24
+ */
25
+ export class LockManager {
26
+
27
+ /**
28
+ * Get the lock file name
29
+ */
30
+ static #getFileName(ctx: ManifestContext, type: LockType): string {
31
+ return path.resolve(ctx.workspacePath, ctx.toolFolder, `${type}.lock`);
32
+ }
33
+
34
+ /**
35
+ * Determine if the given stats are stale for modification time
36
+ */
37
+ static #isStale(stat?: Stats): boolean {
38
+ return !!stat && stat.mtimeMs < (Date.now() - STALE_THRESHOLD * 1.1);
39
+ }
40
+
41
+ /**
42
+ * Get the lock file details
43
+ */
44
+ static async #getDetails(ctx: ManifestContext, type: LockType): Promise<LockDetails> {
45
+ const file = this.#getFileName(ctx, type);
46
+ const stat = await fs.stat(file).catch(() => undefined);
47
+ const stale = this.#isStale(stat);
48
+ let pid: number | undefined;
49
+ if (stat) {
50
+ const { pid: filePid } = JSON.parse(await fs.readFile(file, 'utf8'));
51
+ if (stale) {
52
+ LogUtil.log('lock', [], 'debug', `${type} file is stale: ${stat.mtimeMs} vs ${Date.now()}`);
53
+ } else {
54
+ pid = filePid;
55
+ }
56
+ }
57
+ return { pid, file };
58
+ }
59
+
60
+ /**
61
+ * Acquire the lock file, and register a cleanup on exit
62
+ */
63
+ static #acquireFile(ctx: ManifestContext, type: LockType): void {
64
+ const file = this.#getFileName(ctx, type);
65
+ mkdirSync(path.dirname(file), { recursive: true });
66
+ LogUtil.log('lock', [], 'debug', `Acquiring ${type}`);
67
+ writeFileSync(file, JSON.stringify({ pid: process.pid }), 'utf8');
68
+ }
69
+
70
+ /**
71
+ * Release the lock file (i.e. deleting)
72
+ */
73
+ static #releaseFile(ctx: ManifestContext, type: LockType): void {
74
+ const file = this.#getFileName(ctx, type);
75
+ if (existsSync(file)) {
76
+ rmSync(file, { force: true });
77
+ LogUtil.log('lock', [], 'debug', `Releasing ${type}`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Wait until a lock file is released, or it becomes stale
83
+ */
84
+ static async #waitForRelease(ctx: ManifestContext, type: LockType): Promise<LockStatus> {
85
+ const file = this.#getFileName(ctx, type);
86
+ let remove: (() => void) | undefined = undefined;
87
+
88
+ const prom = new Promise<LockStatus>(resolve => {
89
+ let timer: NodeJS.Timeout | undefined = undefined;
90
+ const handler = async (): Promise<void> => {
91
+ if (timer) {
92
+ clearTimeout(timer);
93
+ }
94
+ const stats = await fs.stat(file).catch(() => undefined);
95
+ if (!stats) {
96
+ resolve('complete');
97
+ } else if (this.#isStale(stats)) {
98
+ resolve('stale');
99
+ } else {
100
+ timer = setTimeout(handler, STALE_THRESHOLD * 1.1);
101
+ }
102
+ };
103
+
104
+ watchFile(file, handler);
105
+ handler();
106
+
107
+ remove = (): void => {
108
+ clearInterval(timer);
109
+ unwatchFile(file, handler);
110
+ };
111
+ });
112
+
113
+ return prom.finally(remove);
114
+ }
115
+
116
+ /**
117
+ * Read the watch lock file and determine its result, communicating with the user as necessary
118
+ */
119
+ static async #getWatchAction(ctx: ManifestContext, log: CompilerLogger, lockType: LockType | undefined, buildState: LockDetails): Promise<LockAction> {
120
+ if (lockType === 'watch') {
121
+ log('info', 'Already running');
122
+ return 'skip';
123
+ } else {
124
+ if (buildState.pid) {
125
+ log('warn', 'Already running, waiting for build to finish');
126
+ switch (await this.#waitForRelease(ctx, 'build')) {
127
+ case 'complete': {
128
+ log('info', 'Completed build');
129
+ return 'skip';
130
+ }
131
+ case 'stale': {
132
+ log('info', 'Became stale, retrying');
133
+ return 'retry';
134
+ }
135
+ }
136
+ } else {
137
+ log('info', 'Already running, and has built');
138
+ return 'skip';
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Read the build lock file and determine its result, communicating with the user as necessary
145
+ */
146
+ static async #getBuildAction(ctx: ManifestContext, log: CompilerLogger, lockType: LockType | undefined): Promise<LockAction> {
147
+ if (lockType === 'watch') {
148
+ log('warn', 'Build already running, waiting to begin watch');
149
+ const res = await this.#waitForRelease(ctx, 'build');
150
+ log('info', `Finished with status of ${res}, retrying`);
151
+ return 'retry';
152
+ } else {
153
+ log('warn', 'Already running, waiting for completion');
154
+ switch (await this.#waitForRelease(ctx, lockType ?? 'build')) {
155
+ case 'complete': {
156
+ log('info', 'Completed');
157
+ return 'skip';
158
+ }
159
+ case 'stale': {
160
+ log('info', 'Became stale, retrying');
161
+ return 'retry';
162
+ }
163
+ }
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Run code with support for lock acquire and release
169
+ */
170
+ static async withLocks(ctx: ManifestContext, fn: (acquire: (type: LockType) => void, release: (type: LockType) => void) => Promise<unknown>): Promise<void> {
171
+ const activeLockTypes = new Set<LockType>();
172
+
173
+ const pinger = path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules', '@travetto/compiler/support/lock-pinger.js');
174
+ const worker = new Worker(pinger, {
175
+ workerData: {
176
+ interval: STALE_THRESHOLD,
177
+ files: []
178
+ }
179
+ });
180
+
181
+ const notify = (): void => worker.postMessage({ files: [...activeLockTypes].map(t => this.#getFileName(ctx, t)) });
182
+
183
+ const stop = (): void => {
184
+ worker.postMessage('stop');
185
+ for (const type of activeLockTypes) {
186
+ this.#releaseFile(ctx, type);
187
+ }
188
+ worker.terminate().then(() => { });
189
+ };
190
+
191
+ process.on('SIGINT', stop);
192
+ process.on('exit', stop);
193
+
194
+ try {
195
+ await new Promise(r => worker.on('online', r));
196
+ await fn(
197
+ type => {
198
+ if (!activeLockTypes.has(type)) {
199
+ activeLockTypes.add(type);
200
+ this.#acquireFile(ctx, type);
201
+ notify();
202
+ }
203
+ },
204
+ type => {
205
+ if (activeLockTypes.has(type)) {
206
+ activeLockTypes.delete(type);
207
+ this.#releaseFile(ctx, type);
208
+ notify();
209
+ }
210
+ }
211
+ );
212
+ } finally {
213
+ stop();
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Reads the lock file states (build + watch) to determine what action should be taken for the compiler
219
+ */
220
+ static async getCompileAction(ctx: ManifestContext, lockType: LockType | undefined): Promise<LockCompileAction> {
221
+ let result: LockAction;
222
+ do {
223
+ result = 'build';
224
+ const buildState = await this.#getDetails(ctx, 'build');
225
+ const watchState = await this.#getDetails(ctx, 'watch');
226
+ if (watchState.pid) { // Existing watch operation
227
+ result = await LogUtil.withLogger('lock', log => this.#getWatchAction(ctx, log, lockType, buildState), true, ['watch', `pid=${watchState.pid}`]);
228
+ } else if (buildState.pid) { // Existing build operation
229
+ result = await LogUtil.withLogger('lock', log => this.#getBuildAction(ctx, log, lockType), true, ['build', `pid=${buildState.pid}`]);
230
+ }
231
+ } while (result === 'retry');
232
+ return result;
233
+ }
234
+ }
package/support/log.ts ADDED
@@ -0,0 +1,51 @@
1
+ export type CompilerLogEvent = [level: 'info' | 'debug' | 'warn', message: string];
2
+ export type CompilerLogger = (...args: CompilerLogEvent) => void;
3
+ export type WithLogger<T> = (log: CompilerLogger) => Promise<T>;
4
+
5
+ const SCOPE_MAX = 15;
6
+
7
+ export class LogUtil {
8
+
9
+ static levels: {
10
+ debug: boolean;
11
+ info: boolean;
12
+ warn: boolean;
13
+ };
14
+
15
+ static set level(value: string) {
16
+ this.levels = {
17
+ warn: /^(debug|info|warn)$/.test(value),
18
+ info: /^(debug|info)$/.test(value),
19
+ debug: /^debug$/.test(value),
20
+ };
21
+ }
22
+
23
+ /**
24
+ * Is object a log event
25
+ */
26
+ static isLogEvent = (o: unknown): o is CompilerLogEvent => o !== null && o !== undefined && Array.isArray(o);
27
+
28
+ /**
29
+ * Log message with filtering by level
30
+ */
31
+ static log(scope: string, args: string[], ...[level, msg]: CompilerLogEvent): void {
32
+ const message = msg.replaceAll(process.cwd(), '.');
33
+ if (LogUtil.levels[level]) {
34
+ const params = [`[${scope.padEnd(SCOPE_MAX, ' ')}]`, ...args, message];
35
+ if (!/(0|false|off|no)$/i.test(process.env.TRV_LOG_TIME ?? '')) {
36
+ params.unshift(new Date().toISOString());
37
+ }
38
+ // eslint-disable-next-line no-console
39
+ console[level]!(...params);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * With logger
45
+ */
46
+ static withLogger<T>(scope: string, op: WithLogger<T>, basic = true, args: string[] = []): Promise<T> {
47
+ const log = this.log.bind(null, scope, args);
48
+ basic && log('debug', 'Started');
49
+ return op(log).finally(() => basic && log('debug', 'Completed'));
50
+ }
51
+ }
@@ -0,0 +1,210 @@
1
+ import path from 'path';
2
+ import fs from 'fs/promises';
3
+ import os from 'os';
4
+ import cp from 'child_process';
5
+ import { createRequire } from 'module';
6
+
7
+ import { DeltaEvent, ManifestContext, ManifestRoot, Package } from '@travetto/manifest';
8
+
9
+ import { LogUtil } from './log';
10
+
11
+ type ModFile = { input: string, output: string, stale: boolean };
12
+ export type CompileResult = 'restart' | 'complete' | 'skipped';
13
+
14
+ const OPT_CACHE: Record<string, import('typescript').CompilerOptions> = {};
15
+ const SRC_REQ = createRequire(path.resolve('node_modules'));
16
+ const RECENT_STAT = (stat: { ctimeMs: number, mtimeMs: number }): number => Math.max(stat.ctimeMs, stat.mtimeMs);
17
+
18
+ /**
19
+ * Transpile utilities for launching
20
+ */
21
+ export class TranspileUtil {
22
+ /**
23
+ * Write text file, and ensure folder exists
24
+ */
25
+ static writeTextFile = (file: string, content: string): Promise<void> =>
26
+ fs.mkdir(path.dirname(file), { recursive: true }).then(() => fs.writeFile(file, content, 'utf8'));
27
+
28
+ /**
29
+ * Returns the compiler options
30
+ */
31
+ static async getCompilerOptions(ctx: ManifestContext): Promise<{}> {
32
+ if (!(ctx.workspacePath in OPT_CACHE)) {
33
+ let tsconfig = path.resolve(ctx.workspacePath, 'tsconfig.json');
34
+
35
+ if (!await fs.stat(tsconfig).then(_ => true, _ => false)) {
36
+ tsconfig = SRC_REQ.resolve('@travetto/compiler/tsconfig.trv.json');
37
+ }
38
+
39
+ const ts = (await import('typescript')).default;
40
+
41
+ const { options } = ts.parseJsonSourceFileConfigFileContent(
42
+ ts.readJsonConfigFile(tsconfig, ts.sys.readFile), ts.sys, ctx.workspacePath
43
+ );
44
+
45
+ OPT_CACHE[ctx.workspacePath] = {
46
+ ...options,
47
+ allowJs: true,
48
+ sourceMap: false,
49
+ inlineSourceMap: true,
50
+ resolveJsonModule: true,
51
+ sourceRoot: ctx.workspacePath,
52
+ rootDir: ctx.workspacePath,
53
+ outDir: path.resolve(ctx.workspacePath),
54
+ module: ctx.moduleType === 'commonjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext,
55
+ };
56
+ }
57
+ return OPT_CACHE[ctx.workspacePath];
58
+ }
59
+
60
+ /**
61
+ * Output a file, support for ts, js, and package.json
62
+ */
63
+ static async transpileFile(ctx: ManifestContext, inputFile: string, outputFile: string): Promise<void> {
64
+ if (inputFile.endsWith('.ts') || inputFile.endsWith('.js')) {
65
+ const compilerOut = path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules');
66
+
67
+ const text = (await fs.readFile(inputFile, 'utf8'))
68
+ .replace(/from '([.][^']+)'/g, (_, i) => `from '${i.replace(/[.]js$/, '')}.js'`)
69
+ .replace(/from '(@travetto\/(.*?))'/g, (_, i, s) => `from '${path.resolve(compilerOut, `${i}${s.includes('/') ? '.js' : '/__index__.js'}`)}'`);
70
+
71
+ const ts = (await import('typescript')).default;
72
+ const content = ts.transpile(text, await this.getCompilerOptions(ctx), inputFile);
73
+ await this.writeTextFile(outputFile, content);
74
+ } else if (inputFile.endsWith('package.json')) {
75
+ const pkg: Package = JSON.parse(await fs.readFile(inputFile, 'utf8'));
76
+ const main = pkg.main?.replace(/[.]ts$/, '.js');
77
+ const files = pkg.files?.map(x => x.replace('.ts', '.js'));
78
+
79
+ const content = JSON.stringify({ ...pkg, main, type: ctx.moduleType, files }, null, 2);
80
+ await this.writeTextFile(outputFile, content);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Scan directory to find all project sources for comparison
86
+ */
87
+ static async getModuleSources(ctx: ManifestContext, module: string, seed: string[]): Promise<ModFile[]> {
88
+ const inputFolder = (ctx.mainModule === module) ?
89
+ process.cwd() :
90
+ path.dirname(SRC_REQ.resolve(`${module}/package.json`));
91
+
92
+ const folders = seed.filter(x => !/[.]/.test(x)).map(x => path.resolve(inputFolder, x));
93
+ const files = seed.filter(x => /[.]/.test(x)).map(x => path.resolve(inputFolder, x));
94
+
95
+ while (folders.length) {
96
+ const sub = folders.pop();
97
+ if (!sub) {
98
+ continue;
99
+ }
100
+
101
+ for (const file of await fs.readdir(sub).catch(() => [])) {
102
+ if (file.startsWith('.')) {
103
+ continue;
104
+ }
105
+ const resolvedInput = path.resolve(sub, file);
106
+ const stat = await fs.stat(resolvedInput);
107
+
108
+ if (stat.isDirectory()) {
109
+ folders.push(resolvedInput);
110
+ } else if (file.endsWith('.d.ts')) {
111
+ // Do nothing
112
+ } else if (file.endsWith('.ts') || file.endsWith('.js')) {
113
+ files.push(resolvedInput);
114
+ }
115
+ }
116
+ }
117
+
118
+ const outputFolder = path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules', module);
119
+ const out: ModFile[] = [];
120
+ for (const input of files) {
121
+ const output = input.replace(inputFolder, outputFolder).replace(/[.]ts$/, '.js');
122
+ const inputTs = await fs.stat(input).then(RECENT_STAT, () => 0);
123
+ if (inputTs) {
124
+ const outputTs = await fs.stat(output).then(RECENT_STAT, () => 0);
125
+ await fs.mkdir(path.dirname(output), { recursive: true, });
126
+ out.push({ input, output, stale: inputTs > outputTs });
127
+ }
128
+ }
129
+
130
+ return out;
131
+ }
132
+
133
+ /**
134
+ * Recompile folder if stale
135
+ */
136
+ static async compileIfStale(ctx: ManifestContext, scope: string, mod: string, seed: string[]): Promise<string[]> {
137
+ const files = await this.getModuleSources(ctx, mod, seed);
138
+ const changes = files.filter(x => x.stale).map(x => x.input);
139
+ const out: string[] = [];
140
+
141
+ try {
142
+ await LogUtil.withLogger(scope, async log => {
143
+ if (files.some(f => f.stale)) {
144
+ log('debug', 'Starting');
145
+ for (const file of files.filter(x => x.stale)) {
146
+ await this.transpileFile(ctx, file.input, file.output);
147
+ }
148
+ if (changes.length) {
149
+ out.push(...changes.map(x => `${mod}/${x}`));
150
+ log('debug', `Source changed: ${changes.join(', ')}`);
151
+ }
152
+ log('debug', 'Completed');
153
+ } else {
154
+ log('debug', 'Skipped');
155
+ }
156
+ }, false, [mod]);
157
+ } catch (err) {
158
+ console.error(err);
159
+ }
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * Run compiler
165
+ */
166
+ static async runCompiler(ctx: ManifestContext, manifest: ManifestRoot, changed: DeltaEvent[], watch: boolean, onMessage: (msg: unknown) => void): Promise<CompileResult> {
167
+ const compiler = path.resolve(ctx.workspacePath, ctx.compilerFolder);
168
+ const main = path.resolve(compiler, 'node_modules', '@travetto/compiler/support/compiler-entry.js');
169
+ const deltaFile = path.resolve(os.tmpdir(), `manifest-delta.${process.pid}.${process.ppid}.${Date.now()}.json`);
170
+
171
+ const changedFiles = changed[0]?.file === '*' ? ['*'] : changed.map(ev =>
172
+ path.resolve(manifest.workspacePath, manifest.modules[ev.module].sourceFolder, ev.file)
173
+ );
174
+
175
+ let proc: cp.ChildProcess | undefined;
176
+ let kill: (() => void) | undefined;
177
+
178
+ try {
179
+ await this.writeTextFile(deltaFile, changedFiles.join('\n'));
180
+
181
+ return await LogUtil.withLogger('compiler-exec', log => new Promise<CompileResult>((res, rej) => {
182
+ proc = cp.spawn(process.argv0, [main, deltaFile, `${watch}`], {
183
+ env: {
184
+ ...process.env,
185
+ TRV_MANIFEST: path.resolve(ctx.workspacePath, ctx.outputFolder, 'node_modules', ctx.mainModule),
186
+ },
187
+ stdio: [0, 1, 2, 'ipc'],
188
+ })
189
+ .on('message', msg => {
190
+ if (LogUtil.isLogEvent(msg)) {
191
+ log(...msg);
192
+ } else if (msg === 'restart') {
193
+ res(msg);
194
+ } else {
195
+ onMessage(msg);
196
+ }
197
+ })
198
+ .on('exit', code => (code !== null && code > 0) ? rej(new Error('Failed during compilation')) : res('complete'));
199
+ kill = (): void => { proc?.kill('SIGKILL'); };
200
+ process.on('exit', kill);
201
+ }));
202
+ } finally {
203
+ if (proc?.killed === false) { proc.kill('SIGKILL'); }
204
+ if (kill) {
205
+ process.removeListener('exit', kill);
206
+ }
207
+ await fs.rm(deltaFile, { force: true });
208
+ }
209
+ }
210
+ }
@@ -0,0 +1,23 @@
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
+ "noEmitHelpers": true,
21
+ "outDir": "build/"
22
+ },
23
+ }
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
@@ -1,3 +0,0 @@
1
- export * from './src/host';
2
- export * from './src/compiler';
3
- export * from './src/transformer';