New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@travetto/compiler

Package Overview
Dependencies
Maintainers
0
Versions
307
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@travetto/compiler - npm Package Compare versions

Comparing version 5.0.2 to 5.0.3

31

bin/common.js
// @ts-check
import { statSync, readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, rmSync } from 'node:fs';
import path from 'node:path';
const { statSync, readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, rmSync } = require('node:fs');
const path = require('node:path');
import { getManifestContext } from '@travetto/manifest/bin/context.js';
/** @typedef {import('@travetto/manifest').ManifestContext} Ctx */

@@ -39,9 +37,19 @@

/** @returns {Promise<import('@travetto/compiler/support/entry.trvc')>} */
async function imp(f = '') { try { return require(f); } catch { return import(f); } }
export async function getEntry() {
async function getEntry() {
process.setSourceMapsEnabled(true); // Ensure source map during compilation/development
process.env.NODE_OPTIONS = `${process.env.NODE_OPTIONS ?? ''} --enable-source-maps`; // Ensure it passes to children
// Load manifest without compiling, just stripping types away
const loc = require.resolve('@travetto/manifest').replace(/__index__.*/, 'src/context.ts');
const src = readFileSync(loc, 'utf8')
// Remove type information
.replace(/\s*[|]\s+undefined/g, '')
.replace(/<([^>]|\n)+>/gsm, '')
.replace(/: (string|[A-Z][a-zA-Z]+)/g, '')
.replace(/^(import )?type .*$/gm, '');
// Load module on demand
const { getManifestContext } = await import(`data:text/javascript;charset=utf-8,${encodeURIComponent(src)}`);
/** @type {Ctx} */
const ctx = getManifestContext();

@@ -71,3 +79,4 @@ const target = getTarget.bind(null, ctx);

try {
return await imp(target('support/entry.trvc.ts').dest).then(v => v.main(ctx));
const res = await import(target('support/entry.trvc.ts').dest);
return await res.main(ctx);
} catch (err) {

@@ -77,2 +86,4 @@ rmSync(target('.').dest, { recursive: true, force: true });

}
}
}
module.exports = { getEntry };
#!/usr/bin/env node
// @ts-check
import { getEntry } from './common.js';
const { getEntry } = require('./common.js');

