Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-import

Package Overview
Dependencies
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-import - npm Package Compare versions

Comparing version 2.0.8 to 2.0.9

__tests__/process-cwd-collision.spec.ts

39

dist/index.d.ts

@@ -1,32 +0,39 @@

export interface ICompilerOptions {
logger?: Partial<Console>;
export interface CompilerOptions {
/**
* Directory when cached JS files are stored. Default: ${ts-import-installation-path}/cache
*/
cacheDir?: string;
/**
* If TypeScript compilation fails but there is cached file, should it be loaded? Default: false
*/
fallback?: boolean;
/**
* Flags that should be used during compilation. Default: --downlevelIteration --emitDecoratorMetadata --experimentalDecorators --module commonjs --resolveJsonModule --skipLibCheck --target es2015
*/
flags?: string[];
/**
* Logger that will be used by compiler. Requires error, warn, info and debug functions. Default: undefined
*/
logger?: Partial<Console>;
}
export interface ICompilationContext {
export interface CompilationContext {
cwd: string;
tsPath: string;
tsDir: string;
tsPath: string;
}
/**
* Compiles TypeScript file to JavaScript, stores it cached and reads js from cache if available.
* @param scriptPath path to script to store in cache equivalent path.
* @param cacheDir
*/
export declare class Compiler {
static defaults: {
fallback: boolean;
cacheDir: string;
flags: string[];
};
options: ICompilerOptions & typeof Compiler.defaults;
constructor(options?: ICompilerOptions);
options: CompilerOptions & typeof Compiler.defaults;
constructor(options?: CompilerOptions);
/**
* Compile scripts.ts to scripts.js, check cache.
* @param scriptsDir
*/
compile(relativeTsPath?: string): Promise<any>;
compileOrFail(ctx: ICompilationContext): Promise<any>;
buildCache(absoluteTsPath: string): Promise<unknown>;
wasModified(tsFilePath: string, jsFilePath: string): Promise<boolean>;
compile(relativeTsPath?: string, cwd?: string): Promise<any>;
private compileOrFail;
private buildCache;
}
export declare const tsImport: Compiler;

@@ -38,18 +38,2 @@ "use strict";

};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
exports.__esModule = true;

@@ -60,42 +44,28 @@ exports.tsImport = exports.Compiler = void 0;

var path = require("path");
var ts_options_defaults_1 = require("ts-options-defaults");
/**
* Compiles TypeScript file to JavaScript, stores it cached and reads js from cache if available.
* @param scriptPath path to script to store in cache equivalent path.
* @param cacheDir
*/
var utils_1 = require("./utils");
var options_defaults_1 = require("options-defaults");
var Compiler = /** @class */ (function () {
function Compiler(options) {
this.options = ts_options_defaults_1.defaults(Compiler.defaults, options);
this.options = options_defaults_1.defaults(Compiler.defaults, options);
}
/**
* Compile scripts.ts to scripts.js, check cache.
* @param scriptsDir
*/
Compiler.prototype.compile = function (relativeTsPath) {
Compiler.prototype.compile = function (relativeTsPath, cwd) {
if (relativeTsPath === void 0) { relativeTsPath = ""; }
if (cwd === void 0) { cwd = process.cwd(); }
return __awaiter(this, void 0, void 0, function () {
var cwd, tsPath, tsDir, compiled;
var tsPath, tsDir, ctx;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
cwd = process.cwd();
tsPath = path.resolve(cwd, relativeTsPath);
if (!fs.existsSync(tsPath)) {
throw new Error("File " + tsPath + " not found to compile.");
}
tsDir = path.dirname(tsPath);
// Switch directory to scripts.ts to resolve node_modules during require.
process.chdir(tsDir);
return [4 /*yield*/, this.compileOrFail({ cwd: cwd, tsDir: tsDir, tsPath: tsPath })["catch"](function (err) {
// Change directory back to cwd to prevent side-effects on error.
process.chdir(cwd);
throw err;
})];
case 1:
compiled = _a.sent();
// Change directory back to cwd and return compiled.
process.chdir(cwd);
return [2 /*return*/, compiled];
tsPath = path.resolve(cwd, relativeTsPath);
if (!fs.existsSync(tsPath)) {
throw new Error("File " + tsPath + " not found to compile.");
}
tsDir = path.dirname(tsPath);
ctx = {
cwd: cwd,
tsPath: tsPath,
tsDir: tsDir
};
return [2 /*return*/, this.compileOrFail(ctx)];
});

@@ -105,39 +75,44 @@ });

Compiler.prototype.compileOrFail = function (ctx) {
var _a, _b, _c, _d, _e, _f, _g;
return __awaiter(this, void 0, void 0, function () {
var logger, tsDir, tsPath, tsFileName, jsFileName, cacheDir, cachedFile, tsWasModified, compiled_1, compiled_2, compiled;
return __generator(this, function (_a) {
switch (_a.label) {
var logger, tsPath, tsDir, cwd, tsFileName, jsFileName, cacheDir, jsPath, tsWasModified, buildError;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
logger = this.options.logger;
tsDir = ctx.tsDir, tsPath = ctx.tsPath;
tsPath = ctx.tsPath, tsDir = ctx.tsDir, cwd = ctx.cwd;
tsFileName = path.basename(tsPath);
jsFileName = tsFileName.replace(/\.[^/.]+$/, ".js");
jsFileName = tsFileName.replace(/\.[^/.]+$/u, ".js");
cacheDir = path.resolve(this.options.cacheDir, "." + tsDir);
cachedFile = path.resolve(cacheDir, jsFileName);
jsPath = path.resolve(cacheDir, jsFileName);
// Check if cached scripts.js exist.
logger === null || logger === void 0 ? void 0 : logger.debug("Looking for cached file at " + cachedFile);
if (!fs.existsSync(cachedFile)) return [3 /*break*/, 6];
return [4 /*yield*/, this.wasModified(tsPath, cachedFile)];
(_a = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _a === void 0 ? void 0 : _a.call(logger, "Looking for cached file at " + jsPath);
if (!fs.existsSync(jsPath)) return [3 /*break*/, 3];
return [4 /*yield*/, utils_1.wasFileModified(tsPath, jsPath)];
case 1:
tsWasModified = _a.sent();
if (!!tsWasModified) return [3 /*break*/, 3];
logger === null || logger === void 0 ? void 0 : logger.debug("File was not modified, importing.");
return [4 /*yield*/, Promise.resolve().then(function () { return require(cachedFile); })];
tsWasModified = _h.sent();
if (!tsWasModified) {
(_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, "File was not modified, importing.");
return [2 /*return*/, utils_1.importJsInDirectory(cwd, jsPath, tsDir)];
}
// Cache is incorrect, rebuild.
(_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, "File was modified, building and importing.");
return [4 /*yield*/, this.buildCache(tsPath)["catch"](function (err) {
var _a, _b;
(_a = logger === null || logger === void 0 ? void 0 : logger.warn) === null || _a === void 0 ? void 0 : _a.call(logger, "Building " + tsPath + " failed.");
(_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, err);
return err;
})];
case 2:
compiled_1 = _a.sent();
return [2 /*return*/, compiled_1];
buildError = _h.sent();
// If we don't want to fallback to last working version of compiled file, throw error.
if (!this.options.fallback && buildError instanceof Error) {
throw buildError;
}
(_d = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _d === void 0 ? void 0 : _d.call(logger, "Caching successfull.");
return [2 /*return*/, utils_1.importJsInDirectory(cwd, jsPath, tsDir)];
case 3:
// Cache is incorrect, rebuild.
logger === null || logger === void 0 ? void 0 : logger.debug("File was modified, building and importing.");
return [4 /*yield*/, this.buildCache(tsPath)];
case 4:
_a.sent();
return [4 /*yield*/, Promise.resolve().then(function () { return require(cachedFile); })];
case 5:
compiled_2 = _a.sent();
return [2 /*return*/, compiled_2];
case 6:
// Create cache directory if it does not exist.
if (!fs.existsSync(cacheDir)) {
logger === null || logger === void 0 ? void 0 : logger.debug("Creating cache directory.");
(_e = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _e === void 0 ? void 0 : _e.call(logger, "Creating cache directory.");
fs.mkdirSync(cacheDir, {

@@ -148,10 +123,8 @@ recursive: true

// Build cache.
logger === null || logger === void 0 ? void 0 : logger.debug("File was not cached, caching...");
(_f = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _f === void 0 ? void 0 : _f.call(logger, "File was not cached, caching...");
return [4 /*yield*/, this.buildCache(tsPath)];
case 7:
_a.sent();
return [4 /*yield*/, Promise.resolve().then(function () { return require(cachedFile); })];
case 8:
compiled = _a.sent();
return [2 /*return*/, compiled];
case 4:
_h.sent();
(_g = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _g === void 0 ? void 0 : _g.call(logger, "Caching successfull.");
return [2 /*return*/, utils_1.importJsInDirectory(cwd, jsPath, tsDir)];
}

@@ -162,30 +135,28 @@ });

Compiler.prototype.buildCache = function (absoluteTsPath) {
var _a = this.options, flags = _a.flags, cacheDir = _a.cacheDir, logger = _a.logger;
// Compile new scripts.ts to .js.
return new Promise(function (resolve, reject) {
var compileCommand = "npx -p typescript tsc '" + absoluteTsPath + "' --rootDir / --outDir '" + cacheDir + "' " + flags.join(' ');
logger === null || logger === void 0 ? void 0 : logger.info("Compiling " + absoluteTsPath);
logger === null || logger === void 0 ? void 0 : logger.debug("Command: " + compileCommand);
childProcess.exec(compileCommand, function (err, stdout, stderr) {
if (err) {
logger === null || logger === void 0 ? void 0 : logger.error(err);
reject(err);
return;
}
logger === null || logger === void 0 ? void 0 : logger.log(stdout);
logger === null || logger === void 0 ? void 0 : logger.error(stderr);
resolve();
});
});
};
Compiler.prototype.wasModified = function (tsFilePath, jsFilePath) {
return __awaiter(this, void 0, void 0, function () {
var _a, tsFileStat, jsFileStat;
var _a, flags, cacheDir, logger;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, Promise.all([fs.promises.stat(tsFilePath), fs.promises.stat(jsFilePath)])];
case 1:
_a = __read.apply(void 0, [_b.sent(), 2]), tsFileStat = _a[0], jsFileStat = _a[1];
return [2 /*return*/, tsFileStat.mtimeMs > jsFileStat.mtimeMs];
}
_a = this.options, flags = _a.flags, cacheDir = _a.cacheDir, logger = _a.logger;
// Compile new scripts.ts to .js.
return [2 /*return*/, new Promise(function (resolve, reject) {
var _a, _b;
var compileCommand = "npx -p typescript tsc '" + absoluteTsPath + "' --rootDir / --outDir '" + cacheDir + "' " + flags.join(" ");
(_a = logger === null || logger === void 0 ? void 0 : logger.info) === null || _a === void 0 ? void 0 : _a.call(logger, "Compiling " + absoluteTsPath);
(_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, "Command: " + compileCommand);
childProcess.exec(compileCommand, function (err, stdout, stderr) {
var _a, _b, _c;
if (err) {
(_a = logger === null || logger === void 0 ? void 0 : logger.error) === null || _a === void 0 ? void 0 : _a.call(logger, err);
reject(err);
return;
}
if (stdout.trim()) {
(_b = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _b === void 0 ? void 0 : _b.call(logger, stdout);
}
if (stderr.trim()) {
(_c = logger === null || logger === void 0 ? void 0 : logger.debug) === null || _c === void 0 ? void 0 : _c.call(logger, stderr);
}
resolve(stdout);
});
})];
});

@@ -195,2 +166,3 @@ });

Compiler.defaults = {
fallback: false,
cacheDir: path.resolve(__dirname, "../cache"),

@@ -197,0 +169,0 @@ flags: [

{
"name": "ts-import",
"version": "2.0.8",
"description": "Import (compile and cache on the fly) TypeScript files dynamically with ease.",
"keywords": [
"compile",
"dynamic",
"import",
"require",
"typescript"
],
"author": "Artur Kurowski <radarsu@gmail.com>",
"homepage": "https://github.com/radarsu/ts-import#readme",
"license": "GPL-3.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"dependencies": {
"ts-options-defaults": "2.0.5"
},
"devDependencies": {
"@radrat-scripts/package": "0.0.79-14",
"@radrat-scripts/readme": "0.0.79-14",
"@radrat/cli": "0.0.79-15",
"@types/node": "^14.6.0",
"typescript": "^4.0.2"
}
"name": "ts-import",
"version": "2.0.9",
"description": "Import (compile and cache on the fly) TypeScript files dynamically with ease.",
"keywords": [
"compile",
"dynamic",
"import",
"require",
"typescript"
],
"author": "Artur Kurowski <radarsu@gmail.com>",
"homepage": "https://github.com/radarsu/ts-import#readme",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"dependencies": {
"options-defaults": "^2.0.9"
},
"devDependencies": {
"@types/node": "^14.11.1",
"jest": "^26.4.2",
"ts-jest": "^26.3.0",
"typescript": "^4.0.2"
},
"gitHead": "382b0029bd9e11b0e27e79c9436f82a8ed8f3335"
}

@@ -1,10 +0,25 @@

import { packageScripts } from '@radrat-scripts/package';
import { readmeScripts } from '@radrat-scripts/readme';
import { IRadratCli } from '@radrat/cli';
import type { Scripts } from '@radrat/cli';
const scripts = async (cli: IRadratCli) => {
await packageScripts(cli);
await readmeScripts(cli);
const scripts: Scripts = async (cli) => {
// Run tests.
await cli.run({
name: `test`,
command: `npx jest`,
});
await cli.run({
name: `test.watch`,
command: `npx jest --watch`,
});
await cli.loadPlugins([
{
name: `@radrat-scripts/package`,
},
{
name: `@radrat-scripts/readme`,
},
]);
};
export default scripts;
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { defaults } from 'ts-options-defaults';
export interface ICompilerOptions {
logger?: Partial<Console>;
import { importJsInDirectory, wasFileModified } from './utils';
import { defaults } from 'options-defaults';
export interface CompilerOptions {
/**
* Directory when cached JS files are stored. Default: ${ts-import-installation-path}/cache
*/
cacheDir?: string;
/**
* If TypeScript compilation fails but there is cached file, should it be loaded? Default: false
*/
fallback?: boolean;
/**
* Flags that should be used during compilation. Default: --downlevelIteration --emitDecoratorMetadata --experimentalDecorators --module commonjs --resolveJsonModule --skipLibCheck --target es2015
*/
flags?: string[];
/**
* Logger that will be used by compiler. Requires error, warn, info and debug functions. Default: undefined
*/
logger?: Partial<Console>;
}
export interface ICompilationContext {
export interface CompilationContext {
cwd: string;
tsPath: string;
tsDir: string;
tsPath: string;
}
/**
* Compiles TypeScript file to JavaScript, stores it cached and reads js from cache if available.
* @param scriptPath path to script to store in cache equivalent path.
* @param cacheDir
*/
export class Compiler {
static defaults = {
fallback: false,
cacheDir: path.resolve(__dirname, `../cache`),

@@ -37,4 +49,5 @@ flags: [

options: ICompilerOptions & typeof Compiler.defaults;
constructor(options?: ICompilerOptions) {
options: CompilerOptions & typeof Compiler.defaults;
constructor(options?: CompilerOptions) {
this.options = defaults(Compiler.defaults, options);

@@ -45,7 +58,5 @@ }

* Compile scripts.ts to scripts.js, check cache.
* @param scriptsDir
*/
async compile(relativeTsPath: string = ``): Promise<any> {
async compile(relativeTsPath = ``, cwd = process.cwd()): Promise<any> {
// Check if file exists.
const cwd = process.cwd();
const tsPath = path.resolve(cwd, relativeTsPath);

@@ -60,42 +71,47 @@

// Switch directory to scripts.ts to resolve node_modules during require.
process.chdir(tsDir);
// Create compilation context.
const ctx: CompilationContext = {
cwd,
tsPath,
tsDir,
};
const compiled = await this.compileOrFail({ cwd, tsDir, tsPath }).catch((err) => {
// Change directory back to cwd to prevent side-effects on error.
process.chdir(cwd);
throw err;
});
// Change directory back to cwd and return compiled.
process.chdir(cwd);
return compiled;
return this.compileOrFail(ctx);
}
async compileOrFail(ctx: ICompilationContext) {
private async compileOrFail(ctx: CompilationContext) {
const { logger } = this.options;
const { tsDir, tsPath } = ctx;
const { tsPath, tsDir, cwd } = ctx;
const tsFileName = path.basename(tsPath);
const jsFileName = tsFileName.replace(/\.[^/.]+$/, `.js`);
const jsFileName = tsFileName.replace(/\.[^/.]+$/u, `.js`);
const cacheDir = path.resolve(this.options.cacheDir, `.${tsDir}`);
const cachedFile = path.resolve(cacheDir, jsFileName);
const jsPath = path.resolve(cacheDir, jsFileName);
// Check if cached scripts.js exist.
logger?.debug(`Looking for cached file at ${cachedFile}`);
if (fs.existsSync(cachedFile)) {
logger?.debug?.(`Looking for cached file at ${jsPath}`);
if (fs.existsSync(jsPath)) {
// Cache is correct, do nothing.
const tsWasModified = await this.wasModified(tsPath, cachedFile);
const tsWasModified = await wasFileModified(tsPath, jsPath);
if (!tsWasModified) {
logger?.debug(`File was not modified, importing.`);
const compiled = await import(cachedFile);
return compiled;
logger?.debug?.(`File was not modified, importing.`);
return importJsInDirectory(cwd, jsPath, tsDir);
}
// Cache is incorrect, rebuild.
logger?.debug(`File was modified, building and importing.`);
await this.buildCache(tsPath);
const compiled = await import(cachedFile);
return compiled;
logger?.debug?.(`File was modified, building and importing.`);
const buildError = await this.buildCache(tsPath).catch((err) => {
logger?.warn?.(`Building ${tsPath} failed.`);
logger?.debug?.(err);
return err;
});
// If we don't want to fallback to last working version of compiled file, throw error.
if (!this.options.fallback && buildError instanceof Error) {
throw buildError;
}
logger?.debug?.(`Caching successfull.`);
return importJsInDirectory(cwd, jsPath, tsDir);
}

@@ -105,3 +121,3 @@

if (!fs.existsSync(cacheDir)) {
logger?.debug(`Creating cache directory.`);
logger?.debug?.(`Creating cache directory.`);
fs.mkdirSync(cacheDir, {

@@ -113,9 +129,9 @@ recursive: true,

// Build cache.
logger?.debug(`File was not cached, caching...`);
logger?.debug?.(`File was not cached, caching...`);
await this.buildCache(tsPath);
const compiled = await import(cachedFile);
return compiled;
logger?.debug?.(`Caching successfull.`);
return importJsInDirectory(cwd, jsPath, tsDir);
}
buildCache(absoluteTsPath: string) {
private async buildCache(absoluteTsPath: string) {
const { flags, cacheDir, logger } = this.options;

@@ -125,9 +141,11 @@

return new Promise((resolve, reject) => {
const compileCommand = `npx -p typescript tsc '${absoluteTsPath}' --rootDir / --outDir '${cacheDir}' ${flags.join(' ')}`;
logger?.info(`Compiling ${absoluteTsPath}`);
logger?.debug(`Command: ${compileCommand}`);
const compileCommand = `npx -p typescript tsc '${absoluteTsPath}' --rootDir / --outDir '${cacheDir}' ${flags.join(
` `,
)}`;
logger?.info?.(`Compiling ${absoluteTsPath}`);
logger?.debug?.(`Command: ${compileCommand}`);
childProcess.exec(compileCommand, (err, stdout, stderr) => {
if (err) {
logger?.error(err);
logger?.error?.(err);
reject(err);

@@ -137,16 +155,16 @@ return;

logger?.log(stdout);
logger?.error(stderr);
if (stdout.trim()) {
logger?.debug?.(stdout);
}
resolve();
if (stderr.trim()) {
logger?.debug?.(stderr);
}
resolve(stdout);
});
});
}
async wasModified(tsFilePath: string, jsFilePath: string) {
const [tsFileStat, jsFileStat] = await Promise.all([fs.promises.stat(tsFilePath), fs.promises.stat(jsFilePath)]);
return tsFileStat.mtimeMs > jsFileStat.mtimeMs;
}
}
export const tsImport = new Compiler();

@@ -6,3 +6,3 @@ {

},
"extends": "../../tsconfig.json"
"extends": "../tsconfig.json"
}
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