Comparing version 1.4.5 to 2.0.0
@@ -18,3 +18,3 @@ import minimist from 'minimist'; | ||
verbose: boolean; | ||
basedir: string; | ||
dir: string; | ||
instanceIsCLI: boolean; | ||
@@ -21,0 +21,0 @@ }; |
@@ -44,3 +44,3 @@ #!/usr/bin/env node | ||
var system_1 = require("../lib/system"); | ||
var __1 = require(".."); | ||
var file_utils_1 = require("../lib/file-utils"); | ||
exports.cliOptions = { | ||
@@ -50,7 +50,3 @@ silent: { short: 's', caption: 'Run silently' }, | ||
verbose: { short: 'v', caption: 'Chat it up' }, | ||
basedir: { short: 'd', paramCaption: '<dir>', caption: 'Base directory to resolve package from' }, | ||
persist: { | ||
caption: "Enable persistence for npm " + chalk_1.default.yellow("(deprecated - prefer 'prepare' script)") | ||
}, | ||
'no-persist': { caption: 'Disable npm persistence ' + chalk_1.default.yellow("(deprecated - prefer 'prepare' script)") }, | ||
dir: { short: 'd', paramCaption: '<dir>', caption: 'TypeScript directory or directory to resolve typescript package from' }, | ||
color: { inverse: true, caption: 'Strip ansi colours from output' } | ||
@@ -62,3 +58,3 @@ }; | ||
check: { | ||
short: 'c', caption: "Check patch status (use with " + chalk_1.default.cyanBright('--basedir') + " to specify TS package location)" | ||
short: 'c', caption: "Check patch status (use with " + chalk_1.default.cyanBright('--dir') + " to specify TS package location)" | ||
}, | ||
@@ -84,3 +80,3 @@ patch: { | ||
var leftCol = left.filter(Boolean).join(chalk_1.default.blue(', ')) + ' ' + chalk_1.default.yellow(paramCaption); | ||
var dots = chalk_1.default.grey('.'.repeat(COL_WIDTH - strip_ansi_1.default(leftCol).length)); | ||
var dots = chalk_1.default.grey('.'.repeat(COL_WIDTH - (0, strip_ansi_1.default)(leftCol).length)); | ||
return leftCol + " " + dots + " " + caption; | ||
@@ -118,3 +114,3 @@ }; | ||
function run(argStr) { | ||
var args = minimist_1.default(instanceIsCLI ? process.argv.slice(2) : argStr.split(' ')); | ||
var args = (0, minimist_1.default)(instanceIsCLI ? process.argv.slice(2) : argStr.split(' ')); | ||
var cmd = args._[0] ? args._[0].toLowerCase() : void 0; | ||
@@ -137,2 +133,4 @@ try { | ||
}, {}); | ||
if (args.basedir) | ||
opts.basedir = args.basedir; | ||
/* Handle special cases */ | ||
@@ -146,3 +144,3 @@ if ((args.v) && (!cmd)) | ||
/* Build & Handle options */ | ||
system_1.parseOptions(__assign({ instanceIsCLI: instanceIsCLI }, opts)); | ||
(0, system_1.parseOptions)(__assign({ instanceIsCLI: instanceIsCLI }, opts)); | ||
/* Handle commands */ | ||
@@ -152,6 +150,6 @@ (function () { | ||
case 'help': | ||
return system_1.Log(menuText, system_1.Log.system); | ||
return (0, system_1.Log)(menuText, system_1.Log.system); | ||
case 'version': | ||
var _a = __1.getTSPackage(system_1.appOptions.basedir), tsVersion = _a.version, packageDir = _a.packageDir; | ||
return system_1.Log('\r\n' + | ||
var _a = (0, file_utils_1.getTSPackage)(system_1.appOptions.dir), tsVersion = _a.version, packageDir = _a.packageDir; | ||
return (0, system_1.Log)('\r\n' + | ||
chalk_1.default.bold.blue('ts-patch: ') + system_1.tspPackageJSON.version + '\r\n' + | ||
@@ -170,12 +168,8 @@ chalk_1.default.bold.blue('typescript: ') + tsVersion + chalk_1.default.gray(" [" + packageDir + "]"), system_1.Log.system); | ||
default: | ||
return (args.persist === undefined) ? | ||
system_1.Log('Invalid command. Try ts-patch /? for more info', system_1.Log.system) : {}; | ||
(0, system_1.Log)('Invalid command. Try ts-patch /? for more info', system_1.Log.system); | ||
} | ||
})(); | ||
/* Handle persist option */ | ||
if (args.persist !== undefined) | ||
(args.persist) ? actions.enablePersistence() : actions.disablePersistence(); | ||
} | ||
catch (e) { | ||
system_1.Log([ | ||
(0, system_1.Log)([ | ||
'!', | ||
@@ -182,0 +176,0 @@ chalk_1.default.bold.yellow(e.name && (e.name !== 'Error') ? "[" + e.name + "]: " : 'Error: ') + chalk_1.default.red(e.message) |
@@ -5,2 +5,13 @@ # Changelog | ||
## [2.0.0](https://github.com/nonara/ts-patch/compare/v1.4.5...v2.0.0) (2021-11-01) | ||
### ⚠ BREAKING CHANGES | ||
* Cleaner, lighter weight patch (#66) | ||
### Features | ||
* Cleaner, lighter weight patch ([#66](https://github.com/nonara/ts-patch/issues/66)) ([78dcff5](https://github.com/nonara/ts-patch/commit/78dcff59bb7dd3ba35ca81b14aab7e07a8c593b8)) | ||
### [1.4.5](https://github.com/nonara/ts-patch/compare/v1.4.4...v1.4.5) (2021-10-25) | ||
@@ -7,0 +18,0 @@ |
@@ -6,3 +6,2 @@ import { TSModule } from './file-utils'; | ||
export declare const RESOURCES_PATH: string; | ||
export declare const HOOKS_FILES: string[]; | ||
export declare const defaultInstallLibraries: string[]; | ||
@@ -12,3 +11,3 @@ /** | ||
*/ | ||
export declare function parseFiles(fileOrFilesOrGlob: string | string[], dir: string, includeSrc?: boolean): TSModule[] & { | ||
export declare function parseFiles(fileOrFilesOrGlob: string | string[], libDir: string, includeSrc?: boolean): TSModule[] & { | ||
patched: TSModule[]; | ||
@@ -22,17 +21,3 @@ unPatchable: TSModule[]; | ||
*/ | ||
export declare const setOptions: (opts?: Partial<{ | ||
logLevel: number; | ||
color: boolean; | ||
silent: boolean; | ||
verbose: boolean; | ||
basedir: string; | ||
instanceIsCLI: boolean; | ||
}> | undefined) => { | ||
logLevel: number; | ||
color: boolean; | ||
silent: boolean; | ||
verbose: boolean; | ||
basedir: string; | ||
instanceIsCLI: boolean; | ||
}; | ||
export declare const setOptions: (opts?: Partial<TSPOptions> | undefined) => TSPOptions; | ||
/** | ||
@@ -60,9 +45,1 @@ * Patch TypeScript modules | ||
export declare function unpatch(fileOrFilesOrGlob: string | string[], opts?: Partial<TSPOptions>): boolean; | ||
/** | ||
* Enable persistence hooks | ||
*/ | ||
export declare function enablePersistence(opts?: Partial<TSPOptions>): void; | ||
/** | ||
* Disable persistence hooks | ||
*/ | ||
export declare function disablePersistence(opts?: Partial<TSPOptions>): void; |
@@ -25,3 +25,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.disablePersistence = exports.enablePersistence = exports.unpatch = exports.patch = exports.check = exports.uninstall = exports.install = exports.setOptions = exports.parseFiles = exports.defaultInstallLibraries = exports.HOOKS_FILES = exports.RESOURCES_PATH = exports.BACKUP_DIRNAME = exports.SRC_FILES = void 0; | ||
exports.unpatch = exports.patch = exports.check = exports.uninstall = exports.install = exports.setOptions = exports.parseFiles = exports.defaultInstallLibraries = exports.RESOURCES_PATH = exports.BACKUP_DIRNAME = exports.SRC_FILES = void 0; | ||
var path = __importStar(require("path")); | ||
@@ -35,3 +35,2 @@ var fs = __importStar(require("fs")); | ||
var system_1 = require("./system"); | ||
var resolve_1 = __importDefault(require("resolve")); | ||
/* ******************************************************************************************************************** | ||
@@ -45,3 +44,2 @@ * Config | ||
exports.RESOURCES_PATH = path.join(system_1.appRoot, system_1.tspPackageJSON.directories.resources); | ||
exports.HOOKS_FILES = ['postinstall', 'postinstall.cmd']; | ||
exports.defaultInstallLibraries = ['tsc.js', 'typescript.js']; | ||
@@ -56,9 +54,9 @@ // endregion | ||
*/ | ||
function parseFiles(fileOrFilesOrGlob, dir, includeSrc) { | ||
function parseFiles(fileOrFilesOrGlob, libDir, includeSrc) { | ||
if (includeSrc === void 0) { includeSrc = false; } | ||
var files = Array.isArray(fileOrFilesOrGlob) ? fileOrFilesOrGlob : | ||
fs.existsSync(file_utils_1.getModuleAbsolutePath(fileOrFilesOrGlob, dir)) ? [fileOrFilesOrGlob] : | ||
fs.existsSync((0, file_utils_1.getModuleAbsolutePath)(fileOrFilesOrGlob, libDir)) ? [fileOrFilesOrGlob] : | ||
glob_1.default.sync(fileOrFilesOrGlob); | ||
var ret = files.map(function (f) { return file_utils_1.getTSModule(file_utils_1.getModuleAbsolutePath(f, dir), includeSrc); }); | ||
return system_1.defineProperties(ret, { | ||
var ret = files.map(function (f) { return (0, file_utils_1.getTSModule)((0, file_utils_1.getModuleAbsolutePath)(f, libDir), includeSrc); }); | ||
return (0, system_1.defineProperties)(ret, { | ||
patched: { get: function () { return ret.filter(function (f) { return f.patchVersion; }); } }, | ||
@@ -79,3 +77,3 @@ unPatchable: { get: function () { return ret.filter(function (f) { return !f.canPatch; }); } }, | ||
try { | ||
file_utils_1.mkdirIfNotExist(backupDir); | ||
(0, file_utils_1.mkdirIfNotExist)(backupDir); | ||
} | ||
@@ -99,3 +97,3 @@ catch (e) { | ||
var backupDir = path.join(tsPackage.packageDir, exports.BACKUP_DIRNAME); | ||
var _a = file_utils_1.getTSModule(path.join(backupDir, currentModule.filename)), file = _a.file, filename = _a.filename, canPatch = _a.canPatch, patchVersion = _a.patchVersion, dir = _a.dir; | ||
var _a = (0, file_utils_1.getTSModule)(path.join(backupDir, currentModule.filename)), file = _a.file, filename = _a.filename, canPatch = _a.canPatch, patchVersion = _a.patchVersion, dir = _a.dir; | ||
/* Verify backup file */ | ||
@@ -113,3 +111,3 @@ if (!canPatch) | ||
/* Verify restored file */ | ||
var restoredModule = file_utils_1.getTSModule(currentModule.file); | ||
var restoredModule = (0, file_utils_1.getTSModule)(currentModule.file); | ||
if (!restoredModule.canPatch) | ||
@@ -121,3 +119,3 @@ throw new system_1.RestoreError(filename, "Restored file is not a valid typescript module! You will need to reinstall typescript."); | ||
if ((fs.readdirSync(backupDir).length < 1) && shell.rm('-rf', backupDir) && shell.error()) | ||
system_1.Log(['!', "Error deleting backup directory" + chalk_1.default.grey("[" + backupDir + "]")], system_1.Log.verbose); | ||
(0, system_1.Log)(['!', "Error deleting backup directory" + chalk_1.default.grey("[" + backupDir + "]")], system_1.Log.verbose); | ||
} | ||
@@ -132,3 +130,3 @@ // endregion | ||
*/ | ||
var setOptions = function (opts) { return system_1.resetOptions(opts); }; | ||
var setOptions = function (opts) { return (0, system_1.resetOptions)(opts); }; | ||
exports.setOptions = setOptions; | ||
@@ -141,3 +139,3 @@ /** | ||
if (ret) | ||
system_1.Log(['+', chalk_1.default.green("ts-patch installed!")]); | ||
(0, system_1.Log)(['+', chalk_1.default.green("ts-patch installed!")]); | ||
return ret; | ||
@@ -152,3 +150,3 @@ } | ||
if (ret) | ||
system_1.Log(['-', chalk_1.default.green("ts-patch removed!")]); | ||
(0, system_1.Log)(['-', chalk_1.default.green("ts-patch removed!")]); | ||
return ret; | ||
@@ -162,5 +160,5 @@ } | ||
if (fileOrFilesOrGlob === void 0) { fileOrFilesOrGlob = exports.SRC_FILES; } | ||
var basedir = system_1.parseOptions(opts).basedir; | ||
var _a = file_utils_1.getTSPackage(basedir), libDir = _a.libDir, packageDir = _a.packageDir, version = _a.version; | ||
system_1.Log("Checking TypeScript " + chalk_1.default.blueBright("v" + version) + " installation in " + chalk_1.default.blueBright(packageDir) + "\r\n"); | ||
var dir = (0, system_1.parseOptions)(opts).dir; | ||
var _a = (0, file_utils_1.getTSPackage)(dir), libDir = _a.libDir, packageDir = _a.packageDir, version = _a.version; | ||
(0, system_1.Log)("Checking TypeScript " + chalk_1.default.blueBright("v" + version) + " installation in " + chalk_1.default.blueBright(packageDir) + "\r\n"); | ||
var modules = parseFiles(fileOrFilesOrGlob, libDir); | ||
@@ -171,3 +169,3 @@ for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) { | ||
if (patchVersion) | ||
system_1.Log(['+', | ||
(0, system_1.Log)(['+', | ||
chalk_1.default.blueBright(filename) + " is patched with ts-patch version " + | ||
@@ -177,6 +175,6 @@ (chalk_1.default[outOfDate ? 'redBright' : 'blueBright'](patchVersion) + " " + (outOfDate ? '(out of date)' : '')) | ||
else if (canPatch) | ||
system_1.Log(['-', chalk_1.default.blueBright(filename) + " is not patched."]); | ||
(0, system_1.Log)(['-', chalk_1.default.blueBright(filename) + " is not patched."]); | ||
else | ||
system_1.Log(['-', chalk_1.default.red(chalk_1.default.redBright(filename) + " is not patched and cannot be patched!")]); | ||
system_1.Log('', system_1.Log.verbose); | ||
(0, system_1.Log)(['-', chalk_1.default.red(chalk_1.default.redBright(filename) + " is not patched and cannot be patched!")]); | ||
(0, system_1.Log)('', system_1.Log.verbose); | ||
} | ||
@@ -192,7 +190,7 @@ return modules; | ||
throw new system_1.PatchError("Must provide a file path, array of files, or glob."); | ||
var basedir = system_1.parseOptions(opts).basedir; | ||
var tsPackage = file_utils_1.getTSPackage(basedir); | ||
var dir = (0, system_1.parseOptions)(opts).dir; | ||
var tsPackage = (0, file_utils_1.getTSPackage)(dir); | ||
var modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); | ||
if (!modules.canUpdateOrPatch.length) { | ||
system_1.Log(['!', | ||
(0, system_1.Log)(['!', | ||
"File" + (modules.length - 1 ? 's' : '') + " already patched with the latest version. For details, run: " + | ||
@@ -207,16 +205,16 @@ chalk_1.default.bgBlackBright('ts-patch check') | ||
var file = m.file, filename = m.filename; | ||
system_1.Log(['~', "Patching " + chalk_1.default.blueBright(filename) + " in " + chalk_1.default.blueBright(path.dirname(file))], system_1.Log.verbose); | ||
(0, system_1.Log)(['~', "Patching " + chalk_1.default.blueBright(filename) + " in " + chalk_1.default.blueBright(path.dirname(file))], system_1.Log.verbose); | ||
// If already patched, load backup module source. Otherwise, backup un-patched | ||
if (m.patchVersion) | ||
m.moduleSrc = | ||
file_utils_1.getTSModule(path.join(tsPackage.packageDir, exports.BACKUP_DIRNAME, m.filename), /* includeSrc */ true).moduleSrc; | ||
(0, file_utils_1.getTSModule)(path.join(tsPackage.packageDir, exports.BACKUP_DIRNAME, m.filename), /* includeSrc */ true).moduleSrc; | ||
else | ||
backup(m, tsPackage); | ||
patcher_1.patchTSModule(m, tsPackage); | ||
(0, patcher_1.patchTSModule)(m, tsPackage); | ||
tsPackage.config.modules[filename] = fs.statSync(file).mtimeMs; | ||
system_1.Log(['+', chalk_1.default.green("Successfully patched " + chalk_1.default.bold.yellow(filename) + ".\r\n")], system_1.Log.verbose); | ||
(0, system_1.Log)(['+', chalk_1.default.green("Successfully patched " + chalk_1.default.bold.yellow(filename) + ".\r\n")], system_1.Log.verbose); | ||
} | ||
tsPackage.config.save(); | ||
if (modules.unPatchable.length > 1) { | ||
system_1.Log(['!', | ||
(0, system_1.Log)(['!', | ||
"Some files can't be patched! Try updating to a newer version of ts-patch. The following files are unable to be " + | ||
@@ -233,7 +231,7 @@ ("patched. [" + modules.unPatchable.map(function (f) { return f.filename; }).join(', ') + "]") | ||
throw new system_1.PatchError("Must provide a file path, array of files, or glob."); | ||
var _a = system_1.parseOptions(opts), basedir = _a.basedir, verbose = _a.verbose, instanceIsCLI = _a.instanceIsCLI; | ||
var tsPackage = file_utils_1.getTSPackage(basedir); | ||
var _a = (0, system_1.parseOptions)(opts), dir = _a.dir, verbose = _a.verbose, instanceIsCLI = _a.instanceIsCLI; | ||
var tsPackage = (0, file_utils_1.getTSPackage)(dir); | ||
var modules = parseFiles(fileOrFilesOrGlob, tsPackage.libDir, true); | ||
if (modules.patched.length < 1) { | ||
system_1.Log(['!', "File" + (modules.length - 1 ? 's' : '') + " not patched. For details, run: " + chalk_1.default.bgBlackBright('ts-patch check')]); | ||
(0, system_1.Log)(['!', "File" + (modules.length - 1 ? 's' : '') + " not patched. For details, run: " + chalk_1.default.bgBlackBright('ts-patch check')]); | ||
return false; | ||
@@ -246,7 +244,7 @@ } | ||
var file = tsModule.file, filename = tsModule.filename; | ||
system_1.Log(['~', "Restoring " + chalk_1.default.blueBright(filename) + " in " + chalk_1.default.blueBright(path.dirname(file))], system_1.Log.verbose); | ||
(0, system_1.Log)(['~', "Restoring " + chalk_1.default.blueBright(filename) + " in " + chalk_1.default.blueBright(path.dirname(file))], system_1.Log.verbose); | ||
try { | ||
restore(tsModule, tsPackage); | ||
delete tsPackage.config.modules[filename]; | ||
system_1.Log(['+', chalk_1.default.green("Successfully restored " + chalk_1.default.bold.yellow(filename) + ".\r\n")], system_1.Log.verbose); | ||
(0, system_1.Log)(['+', chalk_1.default.green("Successfully restored " + chalk_1.default.bold.yellow(filename) + ".\r\n")], system_1.Log.verbose); | ||
} | ||
@@ -270,5 +268,5 @@ catch (e) { | ||
else | ||
system_1.Log(['!', e.message], system_1.Log.verbose); | ||
(0, system_1.Log)(['!', e.message], system_1.Log.verbose); | ||
}); | ||
system_1.Log(''); | ||
(0, system_1.Log)(''); | ||
throw new system_1.RestoreError("[" + Object.keys(errors).join(', ') + "]", 'Try reinstalling typescript.' + | ||
@@ -280,56 +278,3 @@ (!verbose ? ' (Or, run uninstall again with --verbose for specific error detail)' : '')); | ||
exports.unpatch = unpatch; | ||
/** | ||
* Enable persistence hooks | ||
*/ | ||
function enablePersistence(opts) { | ||
var basedir = system_1.parseOptions(opts).basedir; | ||
var _a = file_utils_1.getTSPackage(basedir), config = _a.config, packageDir = _a.packageDir; | ||
system_1.Log(['~', "Enabling persistence in " + chalk_1.default.blueBright(packageDir)], system_1.Log.verbose); | ||
config.persist = true; | ||
config.save(); | ||
/* Copy hooks */ | ||
var hooksDir = path.join(packageDir, '../.hooks'); | ||
var hooksFiles = exports.HOOKS_FILES.map(function (f) { return path.join(exports.RESOURCES_PATH, f); }); | ||
try { | ||
file_utils_1.mkdirIfNotExist(hooksDir); | ||
} | ||
catch (e) { | ||
throw new system_1.PersistenceError("Could not create hooks directory in node_modules: " + e.message); | ||
} | ||
if (shell.cp(hooksFiles, hooksDir) && shell.error()) | ||
throw new system_1.PersistenceError("Error trying to copy persistence hooks: " + shell.error()); | ||
/* Write absolute path to ts-patch in hooks */ | ||
var tspPath; | ||
try { | ||
tspPath = path.dirname(resolve_1.default.sync('ts-patch/package.json', { basedir: packageDir })); | ||
} | ||
catch (e) { } | ||
if (tspPath) | ||
for (var _i = 0, _b = hooksFiles.map(function (f) { return path.join(hooksDir, path.basename(f)); }); _i < _b.length; _i++) { | ||
var file = _b[_i]; | ||
shell.sed('-i', /(?<=^(@SET\s)?tspdir\s*=\s*").+?(?="$)/m, tspPath.split(path.sep).join((path.extname(file) === '.cmd') ? '\\' : '/'), file); | ||
if (shell.error()) | ||
throw new system_1.PersistenceError("Error writing to hooks file '" + path.basename(file) + "': " + shell.error()); | ||
} | ||
system_1.Log(['+', chalk_1.default.green("Enabled persistence for " + chalk_1.default.blueBright(packageDir))]); | ||
} | ||
exports.enablePersistence = enablePersistence; | ||
/** | ||
* Disable persistence hooks | ||
*/ | ||
function disablePersistence(opts) { | ||
var basedir = system_1.parseOptions(opts).basedir; | ||
var _a = file_utils_1.getTSPackage(basedir), config = _a.config, packageDir = _a.packageDir; | ||
system_1.Log(['~', "Disabling persistence in " + chalk_1.default.blueBright(packageDir)], system_1.Log.verbose); | ||
config.persist = false; | ||
config.save(); | ||
/* Remove hooks */ | ||
var hooksDir = path.join(packageDir, '../.hooks'); | ||
var hooksFiles = exports.HOOKS_FILES.map(function (f) { return path.join(hooksDir, f); }); | ||
if (shell.rm('-rf', hooksFiles) && shell.error()) | ||
throw new system_1.PersistenceError("Error trying to remove persistence hooks: " + shell.error()); | ||
system_1.Log(['-', chalk_1.default.green("Disabled persistence for " + chalk_1.default.blueBright(packageDir))]); | ||
} | ||
exports.disablePersistence = disablePersistence; | ||
// endregion | ||
//# sourceMappingURL=actions.js.map |
@@ -18,5 +18,5 @@ /** | ||
/** | ||
* Get TypeScript package info - Resolve from basedir, throws if not cannot find TS package | ||
* Get TypeScript package info - Resolve from dir, throws if not cannot find TS package | ||
*/ | ||
export declare function getTSPackage(basedir?: string): TSPackage; | ||
export declare function getTSPackage(dir?: string): TSPackage; | ||
export interface TSModule { | ||
@@ -38,3 +38,2 @@ filename: string; | ||
readonly version: string; | ||
persist: boolean; | ||
modules: { | ||
@@ -41,0 +40,0 @@ [x: string]: number; |
@@ -31,3 +31,3 @@ "use strict"; | ||
var errors = []; | ||
var basedir = require('global-prefix'); | ||
var dir = require('global-prefix'); | ||
var check = function (dir) { | ||
@@ -42,3 +42,3 @@ try { | ||
}; | ||
var packageDir = (check(basedir) || check(path_1.default.join(basedir, 'lib'))).packageDir; | ||
var packageDir = (check(dir) || check(path_1.default.join(dir, 'lib'))).packageDir; | ||
if (!packageDir) | ||
@@ -53,3 +53,3 @@ throw new system_1.PackageError("Could not find global TypeScript installation! Are you sure it's installed globally?"); | ||
var getModuleAbsolutePath = function (filename, libDir) { | ||
var file = system_1.isAbsolute(filename) ? filename : path_1.default.join(libDir, filename); | ||
var file = (0, system_1.isAbsolute)(filename) ? filename : path_1.default.join(libDir, filename); | ||
if (path_1.default.extname(file) !== '.js') | ||
@@ -70,9 +70,9 @@ file = path_1.default.join(path_1.default.dirname(file), path_1.default.basename(file, path_1.default.extname(file)) + ".js"); | ||
/** | ||
* Get TypeScript package info - Resolve from basedir, throws if not cannot find TS package | ||
* Get TypeScript package info - Resolve from dir, throws if not cannot find TS package | ||
*/ | ||
function getTSPackage(basedir) { | ||
if (basedir === void 0) { basedir = process.cwd(); } | ||
if (!fs_1.default.existsSync(basedir)) | ||
throw new system_1.PackageError(basedir + " is not a valid directory"); | ||
var possiblePackageDirs = [basedir, function () { return path_1.default.dirname(resolve_1.default.sync("typescript/package.json", { basedir: basedir })); }]; | ||
function getTSPackage(dir) { | ||
if (dir === void 0) { dir = process.cwd(); } | ||
if (!fs_1.default.existsSync(dir)) | ||
throw new system_1.PackageError(dir + " is not a valid directory"); | ||
var possiblePackageDirs = [dir, function () { return path_1.default.dirname(resolve_1.default.sync("typescript/package.json", { basedir: dir })); }]; | ||
var _loop_1 = function (d) { | ||
@@ -110,3 +110,3 @@ var packageDir = void 0; | ||
} | ||
throw new system_1.PackageError("Could not find typescript package from " + basedir); | ||
throw new system_1.PackageError("Could not find typescript package from " + dir); | ||
} | ||
@@ -125,4 +125,5 @@ exports.getTSPackage = getTSPackage; | ||
var canPatch = Boolean(fileData.match(/^\(function\s\(ts\)\s?{[\s\S]+?\(ts\s?\|\|\s?\(ts\s?=\s?{}\)\);?$/m)); | ||
var patchVersion = canPatch && | ||
(fileData.match(/(?<=^\s*?var\stspVersion\s?=\s?['"`])(\S+?)(?=['"`])/m) || [])[0]; | ||
var patchVersion = canPatch && (fileData.match(/^\/\/\/\s*tsp:\s*(\S+)/s) || | ||
fileData.match(/(?<=^\s*?var\stspVersion\s?=\s?['"`])(\S+?)(?=['"`])/m) || | ||
[])[1]; | ||
var outOfDate = isOutOfDate(patchVersion); | ||
@@ -147,7 +148,7 @@ return __assign({ file: file, filename: filename, canPatch: canPatch, dir: dir, patchVersion: patchVersion, outOfDate: outOfDate }, (includeSrc && canPatch && { moduleSrc: fileData })); | ||
else | ||
system_1.Log(['!', e.message], system_1.Log.verbose); | ||
(0, system_1.Log)(['!', e.message], system_1.Log.verbose); | ||
} | ||
} | ||
var config = __assign(__assign({ persist: false, modules: {} }, fileData), { version: fileData.version || system_1.tspPackageJSON.version, file: configFile, save: function () { saveConfig(this); } }); | ||
return system_1.defineProperties(config, { | ||
var config = __assign(__assign({ modules: {} }, fileData), { version: fileData.version || system_1.tspPackageJSON.version, file: configFile, save: function () { saveConfig(this); } }); | ||
return (0, system_1.defineProperties)(config, { | ||
version: { writable: false }, | ||
@@ -154,0 +155,0 @@ file: { enumerable: false, writable: false } |
@@ -22,2 +22,3 @@ "use strict"; | ||
* ********************************************************************************************************************/ | ||
var getHeader = function () { return "/// tsp: " + system_1.tspPackageJSON.version + "\n\n"; }; | ||
/** | ||
@@ -27,6 +28,4 @@ * Generate insertion code for module-patch | ||
var generatePatch = function (isTSC) { | ||
return jsPatchSrc | ||
.replace(/(^\s*Object\.assign\(ts,\s*{[\s\S]*tspVersion,[\s\S]+?}\);?$)/m, "var tspVersion = '" + system_1.tspPackageJSON.version + "';\n" + | ||
("var isTSC = " + isTSC + ";\n") + | ||
"$1"); | ||
return jsPatchSrc + | ||
("\nObject.assign(tsp, { isTSC: " + isTSC + ", tspVersion: '" + system_1.tspPackageJSON.version + "' });\n\n"); | ||
}; | ||
@@ -47,5 +46,5 @@ /** | ||
if (tsPackage) { | ||
var _a = tsPackage.version.split('.'), major = _a[0], minor = _a[1]; | ||
if (+major < 3 && +minor < 7) | ||
throw new system_1.WrongTSVersion("ts-patch requires TypeScript v2.7 or higher."); | ||
var major = tsPackage.version.split('.')[0]; | ||
if (+major < 4) | ||
throw new system_1.WrongTSVersion("ts-patch v2 requires TypeScript v4.0 or higher."); | ||
} | ||
@@ -64,4 +63,2 @@ return true; | ||
if (emitPos < 0) | ||
emitPos = restCode.search(/^\s*?var [_\w]+? = program.emit\(/m); // TS 2.7 - 3.5 | ||
if (emitPos < 0) | ||
throw new Error("Could not determine emit call. Please file an issue with your TS version!"); | ||
@@ -71,3 +68,3 @@ var ver = tsPackage.version.split('.'); | ||
var minorVer = +ver[1]; | ||
var diagnosticsArrName = (majorVer > 3 || (majorVer === 3 && minorVer > 7)) ? 'allDiagnostics' : 'diagnostics'; | ||
var diagnosticsArrName = 'allDiagnostics'; | ||
return startCode + | ||
@@ -102,4 +99,5 @@ restCode.substr(0, emitPos) + | ||
fs_1.default.writeFileSync(file, Buffer.concat([ | ||
Buffer.from(getHeader()), | ||
Buffer.from(patchModule(tsModule, tsPackage, fs_1.default.readFileSync(tsFile, 'utf-8'))), | ||
Buffer.from(!file_utils_1.getTSModule(tsFile).patchVersion ? patchSrc : ''), | ||
Buffer.from(!(0, file_utils_1.getTSModule)(tsFile).patchVersion ? patchSrc : ''), | ||
Buffer.from(moduleSrc.replace(/^[\s\S]+(\(function \(ts\) {\s+function countLines[\s\S]+)$/, '$1')) | ||
@@ -110,2 +108,3 @@ ])); | ||
fs_1.default.writeFileSync(file, Buffer.concat([ | ||
Buffer.from(getHeader()), | ||
Buffer.from(moduleSrc), | ||
@@ -129,3 +128,3 @@ Buffer.from(patchSrc) | ||
catch (e) { | ||
throw new system_1.FileWriteError(filename, e.message); | ||
throw new system_1.FileWriteError(filename, e.stack); | ||
} | ||
@@ -132,0 +131,0 @@ } |
@@ -32,3 +32,3 @@ export declare class WrongTSVersion extends Error { | ||
filename: string; | ||
constructor(filename: string, message: string); | ||
constructor(filename: string, message?: string); | ||
} |
@@ -117,3 +117,3 @@ "use strict"; | ||
function FileWriteError(filename, message) { | ||
var _this = _super.call(this, "Error while trying to write to " + filename + (message && ": " + message)) || this; | ||
var _this = _super.call(this, "Error while trying to write to " + filename + (message ? ": " + message : '')) || this; | ||
_this.filename = filename; | ||
@@ -120,0 +120,0 @@ return _this; |
@@ -68,9 +68,9 @@ "use strict"; | ||
exports.appRoot = (function () { | ||
var moduleDir = path_1.default.join(__dirname, '../..'); | ||
var moduleDir = path_1.default.join(__dirname, '../../../'); | ||
var chkFile = function (pkgFile) { | ||
return (fs_1.default.existsSync(pkgFile) && (require(pkgFile).name === 'ts-patch')) ? path_1.default.dirname(pkgFile) : void 0; | ||
}; | ||
var res = chkFile(path_1.default.join(moduleDir, 'package.json')) || chkFile(path_1.default.join(moduleDir, '../..', 'package.json')); | ||
var res = chkFile(path_1.default.join(moduleDir, 'package.json')) || chkFile(path_1.default.join(moduleDir, '../package.json')); | ||
if (!res) | ||
throw new Error("Error getting app root. No valid ts-patch package file found."); | ||
throw new Error("Error getting app root. No valid ts-patch package file found in " + moduleDir); | ||
return res; | ||
@@ -77,0 +77,0 @@ })(); |
@@ -35,3 +35,3 @@ "use strict"; | ||
/* Print message */ | ||
msg = !color ? strip_ansi_1.default(msg) : msg; | ||
msg = !color ? (0, strip_ansi_1.default)(msg) : msg; | ||
if (!instanceIsCLI) | ||
@@ -38,0 +38,0 @@ console.log(msg); |
@@ -1,2 +0,5 @@ | ||
export declare type TSPOptions = typeof defaultOptions; | ||
export declare type TSPOptions = typeof defaultOptions & { | ||
/** @deprecated Use 'dir' */ | ||
basedir?: string; | ||
}; | ||
export declare const defaultOptions: { | ||
@@ -7,3 +10,3 @@ logLevel: number; | ||
verbose: boolean; | ||
basedir: string; | ||
dir: string; | ||
instanceIsCLI: boolean; | ||
@@ -17,3 +20,3 @@ }; | ||
verbose: boolean; | ||
basedir: string; | ||
dir: string; | ||
instanceIsCLI: boolean; | ||
@@ -24,24 +27,3 @@ }; | ||
*/ | ||
export declare const parseOptions: (options?: Partial<{ | ||
logLevel: number; | ||
color: boolean; | ||
silent: boolean; | ||
verbose: boolean; | ||
basedir: string; | ||
instanceIsCLI: boolean; | ||
}> | undefined) => TSPOptions; | ||
export declare const resetOptions: (options?: Partial<{ | ||
logLevel: number; | ||
color: boolean; | ||
silent: boolean; | ||
verbose: boolean; | ||
basedir: string; | ||
instanceIsCLI: boolean; | ||
}> | undefined) => { | ||
logLevel: number; | ||
color: boolean; | ||
silent: boolean; | ||
verbose: boolean; | ||
basedir: string; | ||
instanceIsCLI: boolean; | ||
}; | ||
export declare const parseOptions: (options?: Partial<TSPOptions> | undefined) => TSPOptions; | ||
export declare const resetOptions: (options?: Partial<TSPOptions> | undefined) => TSPOptions; |
@@ -13,6 +13,10 @@ "use strict"; | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from) { | ||
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) | ||
to[j] = from[i]; | ||
return to; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
@@ -30,3 +34,3 @@ Object.defineProperty(exports, "__esModule", { value: true }); | ||
verbose: false, | ||
basedir: process.cwd(), | ||
dir: process.cwd(), | ||
instanceIsCLI: false | ||
@@ -48,7 +52,13 @@ }; | ||
exports.appOptions.color = options['color']; | ||
if (has('global') && has('basedir')) | ||
throw new errors_1.OptionsError("Cannot specify both --global and --basedir"); | ||
if (has('basedir')) { | ||
console.warn("--basedir is deprecated and will be removed in the future. Use --dir instead."); | ||
options.dir = options.dir || options.basedir; | ||
} | ||
if (has('persist')) | ||
console.warn("--persist has been removed. Please use prepare script instead!"); | ||
if (has('global') && has('dir')) | ||
throw new errors_1.OptionsError("Cannot specify both --global and --dir"); | ||
if (has('global')) | ||
options.basedir = file_utils_1.getGlobalTSDir(); | ||
Object.assign(exports.appOptions, helpers_1.pick.apply(void 0, __spreadArray([options], helpers_1.getKeys(exports.defaultOptions)))); | ||
options.dir = (0, file_utils_1.getGlobalTSDir)(); | ||
Object.assign(exports.appOptions, helpers_1.pick.apply(void 0, __spreadArray([options], (0, helpers_1.getKeys)(exports.defaultOptions), false))); | ||
exports.appOptions.logLevel = | ||
@@ -62,4 +72,4 @@ (exports.appOptions.silent) ? logger_1.Log.system : | ||
exports.parseOptions = parseOptions; | ||
var resetOptions = function (options) { return exports.parseOptions(__assign(__assign({}, exports.defaultOptions), options)); }; | ||
var resetOptions = function (options) { return (0, exports.parseOptions)(__assign(__assign({}, exports.defaultOptions), options)); }; | ||
exports.resetOptions = resetOptions; | ||
//# sourceMappingURL=options.js.map |
{ | ||
"name": "ts-patch", | ||
"version": "1.4.5", | ||
"version": "2.0.0", | ||
"description": "Patch typescript to support custom transformers in tsconfig.json", | ||
@@ -30,8 +30,8 @@ "main": "./index.js", | ||
"chalk": "^4.1.0", | ||
"glob": "^7.1.7", | ||
"global-prefix": "^3.0.0", | ||
"minimist": "^1.2.5", | ||
"resolve": "^1.20.0", | ||
"shelljs": "^0.8.4", | ||
"strip-ansi": "^6.0.0", | ||
"glob": "^7.1.7", | ||
"resolve": "^1.20.0" | ||
"strip-ansi": "^6.0.0" | ||
}, | ||
@@ -42,3 +42,3 @@ "bin": { | ||
"peerDependencies": { | ||
"typescript": ">2.7.0" | ||
"typescript": ">=4.0.0" | ||
}, | ||
@@ -45,0 +45,0 @@ "directories": { |
@@ -1,3 +0,2 @@ | ||
import { Bundle, CompilerHost, CompilerOptions, CustomTransformers, Diagnostic, LanguageService, Program, SourceFile, TransformationContext, Transformer, TransformerFactory, TypeChecker } from 'typescript'; | ||
import * as ts from 'typescript'; | ||
import type ts from 'typescript'; | ||
export interface PluginConfig { | ||
@@ -30,3 +29,3 @@ [x: string]: any; | ||
/** | ||
* Apply transformer on d.ts files TS2.9+ | ||
* Apply transformer on d.ts files | ||
*/ | ||
@@ -45,10 +44,11 @@ afterDeclarations?: boolean; | ||
} | ||
export declare type TransformerList = Required<CustomTransformers>; | ||
export declare type TransformerPlugin = TransformerBasePlugin | TransformerFactory<SourceFile>; | ||
export declare type TransformerList = Required<ts.CustomTransformers>; | ||
export declare type TransformerPlugin = TransformerBasePlugin | ts.TransformerFactory<ts.SourceFile>; | ||
export declare type PluginFactory = LSPattern | ProgramPattern | ConfigPattern | CompilerOptionsPattern | TypeCheckerPattern | RawPattern; | ||
export interface TransformerBasePlugin { | ||
before?: TransformerFactory<SourceFile>; | ||
after?: TransformerFactory<SourceFile>; | ||
afterDeclarations?: TransformerFactory<SourceFile | Bundle>; | ||
before?: ts.TransformerFactory<ts.SourceFile>; | ||
after?: ts.TransformerFactory<ts.SourceFile>; | ||
afterDeclarations?: ts.TransformerFactory<ts.SourceFile | ts.Bundle>; | ||
} | ||
export declare type DiagnosticMap = WeakMap<ts.Program, ts.Diagnostic[]>; | ||
export declare type TransformerExtras = { | ||
@@ -63,5 +63,5 @@ /** | ||
library: string; | ||
addDiagnostic: (diag: Diagnostic) => number; | ||
addDiagnostic: (diag: ts.Diagnostic) => number; | ||
removeDiagnostic: (index: number) => void; | ||
diagnostics: readonly Diagnostic[]; | ||
diagnostics: readonly ts.Diagnostic[]; | ||
}; | ||
@@ -74,8 +74,8 @@ export declare type ProgramTransformerExtras = { | ||
}; | ||
export declare type ProgramTransformer = (program: Program, host: CompilerHost | undefined, config: PluginConfig, extras: ProgramTransformerExtras) => Program; | ||
export declare type LSPattern = (ls: LanguageService, config: {}) => TransformerPlugin; | ||
export declare type CompilerOptionsPattern = (compilerOpts: CompilerOptions, config: {}) => TransformerPlugin; | ||
export declare type ProgramTransformer = (program: ts.Program, host: ts.CompilerHost | undefined, config: PluginConfig, extras: ProgramTransformerExtras) => ts.Program; | ||
export declare type LSPattern = (ls: ts.LanguageService, config: {}) => TransformerPlugin; | ||
export declare type CompilerOptionsPattern = (compilerOpts: ts.CompilerOptions, config: {}) => TransformerPlugin; | ||
export declare type ConfigPattern = (config: {}) => TransformerPlugin; | ||
export declare type TypeCheckerPattern = (checker: TypeChecker, config: {}) => TransformerPlugin; | ||
export declare type ProgramPattern = (program: Program, config: {}, extras: TransformerExtras) => TransformerPlugin; | ||
export declare type RawPattern = (context: TransformationContext, program: Program, config: {}) => Transformer<SourceFile>; | ||
export declare type TypeCheckerPattern = (checker: ts.TypeChecker, config: {}) => TransformerPlugin; | ||
export declare type ProgramPattern = (program: ts.Program, config: {}, extras: TransformerExtras) => TransformerPlugin; | ||
export declare type RawPattern = (context: ts.TransformationContext, program: ts.Program, config: {}) => ts.Transformer<ts.SourceFile>; |
[![npm version](https://badge.fury.io/js/ts-patch.svg)](https://badge.fury.io/js/ts-patch) | ||
[![NPM Downloads](https://img.shields.io/npm/dm/ts-patch.svg?style=flat)](https://npmjs.org/package/ts-patch) | ||
![Build Status](https://github.com/nonara/ts-patch/workflows/Build%20(CI)/badge.svg) | ||
[![Coverage Status](https://coveralls.io/repos/github/nonara/ts-patch/badge.svg?branch=master)](https://coveralls.io/github/nonara/ts-patch?branch=master) | ||
![Build Status](https://github.com/nonara/ts-patch/workflows/Build/badge.svg) | ||
@@ -11,6 +10,6 @@ # TS Patch | ||
- Plugins are specified in `tsconfig.json`, or provided programmatically in `CompilerOptions`. | ||
- Based on [ttypescript](https://github.com/cevek/ttypescript) - 100% compatibility in configuration & transformers. | ||
- Based on [ttypescript](https://github.com/cevek/ttypescript) - Fully compatible + offers more features | ||
## Features | ||
* Patch / unpatch any version of typescript (2.7+) | ||
* Patch / unpatch any version of typescript (4.0+) | ||
* Advanced options for patching individual libraries, specific locations, etc. (see `ts-patch /?`) | ||
@@ -29,7 +28,7 @@ * _(New)_ Supports 'transforming' the `Program` instance during creation. (see: [Transforming Program](#transforming-program)) | ||
```shell | ||
# For advanced options, see: ts-patch /? | ||
ts-patch install | ||
# For advanced options, see: ts-patch /? | ||
``` | ||
3. Add `prepare` script (keeps patch persisted after npm installations) | ||
3. Add `prepare` script (keeps patch persisted after npm install) | ||
@@ -46,3 +45,3 @@ `package.json` | ||
## V2 Coming Soon... | ||
## Rewrite Coming Soon... | ||
@@ -52,7 +51,8 @@ With a couple years of hindsight, it's time for a much needed redesign to make a more complete plugin ecosystem! The new | ||
The development of v2 is already underway! To follow that progress, see [this discussion](https://github.com/nonara/ts-patch/discussions/40). | ||
Development is already underway, but my time to work on it is limited! To follow progress, see [this discussion](https://github.com/nonara/ts-patch/discussions/40). | ||
That said — | ||
- The new v2 will still support all legacy packages and config | ||
- v1 will be maintained and patched for any issues, having an end of life no earlier than 2023. | ||
Notes — | ||
- The new version will be a major release | ||
- It will still support all legacy packages and config | ||
- Previous major version will be maintained and patched for any issues for at least one year | ||
@@ -87,21 +87,21 @@ ## Table of Contents | ||
"plugins": [ | ||
// Source Transformer -> 'type' defaults to 'program' | ||
// Source Transformer: 'type' defaults to 'program' | ||
{ "transform": "transformer-module", "someOption1": 123, "someOption2": 321 }, | ||
// Source Transformer -> program signature | ||
// Source Transformer: program signature | ||
{ "transform": "./transformers/my-transformer.ts", "type": "program" }, | ||
// Source Transformer -> program signature, applies after TS transformers | ||
// Source Transformer: program signature, applies after TS transformers | ||
{ "transform": "transformer-module1", "type": "config", "after": true }, | ||
// Source Transformer -> checker signature, applies to TS declarations | ||
// Source Transformer: checker signature, applies to TS declarations | ||
{ "transform": "transformer-module2", "type": "checker", "afterDeclarations": true }, | ||
// Source Transformer -> raw signature | ||
// Source Transformer: raw signature | ||
{ "transform": "transformer-module3", "type": "raw" }, | ||
// Source Transformer -> compilerOptions signature | ||
// Source Transformer: compilerOptions signature | ||
{ "transform": "transformer-module4", "type": "compilerOptions" }, | ||
// Program Transformer -> Only has one signature - notice no type specified, because it does not apply | ||
// Program Transformer: Only has one signature - no type specified, because it does not apply | ||
{ "transform": "transformer-module5", "transformProgram": true } | ||
@@ -193,2 +193,4 @@ ] | ||
[`{ transform: "typescript-transform-paths" }`](https://github.com/LeDDGroup/typescript-transform-paths) | ||
[`{ transform: "typescript-is/lib/transform-inline/transformer" }`](https://github.com/woutervh-/typescript-is) | ||
@@ -206,4 +208,2 @@ | ||
[`{ transform: "typescript-transform-paths" }`](https://github.com/LeDDGroup/typescript-transform-paths) | ||
[`{ transform: "ts-transformer-minify-privates" }`](https://github.com/timocov/ts-transformer-minify-privates) | ||
@@ -213,5 +213,6 @@ | ||
There are some cases where a transformer isn't enough. Several examples are if you want to: | ||
Sometimes you want to do more than just transform source code. For example you may want to: | ||
- TypeCheck code after it's been transformed | ||
- Generate code and add it to the program | ||
- Add or remove emit files during transformation | ||
@@ -277,3 +278,3 @@ | ||
| -------- |----------- | | ||
| diagnostics | Reference to `Diagnostic[]` created during `ts.emitFilesAndReportErrors()` (works with tsc also) | ||
| diagnostics | Reference to `Diagnostic` array | ||
| addDiagnostic() | Directly add `Diagnostic` to `diagnostics` array | | ||
@@ -283,7 +284,4 @@ | removeDiagnostic() | Directly remove `Diagnostic` from `diagnostics` array (uses splice, for safe removal) | ||
#### Notes | ||
- This alters diagnostics during _emit only_. If you want to alter diagnostics in your IDE, create a LanguageService plugin | ||
- If an emit method other than `ts.emitFilesAndReportErrors()` is used, any diagnostics added via `addDiagnostic()` | ||
will still be merged into the result of `program.emit() -> diagnostics` | ||
- This alters diagnostics during _emit only_. If you want to alter diagnostics in your IDE as well, you'll need to create a LanguageService plugin to accompany your source transformer | ||
## Resources | ||
@@ -302,3 +300,3 @@ | ||
| ---- | ---- | ----------- | | ||
| [TS AST Viewer](https://ts-ast-viewer.com/) | Website | Allows you to see the `Node` structure of any TS/JS source, including Flags, `Type`, and `Symbol`. This is the go-to tool for all things TypeScript AST. | ||
| [TS AST Viewer](https://ts-ast-viewer.com/) | Website | Allows you to see the `Node` structure and other TS properties of your source code. | ||
| [ts-query](https://www.npmjs.com/package/@phenomnomnominal/tsquery) | NPM Package | Perform fast CSS-like queries on AST to find specific nodes (by attribute, kind, name, etc) | ||
@@ -323,2 +321,2 @@ | [ts-query Playground](https://tsquery-playground.firebaseapp.com/) | Website | Test `ts-query` in realtime | ||
This project is licensed under the MIT License | ||
This project is licensed under the MIT License, as described in `LICENSE.md` |
declare namespace ts { | ||
const diagnosticMap$1: WeakMap<ts.Program, ts.Diagnostic[]>; | ||
interface PluginConfig { | ||
[x: string]: any; | ||
/** | ||
* Language Server TypeScript Plugin name | ||
*/ | ||
name?: string; | ||
/** | ||
* Path to transformer or transformer module name | ||
*/ | ||
transform?: string; | ||
/** | ||
* tsconfig.json file (for transformer) | ||
*/ | ||
tsConfig?: string; | ||
/** | ||
* The optional name of the exported transform plugin in the transform module. | ||
*/ | ||
import?: string; | ||
/** | ||
* Plugin entry point format type, default is program | ||
*/ | ||
type?: 'ls' | 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions'; | ||
/** | ||
* Apply transformer after internal TypeScript transformers | ||
*/ | ||
after?: boolean; | ||
/** | ||
* Apply transformer on d.ts files TS2.9+ | ||
*/ | ||
afterDeclarations?: boolean; | ||
/** | ||
* Transform *Program* instance (alters during createProgram()) (`type`, `after`, & `afterDeclarations` settings will | ||
* not apply) Entry point must be (program: Program, host?: CompilerHost) => Program | ||
*/ | ||
transformProgram?: boolean; | ||
/** | ||
* Alias to transformProgram | ||
* @deprecated | ||
*/ | ||
beforeEmit?: boolean; | ||
interface PluginConfig { | ||
[x: string]: any; | ||
name?: string; | ||
transform?: string; | ||
tsConfig?: string; | ||
import?: string; | ||
type?: 'ls' | 'program' | 'config' | 'checker' | 'raw' | 'compilerOptions'; | ||
after?: boolean; | ||
afterDeclarations?: boolean; | ||
transformProgram?: boolean; | ||
beforeEmit?: boolean; | ||
} | ||
type TransformerList = Required<ts.CustomTransformers>; | ||
type TransformerPlugin = TransformerBasePlugin | ts.TransformerFactory<ts.SourceFile>; | ||
type PluginFactory = LSPattern | ProgramPattern | ConfigPattern | CompilerOptionsPattern | TypeCheckerPattern | RawPattern; | ||
interface TransformerBasePlugin { | ||
before?: ts.TransformerFactory<ts.SourceFile>; | ||
after?: ts.TransformerFactory<ts.SourceFile>; | ||
afterDeclarations?: ts.TransformerFactory<ts.SourceFile | ts.Bundle>; | ||
} | ||
type DiagnosticMap = WeakMap<ts.Program, ts.Diagnostic[]>; | ||
type TransformerExtras = { | ||
ts: typeof ts; | ||
library: string; | ||
addDiagnostic: (diag: ts.Diagnostic) => number; | ||
removeDiagnostic: (index: number) => void; | ||
diagnostics: readonly ts.Diagnostic[]; | ||
}; | ||
type ProgramTransformerExtras = { | ||
ts: typeof ts; | ||
}; | ||
type ProgramTransformer = (program: ts.Program, host: ts.CompilerHost | undefined, config: PluginConfig, extras: ProgramTransformerExtras) => ts.Program; | ||
type LSPattern = (ls: ts.LanguageService, config: {}) => TransformerPlugin; | ||
type CompilerOptionsPattern = (compilerOpts: ts.CompilerOptions, config: {}) => TransformerPlugin; | ||
type ConfigPattern = (config: {}) => TransformerPlugin; | ||
type TypeCheckerPattern = (checker: ts.TypeChecker, config: {}) => TransformerPlugin; | ||
type ProgramPattern = (program: ts.Program, config: {}, extras: TransformerExtras) => TransformerPlugin; | ||
type RawPattern = (context: ts.TransformationContext, program: ts.Program, config: {}) => ts.Transformer<ts.SourceFile>; | ||
} | ||
type TransformerList = Required<CustomTransformers>; | ||
type TransformerPlugin = TransformerBasePlugin | TransformerFactory<SourceFile>; | ||
type PluginFactory = LSPattern | ProgramPattern | ConfigPattern | CompilerOptionsPattern | TypeCheckerPattern | RawPattern; | ||
interface TransformerBasePlugin { | ||
before?: TransformerFactory<SourceFile>; | ||
after?: TransformerFactory<SourceFile>; | ||
afterDeclarations?: TransformerFactory<SourceFile | Bundle>; | ||
declare namespace ts { | ||
const tspVersion: string; | ||
const originalCreateProgram: typeof ts.createProgram; | ||
const diagnosticMap: WeakMap<ts.Program, ts.Diagnostic[]>; | ||
} | ||
type TransformerExtras = { | ||
/** | ||
* Originating TypeScript instance | ||
*/ | ||
ts: typeof ts; | ||
/** | ||
* TypeScript library file event was triggered in (ie. 'tsserverlibrary' or 'typescript') | ||
*/ | ||
library: string; | ||
addDiagnostic: (diag: Diagnostic) => number; | ||
removeDiagnostic: (index: number) => void; | ||
diagnostics: readonly Diagnostic[]; | ||
}; | ||
type ProgramTransformerExtras = { | ||
/** | ||
* Originating TypeScript instance | ||
*/ | ||
ts: typeof ts; | ||
}; | ||
type ProgramTransformer = (program: Program, host: CompilerHost | undefined, config: PluginConfig, extras: ProgramTransformerExtras) => Program; | ||
type LSPattern = (ls: LanguageService, config: {}) => TransformerPlugin; | ||
type CompilerOptionsPattern = (compilerOpts: CompilerOptions, config: {}) => TransformerPlugin; | ||
type ConfigPattern = (config: {}) => TransformerPlugin; | ||
type TypeCheckerPattern = (checker: TypeChecker, config: {}) => TransformerPlugin; | ||
type ProgramPattern = (program: Program, config: {}, extras: TransformerExtras) => TransformerPlugin; | ||
type RawPattern = (context: TransformationContext, program: Program, config: {}) => Transformer<SourceFile>; | ||
/** | ||
* @example | ||
* | ||
* new PluginCreator([ | ||
* {transform: '@zerollup/ts-transform-paths', someOption: '123'}, | ||
* {transform: '@zerollup/ts-transform-paths', type: 'ls', someOption: '123'}, | ||
* {transform: '@zerollup/ts-transform-paths', type: 'ls', after: true, someOption: '123'} | ||
* ]).createTransformers({ program }) | ||
*/ | ||
class PluginCreator { | ||
private configs; | ||
private resolveBaseDir; | ||
currentProject?: string; | ||
constructor(configs: PluginConfig[], resolveBaseDir?: string); | ||
mergeTransformers(into: TransformerList, source: CustomTransformers | TransformerBasePlugin): this; | ||
createTransformers(params: { | ||
program: Program; | ||
} | { | ||
ls: LanguageService; | ||
}, customTransformers?: CustomTransformers): TransformerList; | ||
getProgramTransformers(): [ProgramTransformer, PluginConfig][]; | ||
private resolveFactory; | ||
static validateConfigs(configs: PluginConfig[]): void; | ||
static createTransformerFromPattern({ factory, config, program, ls }: { | ||
factory: PluginFactory; | ||
config: PluginConfig; | ||
program: Program; | ||
ls?: LanguageService; | ||
}): TransformerBasePlugin; | ||
} | ||
const tspVersion: string; | ||
const originalCreateProgram: typeof createProgram; | ||
const diagnosticMap: typeof diagnosticMap$1; | ||
} |
@@ -1,1204 +0,245 @@ | ||
(function () { | ||
'use strict'; | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
var __assign = function() { | ||
__assign = Object.assign || function __assign(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
"use strict"; | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function (t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) | ||
if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
function __rest(s, e) { | ||
var t = {}; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) | ||
t[p] = s[p]; | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") | ||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) | ||
t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
return __assign.apply(this, arguments); | ||
}; | ||
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); | ||
} | ||
function __values(o) { | ||
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; | ||
if (m) return m.call(o); | ||
if (o && typeof o.length === "number") return { | ||
next: function () { | ||
if (o && i >= o.length) o = void 0; | ||
return { value: o && o[i++], done: !o }; | ||
} | ||
}; | ||
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); | ||
catch (error) { | ||
e = { error: error }; | ||
} | ||
function __read(o, n) { | ||
var m = typeof Symbol === "function" && o[Symbol.iterator]; | ||
if (!m) return o; | ||
var i = m.call(o), r, ar = [], e; | ||
finally { | ||
try { | ||
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); | ||
if (r && !r.done && (m = i["return"])) | ||
m.call(i); | ||
} | ||
catch (error) { e = { error: error }; } | ||
finally { | ||
try { | ||
if (r && !r.done && (m = i["return"])) m.call(i); | ||
} | ||
finally { if (e) throw e.error; } | ||
if (e) | ||
throw e.error; | ||
} | ||
return ar; | ||
} | ||
function __spreadArray(to, from) { | ||
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) | ||
to[j] = from[i]; | ||
return to; | ||
} | ||
/* ****************************************************************************************************************** */ | ||
// region: Constants | ||
/* ****************************************************************************************************************** */ | ||
var diagnosticMap = new WeakMap(); | ||
// endregion | ||
/* ******************************************************************************************************************** | ||
* Helpers | ||
* ********************************************************************************************************************/ | ||
function diagnosticExtrasFactory(program) { | ||
var diagnostics = diagnosticMap.get(program) || diagnosticMap.set(program, []).get(program); | ||
var addDiagnostic = function (diag) { return diagnostics.push(diag); }; | ||
var removeDiagnostic = function (index) { diagnostics.splice(index, 1); }; | ||
return { addDiagnostic: addDiagnostic, removeDiagnostic: removeDiagnostic, diagnostics: diagnostics }; | ||
} | ||
var getCurrentLibrary = function () { return require('path').basename(__filename, require('path').extname(__filename)); }; | ||
var fs$1 = require('fs'); | ||
var _rollupPluginShim1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
'default': fs$1 | ||
}); | ||
var path$1 = require('path'); | ||
var _rollupPluginShim2 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
'default': path$1 | ||
}); | ||
var caller = function () { | ||
// see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi | ||
var origPrepareStackTrace = Error.prepareStackTrace; | ||
Error.prepareStackTrace = function (_, stack) { return stack; }; | ||
var stack = (new Error()).stack; | ||
Error.prepareStackTrace = origPrepareStackTrace; | ||
return stack[2].getFileName(); | ||
}; | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
function getCjsExportFromNamespace (n) { | ||
return n && n['default'] || n; | ||
} | ||
var pathParse = createCommonjsModule(function (module) { | ||
var isWindows = process.platform === 'win32'; | ||
// Regex to split a windows path into into [dir, root, basename, name, ext] | ||
var splitWindowsRe = | ||
/^(((?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?[\\\/]?)(?:[^\\\/]*[\\\/])*)((\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))[\\\/]*$/; | ||
var win32 = {}; | ||
function win32SplitPath(filename) { | ||
return splitWindowsRe.exec(filename).slice(1); | ||
} | ||
win32.parse = function(pathString) { | ||
if (typeof pathString !== 'string') { | ||
throw new TypeError( | ||
"Parameter 'pathString' must be a string, not " + typeof pathString | ||
); | ||
} | ||
var allParts = win32SplitPath(pathString); | ||
if (!allParts || allParts.length !== 5) { | ||
throw new TypeError("Invalid path '" + pathString + "'"); | ||
} | ||
return { | ||
root: allParts[1], | ||
dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1), | ||
base: allParts[2], | ||
ext: allParts[4], | ||
name: allParts[3] | ||
}; | ||
}; | ||
// Split a filename into [dir, root, basename, name, ext], unix version | ||
// 'root' is just a slash, or nothing. | ||
var splitPathRe = | ||
/^((\/?)(?:[^\/]*\/)*)((\.{1,2}|[^\/]+?|)(\.[^.\/]*|))[\/]*$/; | ||
var posix = {}; | ||
function posixSplitPath(filename) { | ||
return splitPathRe.exec(filename).slice(1); | ||
} | ||
posix.parse = function(pathString) { | ||
if (typeof pathString !== 'string') { | ||
throw new TypeError( | ||
"Parameter 'pathString' must be a string, not " + typeof pathString | ||
); | ||
} | ||
var allParts = posixSplitPath(pathString); | ||
if (!allParts || allParts.length !== 5) { | ||
throw new TypeError("Invalid path '" + pathString + "'"); | ||
} | ||
return { | ||
root: allParts[1], | ||
dir: allParts[0].slice(0, -1), | ||
base: allParts[2], | ||
ext: allParts[4], | ||
name: allParts[3], | ||
}; | ||
}; | ||
if (isWindows) | ||
module.exports = win32.parse; | ||
else /* posix */ | ||
module.exports = posix.parse; | ||
module.exports.posix = posix.parse; | ||
module.exports.win32 = win32.parse; | ||
}); | ||
pathParse.posix; | ||
pathParse.win32; | ||
var path = getCjsExportFromNamespace(_rollupPluginShim2); | ||
var parse = path.parse || pathParse; | ||
var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { | ||
var prefix = '/'; | ||
if ((/^([A-Za-z]:)/).test(absoluteStart)) { | ||
prefix = ''; | ||
} else if ((/^\\\\/).test(absoluteStart)) { | ||
prefix = '\\\\'; | ||
return ar; | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) | ||
for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) | ||
ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
} | ||
var paths = [absoluteStart]; | ||
var parsed = parse(absoluteStart); | ||
while (parsed.dir !== paths[paths.length - 1]) { | ||
paths.push(parsed.dir); | ||
parsed = parse(parsed.dir); | ||
} | ||
return paths.reduce(function (dirs, aPath) { | ||
return dirs.concat(modules.map(function (moduleDir) { | ||
return path.resolve(prefix, aPath, moduleDir); | ||
})); | ||
}, []); | ||
}; | ||
var nodeModulesPaths = function nodeModulesPaths(start, opts, request) { | ||
var modules = opts && opts.moduleDirectory | ||
? [].concat(opts.moduleDirectory) | ||
: ['node_modules']; | ||
if (opts && typeof opts.paths === 'function') { | ||
return opts.paths( | ||
request, | ||
start, | ||
function () { return getNodeModulesDirs(start, modules); }, | ||
opts | ||
); | ||
} | ||
var dirs = getNodeModulesDirs(start, modules); | ||
return opts && opts.paths ? dirs.concat(opts.paths) : dirs; | ||
}; | ||
var normalizeOptions = function (x, opts) { | ||
/** | ||
* This file is purposefully a passthrough. It's expected that third-party | ||
* environments will override it at runtime in order to inject special logic | ||
* into `resolve` (by manipulating the options). One such example is the PnP | ||
* code path in Yarn. | ||
*/ | ||
return opts || {}; | ||
}; | ||
/* eslint no-invalid-this: 1 */ | ||
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; | ||
var slice = Array.prototype.slice; | ||
var toStr = Object.prototype.toString; | ||
var funcType = '[object Function]'; | ||
var implementation = function bind(that) { | ||
var target = this; | ||
if (typeof target !== 'function' || toStr.call(target) !== funcType) { | ||
throw new TypeError(ERROR_MESSAGE + target); | ||
} | ||
var args = slice.call(arguments, 1); | ||
var bound; | ||
var binder = function () { | ||
if (this instanceof bound) { | ||
var result = target.apply( | ||
this, | ||
args.concat(slice.call(arguments)) | ||
); | ||
if (Object(result) === result) { | ||
return result; | ||
} | ||
return this; | ||
} else { | ||
return target.apply( | ||
that, | ||
args.concat(slice.call(arguments)) | ||
); | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
var __values = (this && this.__values) || function (o) { | ||
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; | ||
if (m) | ||
return m.call(o); | ||
if (o && typeof o.length === "number") | ||
return { | ||
next: function () { | ||
if (o && i >= o.length) | ||
o = void 0; | ||
return { value: o && o[i++], done: !o }; | ||
} | ||
}; | ||
var boundLength = Math.max(0, target.length - args.length); | ||
var boundArgs = []; | ||
for (var i = 0; i < boundLength; i++) { | ||
boundArgs.push('$' + i); | ||
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); | ||
}; | ||
var __rest = (this && this.__rest) || function (s, e) { | ||
var t = {}; | ||
for (var p in s) | ||
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) | ||
t[p] = s[p]; | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") | ||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) | ||
t[p[i]] = s[p[i]]; | ||
} | ||
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); | ||
if (target.prototype) { | ||
var Empty = function Empty() {}; | ||
Empty.prototype = target.prototype; | ||
bound.prototype = new Empty(); | ||
Empty.prototype = null; | ||
return t; | ||
}; | ||
var tsp; | ||
(function (tsp) { | ||
var activeProgramTransformers = new Set(); | ||
var dirname = require("path").dirname; | ||
function getProjectDir(compilerOptions) { | ||
return compilerOptions.configFilePath && dirname(compilerOptions.configFilePath); | ||
} | ||
function getProjectConfig(compilerOptions, rootFileNames) { | ||
var configFilePath = compilerOptions.configFilePath; | ||
var projectDir = getProjectDir(compilerOptions); | ||
if (configFilePath === undefined) { | ||
var baseDir = (rootFileNames.length > 0) ? dirname(rootFileNames[0]) : projectDir !== null && projectDir !== void 0 ? projectDir : process.cwd(); | ||
configFilePath = ts.findConfigFile(baseDir, ts.sys.fileExists); | ||
if (configFilePath) { | ||
var config = readConfig(configFilePath); | ||
compilerOptions = __assign(__assign({}, config.options), compilerOptions); | ||
projectDir = getProjectDir(compilerOptions); | ||
} | ||
} | ||
return bound; | ||
}; | ||
var functionBind = Function.prototype.bind || implementation; | ||
var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty); | ||
var core$3 = { | ||
assert: true, | ||
"assert/strict": ">= 15", | ||
async_hooks: ">= 8", | ||
buffer_ieee754: "< 0.9.7", | ||
buffer: true, | ||
child_process: true, | ||
cluster: true, | ||
console: true, | ||
constants: true, | ||
crypto: true, | ||
_debug_agent: ">= 1 && < 8", | ||
_debugger: "< 8", | ||
dgram: true, | ||
diagnostics_channel: ">= 15.1", | ||
dns: true, | ||
"dns/promises": ">= 15", | ||
domain: ">= 0.7.12", | ||
events: true, | ||
freelist: "< 6", | ||
fs: true, | ||
"fs/promises": [ | ||
">= 10 && < 10.1", | ||
">= 14" | ||
], | ||
_http_agent: ">= 0.11.1", | ||
_http_client: ">= 0.11.1", | ||
_http_common: ">= 0.11.1", | ||
_http_incoming: ">= 0.11.1", | ||
_http_outgoing: ">= 0.11.1", | ||
_http_server: ">= 0.11.1", | ||
http: true, | ||
http2: ">= 8.8", | ||
https: true, | ||
inspector: ">= 8.0.0", | ||
_linklist: "< 8", | ||
module: true, | ||
net: true, | ||
"node-inspect/lib/_inspect": ">= 7.6.0 && < 12", | ||
"node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", | ||
"node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", | ||
os: true, | ||
path: true, | ||
"path/posix": ">= 15.3", | ||
"path/win32": ">= 15.3", | ||
perf_hooks: ">= 8.5", | ||
process: ">= 1", | ||
punycode: true, | ||
querystring: true, | ||
readline: true, | ||
repl: true, | ||
smalloc: ">= 0.11.5 && < 3", | ||
_stream_duplex: ">= 0.9.4", | ||
_stream_transform: ">= 0.9.4", | ||
_stream_wrap: ">= 1.4.1", | ||
_stream_passthrough: ">= 0.9.4", | ||
_stream_readable: ">= 0.9.4", | ||
_stream_writable: ">= 0.9.4", | ||
stream: true, | ||
"stream/promises": ">= 15", | ||
string_decoder: true, | ||
sys: [ | ||
">= 0.6 && < 0.7", | ||
">= 0.8" | ||
], | ||
timers: true, | ||
"timers/promises": ">= 15", | ||
_tls_common: ">= 0.11.13", | ||
_tls_legacy: ">= 0.11.3 && < 10", | ||
_tls_wrap: ">= 0.11.3", | ||
tls: true, | ||
trace_events: ">= 10", | ||
tty: true, | ||
url: true, | ||
util: true, | ||
"util/types": ">= 15.3", | ||
"v8/tools/arguments": ">= 10 && < 12", | ||
"v8/tools/codemap": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/consarray": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/csvparser": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/logreader": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/profile_view": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/splaytree": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
v8: ">= 1", | ||
vm: true, | ||
wasi: ">= 13.4 && < 13.5", | ||
worker_threads: ">= 11.7", | ||
zlib: true | ||
}; | ||
var core$4 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
'default': core$3 | ||
}); | ||
var data$1 = getCjsExportFromNamespace(core$4); | ||
function specifierIncluded$1(current, specifier) { | ||
var nodeParts = current.split('.'); | ||
var parts = specifier.split(' '); | ||
var op = parts.length > 1 ? parts[0] : '='; | ||
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); | ||
for (var i = 0; i < 3; ++i) { | ||
var cur = parseInt(nodeParts[i] || 0, 10); | ||
var ver = parseInt(versionParts[i] || 0, 10); | ||
if (cur === ver) { | ||
continue; // eslint-disable-line no-restricted-syntax, no-continue | ||
} | ||
if (op === '<') { | ||
return cur < ver; | ||
} | ||
if (op === '>=') { | ||
return cur >= ver; | ||
} | ||
return false; | ||
} | ||
return op === '>='; | ||
return ({ projectDir: projectDir, compilerOptions: compilerOptions }); | ||
} | ||
function matchesRange$1(current, range) { | ||
var specifiers = range.split(/ ?&& ?/); | ||
if (specifiers.length === 0) { | ||
return false; | ||
} | ||
for (var i = 0; i < specifiers.length; ++i) { | ||
if (!specifierIncluded$1(current, specifiers[i])) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
function readConfig(configFileNamePath) { | ||
var projectDir = dirname(configFileNamePath); | ||
var result = ts.readConfigFile(configFileNamePath, ts.sys.readFile); | ||
if (result.error) | ||
throw new Error("Error in tsconfig.json: " + result.error.messageText); | ||
return ts.parseJsonConfigFileContent(result.config, ts.sys, projectDir, undefined, configFileNamePath); | ||
} | ||
function versionIncluded$1(nodeVersion, specifierValue) { | ||
if (typeof specifierValue === 'boolean') { | ||
return specifierValue; | ||
} | ||
var current = typeof nodeVersion === 'undefined' | ||
? process.versions && process.versions.node && process.versions.node | ||
: nodeVersion; | ||
if (typeof current !== 'string') { | ||
throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); | ||
} | ||
if (specifierValue && typeof specifierValue === 'object') { | ||
for (var i = 0; i < specifierValue.length; ++i) { | ||
if (matchesRange$1(current, specifierValue[i])) { | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
return matchesRange$1(current, specifierValue); | ||
function preparePluginsFromCompilerOptions(plugins) { | ||
if (!plugins) | ||
return []; | ||
if ((plugins.length === 1) && plugins[0].customTransformers) { | ||
var _a = plugins[0].customTransformers, _b = _a.before, before = _b === void 0 ? [] : _b, _c = _a.after, after = _c === void 0 ? [] : _c; | ||
return __spreadArray(__spreadArray([], __read(before.map(function (item) { return ({ transform: item }); })), false), __read(after.map(function (item) { return ({ transform: item, after: true }); })), false); | ||
} | ||
return plugins; | ||
} | ||
var isCoreModule = function isCore(x, nodeVersion) { | ||
return src(data$1, x) && versionIncluded$1(nodeVersion, data$1[x]); | ||
}; | ||
var fs = getCjsExportFromNamespace(_rollupPluginShim1); | ||
var realpathFS$1 = fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath; | ||
var defaultIsFile$1 = function isFile(file, cb) { | ||
fs.stat(file, function (err, stat) { | ||
if (!err) { | ||
return cb(null, stat.isFile() || stat.isFIFO()); | ||
} | ||
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); | ||
return cb(err); | ||
}); | ||
}; | ||
var defaultIsDir$1 = function isDirectory(dir, cb) { | ||
fs.stat(dir, function (err, stat) { | ||
if (!err) { | ||
return cb(null, stat.isDirectory()); | ||
} | ||
if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); | ||
return cb(err); | ||
}); | ||
}; | ||
var defaultRealpath = function realpath(x, cb) { | ||
realpathFS$1(x, function (realpathErr, realPath) { | ||
if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr); | ||
else cb(null, realpathErr ? x : realPath); | ||
}); | ||
}; | ||
var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { | ||
if (opts && opts.preserveSymlinks === false) { | ||
realpath(x, cb); | ||
} else { | ||
cb(null, x); | ||
function createProgram(rootNamesOrOptions, options, host, oldProgram, configFileParsingDiagnostics) { | ||
var e_1, _a, e_2, _b; | ||
var _c; | ||
var rootNames; | ||
var createOpts = !Array.isArray(rootNamesOrOptions) ? rootNamesOrOptions : void 0; | ||
if (createOpts) { | ||
rootNames = createOpts.rootNames; | ||
options = createOpts.options; | ||
host = createOpts.host; | ||
oldProgram = createOpts.oldProgram; | ||
configFileParsingDiagnostics = createOpts.configFileParsingDiagnostics; | ||
} | ||
}; | ||
var defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) { | ||
readFile(pkgfile, function (readFileErr, body) { | ||
if (readFileErr) cb(readFileErr); | ||
else { | ||
try { | ||
var pkg = JSON.parse(body); | ||
cb(null, pkg); | ||
} catch (jsonErr) { | ||
cb(null); | ||
} | ||
} | ||
}); | ||
}; | ||
var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) { | ||
var dirs = nodeModulesPaths(start, opts, x); | ||
for (var i = 0; i < dirs.length; i++) { | ||
dirs[i] = path.join(dirs[i], x); | ||
else { | ||
options = options; | ||
rootNames = rootNamesOrOptions; | ||
} | ||
return dirs; | ||
}; | ||
var async = function resolve(x, options, callback) { | ||
var cb = callback; | ||
var opts = options; | ||
if (typeof options === 'function') { | ||
cb = opts; | ||
opts = {}; | ||
var projectConfig = getProjectConfig(options, rootNames); | ||
if (tsp.isTSC) { | ||
options = projectConfig.compilerOptions; | ||
if (createOpts) | ||
createOpts.options = options; | ||
} | ||
if (typeof x !== 'string') { | ||
var err = new TypeError('Path must be a string.'); | ||
return process.nextTick(function () { | ||
cb(err); | ||
}); | ||
} | ||
opts = normalizeOptions(x, opts); | ||
var isFile = opts.isFile || defaultIsFile$1; | ||
var isDirectory = opts.isDirectory || defaultIsDir$1; | ||
var readFile = opts.readFile || fs.readFile; | ||
var realpath = opts.realpath || defaultRealpath; | ||
var readPackage = opts.readPackage || defaultReadPackage; | ||
if (opts.readFile && opts.readPackage) { | ||
var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.'); | ||
return process.nextTick(function () { | ||
cb(conflictErr); | ||
}); | ||
} | ||
var packageIterator = opts.packageIterator; | ||
var extensions = opts.extensions || ['.js']; | ||
var includeCoreModules = opts.includeCoreModules !== false; | ||
var basedir = opts.basedir || path.dirname(caller()); | ||
var parent = opts.filename || basedir; | ||
opts.paths = opts.paths || []; | ||
// ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory | ||
var absoluteStart = path.resolve(basedir); | ||
maybeRealpath( | ||
realpath, | ||
absoluteStart, | ||
opts, | ||
function (err, realStart) { | ||
if (err) cb(err); | ||
else init(realStart); | ||
var program = createOpts ? | ||
ts.originalCreateProgram(createOpts) : | ||
ts.originalCreateProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics); | ||
var plugins = preparePluginsFromCompilerOptions(options.plugins); | ||
var pluginCreator = new tsp.PluginCreator(plugins, (_c = projectConfig.projectDir) !== null && _c !== void 0 ? _c : process.cwd()); | ||
var programTransformers = new Map(pluginCreator.getProgramTransformers()); | ||
try { | ||
for (var _d = __values(pluginCreator.getProgramTransformers()), _e = _d.next(); !_e.done; _e = _d.next()) { | ||
var _f = __read(_e.value, 1), transformer = _f[0]; | ||
if (activeProgramTransformers.has(transformer)) | ||
programTransformers.delete(transformer); | ||
else | ||
activeProgramTransformers.add(transformer); | ||
} | ||
); | ||
var res; | ||
function init(basedir) { | ||
if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { | ||
res = path.resolve(basedir, x); | ||
if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; | ||
if ((/\/$/).test(x) && res === basedir) { | ||
loadAsDirectory(res, opts.package, onfile); | ||
} else loadAsFile(res, opts.package, onfile); | ||
} else if (includeCoreModules && isCoreModule(x)) { | ||
return cb(null, x); | ||
} else loadNodeModules(x, basedir, function (err, n, pkg) { | ||
if (err) cb(err); | ||
else if (n) { | ||
return maybeRealpath(realpath, n, opts, function (err, realN) { | ||
if (err) { | ||
cb(err); | ||
} else { | ||
cb(null, realN, pkg); | ||
} | ||
}); | ||
} else { | ||
var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
moduleError.code = 'MODULE_NOT_FOUND'; | ||
cb(moduleError); | ||
} | ||
}); | ||
} | ||
function onfile(err, m, pkg) { | ||
if (err) cb(err); | ||
else if (m) cb(null, m, pkg); | ||
else loadAsDirectory(res, function (err, d, pkg) { | ||
if (err) cb(err); | ||
else if (d) { | ||
maybeRealpath(realpath, d, opts, function (err, realD) { | ||
if (err) { | ||
cb(err); | ||
} else { | ||
cb(null, realD, pkg); | ||
} | ||
}); | ||
} else { | ||
var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
moduleError.code = 'MODULE_NOT_FOUND'; | ||
cb(moduleError); | ||
} | ||
}); | ||
catch (e_1_1) { | ||
e_1 = { error: e_1_1 }; | ||
} | ||
function loadAsFile(x, thePackage, callback) { | ||
var loadAsFilePackage = thePackage; | ||
var cb = callback; | ||
if (typeof loadAsFilePackage === 'function') { | ||
cb = loadAsFilePackage; | ||
loadAsFilePackage = undefined; | ||
finally { | ||
try { | ||
if (_e && !_e.done && (_a = _d.return)) | ||
_a.call(_d); | ||
} | ||
var exts = [''].concat(extensions); | ||
load(exts, x, loadAsFilePackage); | ||
function load(exts, x, loadPackage) { | ||
if (exts.length === 0) return cb(null, undefined, loadPackage); | ||
var file = x + exts[0]; | ||
var pkg = loadPackage; | ||
if (pkg) onpkg(null, pkg); | ||
else loadpkg(path.dirname(file), onpkg); | ||
function onpkg(err, pkg_, dir) { | ||
pkg = pkg_; | ||
if (err) return cb(err); | ||
if (dir && pkg && opts.pathFilter) { | ||
var rfile = path.relative(dir, file); | ||
var rel = rfile.slice(0, rfile.length - exts[0].length); | ||
var r = opts.pathFilter(pkg, x, rel); | ||
if (r) return load( | ||
[''].concat(extensions.slice()), | ||
path.resolve(dir, r), | ||
pkg | ||
); | ||
} | ||
isFile(file, onex); | ||
} | ||
function onex(err, ex) { | ||
if (err) return cb(err); | ||
if (ex) return cb(null, file, pkg); | ||
load(exts.slice(1), x, pkg); | ||
} | ||
finally { | ||
if (e_1) | ||
throw e_1.error; | ||
} | ||
} | ||
function loadpkg(dir, cb) { | ||
if (dir === '' || dir === '/') return cb(null); | ||
if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { | ||
return cb(null); | ||
try { | ||
for (var programTransformers_1 = __values(programTransformers), programTransformers_1_1 = programTransformers_1.next(); !programTransformers_1_1.done; programTransformers_1_1 = programTransformers_1.next()) { | ||
var _g = __read(programTransformers_1_1.value, 2), programTransformer = _g[0], config = _g[1]; | ||
var newProgram = programTransformer(program, host, config, { ts: ts }); | ||
if (typeof (newProgram === null || newProgram === void 0 ? void 0 : newProgram["emit"]) === "function") | ||
program = newProgram; | ||
} | ||
if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null); | ||
maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { | ||
if (unwrapErr) return loadpkg(path.dirname(dir), cb); | ||
var pkgfile = path.join(pkgdir, 'package.json'); | ||
isFile(pkgfile, function (err, ex) { | ||
// on err, ex is false | ||
if (!ex) return loadpkg(path.dirname(dir), cb); | ||
readPackage(readFile, pkgfile, function (err, pkgParam) { | ||
if (err) cb(err); | ||
var pkg = pkgParam; | ||
if (pkg && opts.packageFilter) { | ||
pkg = opts.packageFilter(pkg, pkgfile); | ||
} | ||
cb(null, pkg, dir); | ||
}); | ||
}); | ||
}); | ||
} | ||
function loadAsDirectory(x, loadAsDirectoryPackage, callback) { | ||
var cb = callback; | ||
var fpkg = loadAsDirectoryPackage; | ||
if (typeof fpkg === 'function') { | ||
cb = fpkg; | ||
fpkg = opts.package; | ||
} | ||
maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { | ||
if (unwrapErr) return cb(unwrapErr); | ||
var pkgfile = path.join(pkgdir, 'package.json'); | ||
isFile(pkgfile, function (err, ex) { | ||
if (err) return cb(err); | ||
if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb); | ||
readPackage(readFile, pkgfile, function (err, pkgParam) { | ||
if (err) return cb(err); | ||
var pkg = pkgParam; | ||
if (pkg && opts.packageFilter) { | ||
pkg = opts.packageFilter(pkg, pkgfile); | ||
} | ||
if (pkg && pkg.main) { | ||
if (typeof pkg.main !== 'string') { | ||
var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); | ||
mainError.code = 'INVALID_PACKAGE_MAIN'; | ||
return cb(mainError); | ||
} | ||
if (pkg.main === '.' || pkg.main === './') { | ||
pkg.main = 'index'; | ||
} | ||
loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) { | ||
if (err) return cb(err); | ||
if (m) return cb(null, m, pkg); | ||
if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb); | ||
var dir = path.resolve(x, pkg.main); | ||
loadAsDirectory(dir, pkg, function (err, n, pkg) { | ||
if (err) return cb(err); | ||
if (n) return cb(null, n, pkg); | ||
loadAsFile(path.join(x, 'index'), pkg, cb); | ||
}); | ||
}); | ||
return; | ||
} | ||
loadAsFile(path.join(x, '/index'), pkg, cb); | ||
}); | ||
}); | ||
}); | ||
catch (e_2_1) { | ||
e_2 = { error: e_2_1 }; | ||
} | ||
function processDirs(cb, dirs) { | ||
if (dirs.length === 0) return cb(null, undefined); | ||
var dir = dirs[0]; | ||
isDirectory(path.dirname(dir), isdir); | ||
function isdir(err, isdir) { | ||
if (err) return cb(err); | ||
if (!isdir) return processDirs(cb, dirs.slice(1)); | ||
loadAsFile(dir, opts.package, onfile); | ||
finally { | ||
try { | ||
if (programTransformers_1_1 && !programTransformers_1_1.done && (_b = programTransformers_1.return)) | ||
_b.call(programTransformers_1); | ||
} | ||
function onfile(err, m, pkg) { | ||
if (err) return cb(err); | ||
if (m) return cb(null, m, pkg); | ||
loadAsDirectory(dir, opts.package, ondir); | ||
finally { | ||
if (e_2) | ||
throw e_2.error; | ||
} | ||
function ondir(err, n, pkg) { | ||
if (err) return cb(err); | ||
if (n) return cb(null, n, pkg); | ||
processDirs(cb, dirs.slice(1)); | ||
} | ||
} | ||
function loadNodeModules(x, start, cb) { | ||
var thunk = function () { return getPackageCandidates$1(x, start, opts); }; | ||
processDirs( | ||
cb, | ||
packageIterator ? packageIterator(x, start, thunk, opts) : thunk() | ||
); | ||
programTransformers.forEach(function (c, transformer) { return activeProgramTransformers.delete(transformer); }); | ||
if (!program.originalEmit) { | ||
program.originalEmit = program.emit; | ||
program.emit = newEmit; | ||
} | ||
}; | ||
var core$1 = { | ||
assert: true, | ||
"assert/strict": ">= 15", | ||
async_hooks: ">= 8", | ||
buffer_ieee754: "< 0.9.7", | ||
buffer: true, | ||
child_process: true, | ||
cluster: true, | ||
console: true, | ||
constants: true, | ||
crypto: true, | ||
_debug_agent: ">= 1 && < 8", | ||
_debugger: "< 8", | ||
dgram: true, | ||
diagnostics_channel: ">= 15.1", | ||
dns: true, | ||
"dns/promises": ">= 15", | ||
domain: ">= 0.7.12", | ||
events: true, | ||
freelist: "< 6", | ||
fs: true, | ||
"fs/promises": [ | ||
">= 10 && < 10.1", | ||
">= 14" | ||
], | ||
_http_agent: ">= 0.11.1", | ||
_http_client: ">= 0.11.1", | ||
_http_common: ">= 0.11.1", | ||
_http_incoming: ">= 0.11.1", | ||
_http_outgoing: ">= 0.11.1", | ||
_http_server: ">= 0.11.1", | ||
http: true, | ||
http2: ">= 8.8", | ||
https: true, | ||
inspector: ">= 8.0.0", | ||
_linklist: "< 8", | ||
module: true, | ||
net: true, | ||
"node-inspect/lib/_inspect": ">= 7.6.0 && < 12", | ||
"node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", | ||
"node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", | ||
os: true, | ||
path: true, | ||
"path/posix": ">= 15.3", | ||
"path/win32": ">= 15.3", | ||
perf_hooks: ">= 8.5", | ||
process: ">= 1", | ||
punycode: true, | ||
querystring: true, | ||
readline: true, | ||
repl: true, | ||
smalloc: ">= 0.11.5 && < 3", | ||
_stream_duplex: ">= 0.9.4", | ||
_stream_transform: ">= 0.9.4", | ||
_stream_wrap: ">= 1.4.1", | ||
_stream_passthrough: ">= 0.9.4", | ||
_stream_readable: ">= 0.9.4", | ||
_stream_writable: ">= 0.9.4", | ||
stream: true, | ||
"stream/promises": ">= 15", | ||
string_decoder: true, | ||
sys: [ | ||
">= 0.6 && < 0.7", | ||
">= 0.8" | ||
], | ||
timers: true, | ||
"timers/promises": ">= 15", | ||
_tls_common: ">= 0.11.13", | ||
_tls_legacy: ">= 0.11.3 && < 10", | ||
_tls_wrap: ">= 0.11.3", | ||
tls: true, | ||
trace_events: ">= 10", | ||
tty: true, | ||
url: true, | ||
util: true, | ||
"util/types": ">= 15.3", | ||
"v8/tools/arguments": ">= 10 && < 12", | ||
"v8/tools/codemap": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/consarray": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/csvparser": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/logreader": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/profile_view": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
"v8/tools/splaytree": [ | ||
">= 4.4.0 && < 5", | ||
">= 5.2.0 && < 12" | ||
], | ||
v8: ">= 1", | ||
vm: true, | ||
wasi: ">= 13.4 && < 13.5", | ||
worker_threads: ">= 11.7", | ||
zlib: true | ||
}; | ||
var core$2 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
'default': core$1 | ||
}); | ||
var data = getCjsExportFromNamespace(core$2); | ||
var current = (process.versions && process.versions.node && process.versions.node.split('.')) || []; | ||
function specifierIncluded(specifier) { | ||
var parts = specifier.split(' '); | ||
var op = parts.length > 1 ? parts[0] : '='; | ||
var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); | ||
for (var i = 0; i < 3; ++i) { | ||
var cur = parseInt(current[i] || 0, 10); | ||
var ver = parseInt(versionParts[i] || 0, 10); | ||
if (cur === ver) { | ||
continue; // eslint-disable-line no-restricted-syntax, no-continue | ||
function newEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { | ||
var e_3, _a; | ||
var additionalArgs = []; | ||
for (var _i = 5; _i < arguments.length; _i++) { | ||
additionalArgs[_i - 5] = arguments[_i]; | ||
} | ||
if (op === '<') { | ||
return cur < ver; | ||
} else if (op === '>=') { | ||
return cur >= ver; | ||
} else { | ||
return false; | ||
} | ||
} | ||
return op === '>='; | ||
} | ||
function matchesRange(range) { | ||
var specifiers = range.split(/ ?&& ?/); | ||
if (specifiers.length === 0) { return false; } | ||
for (var i = 0; i < specifiers.length; ++i) { | ||
if (!specifierIncluded(specifiers[i])) { return false; } | ||
} | ||
return true; | ||
} | ||
function versionIncluded(specifierValue) { | ||
if (typeof specifierValue === 'boolean') { return specifierValue; } | ||
if (specifierValue && typeof specifierValue === 'object') { | ||
for (var i = 0; i < specifierValue.length; ++i) { | ||
if (matchesRange(specifierValue[i])) { return true; } | ||
} | ||
return false; | ||
} | ||
return matchesRange(specifierValue); | ||
} | ||
var core = {}; | ||
for (var mod in data) { // eslint-disable-line no-restricted-syntax | ||
if (Object.prototype.hasOwnProperty.call(data, mod)) { | ||
core[mod] = versionIncluded(data[mod]); | ||
} | ||
} | ||
var core_1 = core; | ||
var isCore = function isCore(x) { | ||
return isCoreModule(x); | ||
}; | ||
var realpathFS = fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync; | ||
var defaultIsFile = function isFile(file) { | ||
try { | ||
var stat = fs.statSync(file); | ||
} catch (e) { | ||
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; | ||
throw e; | ||
} | ||
return stat.isFile() || stat.isFIFO(); | ||
}; | ||
var defaultIsDir = function isDirectory(dir) { | ||
try { | ||
var stat = fs.statSync(dir); | ||
} catch (e) { | ||
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; | ||
throw e; | ||
} | ||
return stat.isDirectory(); | ||
}; | ||
var defaultRealpathSync = function realpathSync(x) { | ||
try { | ||
return realpathFS(x); | ||
} catch (realpathErr) { | ||
if (realpathErr.code !== 'ENOENT') { | ||
throw realpathErr; | ||
} | ||
} | ||
return x; | ||
}; | ||
var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { | ||
if (opts && opts.preserveSymlinks === false) { | ||
return realpathSync(x); | ||
} | ||
return x; | ||
}; | ||
var defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) { | ||
var body = readFileSync(pkgfile); | ||
try { | ||
var pkg = JSON.parse(body); | ||
return pkg; | ||
} catch (jsonErr) {} | ||
}; | ||
var getPackageCandidates = function getPackageCandidates(x, start, opts) { | ||
var dirs = nodeModulesPaths(start, opts, x); | ||
for (var i = 0; i < dirs.length; i++) { | ||
dirs[i] = path.join(dirs[i], x); | ||
} | ||
return dirs; | ||
}; | ||
var sync = function resolveSync(x, options) { | ||
if (typeof x !== 'string') { | ||
throw new TypeError('Path must be a string.'); | ||
} | ||
var opts = normalizeOptions(x, options); | ||
var isFile = opts.isFile || defaultIsFile; | ||
var readFileSync = opts.readFileSync || fs.readFileSync; | ||
var isDirectory = opts.isDirectory || defaultIsDir; | ||
var realpathSync = opts.realpathSync || defaultRealpathSync; | ||
var readPackageSync = opts.readPackageSync || defaultReadPackageSync; | ||
if (opts.readFileSync && opts.readPackageSync) { | ||
throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.'); | ||
} | ||
var packageIterator = opts.packageIterator; | ||
var extensions = opts.extensions || ['.js']; | ||
var includeCoreModules = opts.includeCoreModules !== false; | ||
var basedir = opts.basedir || path.dirname(caller()); | ||
var parent = opts.filename || basedir; | ||
opts.paths = opts.paths || []; | ||
// ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory | ||
var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts); | ||
if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) { | ||
var res = path.resolve(absoluteStart, x); | ||
if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; | ||
var m = loadAsFileSync(res) || loadAsDirectorySync(res); | ||
if (m) return maybeRealpathSync(realpathSync, m, opts); | ||
} else if (includeCoreModules && isCoreModule(x)) { | ||
return x; | ||
} else { | ||
var n = loadNodeModulesSync(x, absoluteStart); | ||
if (n) return maybeRealpathSync(realpathSync, n, opts); | ||
} | ||
var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); | ||
err.code = 'MODULE_NOT_FOUND'; | ||
throw err; | ||
function loadAsFileSync(x) { | ||
var pkg = loadpkg(path.dirname(x)); | ||
if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { | ||
var rfile = path.relative(pkg.dir, x); | ||
var r = opts.pathFilter(pkg.pkg, x, rfile); | ||
if (r) { | ||
x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign | ||
var transformers = pluginCreator.createTransformers({ program: program }, customTransformers); | ||
var result = program.originalEmit.apply(program, __spreadArray([targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, transformers], __read(additionalArgs), false)); | ||
try { | ||
for (var _b = __values(tsp.diagnosticMap.get(program) || []), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var diagnostic = _c.value; | ||
if (!result.diagnostics.includes(diagnostic)) | ||
result.diagnostics.push(diagnostic); | ||
} | ||
} | ||
if (isFile(x)) { | ||
return x; | ||
catch (e_3_1) { | ||
e_3 = { error: e_3_1 }; | ||
} | ||
for (var i = 0; i < extensions.length; i++) { | ||
var file = x + extensions[i]; | ||
if (isFile(file)) { | ||
return file; | ||
} | ||
} | ||
} | ||
function loadpkg(dir) { | ||
if (dir === '' || dir === '/') return; | ||
if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) { | ||
return; | ||
} | ||
if ((/[/\\]node_modules[/\\]*$/).test(dir)) return; | ||
var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); | ||
if (!isFile(pkgfile)) { | ||
return loadpkg(path.dirname(dir)); | ||
} | ||
var pkg = readPackageSync(readFileSync, pkgfile); | ||
if (pkg && opts.packageFilter) { | ||
// v2 will pass pkgfile | ||
pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment | ||
} | ||
return { pkg: pkg, dir: dir }; | ||
} | ||
function loadAsDirectorySync(x) { | ||
var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); | ||
if (isFile(pkgfile)) { | ||
finally { | ||
try { | ||
var pkg = readPackageSync(readFileSync, pkgfile); | ||
} catch (e) {} | ||
if (pkg && opts.packageFilter) { | ||
// v2 will pass pkgfile | ||
pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment | ||
if (_c && !_c.done && (_a = _b.return)) | ||
_a.call(_b); | ||
} | ||
if (pkg && pkg.main) { | ||
if (typeof pkg.main !== 'string') { | ||
var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); | ||
mainError.code = 'INVALID_PACKAGE_MAIN'; | ||
throw mainError; | ||
} | ||
if (pkg.main === '.' || pkg.main === './') { | ||
pkg.main = 'index'; | ||
} | ||
try { | ||
var m = loadAsFileSync(path.resolve(x, pkg.main)); | ||
if (m) return m; | ||
var n = loadAsDirectorySync(path.resolve(x, pkg.main)); | ||
if (n) return n; | ||
} catch (e) {} | ||
finally { | ||
if (e_3) | ||
throw e_3.error; | ||
} | ||
} | ||
return loadAsFileSync(path.join(x, '/index')); | ||
return result; | ||
} | ||
function loadNodeModulesSync(x, start) { | ||
var thunk = function () { return getPackageCandidates(x, start, opts); }; | ||
var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); | ||
for (var i = 0; i < dirs.length; i++) { | ||
var dir = dirs[i]; | ||
if (isDirectory(path.dirname(dir))) { | ||
var m = loadAsFileSync(dir); | ||
if (m) return m; | ||
var n = loadAsDirectorySync(dir); | ||
if (n) return n; | ||
} | ||
} | ||
} | ||
}; | ||
async.core = core_1; | ||
async.isCore = isCore; | ||
async.sync = sync; | ||
var resolve = async; | ||
/* ****************************************************************************************************************** */ | ||
// region: Module Vars & Ambients | ||
/* ****************************************************************************************************************** */ | ||
return program; | ||
} | ||
tsp.createProgram = createProgram; | ||
})(tsp || (tsp = {})); | ||
var tsp; | ||
(function (tsp) { | ||
Object.defineProperties(ts, { | ||
isTSC: { get: function () { return tsp.isTSC; }, enumerable: true }, | ||
tspVersion: { get: function () { return tsp.tspVersion; }, enumerable: true }, | ||
PluginCreator: { get: function () { return tsp.PluginCreator; }, enumerable: true }, | ||
originalCreateProgram: { value: ts.createProgram, enumerable: true }, | ||
createProgram: { value: tsp.createProgram }, | ||
diagnosticMap: { get: function () { return tsp.diagnosticMap; }, enumerable: true } | ||
}); | ||
})(tsp || (tsp = {})); | ||
var tsp; | ||
(function (tsp) { | ||
var path = require("path"); | ||
var fs = require("fs"); | ||
var tsNodeIncluded = false; | ||
var requireStack = []; | ||
// endregion | ||
/* ****************************************************************************************************************** */ | ||
// region: PluginCreator | ||
/* ****************************************************************************************************************** */ | ||
/** | ||
* @example | ||
* | ||
* new PluginCreator([ | ||
* {transform: '@zerollup/ts-transform-paths', someOption: '123'}, | ||
* {transform: '@zerollup/ts-transform-paths', type: 'ls', someOption: '123'}, | ||
* {transform: '@zerollup/ts-transform-paths', type: 'ls', after: true, someOption: '123'} | ||
* ]).createTransformers({ program }) | ||
*/ | ||
var PluginCreator = /** @class */ (function () { | ||
var PluginCreator = (function () { | ||
function PluginCreator(configs, resolveBaseDir) { | ||
var e_1, _a; | ||
if (resolveBaseDir === void 0) { resolveBaseDir = process.cwd(); } | ||
var e_4, _a; | ||
if (resolveBaseDir === void 0) { | ||
resolveBaseDir = process.cwd(); | ||
} | ||
this.configs = configs; | ||
@@ -1208,15 +249,20 @@ this.resolveBaseDir = resolveBaseDir; | ||
try { | ||
// Support for deprecated 1.1 name | ||
for (var configs_1 = __values(configs), configs_1_1 = configs_1.next(); !configs_1_1.done; configs_1_1 = configs_1.next()) { | ||
var config = configs_1_1.value; | ||
if (config['beforeEmit']) | ||
if (config["beforeEmit"]) | ||
config.transformProgram = true; | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
catch (e_4_1) { | ||
e_4 = { error: e_4_1 }; | ||
} | ||
finally { | ||
try { | ||
if (configs_1_1 && !configs_1_1.done && (_a = configs_1.return)) _a.call(configs_1); | ||
if (configs_1_1 && !configs_1_1.done && (_a = configs_1.return)) | ||
_a.call(configs_1); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
finally { | ||
if (e_4) | ||
throw e_4.error; | ||
} | ||
} | ||
@@ -1228,13 +274,13 @@ } | ||
if (source.before) | ||
(_a = into.before).push.apply(_a, __spreadArray([], __read(slice(source.before)))); | ||
(_a = into.before).push.apply(_a, __spreadArray([], __read(slice(source.before)), false)); | ||
if (source.after) | ||
(_b = into.after).push.apply(_b, __spreadArray([], __read(slice(source.after)))); | ||
(_b = into.after).push.apply(_b, __spreadArray([], __read(slice(source.after)), false)); | ||
if (source.afterDeclarations) | ||
(_c = into.afterDeclarations).push.apply(_c, __spreadArray([], __read(slice(source.afterDeclarations)))); | ||
(_c = into.afterDeclarations).push.apply(_c, __spreadArray([], __read(slice(source.afterDeclarations)), false)); | ||
return this; | ||
}; | ||
PluginCreator.prototype.createTransformers = function (params, customTransformers) { | ||
var e_2, _a; | ||
var e_5, _a; | ||
var transformers = { before: [], after: [], afterDeclarations: [] }; | ||
var _b = __read(('ls' in params) ? [params.ls, params.ls.getProgram()] : [void 0, params.program], 2), ls = _b[0], program = _b[1]; | ||
var _b = __read(("ls" in params) ? [params.ls, params.ls.getProgram()] : [void 0, params.program], 2), ls = _b[0], program = _b[1]; | ||
try { | ||
@@ -1251,10 +297,15 @@ for (var _c = __values(this.configs), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
catch (e_5_1) { | ||
e_5 = { error: e_5_1 }; | ||
} | ||
finally { | ||
try { | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
if (_d && !_d.done && (_a = _c.return)) | ||
_a.call(_c); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
finally { | ||
if (e_5) | ||
throw e_5.error; | ||
} | ||
} | ||
// Chain custom transformers at the end | ||
if (customTransformers) | ||
@@ -1265,3 +316,3 @@ this.mergeTransformers(transformers, customTransformers); | ||
PluginCreator.prototype.getProgramTransformers = function () { | ||
var e_3, _a; | ||
var e_6, _a; | ||
var res = []; | ||
@@ -1279,59 +330,34 @@ try { | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
catch (e_6_1) { | ||
e_6 = { error: e_6_1 }; | ||
} | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
if (_c && !_c.done && (_a = _b.return)) | ||
_a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
finally { | ||
if (e_6) | ||
throw e_6.error; | ||
} | ||
} | ||
return res; | ||
}; | ||
/* *********************************************************** | ||
* Helpers | ||
* ***********************************************************/ | ||
PluginCreator.prototype.resolveFactory = function (config) { | ||
var _a; | ||
var tsConfig = config.tsConfig; | ||
var tsConfig = config.tsConfig && path.resolve(this.resolveBaseDir, config.tsConfig); | ||
var transform = config.transform; | ||
var importKey = config.import || 'default'; | ||
/* Add support for TS transformers */ | ||
var importKey = config.import || "default"; | ||
var tsConfigCleanup; | ||
if (transform.match(/\.ts$/)) { | ||
// If tsConfig is specified and it differs, we need to re-register tsNode | ||
if (tsNodeIncluded && (tsConfig !== this.currentProject)) | ||
tsNodeIncluded = false; | ||
if (tsConfig) | ||
tsConfig = path$1.resolve(this.resolveBaseDir, tsConfig); | ||
this.currentProject = tsConfig; | ||
if (!tsNodeIncluded) { | ||
/* Try to add path mapping support, if paths specified */ | ||
var tsConfigData = void 0; | ||
try { | ||
tsConfigData = tsConfig && JSON.parse(fs$1.readFileSync(tsConfig, 'utf8')); | ||
} | ||
catch (_b) { } | ||
if (tsConfig && ((_a = tsConfigData === null || tsConfigData === void 0 ? void 0 : tsConfigData.compilerOptions) === null || _a === void 0 ? void 0 : _a.paths)) { | ||
try { | ||
var tsConfigPaths = require('tsconfig-paths'); | ||
var absoluteBaseUrl = tsConfigPaths.loadConfig(tsConfig).absoluteBaseUrl; | ||
tsConfigCleanup = tsConfigPaths.register({ | ||
baseUrl: absoluteBaseUrl, | ||
paths: tsConfigData.compilerOptions.paths | ||
}); | ||
} | ||
catch (e) { | ||
if (e.code === 'MODULE_NOT_FOUND') | ||
console.warn("Warning: Paths specified in transformer tsconfig.json, but they can't be resolved. " + | ||
"Try adding 'tsconfig-paths' as a dev dependency"); | ||
else | ||
throw e; | ||
} | ||
} | ||
/* Register tsNode */ | ||
try { | ||
require('ts-node').register(__assign(__assign({ transpileOnly: true }, (tsConfig ? { project: tsConfig } : { skipProject: true })), { compilerOptions: { | ||
target: 'ES2018', | ||
jsx: 'react', | ||
require("ts-node").register(__assign(__assign({ transpileOnly: true }, (tsConfig ? { project: tsConfig } : { skipProject: true })), { compilerOptions: { | ||
target: "ES2018", | ||
jsx: "react", | ||
esModuleInterop: true, | ||
module: 'commonjs', | ||
module: "commonjs", | ||
} })); | ||
@@ -1341,3 +367,3 @@ tsNodeIncluded = true; | ||
catch (e) { | ||
if (e.code === 'MODULE_NOT_FOUND') | ||
if (e.code === "MODULE_NOT_FOUND") | ||
throw new Error("Cannot use a typescript-based transformer without ts-node installed. " + | ||
@@ -1349,21 +375,36 @@ "Either add ts-node as a (dev)-dependency or install globally."); | ||
} | ||
var tsConfigData = tsConfig && ts.readConfigFile(tsConfig, ts.sys.readFile).config; | ||
if ((_a = tsConfigData === null || tsConfigData === void 0 ? void 0 : tsConfigData.compilerOptions) === null || _a === void 0 ? void 0 : _a.paths) { | ||
try { | ||
var tsConfigPaths = require("tsconfig-paths"); | ||
var absoluteBaseUrl = tsConfigPaths.loadConfig(tsConfig).absoluteBaseUrl; | ||
tsConfigCleanup = tsConfigPaths.register({ | ||
baseUrl: absoluteBaseUrl, | ||
paths: tsConfigData.compilerOptions.paths | ||
}); | ||
} | ||
catch (e) { | ||
if (e.code === "MODULE_NOT_FOUND") | ||
console.warn("Paths specified in transformer tsconfig.json, but they may not be able to be resolved. " + | ||
"If not, try adding 'tsconfig-paths' as a dev dependency"); | ||
else | ||
throw e; | ||
} | ||
} | ||
} | ||
var modulePath = resolve.sync(transform, { basedir: this.resolveBaseDir }); | ||
/* Prevent recursive requiring of createTransformers (issue with ts-node) */ | ||
var modulePath = require.resolve(transform, { paths: [this.resolveBaseDir] }); | ||
if (requireStack.indexOf(modulePath) > -1) | ||
return; | ||
/* Load plugin */ | ||
requireStack.push(modulePath); | ||
var commonjsModule = require(modulePath); | ||
requireStack.pop(); | ||
// Un-register path mapping if in place | ||
tsConfigCleanup === null || tsConfigCleanup === void 0 ? void 0 : tsConfigCleanup(); | ||
var factoryModule = (typeof commonjsModule === 'function') ? { default: commonjsModule } : commonjsModule; | ||
var factoryModule = (typeof commonjsModule === "function") ? { default: commonjsModule } : commonjsModule; | ||
var factory = factoryModule[importKey]; | ||
if (!factory) | ||
throw new Error("tsconfig.json > plugins: \"" + transform + "\" does not have an export \"" + importKey + "\": " + | ||
require('util').inspect(factoryModule)); | ||
if (typeof factory !== 'function') { | ||
require("util").inspect(factoryModule)); | ||
if (typeof factory !== "function") { | ||
throw new Error("tsconfig.json > plugins: \"" + transform + "\" export \"" + importKey + "\" is not a plugin: " + | ||
require('util').inspect(factory)); | ||
require("util").inspect(factory)); | ||
} | ||
@@ -1373,3 +414,3 @@ return factory; | ||
PluginCreator.validateConfigs = function (configs) { | ||
var e_4, _a; | ||
var e_7, _a; | ||
try { | ||
@@ -1379,11 +420,17 @@ for (var configs_2 = __values(configs), configs_2_1 = configs_2.next(); !configs_2_1.done; configs_2_1 = configs_2.next()) { | ||
if (!config.name && !config.transform) | ||
throw new Error('tsconfig.json plugins error: transform must be present'); | ||
throw new Error("tsconfig.json plugins error: transform must be present"); | ||
} | ||
} | ||
catch (e_4_1) { e_4 = { error: e_4_1 }; } | ||
catch (e_7_1) { | ||
e_7 = { error: e_7_1 }; | ||
} | ||
finally { | ||
try { | ||
if (configs_2_1 && !configs_2_1.done && (_a = configs_2.return)) _a.call(configs_2); | ||
if (configs_2_1 && !configs_2_1.done && (_a = configs_2.return)) | ||
_a.call(configs_2); | ||
} | ||
finally { if (e_4) throw e_4.error; } | ||
finally { | ||
if (e_7) | ||
throw e_7.error; | ||
} | ||
} | ||
@@ -1393,8 +440,8 @@ }; | ||
var factory = _a.factory, config = _a.config, program = _a.program, ls = _a.ls; | ||
var transform = config.transform, after = config.after, afterDeclarations = config.afterDeclarations; config.name; config.type; config.transformProgram; var cleanConfig = __rest(config, ["transform", "after", "afterDeclarations", "name", "type", "transformProgram"]); | ||
var transform = config.transform, after = config.after, afterDeclarations = config.afterDeclarations, name = config.name, type = config.type, transformProgram = config.transformProgram, cleanConfig = __rest(config, ["transform", "after", "afterDeclarations", "name", "type", "transformProgram"]); | ||
if (!transform) | ||
throw new Error('Not a valid config entry: "transform" key not found'); | ||
throw new Error("Not a valid config entry: \"transform\" key not found"); | ||
var ret; | ||
switch (config.type) { | ||
case 'ls': | ||
case "ls": | ||
if (!ls) | ||
@@ -1404,14 +451,14 @@ throw new Error("Plugin " + transform + " needs a LanguageService"); | ||
break; | ||
case 'config': | ||
case "config": | ||
ret = factory(cleanConfig); | ||
break; | ||
case 'compilerOptions': | ||
case "compilerOptions": | ||
ret = factory(program.getCompilerOptions(), cleanConfig); | ||
break; | ||
case 'checker': | ||
case "checker": | ||
ret = factory(program.getTypeChecker(), cleanConfig); | ||
break; | ||
case undefined: | ||
case 'program': | ||
var _b = diagnosticExtrasFactory(program), addDiagnostic = _b.addDiagnostic, removeDiagnostic = _b.removeDiagnostic, diagnostics = _b.diagnostics; | ||
case "program": | ||
var _b = tsp.diagnosticExtrasFactory(program), addDiagnostic = _b.addDiagnostic, removeDiagnostic = _b.removeDiagnostic, diagnostics = _b.diagnostics; | ||
ret = factory(program, cleanConfig, { | ||
@@ -1422,6 +469,6 @@ ts: ts, | ||
diagnostics: diagnostics, | ||
library: getCurrentLibrary() | ||
library: tsp.getCurrentLibrary() | ||
}); | ||
break; | ||
case 'raw': | ||
case "raw": | ||
ret = function (ctx) { return factory(ctx, program, cleanConfig); }; | ||
@@ -1432,3 +479,3 @@ break; | ||
} | ||
if (typeof ret === 'function') | ||
if (typeof ret === "function") | ||
return after ? ({ after: ret }) : | ||
@@ -1441,175 +488,15 @@ afterDeclarations ? ({ afterDeclarations: ret }) : | ||
}()); | ||
// endregion | ||
/* | ||
* The logic in this file is based on TTypescript (https://github.com/cevek/ttypescript) | ||
* Credit & thanks go to cevek (https://github.com/cevek) for the incredible work! | ||
*/ | ||
/* ****************************************************************************************************************** */ | ||
// region: Constants & Ambients | ||
/* ****************************************************************************************************************** */ | ||
var activeProgramTransformers = new Set(); | ||
var dirname = require('path').dirname; | ||
// endregion | ||
/* ****************************************************************************************************************** */ | ||
// region: Helpers | ||
/* ****************************************************************************************************************** */ | ||
function getProjectDir(compilerOptions) { | ||
return compilerOptions.configFilePath && dirname(compilerOptions.configFilePath); | ||
tsp.PluginCreator = PluginCreator; | ||
})(tsp || (tsp = {})); | ||
var tsp; | ||
(function (tsp) { | ||
tsp.diagnosticMap = new WeakMap(); | ||
function diagnosticExtrasFactory(program) { | ||
var diagnostics = tsp.diagnosticMap.get(program) || tsp.diagnosticMap.set(program, []).get(program); | ||
var addDiagnostic = function (diag) { return diagnostics.push(diag); }; | ||
var removeDiagnostic = function (index) { diagnostics.splice(index, 1); }; | ||
return { addDiagnostic: addDiagnostic, removeDiagnostic: removeDiagnostic, diagnostics: diagnostics }; | ||
} | ||
function getProjectConfig(compilerOptions, rootFileNames) { | ||
var configFilePath = compilerOptions.configFilePath; | ||
var projectDir = getProjectDir(compilerOptions); | ||
if (configFilePath === undefined) { | ||
var baseDir = (rootFileNames.length > 0) ? dirname(rootFileNames[0]) : projectDir !== null && projectDir !== void 0 ? projectDir : process.cwd(); | ||
configFilePath = ts.findConfigFile(baseDir, ts.sys.fileExists); | ||
if (configFilePath) { | ||
var config = readConfig(configFilePath); | ||
compilerOptions = __assign(__assign({}, config.options), compilerOptions); | ||
projectDir = getProjectDir(compilerOptions); | ||
} | ||
} | ||
return ({ projectDir: projectDir, compilerOptions: compilerOptions }); | ||
} | ||
function readConfig(configFileNamePath) { | ||
var projectDir = dirname(configFileNamePath); | ||
var result = ts.readConfigFile(configFileNamePath, ts.sys.readFile); | ||
if (result.error) | ||
throw new Error('Error in tsconfig.json: ' + result.error.messageText); | ||
return ts.parseJsonConfigFileContent(result.config, ts.sys, projectDir, undefined, configFileNamePath); | ||
} | ||
function preparePluginsFromCompilerOptions(plugins) { | ||
if (!plugins) | ||
return []; | ||
// Old transformers system | ||
if ((plugins.length === 1) && plugins[0].customTransformers) { | ||
var _a = plugins[0].customTransformers, _b = _a.before, before = _b === void 0 ? [] : _b, _c = _a.after, after = _c === void 0 ? [] : _c; | ||
return __spreadArray(__spreadArray([], __read(before.map(function (item) { return ({ transform: item }); }))), __read(after.map(function (item) { return ({ transform: item, after: true }); }))); | ||
} | ||
return plugins; | ||
} | ||
// endregion | ||
/* ****************************************************************************************************************** */ | ||
// region: createProgram - (patched method) | ||
/* ****************************************************************************************************************** */ | ||
function createProgram(rootNamesOrOptions, options, host, oldProgram, configFileParsingDiagnostics) { | ||
var e_1, _a, e_2, _b; | ||
var _c; | ||
var rootNames; | ||
/* Determine options */ | ||
var createOpts = !Array.isArray(rootNamesOrOptions) ? rootNamesOrOptions : void 0; | ||
if (createOpts) { | ||
rootNames = createOpts.rootNames; | ||
options = createOpts.options; | ||
host = createOpts.host; | ||
oldProgram = createOpts.oldProgram; | ||
configFileParsingDiagnostics = createOpts.configFileParsingDiagnostics; | ||
} | ||
else { | ||
options = options; | ||
rootNames = rootNamesOrOptions; | ||
} | ||
/* Get Config */ | ||
var projectConfig = getProjectConfig(options, rootNames); | ||
if (isTSC) { | ||
options = projectConfig.compilerOptions; | ||
if (createOpts) | ||
createOpts.options = options; | ||
} | ||
/* Invoke TS createProgram */ | ||
var program = createOpts ? | ||
ts.originalCreateProgram(createOpts) : | ||
ts.originalCreateProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics); | ||
/* Prepare Plugins */ | ||
var plugins = preparePluginsFromCompilerOptions(options.plugins); | ||
var pluginCreator = new PluginCreator(plugins, (_c = projectConfig.projectDir) !== null && _c !== void 0 ? _c : process.cwd()); | ||
/* Prevent recursion in Program transformers */ | ||
var programTransformers = new Map(pluginCreator.getProgramTransformers()); | ||
try { | ||
for (var _d = __values(pluginCreator.getProgramTransformers()), _e = _d.next(); !_e.done; _e = _d.next()) { | ||
var _f = __read(_e.value, 1), transformer = _f[0]; | ||
if (activeProgramTransformers.has(transformer)) | ||
programTransformers.delete(transformer); | ||
else | ||
activeProgramTransformers.add(transformer); | ||
} | ||
} | ||
catch (e_1_1) { e_1 = { error: e_1_1 }; } | ||
finally { | ||
try { | ||
if (_e && !_e.done && (_a = _d.return)) _a.call(_d); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
} | ||
try { | ||
/* Transform Program */ | ||
for (var programTransformers_1 = __values(programTransformers), programTransformers_1_1 = programTransformers_1.next(); !programTransformers_1_1.done; programTransformers_1_1 = programTransformers_1.next()) { | ||
var _g = __read(programTransformers_1_1.value, 2), programTransformer = _g[0], config = _g[1]; | ||
var newProgram = programTransformer(program, host, config, { ts: ts }); | ||
if (typeof (newProgram === null || newProgram === void 0 ? void 0 : newProgram['emit']) === 'function') | ||
program = newProgram; | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (programTransformers_1_1 && !programTransformers_1_1.done && (_b = programTransformers_1.return)) _b.call(programTransformers_1); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
programTransformers.forEach(function (c, transformer) { return activeProgramTransformers.delete(transformer); }); | ||
/* Hook emit method */ | ||
if (!program.originalEmit) { | ||
program.originalEmit = program.emit; | ||
program.emit = newEmit; | ||
} | ||
function newEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { | ||
var e_3, _a; | ||
var additionalArgs = []; | ||
for (var _i = 5; _i < arguments.length; _i++) { | ||
additionalArgs[_i - 5] = arguments[_i]; | ||
} | ||
/* Merge in our transformers */ | ||
var transformers = pluginCreator.createTransformers({ program: program }, customTransformers); | ||
/* Invoke TS emit */ | ||
var result = program.originalEmit.apply(program, __spreadArray([targetSourceFile, | ||
writeFile, | ||
cancellationToken, | ||
emitOnlyDtsFiles, | ||
transformers], __read(additionalArgs))); | ||
try { | ||
/* Merge in transformer diagnostics */ | ||
for (var _b = __values(diagnosticMap.get(program) || []), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var diagnostic = _c.value; | ||
if (!result.diagnostics.includes(diagnostic)) | ||
result.diagnostics.push(diagnostic); | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
return result; | ||
} | ||
return program; | ||
} | ||
// endregion | ||
/* | ||
* Note: This file is used to generate module-patch.js (see rollup.config.js) | ||
*/ | ||
/* ******************************************************************************************************************** | ||
* Link to ts object | ||
* ********************************************************************************************************************/ | ||
Object.assign(ts, { | ||
tspVersion: tspVersion, | ||
PluginCreator: PluginCreator, | ||
originalCreateProgram: ts.createProgram, | ||
createProgram: createProgram, | ||
diagnosticMap: diagnosticMap | ||
}); | ||
}()); | ||
tsp.diagnosticExtrasFactory = diagnosticExtrasFactory; | ||
tsp.getCurrentLibrary = function () { return require("path").basename(__filename, require("path").extname(__filename)); }; | ||
})(tsp || (tsp = {})); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Uses eval
Supply chain riskPackage uses dynamic code execution (e.g., eval()), which is a dangerous practice. This can prevent the code from running in certain environments and increases the risk that the code may contain exploits or malicious behavior.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
0
164453
40
1911
1
311