Skip to content

Commit

Permalink
feat: stricter file loader + enhanced cjs/esm build
Browse files Browse the repository at this point in the history
  • Loading branch information
tada5hi committed Jan 14, 2023
1 parent 2e5ec68 commit 85b7e70
Show file tree
Hide file tree
Showing 16 changed files with 501 additions and 231 deletions.
289 changes: 283 additions & 6 deletions package-lock.json

Large diffs are not rendered by default.

17 changes: 14 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,16 @@
"type": "git",
"url": "https://github.com/tada5hi/locter.git"
},
"main": "dist/index.cjs.js",
"module": "dist/index.esm.js",
"types": "dist/types/index.d.ts",
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"require": "./dist/index.cjs",
"import": "./dist/index.mjs"
}
},
"files": [
"dist/"
],
Expand Down Expand Up @@ -46,13 +53,15 @@
"@commitlint/cz-commitlint": "^17.4.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-terser": "^0.3.0",
"@semantic-release/changelog": "^6.0.2",
"@semantic-release/commit-analyzer": "^9.0.2",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^8.0.7",
"@semantic-release/npm": "^9.0.1",
"@semantic-release/release-notes-generator": "^10.0.3",
"@tada5hi/eslint-config-typescript": "^1.1.0",
"@tada5hi/tsconfig": "^0.1.0",
"@types/glob": "^8.0.0",
"@types/is-file-esm": "^1.0.0",
"@types/jest": "^27.5.0",
Expand All @@ -64,6 +73,8 @@
"eslint": "^8.31.0",
"husky": "^8.0.3",
"jest": "^27.5.1",
"magic-string": "^0.27.0",
"mlly": "^1.1.0",
"rimraf": "^3.0.2",
"rollup": "^3.10.0",
"semantic-release": "^19.0.5",
Expand Down
79 changes: 47 additions & 32 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,42 @@

import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import terser from '@rollup/plugin-terser';
import pkg from './package.json' assert { type: 'json' };
import { findStaticImports } from 'mlly';
import MagicString from 'magic-string';

const extensions = [
'.js', '.jsx', '.ts', '.tsx',
];

const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/;

const CJSShim = `
import __cjs_url__ from 'url';
import __cjs_path__ from 'path';
import __cjs_mod__ from 'module';
const __filename = __cjs_url__.fileURLToPath(import.meta.url);
const __dirname = __cjs_path__.dirname(__filename);
const require = __cjs_mod__.createRequire(import.meta.url);
`;

function transformCJSToESM(code) {
if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) {
return null;
}

const lastESMImport = findStaticImports(code).pop();
const indexToAppend = lastESMImport ? lastESMImport.end : 0;
const s = new MagicString(code);
s.appendRight(indexToAppend, CJSShim);

return {
code: s.toString(),
map: s.generateMap(),
};
}

export default [
{
input: './src/index.ts',
Expand All @@ -35,46 +65,31 @@ export default [
include: [
'src/**/*',
],
})
}),

{
renderChunk(code, _chunk, opts) {
if (opts.format === "es") {
return transformCJSToESM(code);
}

return null;
}
},

terser()
],
output: [
{
file: pkg.module,
format: 'esm',
sourcemap: true
},
],
},
{
input: './src/index.ts',

// Specify here external modules which you don't want to include in your bundle (for instance: 'lodash', 'moment' etc.)
// https://rollupjs.org/guide/en/#external
external: [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
],

plugins: [
// Allows node_modules resolution
resolve({ extensions }),

// Compile TypeScript/JavaScript files
babel({
extensions,
babelHelpers: 'bundled',
include: [
'src/**/*',
],
plugins: [
"dynamic-import-node"
]
})
],
output: [
{
file: pkg.main,
format: 'cjs'
format: 'cjs',
sourcemap: true
}
],
},
}
];
8 changes: 4 additions & 4 deletions src/loader/file-type/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
* view the LICENSE file that was distributed with this source code.
*/

import fs from 'fs';
import path from 'path';
import fs from 'node:fs';
import path from 'node:path';
import { LocatorInfo } from '../../locator';
import { handleFileLoadError } from '../../utils';
import { buildLoaderFilePath } from '../utils';

export async function loadJsonFile(input: LocatorInfo | string) : Promise<unknown | undefined> {
export async function loadJsonFile(input: LocatorInfo | string) : Promise<unknown> {
let filePath : string;

if (typeof input === 'string') {
Expand All @@ -28,7 +28,7 @@ export async function loadJsonFile(input: LocatorInfo | string) : Promise<unknow
}
}

export function loadJsonFileSync(input: LocatorInfo | string) : unknown | undefined {
export function loadJsonFileSync(input: LocatorInfo | string) : unknown {
let filePath : string;

if (typeof input === 'string') {
Expand Down
20 changes: 8 additions & 12 deletions src/loader/file-type/script/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { BaseError } from 'ebec';
import { pathToFileURL } from 'url';
import { pathToFileURL } from 'node:url';
import { LocatorInfo, pathToLocatorInfo } from '../../../locator';
import {
handleFileLoadError, hasStringProperty, isObject,
Expand All @@ -18,7 +18,7 @@ import { getExportItem } from './utils';
export async function loadScriptFile(
data: LocatorInfo | string,
options?: ScriptFileLoadOptions,
) : Promise<unknown | undefined> {
) : Promise<unknown> {
let locatorInfo : LocatorInfo;

if (typeof data === 'string') {
Expand Down Expand Up @@ -83,16 +83,12 @@ export async function loadScriptFile(
export async function loadScriptFileExport(
data: LocatorInfo | string,
filterFn?: LoaderFilterFn,
) : Promise<ScriptFileExportItem | undefined> {
try {
const output = await loadScriptFile(data);
if (typeof output === 'object') {
return getExportItem(output, filterFn);
}
) : Promise<ScriptFileExportItem> {
const output = await loadScriptFile(data);

return undefined;
} catch (e) {
/* istanbul ignore next */
return handleFileLoadError(e);
if (typeof output === 'object' && !!output) {
return getExportItem(output, filterFn);
}

throw new BaseError('Cannot extract specific module export');
}
26 changes: 9 additions & 17 deletions src/loader/file-type/script/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { BaseError } from 'ebec';
import { LoaderFilterFn, ScriptFileExportItem, ScriptFileLoadOptions } from './type';
import { getExportItem } from './utils';
import { LocatorInfo, isLocatorInfo, pathToLocatorInfo } from '../../../locator';
import { LocatorInfo, pathToLocatorInfo } from '../../../locator';
import { buildLoaderFilePath } from '../../utils';
import {
handleFileLoadError, hasStringProperty, isObject,
Expand All @@ -17,7 +17,7 @@ import {
export function loadScriptFileSync(
data: LocatorInfo | string,
options?: ScriptFileLoadOptions,
) : unknown | undefined {
) : unknown {
let locatorInfo : LocatorInfo;

if (typeof data === 'string') {
Expand All @@ -31,7 +31,7 @@ export function loadScriptFileSync(
const filePath = buildLoaderFilePath(locatorInfo, options.withExtension);

try {
// eslint-disable-next-line @typescript-eslint/no-var-requires, global-require,import/no-dynamic-require
// eslint-disable-next-line global-require,import/no-dynamic-require
return require(filePath);
} catch (e) {
/* istanbul ignore next */
Expand Down Expand Up @@ -66,20 +66,12 @@ export function loadScriptFileSync(
export function loadScriptFileExportSync(
data: LocatorInfo | string,
filterFn?: LoaderFilterFn,
) : ScriptFileExportItem | undefined {
const filePath = isLocatorInfo(data) ?
buildLoaderFilePath(data) :
data;
) : ScriptFileExportItem {
const output = loadScriptFileSync(data);

try {
const data = loadScriptFileSync(filePath);

if (typeof data === 'object') {
return getExportItem(data, filterFn);
}

return undefined;
} catch (e) {
return handleFileLoadError(e);
if (typeof output === 'object' && !!output) {
return getExportItem(output, filterFn);
}

throw new BaseError('Cannot extract specific module export');
}
24 changes: 12 additions & 12 deletions src/loader/file-type/script/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,30 @@
* view the LICENSE file that was distributed with this source code.
*/

import { BaseError } from 'ebec';
import { hasOwnProperty } from '../../../utils';
import { LoaderFilterFn, ScriptFileExportItem } from './type';

export function getExportItem(
data: Record<string, any>,
filterFn: LoaderFilterFn,
) : ScriptFileExportItem | undefined {
filterFn?: LoaderFilterFn,
) : ScriptFileExportItem {
if (filterFn) {
const keys = Object.keys(data);
for (let i = 0; i < keys.length; i++) {
if (filterFn(keys[i], data[keys[i]])) {
if (filterFn(keys[i] as string, data[keys[i] as string])) {
return {
key: keys[i],
value: data[keys[i]],
key: keys[i] as string,
value: data[keys[i] as string],
};
}
}
} else {
return {
key: 'default',
value: hasOwnProperty(data, 'default') ? data.default : data,
};

throw new BaseError('Cannot find specific module export.');
}

/* istanbul ignore next */
return undefined;
return {
key: 'default',
value: hasOwnProperty(data, 'default') ? data.default : data,
};
}
12 changes: 2 additions & 10 deletions src/loader/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,7 @@ import {
loadScriptFileSync,
} from './file-type';

export async function loadFile(input: LocatorInfo | string) : Promise<unknown | undefined> {
if (!input) {
return undefined;
}

export async function loadFile(input: LocatorInfo | string) : Promise<unknown> {
let info : LocatorInfo;
if (typeof input === 'string') {
info = pathToLocatorInfo(input);
Expand All @@ -32,11 +28,7 @@ export async function loadFile(input: LocatorInfo | string) : Promise<unknown |
return loadScriptFile(info);
}

export function loadFileSync(input: LocatorInfo | string) : unknown | undefined {
if (!input) {
return undefined;
}

export function loadFileSync(input: LocatorInfo | string) : unknown {
let info : LocatorInfo;
if (typeof input === 'string') {
info = pathToLocatorInfo(input);
Expand Down
2 changes: 1 addition & 1 deletion src/loader/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* view the LICENSE file that was distributed with this source code.
*/

import path from 'path';
import path from 'node:path';
import { LocatorInfo } from '../locator';

export function buildLoaderFilePath(info: LocatorInfo, withExtension?: boolean) {
Expand Down
18 changes: 9 additions & 9 deletions src/locator/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* view the LICENSE file that was distributed with this source code.
*/

import { glob } from 'glob';
import { promisify } from 'util';
import glob from 'glob';
import { promisify } from 'node:util';
import { LocatorInfo, LocatorOptions } from './type';
import { buildLocatorOptions, pathToLocatorInfo } from './utils';

Expand All @@ -25,16 +25,16 @@ export async function locateFiles(
const items : LocatorInfo[] = [];

for (let i = 0; i < patterns.length; i++) {
for (let j = 0; j < options.path.length; j++) {
const files = await globAsync(patterns[i], {
for (let j = 0; j < (options as LocatorOptions).path.length; j++) {
const files = await globAsync(patterns[i] as string, {
absolute: true,
cwd: options.path[j],
cwd: (options as LocatorOptions).path[j],
nodir: true,
ignore: options.ignore,
});

for (let k = 0; k < files.length; k++) {
items.push(pathToLocatorInfo(files[k], true));
items.push(pathToLocatorInfo(files[k] as string, true));
}
}
}
Expand All @@ -53,10 +53,10 @@ export async function locateFile(
[pattern];

for (let i = 0; i < patterns.length; i++) {
for (let j = 0; j < options.path.length; j++) {
const files = await globAsync(patterns[i], {
for (let j = 0; j < (options as LocatorOptions).path.length; j++) {
const files = await globAsync(patterns[i] as string, {
absolute: true,
cwd: options.path[j],
cwd: (options as LocatorOptions).path[j],
nodir: true,
ignore: options.ignore,
});
Expand Down
Loading

0 comments on commit 85b7e70

Please sign in to comment.