Skip to content

Commit

Permalink
style: added linter
Browse files Browse the repository at this point in the history
  • Loading branch information
steven-pribilinskiy committed Dec 28, 2023
1 parent 638e13a commit 6b0f812
Show file tree
Hide file tree
Showing 8 changed files with 6,164 additions and 363 deletions.
6,401 changes: 6,075 additions & 326 deletions package-lock.json

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
},
"scripts": {
"build": "tsc",
"lint": "eslint src/**/*.ts",
"test": "jest"
},
"dependencies": {
Expand All @@ -25,6 +26,7 @@
"mkdirp": "^2.1.6"
},
"devDependencies": {
"@cloudbeds/eslint-config": "^2.5.1",
"@types/download": "^8.0.2",
"@types/jest": "^29.5.2",
"@types/minimist": "^1.2.2",
Expand All @@ -37,5 +39,21 @@
"peerDependencies": {
"typescript": ">= 4.5.5",
"webpack": "^5.87.0"
},
"eslintConfig": {
"extends": "@cloudbeds/eslint-config",
"overrides": [
{
"files": [
"*.ts"
],
"rules": {
"@typescript-eslint/no-var-requires": "off",
"import/no-dynamic-require": "off",
"global-require": "off",
"no-console": "off"
}
}
]
}
}
32 changes: 19 additions & 13 deletions src/plugin.spec.ts → src/__tests__/plugin.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import webpack, { Compilation, Compiler } from 'webpack';
import webpack, {
Compilation, Compiler,
} from 'webpack';

import { downloadTypes } from './helpers/downloadTypes';
import { ModuleFederationTypesPlugin } from './plugin';
import { ModuleFederationPluginOptions, ModuleFederationTypesPluginOptions } from './types';
import { DEFAULT_DIR_DOWNLOADED_TYPES, DEFAULT_DIR_EMITTED_TYPES } from './constants';
import { downloadTypes } from '../helpers/downloadTypes';
import { ModuleFederationTypesPlugin } from '../plugin';
import {
ModuleFederationPluginOptions, ModuleFederationTypesPluginOptions,
} from '../types';
import {
DEFAULT_DIR_DOWNLOADED_TYPES, DEFAULT_DIR_EMITTED_TYPES,
} from '../constants';

jest.mock('./helpers/downloadTypes');
jest.mock('../helpers/downloadTypes');

const mockDownloadTypes = downloadTypes as jest.MockedFunction<typeof downloadTypes>;
const mockAfterEmit = jest.fn();
Expand All @@ -19,16 +25,16 @@ const mockLogger = {
} as Compilation['logger'];

function installPlugin(
moduleFederationPluginOptions: ModuleFederationPluginOptions = {},
typesPluginOptions?: ModuleFederationTypesPluginOptions
moduleFederationPluginOptions?: ModuleFederationPluginOptions,
typesPluginOptions?: ModuleFederationTypesPluginOptions,
): ModuleFederationTypesPlugin {
const pluginInstance = new ModuleFederationTypesPlugin(typesPluginOptions);

pluginInstance.apply({
getInfrastructureLogger: jest.fn().mockReturnValue(mockLogger) as Compiler['infrastructureLogger'],
options: {
plugins: [
new ModuleFederationPlugin(moduleFederationPluginOptions),
new ModuleFederationPlugin(moduleFederationPluginOptions || {}),
],
},
hooks: {
Expand All @@ -50,16 +56,16 @@ function installPlugin(
describe('ModuleFederationTypesPlugin', () => {
test('does nothing when options are not provided to the ModuleFederationPlugin', () => {
installPlugin();
expect(mockAfterEmit).not.toBeCalled();
expect(mockAfterEmit).not.toHaveBeenCalled();
});

test('remoteManifestUrls setting initiates download of remote entry manifest files on startup', () => {
const moduleFederationPluginOptions = {
name: 'mfeDashboard',
remotes: {
mfeOther: `mfeOther@[mfeOtherUrl]/remoteEntry.js`,
mfeOther: 'mfeOther@[mfeOtherUrl]/remoteEntry.js',
mfeTranslations: 'mfeTranslations@[mfeTranslationsUrl]/remoteEntry.js',
}
},
};
const typesPluginOptions: ModuleFederationTypesPluginOptions = {
remoteEntryUrls: {
Expand All @@ -68,7 +74,7 @@ describe('ModuleFederationTypesPlugin', () => {
remoteManifestUrls: {
mfeOther: 'https://example.com/some-mfe-remote-entry.json',
registry: 'https://example.com/remote-entries.json',
}
},
};
installPlugin(moduleFederationPluginOptions, typesPluginOptions);

Expand Down
9 changes: 6 additions & 3 deletions src/helpers/cloudbedsRemoteManifests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import {
CloudbedsCloudfrontDomain,
CLOUDBEDS_REMOTES_MANIFEST_FILE_NAME,
} from '../constants';
import { ModuleFederationTypesPluginOptions, RemoteManifestUrls } from '../types';
import {
ModuleFederationTypesPluginOptions, RemoteManifestUrls,
} from '../types';

import { isValidUrl } from './validation';

export function getRemoteManifestUrls(options?: ModuleFederationTypesPluginOptions): RemoteManifestUrls | undefined {
Expand All @@ -27,14 +30,14 @@ export function getRemoteManifestUrls(options?: ModuleFederationTypesPluginOptio
...(artifactsBaseUrl ? { artifactsBaseUrl } : null),
registry: `${manifestBaseUrl}/${CLOUDBEDS_REMOTES_MANIFEST_FILE_NAME}`,
...options?.remoteManifestUrls,
}
};
}

if (options?.remoteManifestUrl) {
return {
...options?.remoteManifestUrls,
registry: options?.remoteManifestUrl,
}
};
}

return options?.remoteManifestUrls;
Expand Down
42 changes: 31 additions & 11 deletions src/helpers/compileTypes.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';

import mkdirp from 'mkdirp';
import ts from 'typescript';

import { getLogger } from './logger';
import {
CompileTypesResult, FederationConfig,
} from '../types';

import { CompileTypesResult, FederationConfig } from '../types';
import { getLogger } from './logger';
import { getAllFilePaths } from './files';

export function getTSConfigCompilerOptions(tsconfigFileNameOrPath: string): ts.CompilerOptions {
Expand All @@ -27,7 +30,12 @@ export function reportCompileDiagnostic(diagnostic: ts.Diagnostic): void {
logger.log(' at', `${diagnostic.file!.fileName}:${line + 1}`, '\n');
}

export function compileTypes(tsconfigPath: string, exposedComponents: string[], outFile: string, dirGlobalTypes: string): CompileTypesResult {
export function compileTypes(
tsconfigPath: string,
exposedComponents: string[],
outFile: string,
dirGlobalTypes: string,
): CompileTypesResult {
const logger = getLogger();

const exposedFileNames = Object.values(exposedComponents);
Expand All @@ -48,13 +56,18 @@ export function compileTypes(tsconfigPath: string, exposedComponents: string[],
}

// Create a Program with an in-memory emit to avoid a case when wrong typings are downloaded
let fileContent: string = '';
let fileContent = '';
const host = ts.createCompilerHost(compilerOptions);
host.writeFile = (_fileName: string, contents: string) => fileContent = contents;
host.writeFile = (_fileName: string, contents: string) => {
fileContent = contents;
return contents;
};

// Including global type definitions from `src/@types` directory
if (fs.existsSync(dirGlobalTypes)) {
exposedFileNames.push(...getAllFilePaths(`./${dirGlobalTypes}`).filter(path => path.endsWith('.d.ts')));
exposedFileNames.push(
...getAllFilePaths(`./${dirGlobalTypes}`).filter(filePath => filePath.endsWith('.d.ts')),
);
}
logger.log('Including a set of root files in compilation', exposedFileNames);

Expand All @@ -73,7 +86,10 @@ export function includeTypesFromNodeModules(federationConfig: FederationConfig,
let typingsWithNpmPackages = typings;

const exposedNpmPackages = Object.entries(federationConfig.exposes)
.filter(([, path]) => !path.startsWith('.') || path.startsWith('./node_modules/'))
.filter(([, packagePath]) => (
!packagePath.startsWith('.')
|| packagePath.startsWith('./node_modules/')
))
.map(([exposedModuleKey, exposeTargetPath]) => [
exposedModuleKey.replace(/^\.\//, ''),
exposeTargetPath.replace('./node_modules/', ''),
Expand Down Expand Up @@ -112,14 +128,18 @@ export function rewritePathsWithExposedFederatedModules(

// Collect all instances of `declare module "..."`
let execResults: null | string[] = [];
while ((execResults = regexDeclareModule.exec(typings)) !== null) {
while (true) {
execResults = regexDeclareModule.exec(typings);
if (execResults === null) {
break;
}
declaredModulePaths.push(execResults[1]);
}

let typingsUpdated: string = typings;

// Replace and prefix paths by exposed remote names
declaredModulePaths.forEach((importPath) => {
declaredModulePaths.forEach(importPath => {
// Aliases are not included in the emitted declarations hence the need to use `endsWith`
const [exposedModuleKey, ...exposedModuleNameAliases] = Object.keys(federationConfig.exposes)
.filter(key => (
Expand All @@ -132,7 +152,7 @@ export function rewritePathsWithExposedFederatedModules(
? `${federationConfig.name}/${exposedModuleKey}`
: `#not-for-import/${federationConfig.name}/${importPath}`;

federatedModulePath = federatedModulePath.replace(/\/index$/, '')
federatedModulePath = federatedModulePath.replace(/\/index$/, '');

// language=TypeScript
const createAliasModule = (modulePath: string) => `
Expand Down
19 changes: 11 additions & 8 deletions src/helpers/downloadTypes.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import download from 'download';
import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';

import { RemoteManifest, RemoteManifestUrls, RemotesRegistryManifest, RemoteEntryUrls } from '../types';
import download from 'download';
import mkdirp from 'mkdirp';

import {
RemoteManifest, RemoteManifestUrls, RemotesRegistryManifest, RemoteEntryUrls,
} from '../types';

import { getLogger } from './logger';
import { toCamelCase } from './toCamelCase';
Expand Down Expand Up @@ -47,7 +50,7 @@ async function downloadRemoteEntryTypes(
if (remoteName !== remoteOriginalName) {
types = types.replace(
new RegExp(`declare module "${remoteOriginalName}(.*)"`, 'g'),
(_, $1) => `declare module "${remoteName}${$1}"`
(_, $1) => `declare module "${remoteName}${$1}"`,
);
}

Expand Down Expand Up @@ -82,15 +85,15 @@ export async function downloadRemoteEntryURLsFromManifests(remoteManifestUrls?:
const { artifactsBaseUrl, ...manifestUrls } = remoteManifestUrls;

const remoteManifests = (await Promise.all(
Object.values(manifestUrls).map(url => downloadRemoteEntryManifest(url))
Object.values(manifestUrls).map(url => downloadRemoteEntryManifest(url)),
)) as (RemoteManifest | RemotesRegistryManifest | RemoteEntryUrls)[];

// Combine remote entry URLs from all manifests
Object.keys(manifestUrls).forEach((remoteName, index) => {
if (remoteName === 'registry') {
const remotesManifest = remoteManifests[index];
if (Array.isArray(remotesManifest)) {
(remoteManifests[index] as RemotesRegistryManifest).forEach((remoteManifest) => {
(remoteManifests[index] as RemotesRegistryManifest).forEach(remoteManifest => {
remoteEntryURLs[remoteManifest.scope] = remoteManifest.url;
});
} else {
Expand Down Expand Up @@ -125,7 +128,7 @@ export async function downloadTypes(
};
} catch (err) {
logger.warn('Failed to load remote manifest file: ', (err as Dict)?.url);
logger.log(err)
logger.log(err);
return;
}

Expand All @@ -144,7 +147,7 @@ export async function downloadTypes(
remoteLocation,
`${remoteEntryBaseUrl}/${dirEmittedTypes}/index.d.ts`,
dirDownloadedTypes,
)
);

promises.push(promiseDownload);
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function getAllFilePaths(dirPath: string, arrayOfFiles: string[] = []): s
} else {
arrayOfFiles.push(`${dirPath}/${file}`);
}
})
});

return arrayOfFiles;
}
4 changes: 3 additions & 1 deletion src/helpers/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Compilation, Compiler } from 'webpack';
import {
Compilation, Compiler,
} from 'webpack';

let loggerInstance: Compilation['logger'];

Expand Down

0 comments on commit 6b0f812

Please sign in to comment.