Skip to content

Commit

Permalink
__dirname
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Del Core committed Sep 22, 2024
1 parent 10ab803 commit f7b55f1
Show file tree
Hide file tree
Showing 10 changed files with 440 additions and 438 deletions.
4 changes: 4 additions & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import chalk from 'chalk';
import { Command, Option, CommanderError } from 'commander';

Expand All @@ -9,6 +10,9 @@ import init from './init.js';
import validate from './validate.js';
import { InvalidUserInputError, InvalidConfigError } from './errors.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const packageJson = readFileSync(
path.join(__dirname, '..', 'package.json'),
'utf-8',
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import semver from 'semver';
import chalk from 'chalk';
import findUp from 'find-up';
import inquirer from 'inquirer';
import { fileURLToPath } from 'url';
import { PluginManager, PluginManagerOptions } from 'live-plugin-manager';

import * as core from '@hypermod/core';
Expand All @@ -21,6 +22,9 @@ import {
import ModuleLoader from './utils/module-loader.js';
import { getConfigPrompt, getMultiConfigPrompt } from './prompt.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default async function main(
paths: string[],
flags: Partial<core.Flags>,
Expand Down
16 changes: 12 additions & 4 deletions packages/cli/src/utils/module-loader.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import path from 'path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';
import { installPackage } from '@antfu/install-pkg';

import { ModuleLoader } from '@hypermod/fetcher';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
* Register the TSX plugin to allow require TS(X) files.
*/
Expand All @@ -14,9 +18,13 @@ const ModuleLoader = (config: {
npmRegistryUrl?: string;
authToken?: string;
}): ModuleLoader => {
const getInfo = (packageName: string) => {
const entryPath = require.resolve(packageName);
const location = entryPath.split(packageName)[0] + packageName;
const getInfo = async (packageName: string) => {
// @ts-expect-error - TS doesn't know about import.meta
const entryPath = await import.meta.resolve(packageName);
const location = (entryPath.split(packageName)[0] + packageName).replace(
'file://',
'',
);
const pkgJsonRaw = fs.readFileSync(
path.join(location, 'package.json'),
'utf8',
Expand Down Expand Up @@ -44,7 +52,7 @@ const ModuleLoader = (config: {
],
});

const { pkgJson } = getInfo(packageName);
const { pkgJson } = await getInfo(packageName);

// Install whitelisted devDependencies
if (pkgJson?.hypermod?.dependencies) {
Expand Down
87 changes: 33 additions & 54 deletions packages/core/lib/Worker.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,47 @@
/* eslint-disable @typescript-eslint/no-var-requires */
'use strict';

const path = require('path');
const { EventEmitter } = require('events');
const async = require('neo-async');
const fs = require('graceful-fs');
const writeFileAtomic = require('write-file-atomic');
const { DEFAULT_EXTENSIONS } = require('@babel/core');
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'graceful-fs';
import { EventEmitter } from 'events';
import async from 'neo-async';
import writeFileAtomic from 'write-file-atomic';

const getParser = require('jscodeshift/src/getParser');
const jscodeshift = require('jscodeshift/src/core');
import getParser from 'jscodeshift/src/getParser.js';
import jscodeshift from 'jscodeshift/src/core.js';

let presetEnv;
try {
presetEnv = require('@babel/preset-env');
} catch (_) {}
const __filename = fileURLToPath(import.meta.url);

/**
* Register the TSX plugin to allow require TS(X) files.
*/
import { register } from 'tsx/esm/api';
register();

let emitter;
let finish;
let notify;
let transform;
let parserFromTransform;

if (module.parent) {
if (import.meta.url.replace('file://', '') !== process.argv[1]) {
emitter = new EventEmitter();
// @ts-expect-error
emitter.send = data => run(data);
finish = () => emitter.emit('disconnect');
notify = data => emitter.emit('message', data);

module.exports = args => {
setup(args[0], args[1]);
return emitter;
};
} else {
finish = () => setImmediate(() => process.disconnect());
notify = data => process.send(data);
process.on('message', data => run(data));
setup(process.argv[2], process.argv[3]);
await setup(process.argv[2], process.argv[3]);
}

// Used by `run-in-band` to run the worker in the same process
export default async function main(args) {
await setup(args[0], args[1]);
return emitter;
}

function prepareJscodeshift(options) {
Expand All @@ -59,59 +63,34 @@ function retrievePath(str) {
}

function getModule(mod) {
return mod.hasOwnProperty('default') ? mod.default : mod;
return Boolean(mod.default) ? mod.default : mod;
}

function setup(entryPath, babel) {
if (babel === 'babel') {
const presets = [];
if (presetEnv) {
presets.push([presetEnv.default, { targets: { node: true } }]);
}

presets.push(require('@babel/preset-typescript').default);

require('@babel/register')({
configFile: false,
babelrc: false,
presets,
plugins: [
require('@babel/plugin-proposal-class-properties').default,
require('@babel/plugin-proposal-nullish-coalescing-operator').default,
require('@babel/plugin-proposal-optional-chaining').default,
require('@babel/plugin-transform-modules-commonjs').default,
],
extensions: [...DEFAULT_EXTENSIONS, '.ts', '.tsx'],
// By default, babel register only compiles things inside the current working directory.
// https://github.com/babel/babel/blob/2a4f16236656178e84b05b8915aab9261c55782c/packages/babel-register/src/node.js#L140-L157
ignore: [
// Ignore parser related files
/@babel\/parser/,
/\/flow-parser\//,
/\/recast\//,
/\/ast-types\//,
],
});
}
async function getModuleName(path) {
const moduleName = retrievePath(path).split('node_modules/')[1];
const pkg = await import(moduleName);
return getModule(pkg);
}

async function setup(entryPath) {
const transformId = retrieveTransformId(entryPath);
const presetId = retrievePresetId(entryPath);

let transformPkg;
let transformModule;

if (transformId) {
transformPkg = getModule(require(path.resolve(retrievePath(entryPath))));
transformPkg = await getModuleName(entryPath);
transformModule = transformPkg.transforms[transformId];
}

if (presetId) {
transformPkg = getModule(require(path.resolve(retrievePath(entryPath))));
transformPkg = await getModuleName(entryPath);
transformModule = transformPkg.presets[presetId];
}

if (!transformId && !presetId) {
transformModule = require(path.resolve(entryPath));
transformModule = await import(path.resolve(entryPath));
}

transform = getModule(transformModule);
Expand Down
Loading

0 comments on commit f7b55f1

Please sign in to comment.