Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support path alias for webpack and babel #9205

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/osd-babel-preset/node_preset.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
* under the License.
*/

const path = require('path');

module.exports = (_, options = {}) => {
return {
presets: [
Expand Down Expand Up @@ -60,5 +62,17 @@ module.exports = (_, options = {}) => {
],
require('./common_preset'),
],
plugins: [
[
require.resolve('babel-plugin-module-resolver'),
{
root: [path.resolve(__dirname, '../..')],
alias: {
'opensearch-dashboards/server': './src/core/server',
'opensearch-dashboards/public': './src/core/public',
},
},
],
],
};
};
1 change: 1 addition & 0 deletions packages/osd-babel-preset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@babel/preset-react": "^7.22.9",
"@babel/preset-typescript": "^7.22.9",
"babel-plugin-add-module-exports": "^1.0.4",
"babel-plugin-module-resolver": "^5.0.1",
"babel-plugin-styled-components": "^2.0.2",
"babel-plugin-transform-react-remove-prop-types": "^0.4.24",
"browserslist": "^4.21.10",
Expand Down
102 changes: 21 additions & 81 deletions packages/osd-optimizer/src/worker/bundle_refs_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
*/

import Path from 'path';
import Fs from 'fs';

import webpack from 'webpack';

Expand All @@ -29,20 +28,6 @@ import { BundleRefModule } from './bundle_ref_module';

const RESOLVE_EXTENSIONS = ['.js', '.ts', '.tsx'];

function safeStat(path: string): Promise<Fs.Stats | undefined> {
return new Promise((resolve, reject) => {
Fs.stat(path, (error, stat) => {
if (error?.code === 'ENOENT') {
resolve(undefined);
} else if (error) {
reject(error);
} else {
resolve(stat);
}
});
});
}