@@ -6,0 +6,0 @@ const help = () => [

{
"name": "@travetto/compiler",
"version": "5.0.2",
"version": "5.0.3",
"description": "The compiler infrastructure for the Travetto framework",

@@ -16,3 +16,2 @@ "keywords": [

},
"type": "module",
"files": [

@@ -38,8 +37,8 @@ "__index__.ts",

"@parcel/watcher": "^2.4.1",
"@travetto/manifest": "^5.0.1",
"@travetto/transformer": "^5.0.2",
"@travetto/manifest": "^5.0.2",
"@travetto/transformer": "^5.0.3",
"@types/node": "^22.5.1"
},
"peerDependencies": {
"@travetto/cli": "^5.0.2"
"@travetto/cli": "^5.0.3"
},

@@ -46,0 +45,0 @@ "peerDependenciesMeta": {

@@ -30,2 +30,3 @@ import fs from 'node:fs/promises';

const dirtyFiles = ManifestModuleUtil.getFileType(dirty) === 'ts' ? [dirty] : (await fs.readFile(dirty, 'utf8')).split(/\n/).filter(x => !!x);
log.debug('Running compiler with dirty file', dirtyFiles);
await new Compiler(state, dirtyFiles, watch === 'true').run();

@@ -45,3 +46,3 @@ }

this.#state.getAllFiles() :
dirtyFiles.map(f => this.#state.getBySource(f)!.inputFile);
dirtyFiles.map(f => this.#state.getBySource(f)!.sourceFile);
this.#watch = watch;

@@ -95,3 +96,3 @@

getCompiler(): CompileEmitter {
return (inputFile: string, needsNewProgram?: boolean) => this.#state.writeInputFile(inputFile, needsNewProgram);
return (sourceFile: string, needsNewProgram?: boolean) => this.#state.compileSourceFile(sourceFile, needsNewProgram);
}

@@ -171,5 +172,5 @@

if (ev.action !== 'delete') {
const err = await emitter(ev.entry.inputFile, true);
const err = await emitter(ev.entry.sourceFile, true);
if (err) {
log.info('Compilation Error', CompilerUtil.buildTranspileError(ev.entry.inputFile, err));
log.info('Compilation Error', CompilerUtil.buildTranspileError(ev.entry.sourceFile, err));
} else {

@@ -176,0 +177,0 @@ log.info(`Compiled ${ev.entry.sourceFile} on ${ev.action}`);

@@ -12,12 +12,2 @@ import ts from 'typescript';

function folderMapper(root: string, prefix: string): { dir: string, translate: (val: string) => string } {
let matched: string = '~~';
prefix = `/${prefix}`;
const final = path.resolve(root).replace(/\/[^\/]+/, m => {
matched = m;
return prefix;
});
return { dir: final, translate: (file: string) => file.replace(prefix, matched) };
}
export class CompilerState implements ts.CompilerHost {

@@ -31,10 +21,8 @@

#rootDir: string;
#inputPathToSourcePath: (file: string) => string;
#outputPath: string;
#inputFiles = new Set<string>();
#inputDirectoryToSource = new Map<string, string>();
#inputToEntry = new Map<string, CompileStateEntry>();
#sourceFiles = new Set<string>();
#sourceDirectory = new Map<string, string>();
#sourceToEntry = new Map<string, CompileStateEntry>();
#outputToEntry = new Map<string, CompileStateEntry>();
#tscOutputFileToOuptut = new Map<string, string>();

@@ -52,4 +40,4 @@ #sourceContents = new Map<string, string | undefined>();

#readFile(inputFile: string): string | undefined {
return ts.sys.readFile(this.#inputToEntry.get(inputFile)?.sourceFile ?? this.#inputPathToSourcePath(inputFile));
#readFile(sourceFile: string): string | undefined {
return ts.sys.readFile(this.#sourceToEntry.get(sourceFile)?.sourceFile ?? sourceFile);
}

@@ -60,7 +48,11 @@

this.#manifest = idx.manifest;
const mapper = folderMapper(this.#manifest.workspace.path, '##');
this.#rootDir = mapper.dir;
this.#inputPathToSourcePath = mapper.translate;
this.#outputPath = path.resolve(this.#manifest.workspace.path, this.#manifest.build.outputFolder);
this.#outputPath = path.resolve(this.#manifest.workspace.path, this.#manifest.build.outputFolder);
this.#compilerOptions = {
...await TypescriptUtil.getCompilerOptions(this.#manifest),
rootDir: this.#manifest.workspace.path,
outDir: this.#outputPath
};
this.#modules = Object.values(this.#manifest.modules);

@@ -81,3 +73,3 @@

for (const [file, type] of files) {
if (CompilerUtil.validFile(type) || type === 'typings') {
if (CompilerUtil.validFile(type)) {
this.registerInput(x, file);

@@ -90,8 +82,2 @@ }

this.#compilerOptions = {
...await TypescriptUtil.getCompilerOptions(this.#manifest),
rootDir: this.#rootDir,
outDir: this.#outputPath
};
return this;

@@ -117,3 +103,3 @@ }

return this.getBySource(randomSource)!.inputFile;
return this.getBySource(randomSource)!.sourceFile;
}

@@ -130,15 +116,21 @@

async writeInputFile(inputFile: string, needsNewProgram = false): Promise<CompileEmitError | undefined> {
async compileSourceFile(sourceFile: string, needsNewProgram = false): Promise<CompileEmitError | undefined> {
const output = this.#sourceToEntry.get(sourceFile)?.outputFile;
if (!output) {
return;
}
const program = await this.createProgram(needsNewProgram);
try {
switch (ManifestModuleUtil.getFileType(inputFile)) {
switch (ManifestModuleUtil.getFileType(sourceFile)) {
case 'typings':
case 'package-json':
this.writeFile(this.#inputToEntry.get(inputFile)!.outputFile!, this.readFile(inputFile)!, false), undefined;
this.writeFile(output, this.readFile(sourceFile)!, false), undefined;
break;
case 'js':
this.writeFile(this.#inputToEntry.get(inputFile)!.outputFile!, ts.transpile(this.readFile(inputFile)!, this.#compilerOptions), false);
this.writeFile(output, ts.transpile(this.readFile(sourceFile)!, this.#compilerOptions), false);
break;
case 'ts': {
const result = program.emit(
program.getSourceFile(inputFile)!,
program.getSourceFile(sourceFile)!,
(...args) => this.writeFile(...args), undefined, false,

@@ -164,30 +156,35 @@ this.#transformerManager.get()

registerInput(module: ManifestModule, moduleFile: string): CompileStateEntry {
const relativeInput = `${module.outputFolder}/${moduleFile}`;
const sourceFile = path.resolve(this.#manifest.workspace.path, module.sourceFolder, moduleFile);
const relativeSource = `${module.sourceFolder || '.'}/${moduleFile}`;
const relativeOutput = `${module.outputFolder}/${moduleFile}`;
const sourceFile = path.resolve(this.#manifest.workspace.path, relativeSource);
const sourceFolder = path.dirname(sourceFile);
const inputFile = path.resolve(this.#rootDir, relativeInput); // Ensure input is isolated
const inputFolder = path.dirname(inputFile);
const fileType = ManifestModuleUtil.getFileType(moduleFile);
const outputFile = fileType === 'typings' ?
undefined :
path.resolve(this.#outputPath, ManifestModuleUtil.withOutputExtension(relativeInput));
const isTypings = fileType === 'typings';
const tscOutputFile = path.resolve(this.#outputPath, ManifestModuleUtil.withOutputExtension(relativeSource));
const outputFile = path.resolve(this.#outputPath, ManifestModuleUtil.withOutputExtension(relativeOutput));
const entry = { sourceFile, inputFile, outputFile, module };
const entry: CompileStateEntry = { sourceFile, outputFile, module, tscOutputFile };
this.#inputToEntry.set(inputFile, entry);
this.#outputToEntry.set(outputFile, entry);
this.#sourceFiles.add(sourceFile);
this.#sourceHashes.set(sourceFile, -1); // Unknown
this.#sourceToEntry.set(sourceFile, entry);
this.#inputDirectoryToSource.set(inputFolder, sourceFolder);
this.#sourceDirectory.set(sourceFolder, sourceFolder);
if (outputFile) {
this.#outputToEntry.set(outputFile, entry);
this.#tscOutputFileToOuptut.set(tscOutputFile, outputFile);
this.#tscOutputFileToOuptut.set(`${tscOutputFile}.map`, `${outputFile}.map`);
if (!isTypings) {
const srcBase = `${ManifestModuleUtil.withoutSourceExtension(tscOutputFile)}.d.ts`;
const outBase = `${ManifestModuleUtil.withoutSourceExtension(outputFile)}.d.ts`;
this.#tscOutputFileToOuptut.set(`${srcBase}.map`, `${outBase}.map`);
this.#tscOutputFileToOuptut.set(srcBase, outBase);
}
this.#inputFiles.add(inputFile);
this.#sourceHashes.set(sourceFile, -1); // Unknown
return entry;
}
checkIfSourceChanged(inputFile: string): boolean {
const contents = this.#readFile(inputFile);
const prevHash = this.#sourceHashes.get(inputFile);
checkIfSourceChanged(sourceFile: string): boolean {
const contents = this.#readFile(sourceFile);
const prevHash = this.#sourceHashes.get(sourceFile);
if (!contents || (contents.length === 0 && prevHash)) {

@@ -199,5 +196,5 @@ return false; // Ignore empty file

if (changed) {
this.#sourceHashes.set(inputFile, currentHash);
this.#sourceContents.set(inputFile, contents);
this.#sourceFileObjects.delete(inputFile);
this.#sourceHashes.set(sourceFile, currentHash);
this.#sourceContents.set(sourceFile, contents);
this.#sourceFileObjects.delete(sourceFile);
}

@@ -207,17 +204,23 @@ return changed;

removeInput(inputFile: string): void {
const { outputFile, sourceFile } = this.#inputToEntry.get(inputFile)!;
if (outputFile) {
this.#outputToEntry.delete(outputFile);
removeSource(sourceFile: string): void {
const entry = this.#sourceToEntry.get(sourceFile)!;
if (entry.outputFile) {
this.#outputToEntry.delete(entry.outputFile);
}
this.#sourceFileObjects.delete(inputFile);
this.#sourceContents.delete(inputFile);
this.#sourceHashes.delete(inputFile);
this.#sourceFileObjects.delete(sourceFile);
this.#sourceContents.delete(sourceFile);
this.#sourceHashes.delete(sourceFile);
this.#sourceToEntry.delete(sourceFile);
this.#inputToEntry.delete(inputFile);
this.#inputFiles.delete(inputFile);
this.#sourceFiles.delete(sourceFile);
const tscOutputDts = `${ManifestModuleUtil.withoutSourceExtension(entry.tscOutputFile)}.d.ts`;
this.#tscOutputFileToOuptut.delete(entry.tscOutputFile);
this.#tscOutputFileToOuptut.delete(`${entry.tscOutputFile}.map`);
this.#tscOutputFileToOuptut.delete(tscOutputDts);
this.#tscOutputFileToOuptut.delete(`${tscOutputDts}.map`);
}
getAllFiles(): string[] {
return [...this.#inputFiles];
return [...this.#sourceFiles];
}

@@ -227,3 +230,3 @@

getCanonicalFileName(file: string): string { return file; }
getCurrentDirectory(): string { return this.#rootDir; }
getCurrentDirectory(): string { return this.#manifest.workspace.path; }
getDefaultLibFileName(opts: ts.CompilerOptions): string { return ts.getDefaultLibFileName(opts); }

@@ -234,8 +237,8 @@ getNewLine(): string { return ts.sys.newLine; }

fileExists(inputFile: string): boolean {
return this.#inputToEntry.has(inputFile) || ts.sys.fileExists(this.#inputPathToSourcePath(inputFile));
fileExists(sourceFile: string): boolean {
return this.#sourceToEntry.has(sourceFile) || ts.sys.fileExists(sourceFile);
}
directoryExists(inputDir: string): boolean {
return this.#inputDirectoryToSource.has(inputDir) || ts.sys.directoryExists(this.#inputPathToSourcePath(inputDir));
directoryExists(sourceDir: string): boolean {
return this.#sourceDirectory.has(sourceDir) || ts.sys.directoryExists(sourceDir);
}

@@ -253,23 +256,20 @@

text = CompilerUtil.rewritePackageJSON(this.#manifest, text);
} else if (!this.#compilerOptions.inlineSourceMap && this.#compilerOptions.sourceMap && outputFile.endsWith('.map')) {
text = CompilerUtil.rewriteSourceMap(this.#manifest, text, f => this.#outputToEntry.get(f.replace(/[.]map$/, ''))!);
} else if (this.#compilerOptions.inlineSourceMap && CompilerUtil.isSourceMapUrlPosData(data)) {
text = CompilerUtil.rewriteInlineSourceMap(this.#manifest, text, f => this.#outputToEntry.get(f)!, data);
}
ts.sys.writeFile(outputFile, text, bom);
const location = this.#tscOutputFileToOuptut.get(outputFile)! ?? outputFile;
ts.sys.writeFile(location, text, bom);
}
readFile(inputFile: string): string | undefined {
const res = this.#sourceContents.get(inputFile) ?? this.#readFile(inputFile);
this.#sourceContents.set(inputFile, res);
readFile(sourceFile: string): string | undefined {
const res = this.#sourceContents.get(sourceFile) ?? this.#readFile(sourceFile);
this.#sourceContents.set(sourceFile, res);
return res;
}
getSourceFile(inputFile: string, language: ts.ScriptTarget): ts.SourceFile {
if (!this.#sourceFileObjects.has(inputFile)) {
const content = this.readFile(inputFile)!;
this.#sourceFileObjects.set(inputFile, ts.createSourceFile(inputFile, content ?? '', language));
getSourceFile(sourceFile: string, language: ts.ScriptTarget): ts.SourceFile {
if (!this.#sourceFileObjects.has(sourceFile)) {
const content = this.readFile(sourceFile)!;
this.#sourceFileObjects.set(sourceFile, ts.createSourceFile(sourceFile, content ?? '', language));
}
return this.#sourceFileObjects.get(inputFile)!;
return this.#sourceFileObjects.get(sourceFile)!;
}
}

@@ -8,2 +8,2 @@ import type ts from 'typescript';

export type CompileEmitEvent = { file: string, i: number, total: number, err?: CompileEmitError };
export type CompileStateEntry = { sourceFile: string, inputFile: string, outputFile?: string, module: ManifestModule };
export type CompileStateEntry = { sourceFile: string, tscOutputFile: string, outputFile?: string, module: ManifestModule };
import ts from 'typescript';
import { path, ManifestContext, ManifestModuleFileType, ManifestModuleUtil, ManifestRoot, Package } from '@travetto/manifest';
import { ManifestModuleFileType, ManifestModuleUtil, ManifestRoot, Package } from '@travetto/manifest';
type OutputToSource = (outputFile: string) => ({ sourceFile: string } | undefined);
const nativeCwd = process.cwd();

@@ -17,55 +15,5 @@

*/
static validFile = (type: ManifestModuleFileType): boolean => type === 'ts' || type === 'package-json' || type === 'js';
static validFile = (type: ManifestModuleFileType): boolean => type === 'ts' || type === 'package-json' || type === 'js' || type === 'typings';
/**
* Determines if write callback data has sourcemap information
* @param data
* @returns
*/
static isSourceMapUrlPosData(data?: ts.WriteFileCallbackData): data is { sourceMapUrlPos: number } {
return data !== undefined && data !== null && typeof data === 'object' && ('sourceMapUrlPos' in data);
}
/**
* Rewrite's sourcemap locations to real folders
* @returns
*/
static rewriteSourceMap(ctx: ManifestContext, text: string, outputToSource: OutputToSource): string {
const data: { sourceRoot?: string, sources: string[] } = JSON.parse(text);
const output = ManifestModuleUtil.withOutputExtension(path.resolve(ctx.workspace.path, ctx.build.outputFolder, data.sources[0]));
const { sourceFile } = outputToSource(output) ?? {};
if (sourceFile) {
delete data.sourceRoot;
data.sources = [sourceFile];
text = JSON.stringify(data);
}
return text;
}
/**
* Rewrite's inline sourcemap locations to real folders
* @param text
* @param outputToSource
* @param writeData
* @returns
*/
static rewriteInlineSourceMap(
ctx: ManifestContext,
text: string,
outputToSource: OutputToSource,
{ sourceMapUrlPos }: ts.WriteFileCallbackData & { sourceMapUrlPos: number }
): string {
const sourceMapUrl = text.substring(sourceMapUrlPos);
const [prefix, sourceMapData] = sourceMapUrl.split('base64,');
const rewritten = this.rewriteSourceMap(ctx, Buffer.from(sourceMapData, 'base64url').toString('utf8'), outputToSource);
return [
text.substring(0, sourceMapUrlPos),
prefix,
'base64,',
Buffer.from(rewritten, 'utf8').toString('base64url')
].join('');
}
/**
* Rewrites the package.json to target output file names, and pins versions

@@ -72,0 +20,0 @@ * @param manifest

@@ -192,6 +192,6 @@ import os from 'node:os';

continue;
} else if (action === 'update' && !this.#state.checkIfSourceChanged(entry.inputFile)) {
} else if (action === 'update' && !this.#state.checkIfSourceChanged(entry.sourceFile)) {
continue;
} else if (action === 'delete') {
this.#state.removeInput(entry.inputFile);
this.#state.removeSource(entry.sourceFile);
}

@@ -198,0 +198,0 @@

@@ -36,4 +36,4 @@ import { createRequire } from 'node:module';

/** Convert a file to a given ext */
static #sourceToExtension(inputFile: string, ext: string): string {
return inputFile.replace(/[.][tj]sx?$/, ext);
static #sourceToExtension(sourceFile: string, ext: string): string {
return sourceFile.replace(/[.][tj]sx?$/, ext);
}

@@ -44,4 +44,4 @@

*/
static #sourceToOutputExt(inputFile: string): string {
return this.#sourceToExtension(inputFile, '.js');
static #sourceToOutputExt(sourceFile: string): string {
return this.#sourceToExtension(sourceFile, '.js');
}

@@ -52,8 +52,8 @@

*/
static async #transpileFile(ctx: ManifestContext, inputFile: string, outputFile: string): Promise<void> {
const type = CommonUtil.getFileType(inputFile);
static async #transpileFile(ctx: ManifestContext, sourceFile: string, outputFile: string): Promise<void> {
const type = CommonUtil.getFileType(sourceFile);
if (type === 'js' || type === 'ts') {
const compilerOut = CommonUtil.resolveWorkspace(ctx, ctx.build.compilerFolder, 'node_modules');
const text = (await fs.readFile(inputFile, 'utf8'))
const text = (await fs.readFile(sourceFile, 'utf8'))
.replace(/from '([.][^']+)'/g, (_, i) => `from '${i.replace(/[.]js$/, '')}.js'`)

@@ -67,6 +67,6 @@ .replace(/from '(@travetto\/(.*?))'/g, (_, i, s) => `from '${compilerOut}/${i}${s.includes('/') ? '.js' : '/__index__.js'}'`);

inlineSourceMap: true,
}, inputFile);
}, sourceFile);
await CommonUtil.writeTextFile(outputFile, content);
} else if (type === 'package-json') {
const pkg: Package = JSON.parse(await fs.readFile(inputFile, 'utf8'));
const pkg: Package = JSON.parse(await fs.readFile(sourceFile, 'utf8'));
const main = pkg.main ? this.#sourceToOutputExt(pkg.main) : undefined;

@@ -73,0 +73,0 @@ const files = pkg.files?.map(x => this.#sourceToOutputExt(x));

import fs from 'node:fs/promises';
import type { CompilerOptions } from 'typescript';

@@ -6,3 +7,3 @@ import type { ManifestContext } from '@travetto/manifest';

const OPT_CACHE: Record<string, import('typescript').CompilerOptions> = {};
const OPT_CACHE: Record<string, CompilerOptions> = {};

@@ -9,0 +10,0 @@ export class TypescriptUtil {

@@ -11,2 +11,4 @@ {

"strict": true,
"declaration": true,
"declarationMap": true,
"esModuleInterop": true,

@@ -13,0 +15,0 @@ "strictPropertyInitialization": false,

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc