Skip to content

Commit

Permalink
Fix esm related errors
Browse files Browse the repository at this point in the history
  • Loading branch information
vilicvane committed Oct 26, 2023
1 parent b8d0057 commit b78d346
Show file tree
Hide file tree
Showing 18 changed files with 92 additions and 61 deletions.
3 changes: 1 addition & 2 deletions .magicspace/boilerplate.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@
"name": "library"
},
{
"name": "test",
"noEmit": true
"name": "test"
}
]
},
Expand Down
3 changes: 3 additions & 0 deletions packages/boilerplate-url-resolver/src/program/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node

import type * as HTTP from 'http';
import {createRequire} from 'module';
import * as Path from 'path';

import {main} from 'main-function';
Expand All @@ -15,6 +16,8 @@ const agent = HTTP_PROXY
? (new ProxyAgent(HTTP_PROXY) as unknown as HTTP.Agent)
: undefined;

const require = createRequire(import.meta.url);

main(async () => {
const {
url,
Expand Down
3 changes: 2 additions & 1 deletion packages/boilerplate-url/src/library/boilerplate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Path from 'path';
import {fileURLToPath} from 'url';

import {boilerplate, composables, x} from '@magicspace/core';

Expand All @@ -14,7 +15,7 @@ export default boilerplate<Options>(async options => {
return {
composables: await composables(
{
root: Path.join(__dirname, '../composables'),
root: Path.join(fileURLToPath(import.meta.url), '../../composables'),
pattern: '*.js',
},
options,
Expand Down
3 changes: 2 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
},
"dependencies": {
"@magicspace/core": "^0.3.3",
"@types/global-agent": "^2.1.2",
"chalk": "^5.3.0",
"clime": "^0.5.14",
"clime": "^0.5.16",
"fs-extra": "^11.1.0",
"global-agent": "^3.0.0",
"prompts": "^2.4.2",
Expand Down
10 changes: 5 additions & 5 deletions packages/cli/src/program/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
option,
param,
} from 'clime';
import {existsSync, outputFile} from 'fs-extra';
import FSExtra from 'fs-extra';
import prompts from 'prompts';

import {CONFIG_SCHEMA_FILE_NAME} from '../@constants.js';
Expand Down Expand Up @@ -45,13 +45,13 @@ export default class extends Command {
): Promise<string | void> {
const magicspaceDir = Path.resolve(DEFAULT_MAGICSPACE_DIRNAME);

if (existsSync(magicspaceDir)) {
if (FSExtra.existsSync(magicspaceDir)) {
throw new ExpectedError(
`Folder ${JSON.stringify(DEFAULT_MAGICSPACE_DIRNAME)} already exists`,
);
}

const {examples, Options} = resolveBoilerplateModule(
const {examples, Options} = await resolveBoilerplateModule(
boilerplate,
process.cwd(),
);
Expand Down Expand Up @@ -91,7 +91,7 @@ export default class extends Command {
)
: boilerplate;

await outputFile(
await FSExtra.outputFile(
configFilePath,
`${JSON.stringify(
{
Expand All @@ -112,7 +112,7 @@ export default class extends Command {
CONFIG_SCHEMA_FILE_NAME,
);

await outputFile(
await FSExtra.outputFile(
configSchemaPath,
JSON.stringify(buildConfigSchema(Options), undefined, 2),
);
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/program/commands/default.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import {createRequire} from 'module';

import type {HelpInfo, SubcommandDefinition} from 'clime';
import {Command, Options, command, metadata, option} from 'clime';

const require = createRequire(import.meta.url);

export const subcommands: SubcommandDefinition[] = [
{name: 'create'},
{name: 'init'},
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/program/commands/update-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
resolveMagicspaceBoilerplateConfig,
} from '@magicspace/core';
import {Command, ExpectedError, command, metadata, param} from 'clime';
import * as FSExtra from 'fs-extra';
import FSExtra from 'fs-extra';

import {CommonOptions} from '../@command.js';
import {CONFIG_SCHEMA_FILE_NAME} from '../@constants.js';
Expand Down
16 changes: 10 additions & 6 deletions packages/cli/src/program/main.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
#!/usr/bin/env node

import * as Path from 'path';

process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE = '';

import 'global-agent/bootstrap';
import {fileURLToPath} from 'url';

import {CLI, Shim} from 'clime';
import {bootstrap} from 'global-agent';

bootstrap({
environmentVariableNamespace: '',
});

const cli = new CLI('magicspace', Path.join(__dirname, 'commands'));
const cli = new CLI(
'magicspace',
fileURLToPath(new URL('commands', import.meta.url)),
);

const shim = new Shim(cli);

Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/library/@constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as Path from 'path';
import {fileURLToPath} from 'url';

export const PACKAGE_DIR = Path.join(__dirname, '../..');
export const PACKAGE_DIR = Path.join(
fileURLToPath(import.meta.url),
'../../..',
);

export const TEMP_MAGIC_REPOSITORY_DIR_PREFIX = 'magicspace';

Expand Down
24 changes: 18 additions & 6 deletions packages/core/src/library/@utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import * as ChildProcess from 'child_process';
import {createRequire} from 'module';
import * as Path from 'path';

import {existsSync, moveSync, readdirSync, rmdirSync, statSync} from 'fs-extra';
import FSExtra from 'fs-extra';
import npmPath from 'npm-path';
import {__importDefault} from 'tslib';

const require = createRequire(import.meta.url);

export class SpawnSyncFailure {
constructor(
Expand Down Expand Up @@ -81,9 +85,9 @@ export async function npmRun(
* @returns `true` if content completely moved, otherwise `false`.
*/
export function conservativelyMove(from: string, to: string): boolean {
if (existsSync(to)) {
if (statSync(to).isDirectory()) {
const names = readdirSync(from);
if (FSExtra.existsSync(to)) {
if (FSExtra.statSync(to).isDirectory()) {
const names = FSExtra.readdirSync(from);

const completelyMoved = names
.map(name =>
Expand All @@ -92,7 +96,7 @@ export function conservativelyMove(from: string, to: string): boolean {
.every(result => result);

if (completelyMoved) {
rmdirSync(from);
FSExtra.rmdirSync(from);
return true;
} else {
return false;
Expand All @@ -101,7 +105,7 @@ export function conservativelyMove(from: string, to: string): boolean {
return false;
}
} else if (Path.relative(from, to).startsWith(`..${Path.sep}`)) {
moveSync(from, to);
FSExtra.moveSync(from, to);
return true;
} else {
return false;
Expand All @@ -111,3 +115,11 @@ export function conservativelyMove(from: string, to: string): boolean {
export function removePathExtension(path: string): string {
return path.slice(0, -Path.extname(path).length);
}

export async function requireOrImport(path: string): Promise<any> {
try {
return __importDefault(require(path));
} catch {
return import(path);
}
}
4 changes: 2 additions & 2 deletions packages/core/src/library/boilerplate/composables.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as Path from 'path';

import FastGlob from 'fast-glob';
import {__importDefault} from 'tslib';

import {requireOrImport} from '../@utils.js';
import type {Composable, FileGenerics} from '../file/index.js';

import type {ComposableModuleDefault} from './composable.js';
Expand Down Expand Up @@ -62,7 +62,7 @@ export async function composables(
const allComposables: BoilerplateComposable[] = [];

for (const composableModulePath of pathSet) {
let composables = __importDefault(require(composableModulePath))
let composables = (await requireOrImport(composableModulePath))
.default as ComposableModuleDefault;

if (typeof composables === 'function') {
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/library/composables.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as FS from 'fs';
import * as Path from 'path';

import {sync as fastGlobSync} from 'fast-glob';
import FastGlob from 'fast-glob';
import * as Handlebars from 'handlebars';

import {removePathExtension} from './@utils.js';
Expand Down Expand Up @@ -150,7 +150,7 @@ export function copy(
patterns = [patterns];
}

const paths = fastGlobSync(patterns, {
const paths = FastGlob.sync(patterns, {
cwd: dir,
dot: true,
onlyFiles: true,
Expand Down
30 changes: 14 additions & 16 deletions packages/core/src/library/config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import {readFile} from 'fs/promises';
import {createRequire} from 'module';
import * as Path from 'path';
import {fileURLToPath} from 'url';

import {create as enhancedResolveCreate} from 'enhanced-resolve';
import EnhancedResolve from 'enhanced-resolve';
import _ from 'lodash';
import stripJSONComments from 'strip-json-comments';
import {__importDefault} from 'tslib';
import type {JSONSchema} from 'x-value';
import * as x from 'x-value';

import {requireOrImport} from './@utils.js';
import type {
Boilerplate,
BoilerplateComposable,
Expand All @@ -17,7 +19,9 @@ import type {

const hasOwnProperty = Object.prototype.hasOwnProperty;

const resolve = enhancedResolveCreate.sync({
const require = createRequire(import.meta.url);

const resolve = EnhancedResolve.create.sync({
conditionNames: ['node', 'require'],
});

Expand Down Expand Up @@ -64,23 +68,19 @@ export async function resolveMagicspaceBoilerplateConfig(
const jsonc = await readFile(path, 'utf8');
module = JSON.parse(stripJSONComments(jsonc));
} else {
try {
module = __importDefault(require(path)).default;
} catch {
module = (await import(path)).default;
}
module = (await requireOrImport(path)).default;
}

return {path, module};
}

export function resolveBoilerplateModule(
export async function resolveBoilerplateModule(
specifier: string,
dir: string,
): BoilerplateModule {
): Promise<BoilerplateModule> {
const dirs = [
dir,
__dirname, // fallback to magicspace installation location.
Path.dirname(fileURLToPath(import.meta.url)), // fallback to magicspace installation location.
];

let boilerplateModulePath: string | false | undefined;
Expand All @@ -102,7 +102,7 @@ export function resolveBoilerplateModule(
);
}

return __importDefault(require(boilerplateModulePath));
return await requireOrImport(boilerplateModulePath);
}

export async function resolveMagicspaceConfig(
Expand All @@ -123,10 +123,8 @@ export async function resolveMagicspaceConfig(

const {boilerplate: boilerplateSpecifier, options} = config;

const {default: boilerplateBuilder, Options} = resolveBoilerplateModule(
boilerplateSpecifier,
configDir,
);
const {default: boilerplateBuilder, Options} =
await resolveBoilerplateModule(boilerplateSpecifier, configDir);

if (Options) {
Options.asserts(options);
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/library/file/file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as FSExtra from 'fs-extra';
import FSExtra from 'fs-extra';

import type {BoilerplateComposable} from '../boilerplate/index.js';

Expand Down
14 changes: 7 additions & 7 deletions packages/core/src/library/space/@git.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as Path from 'path';

import {existsSync, outputFileSync, readFileSync, removeSync} from 'fs-extra';
import FSExtra from 'fs-extra';
import _ from 'lodash';

import {
Expand Down Expand Up @@ -53,7 +53,7 @@ export class ProjectGit extends Git {
isMerging(): boolean {
const mergeHeadFilePath = Path.join(this.dir, '.git/MERGE_HEAD');

return existsSync(mergeHeadFilePath);
return FSExtra.existsSync(mergeHeadFilePath);
}

makeInitialCommit(): void {
Expand Down Expand Up @@ -150,7 +150,7 @@ export class ProjectGit extends Git {
this.logger?.stdout(error.stdout);
}

outputFileSync(
FSExtra.outputFileSync(
Path.join(this.dir, '.git/MERGE_MSG'),
type === 'initialize'
? MAGICSPACE_INITIALIZE_MERGE_MESSAGE
Expand All @@ -161,11 +161,11 @@ export class ProjectGit extends Git {
listPossibleDirectoryRenames(): Rename[] {
const mergeHeadFilePath = Path.join(this.dir, '.git/MERGE_HEAD');

if (!existsSync(mergeHeadFilePath)) {
if (!FSExtra.existsSync(mergeHeadFilePath)) {
throw new Error('Expecting .git/MERGE_HEAD to be present');
}

const mergeHead = readFileSync(mergeHeadFilePath, 'utf8').trim();
const mergeHead = FSExtra.readFileSync(mergeHeadFilePath, 'utf8').trim();

const diff = spawnSync(this.dir, 'git', [
'show',
Expand Down Expand Up @@ -261,14 +261,14 @@ export class ProjectGit extends Git {
.filter((rename): rename is Rename => !!rename);

return _.uniqBy(renames, ({from, to}) => JSON.stringify({from, to})).filter(
rename => existsSync(rename.from),
rename => FSExtra.existsSync(rename.from),
);
}
}

export class TempGit extends Git {
cloneProjectRepositoryWithoutCheckout(projectDir: string): void {
removeSync(this.dir);
FSExtra.removeSync(this.dir);

spawnSync(projectDir, 'git', [
'clone',
Expand Down
Loading

0 comments on commit b78d346

Please sign in to comment.