interface RequestData {
context: string;
dependencies: Array<{ request: string }>;
Expand Down Expand Up @@ -80,7 +65,7 @@ export class BundleRefsPlugin {
const context = data.context;
const dep = data.dependencies[0];

this.maybeReplaceImport(context, dep.request).then(
this.maybeReplaceImport(context, dep.request, compiler).then(
(module) => {
if (!module) {
wrappedFactory(data, callback);
Expand Down Expand Up @@ -134,64 +119,17 @@ export class BundleRefsPlugin {
});
}

private cachedResolveRefEntry(ref: BundleRef) {
const cached = this.resolvedRefEntryCache.get(ref);

if (cached) {
return cached;
}

const absoluteRequest = Path.resolve(ref.contextDir, ref.entry);
const promise = this.cachedResolveRequest(absoluteRequest).then((resolved) => {
if (!resolved) {
throw new Error(`Unable to resolve request [${ref.entry}] relative to [${ref.contextDir}]`);
}

return resolved;
});
this.resolvedRefEntryCache.set(ref, promise);
return promise;
}

private cachedResolveRequest(absoluteRequest: string) {
const cached = this.resolvedRequestCache.get(absoluteRequest);

if (cached) {
return cached;
}

const promise = this.resolveRequest(absoluteRequest);
this.resolvedRequestCache.set(absoluteRequest, promise);
return promise;
}

private async resolveRequest(absoluteRequest: string) {
const stats = await safeStat(absoluteRequest);
if (stats && stats.isFile()) {
return absoluteRequest;
}

// look for an index file in directories
if (stats?.isDirectory()) {
for (const ext of RESOLVE_EXTENSIONS) {
const indexPath = Path.resolve(absoluteRequest, `index${ext}`);
const indexStats = await safeStat(indexPath);
if (indexStats?.isFile()) {
return indexPath;
private async resolve(request: string, startPath: string, compiler: webpack.Compiler) {
const resolver = compiler.resolverFactory.get('normal');
return new Promise<string | undefined>((resolve, reject) => {
resolver.resolve({}, startPath, request, {}, (err: unknown | null, resolvedPath: string) => {
if (err) {
reject(err);
} else {
resolve(resolvedPath);
}
}
}

// look for a file with one of the supported extensions
for (const ext of RESOLVE_EXTENSIONS) {
const filePath = `${absoluteRequest}${ext}`;
const fileStats = await safeStat(filePath);
if (fileStats?.isFile()) {
return filePath;
}
}

return;
});
});
}

/**
Expand All @@ -200,9 +138,12 @@ export class BundleRefsPlugin {
* then an error is thrown. If the request does not resolve to a bundleRef then
* undefined is returned. Otherwise it returns the referenced bundleRef.
*/
private async maybeReplaceImport(context: string, request: string) {
// ignore imports that have loaders defined or are not relative seeming
if (request.includes('!') || !request.startsWith('.')) {
private async maybeReplaceImport(context: string, request: string, compiler: webpack.Compiler) {
const alias = Object.keys(compiler.options.resolve?.alias ?? {});
const isAliasRequest = alias.some((a) => request.startsWith(a));

// For non-alias import path, ignore imports that have loaders defined or are not relative seeming
if (!isAliasRequest && (request.includes('!') || !request.startsWith('.'))) {
return;
}

Expand All @@ -211,13 +152,12 @@ export class BundleRefsPlugin {
return;
}

const absoluteRequest = Path.resolve(context, request);
if (absoluteRequest.startsWith(this.ignorePrefix)) {
const resolved = await this.resolve(request, context, compiler);
if (!resolved) {
return;
}

const resolved = await this.cachedResolveRequest(absoluteRequest);
if (!resolved) {
if (resolved.startsWith(this.ignorePrefix)) {
return;
}

Expand All @@ -228,7 +168,7 @@ export class BundleRefsPlugin {
}

for (const ref of possibleRefs) {
const resolvedEntry = await this.cachedResolveRefEntry(ref);
const resolvedEntry = await this.resolve(`./${ref.entry}`, ref.contextDir, compiler);
if (resolved !== resolvedEntry) {
continue;
}
Expand Down
1 change: 1 addition & 0 deletions packages/osd-optimizer/src/worker/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,7 @@ export function getWebpackConfig(bundle: Bundle, bundleRefs: BundleRefs, worker:
mainFields: ['browser', 'main'],
alias: {
core_app_image_assets: Path.resolve(worker.repoRoot, 'src/core/public/core_app/images'),
'opensearch-dashboards/public': Path.resolve(worker.repoRoot, 'src/core/public'),
},
},

Expand Down
8 changes: 6 additions & 2 deletions src/plugins/workspace/public/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@
import { BehaviorSubject, Observable, Subscriber } from 'rxjs';
import { waitFor } from '@testing-library/dom';
import { first } from 'rxjs/operators';
import { applicationServiceMock, chromeServiceMock, coreMock } from '../../../core/public/mocks';
import {
applicationServiceMock,
chromeServiceMock,
coreMock,
} from 'opensearch-dashboards/public/mocks';
import {
ChromeBreadcrumb,
NavGroupStatus,
DEFAULT_NAV_GROUPS,
AppNavLinkStatus,
WorkspaceAvailability,
AppStatus,
} from '../../../core/public';
} from 'opensearch-dashboards/public';
import { WORKSPACE_FATAL_ERROR_APP_ID, WORKSPACE_DETAIL_APP_ID } from '../common/constants';
import { savedObjectsManagementPluginMock } from '../../saved_objects_management/public/mocks';
import { managementPluginMock } from '../../management/public/mocks';
Expand Down
4 changes: 2 additions & 2 deletions src/plugins/workspace/public/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import {
DEFAULT_NAV_GROUPS,
NavGroupType,
ALL_USE_CASE_ID,
} from '../../../core/public';
} from 'opensearch-dashboards/public';
import { getWorkspaceIdFromUrl } from 'opensearch-dashboards/public/utils';
import {
WORKSPACE_FATAL_ERROR_APP_ID,
WORKSPACE_DETAIL_APP_ID,
Expand All @@ -32,7 +33,6 @@ import {
WORKSPACE_NAVIGATION_APP_ID,
WORKSPACE_COLLABORATORS_APP_ID,
} from '../common/constants';
import { getWorkspaceIdFromUrl } from '../../../core/public/utils';
import { Services, WorkspaceUseCase, WorkspacePluginSetup } from './types';
import { WorkspaceClient } from './workspace_client';
import { SavedObjectsManagementPluginSetup } from '../../../plugins/saved_objects_management/public';
Expand Down
10 changes: 7 additions & 3 deletions src/plugins/workspace/server/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@
*/

import { OnPostAuthHandler, OnPreRoutingHandler } from 'src/core/server';
import { coreMock, httpServerMock, uiSettingsServiceMock } from '../../../core/server/mocks';
import {
coreMock,
httpServerMock,
uiSettingsServiceMock,
} from 'opensearch-dashboards/server/mocks';
import { WorkspacePlugin, WorkspacePluginDependencies } from './plugin';
import {
getACLAuditor,
getClientCallAuditor,
getWorkspaceState,
updateWorkspaceState,
} from '../../../core/server/utils';
import * as serverUtils from '../../../core/server/utils/auth_info';
} from 'opensearch-dashboards/server/utils';
import * as serverUtils from 'opensearch-dashboards/server/utils/auth_info';
import { SavedObjectsPermissionControl } from './permission_control/client';
import { DataSourcePluginSetup } from '../../data_source/server';
import { DataSourceError } from '../../data_source/common/data_sources';
Expand Down
24 changes: 12 additions & 12 deletions src/plugins/workspace/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,18 @@ import {
Logger,
CoreStart,
SharedGlobalConfig,
} from '../../../core/server';
} from 'opensearch-dashboards/server';
import {
cleanWorkspaceId,
cleanUpACLAuditor,
cleanUpClientCallAuditor,
getACLAuditor,
getWorkspaceIdFromUrl,
getWorkspaceState,
initializeACLAuditor,
initializeClientCallAuditor,
updateWorkspaceState,
} from 'opensearch-dashboards/server/utils';
import {
WORKSPACE_SAVED_OBJECTS_CLIENT_WRAPPER_ID,
WORKSPACE_CONFLICT_CONTROL_SAVED_OBJECTS_CLIENT_WRAPPER_ID,
Expand All @@ -33,17 +44,6 @@ import { IWorkspaceClientImpl, WorkspacePluginSetup, WorkspacePluginStart } from
import { WorkspaceClient } from './workspace_client';
import { registerRoutes } from './routes';
import { WorkspaceSavedObjectsClientWrapper } from './saved_objects';
import {
cleanWorkspaceId,
cleanUpACLAuditor,
cleanUpClientCallAuditor,
getACLAuditor,
getWorkspaceIdFromUrl,
getWorkspaceState,
initializeACLAuditor,
initializeClientCallAuditor,
updateWorkspaceState,
} from '../../../core/server/utils';
import { WorkspaceConflictSavedObjectsClientWrapper } from './saved_objects/saved_objects_wrapper_for_check_workspace_conflict';
import {
SavedObjectsPermissionControl,
Expand Down
6 changes: 3 additions & 3 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
// Allows for importing from `opensearch-dashboards` package for the exported types.
"opensearch-dashboards": ["./opensearch_dashboards"],
"opensearch-dashboards/public": ["src/core/public"],
"opensearch-dashboards/public/*": ["src/core/public/*"],
"opensearch-dashboards/server": ["src/core/server"],
"opensearch-dashboards/server/*": ["src/core/server/*"],
"plugins/*": ["src/legacy/core_plugins/*/public/"],
"test_utils/*": [
"src/test_utils/public/*"
],
"test_utils/*": ["src/test_utils/public/*"],
"fixtures/*": ["src/fixtures/*"],
"@opensearch-project/opensearch": ["node_modules/@opensearch-project/opensearch/api/new"],
"@opensearch-project/opensearch/lib/*": ["node_modules/@opensearch-project/opensearch/lib/*"],
Expand Down
Loading
Loading