Skip to content

Commit

Permalink
Fixed missing dependancy in package.json and fixed build script errors.
Browse files Browse the repository at this point in the history
Fixed eslint errors with globalThis and self.
Also fixed an oversight in testutil.mjs that was causing the tests to fail with the new changes.
  • Loading branch information
ILOVEPIE committed Jun 12, 2024
1 parent 8241908 commit 6c544d7
Show file tree
Hide file tree
Showing 7 changed files with 346 additions and 119 deletions.
42 changes: 40 additions & 2 deletions buildLib/esbuild-plugin-swc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,31 @@ SOFTWARE.

import { transform, transformSync } from '@swc/core';
import path from 'node:path';
import process from 'node:process';
import fs from 'node:fs/promises';
import { existsSync } from 'node:fs';

function getNodeModulesDirectoryForPath(currentDir){
let relativePath = "node_modules";
let resolvedPath = path.resolve(currentDir, relativePath);

function countSeparators(str) {
let count = 0;
for(let i = 0; i < str.length; i++) {
if(str[i] == path.sep)
count++;
}
return count;
}

while(!existsSync(resolvedPath)){
if(countSeparators(resolvedPath) <= 1){
throw new Error("Could not find node_modules directory");
}
relativePath = path.join("..", relativePath);
resolvedPath = path.resolve(currentDir, relativePath);
}
return resolvedPath;
}

function assignDeep(target, source) {
for (const key in source) {
Expand All @@ -54,14 +77,26 @@ export default function swcPlugin(options, isAsync) {
name: 'esbuild:swc',
setup(builder) {
builder.onResolve({ filter: /\.(m?[tj]s)$/ }, (args) => {
const fullPath = path.resolve(args.resolveDir, args.path);
let fullPath;
let defaultPath = path.resolve(args.resolveDir, args.path);
if(args.kind == 'import-statement'){
if(existsSync(defaultPath)){
fullPath = defaultPath;
}else{
let nodeModulesPath = getNodeModulesDirectoryForPath(args.resolveDir);
fullPath = path.join(nodeModulesPath, args.path);
}
}else{
fullPath = defaultPath;
}
return {
path: fullPath,
};
});
builder.onLoad({ filter: /\.(m?[tj]s)$/ }, async (args) => {
const code = await fs.readFile(args.path, 'utf-8');
const isTS = args.path.endsWith('.ts');
const isCoreJs = args.path.indexOf('core-js') !== -1;
const initialOptions = {
jsc: {
parser: {
Expand All @@ -73,6 +108,9 @@ export default function swcPlugin(options, isAsync) {
sourceFileName: path.relative(options.root,args.path)
};
const finalOptions = assignDeep(assignDeep({}, initialOptions), options);
if(isCoreJs){
delete finalOptions.env.mode;
}
let result;
if (isAsync) {
result = await transform(code, finalOptions);
Expand Down
78 changes: 54 additions & 24 deletions esbuild-runner.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as esbuild from 'esbuild'
import Path from 'node:path';
import { createRequire } from 'node:module';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

import semver from 'semver';

Expand All @@ -14,47 +15,59 @@ import swcPlugin from './buildLib/esbuild-plugin-swc.mjs';

function getScriptPath(){
try{
return import.meta.url;
return fileURLToPath(import.meta.url);
}catch(e){
return __filename||null;
}
}

function getScriptDirectory(){
try{
return Path.dirname(import.meta.url);
return Path.dirname(fileURLToPath(import.meta.url));
}catch(e){
return __dirname||null;
}
}

const resolveFileFromPackage = (function(){
return ((new Function("try{return import.meta.resolve;}catch(e){return null}"))()||createRequire(getScriptPath()).resolve);
const rawResolve = ((function(){try{return import.meta.resolve;}catch(e){return null}})()||createRequire(getScriptPath()).resolve);
return function(fileToResolve){
const result = rawResolve(fileToResolve);
if(result.startsWith("file:")){
return fileURLToPath(result);
}
return result;
};
})();

function readKeyFromPackageJson(key,pkg) {
let resolvedPath;
if(typeof pkg == "undefined" || pkg == null){
let currentDir = getScriptDirectory;
let relativePath = "package.json";
resolvedPath = Path.resolve(currentDir, relativePath);
function getOwnPackageJsonPath(){
let currentDir = getScriptDirectory();
let relativePath = "package.json";
let resolvedPath = Path.resolve(currentDir, relativePath);

function countSeparators(str) {
let count = 0;
for(let i = 0; i < str.length; i++) {
if(str[i] == Path.sep)
count++;
}
return count;
function countSeparators(str) {
let count = 0;
for(let i = 0; i < str.length; i++) {
if(str[i] == Path.sep)
count++;
}
return count;
}

while(!existsSync(resolvedPath)){
if(countSeparators(resolvedPath) <= 1){
throw new Error("Could not find package.json file");
}
relativePath = Path.join("..", relativePath);
resolvedPath = Path.resolve(currentDir, relativePath);
while(!existsSync(resolvedPath)){
if(countSeparators(resolvedPath) <= 1){
throw new Error("Could not find package.json file");
}
relativePath = Path.join("..", relativePath);
resolvedPath = Path.resolve(currentDir, relativePath);
}
return resolvedPath;
}

function readKeyFromPackageJson(key,pkg) {
let resolvedPath;
if(typeof pkg == "undefined" || pkg == null){
resolvedPath = getOwnPackageJsonPath();
}else{
resolvedPath = resolveFileFromPackage(Path.join(pkg,"package.json"));
if(!resolvedPath||!existsSync(resolvedPath)){
Expand Down Expand Up @@ -233,19 +246,36 @@ async function build(params) {
if(!semver.satisfies(installedCoreJsVersion, readKeyFromPackageJson("devDependencies.core-js"))){
throw new Error("Please update your dependencies, the core-js version installed does not match the version specified in the package.json file.");
}

const swcTargets = {
"es2015": {
"chrome": "49",
"firefox": "44",
"safari": "10",
"edge": "13",
"opera": "36",
"node": "13.2.0"
},
"compat": compatTargets
};

swcConfig.env = {
"bugfixes": true,
"mode": "usage",
"coreJs": installedCoreJsVersion
};
swcConfig.env.targets = swcTargets[params.options.target??'es2015']||swcTargets["es2015"];
if(params.options.target == "compat") {
swcConfig.env.targets = compatTargets;
swcConfig.jsc.minify.compress.ecma = 3;
esbuildTarget = convertToEsbuildTarget(compatTargets);
//esbuild does not officialy support es3 but outputs es3 compatable code when you specifiy es5 as the target.
esbuildTarget.push("es5");
}else{
swcConfig.jsc.target = params.options.target??'es2015';
const ecmaVersion = parseInt((params.options.target??'es2015').slice(2));
if(isNaN(ecmaVersion)){
ecmaVersion = 2015;
}
swcConfig.jsc.minify.compress.ecma = ecmaVersion;
esbuildTarget = params.options.target??'es2015';
}
}
Expand Down
2 changes: 2 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export default [
sourceType: "module",
globals: {
console: "readonly",
globalThis: "readonly", // this is to get eslint to stop complaining about globalThis, it's pollyfilled in the code.
self: "readonly", // this is to get eslint to stop complaining about self, it's only used if globalThis is not available.
// ugly platform-dependant classes and objects
DecompressionStream: "readonly",
Response: "readonly",
Expand Down
Loading

0 comments on commit 6c544d7

Please sign in to comment.