UNPKG

@plugjs/tsrun

Version:

A simple TypeScript runner --------------------------

187 lines (183 loc) 7.33 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/loader-commonjs.cts var import_node_module = __toESM(require("node:module")); var import_node_path2 = __toESM(require("node:path")); // src/loader-shared.ts var import_node_fs = __toESM(require("node:fs"), 1); var import_node_path = __toESM(require("node:path"), 1); var import_node_util = __toESM(require("node:util"), 1); var import_esbuild = __toESM(require("esbuild"), 1); var CJS = "commonjs"; var ESM = "module"; var _debugLog = import_node_util.default.debuglog("plug:ts-loader"); var _debug = _debugLog.enabled; function logMessage(mode, arg, ...args) { if (!_debug) return; const t = mode === ESM ? "esm" : mode === CJS ? "cjs" : "---"; _debugLog(`[${t}] ${arg}`, ...args); } function throwError(mode, message, options = {}) { const t = mode === ESM ? "esm" : mode === CJS ? "cjs" : "---"; const prefix = `[ts-loader|${t}|pid=${process.pid}]`; const { start = throwError, ...extra } = options; const error = new Error(`${prefix} ${message}`); Error.captureStackTrace(error, start); Object.assign(error, extra); throw error; } function moduleType(mode) { if (process.env.__TS_LOADER_FORCE_TYPE) { const type = process.env.__TS_LOADER_FORCE_TYPE; if (type === CJS || type === ESM) { logMessage(mode, `Forcing type to "${type}" from environment`); return type; } else { throwError(mode, `Invalid type "${process.env.__TS_LOADER_FORCE_TYPE}"`); } } const _findType = (directory) => { const packageFile = import_node_path.default.join(directory, "package.json"); try { const packageData = import_node_fs.default.readFileSync(packageFile, "utf-8"); const packageJson = JSON.parse(packageData); const packageType = packageJson.type; switch (packageType) { case void 0: logMessage(mode, `File "${packageFile}" does not declare a default type`); return CJS; case CJS: case ESM: logMessage(mode, `File "${packageFile}" declares type as "${CJS}"`); return packageType; default: logMessage(mode, `File "${packageFile}" specifies unknown type "${packageType}"`); return CJS; } } catch (cause) { if (cause.code !== "ENOENT" && cause.code !== "EISDIR") { throwError(mode, `Unable to read or parse "${packageFile}"`, { cause, start: _findType }); } } const parent = import_node_path.default.dirname(directory); if (directory !== parent) return _findType(directory); logMessage(mode, `Type defaulted to "${CJS}"`); return CJS; }; return _findType(process.cwd()); } function _esbReport(kind, messages = []) { const output = process.stderr; const options = { color: !!output.isTTY, terminalWidth: output.columns || 80 }; const array = import_esbuild.default.formatMessagesSync(messages, { kind, ...options }); array.forEach((message) => output.write(`${message} `)); } function esbTranpile(filename, type) { logMessage(type, `Transpiling "${filename}" as "${type}"`); const [format, __fileurl] = type === ESM ? ["esm", "import.meta.url"] : ["cjs", "__filename"]; const options = { sourcefile: filename, // the original filename we're parsing format, // what are we actually transpiling to??? loader: "ts", // the format is always "typescript" sourcemap: "inline", // always inline source maps sourcesContent: false, // do not include sources content in sourcemap platform: "node", // d'oh! :-) minifyWhitespace: true, // https://github.com/evanw/esbuild/releases/tag/v0.16.14 logLevel: "silent", // catching those in our _esbReport below target: `node${process.versions["node"]}`, // target _this_ version define: { __fileurl } // from "globals.d.ts" }; if (_debug) { if (format === "esm") { options.banner = `;(await import('node:util')).debuglog('plug:ts-loader')('[esm] Loaded "%s"', ${__fileurl});`; } else if (format === "cjs") { options.banner = `;require('node:util').debuglog('plug:ts-loader')('[cjs] Loaded "%s"', ${__fileurl});`; } } let result; try { const source = import_node_fs.default.readFileSync(filename, "utf-8"); result = import_esbuild.default.transformSync(source, options); } catch (cause) { _esbReport("error", cause.errors); _esbReport("warning", cause.warnings); throwError(type, `ESBuild error transpiling "${filename}"`, { cause, start: esbTranpile }); } if (_debug) _esbReport("warning", result.warnings); return result.code; } // src/loader-commonjs.cts var _type = moduleType(CJS); var loader = (module2, filename) => { logMessage(CJS, `Attempting to load "${filename}"`); const ext = import_node_path2.default.extname(filename); if (ext === ".ts") { if (_type === ESM) { throwError(CJS, `Must use import to load ES Module: ${filename}`, { code: "ERR_REQUIRE_ESM" }); } } else if (ext !== ".cts") { throwError(CJS, `Unsupported filename "${filename}"`); } const source = esbTranpile(filename, CJS); try { module2._compile(source, filename); } catch (cause) { console.error(`Error compiling module "${filename}"`, cause); } }; var _oldResolveFilename = import_node_module.default._resolveFilename; import_node_module.default._resolveFilename = function(request, parent, ...args) { try { return _oldResolveFilename.call(this, request, parent, ...args); } catch (error) { if (error.code !== "MODULE_NOT_FOUND") throw error; const match = request.match(/(.*)(\.[mc]?js$)/); if (parent && match) { const [, name, ext] = match; const tsrequest = name + ext.replace("js", "ts"); try { const result = _oldResolveFilename.call(this, tsrequest, parent, ...args); logMessage(CJS, `Resolution for "${request}" intercepted as "${tsrequest}`); return result; } catch { throw error; } } throw error; } }; import_node_module.default._extensions[".ts"] = import_node_module.default._extensions[".cts"] = loader; logMessage(CJS, "TypeScript loader for CommonJS loaded"); //# sourceMappingURL=loader-commonjs.cjs.map