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

Improvements to new resolver #8844

Merged
merged 2 commits into from
Feb 21, 2023
Merged
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
53 changes: 46 additions & 7 deletions packages/core/core/src/Dependency.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import type {
} from '@parcel/types';
import type {Dependency, Environment, Target} from './types';
import {hashString} from '@parcel/hash';
import {SpecifierType, Priority, BundleBehavior} from './types';
import {
SpecifierType,
Priority,
BundleBehavior,
ExportsCondition,
} from './types';

import {toInternalSourceLocation} from './utils';
import {toProjectPath} from './projectPath';
Expand All @@ -28,6 +33,7 @@ type DependencyOpts = {|
isOptional?: boolean,
loc?: SourceLocation,
env: Environment,
packageConditions?: Array<string>,
meta?: Meta,
resolveFrom?: FilePath,
range?: SemverRange,
Expand All @@ -53,15 +59,13 @@ export function createDependency(
(opts.pipeline ?? '') +
opts.specifierType +
(opts.bundleBehavior ?? '') +
(opts.priority ?? 'sync'),
(opts.priority ?? 'sync') +
(opts.packageConditions ? JSON.stringify(opts.packageConditions) : ''),
);

return {
...opts,
resolveFrom: toProjectPath(projectRoot, opts.resolveFrom),
sourcePath: toProjectPath(projectRoot, opts.sourcePath),
let dep: Dependency = {
id,
loc: toInternalSourceLocation(projectRoot, opts.loc),
specifier: opts.specifier,
specifierType: SpecifierType[opts.specifierType],
priority: Priority[opts.priority ?? 'sync'],
needsStableName: opts.needsStableName ?? false,
Expand All @@ -70,7 +74,13 @@ export function createDependency(
: null,
isEntry: opts.isEntry ?? false,
isOptional: opts.isOptional ?? false,
loc: toInternalSourceLocation(projectRoot, opts.loc),
env: opts.env,
meta: opts.meta || {},
target: opts.target,
sourceAssetId: opts.sourceAssetId,
sourcePath: toProjectPath(projectRoot, opts.sourcePath),
resolveFrom: toProjectPath(projectRoot, opts.resolveFrom),
range: opts.range,
symbols:
opts.symbols &&
Expand All @@ -85,7 +95,14 @@ export function createDependency(
},
]),
),
pipeline: opts.pipeline,
};

if (opts.packageConditions) {
convertConditions(opts.packageConditions, dep);
}

return dep;
}

export function mergeDependencies(a: Dependency, b: Dependency): void {
Expand All @@ -101,3 +118,25 @@ export function mergeDependencies(a: Dependency, b: Dependency): void {
if (isEntry) a.isEntry = true;
if (!isOptional) a.isOptional = false;
}

function convertConditions(conditions: Array<string>, dep: Dependency) {
// Store common package conditions as bit flags to reduce size.
// Custom conditions are stored as strings.
let packageConditions = 0;
let customConditions = [];
for (let condition of conditions) {
if (ExportsCondition[condition]) {
packageConditions |= ExportsCondition[condition];
} else {
customConditions.push(condition);
}
}

if (packageConditions) {
dep.packageConditions = packageConditions;
}

if (customConditions.length) {
dep.customPackageConditions = customConditions;
}
}
10 changes: 8 additions & 2 deletions packages/core/core/src/Transformation.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
Transformer,
TransformerResult,
PackageName,
ResolveOptions,
SemverRange,
} from '@parcel/types';
import type {WorkerApi} from '@parcel/workers';
Expand Down Expand Up @@ -734,12 +735,17 @@ export default class Transformation {
): Promise<$ReadOnlyArray<TransformerResult | UncommittedAsset>> {
const logger = new PluginLogger({origin: transformerName});

const resolve = async (from: FilePath, to: string): Promise<FilePath> => {
const resolve = async (
from: FilePath,
to: string,
options?: ResolveOptions,
): Promise<FilePath> => {
let result = await pipeline.resolverRunner.resolve(
createDependency(this.options.projectRoot, {
env: asset.value.env,
specifier: to,
specifierType: 'esm', // ???
specifierType: options?.specifierType || 'esm',
packageConditions: options?.packageConditions,
sourcePath: from,
}),
);
Expand Down
23 changes: 22 additions & 1 deletion packages/core/core/src/public/Dependency.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ import nullthrows from 'nullthrows';
import Environment from './Environment';
import Target from './Target';
import {MutableDependencySymbols} from './Symbols';
import {SpecifierType as SpecifierTypeMap, Priority} from '../types';
import {
SpecifierType as SpecifierTypeMap,
Priority,
ExportsCondition,
} from '../types';
import {fromProjectPath} from '../projectPath';
import {fromInternalSourceLocation} from '../utils';

Expand Down Expand Up @@ -101,6 +105,23 @@ export default class Dependency implements IDependency {
return new Environment(this.#dep.env, this.#options);
}

get packageConditions(): ?Array<string> {
// Merge custom conditions with conditions stored as bitflags.
// Order is not important because exports conditions are resolved
// in the order they are declared in the package.json.
let conditions = this.#dep.customPackageConditions;
if (this.#dep.packageConditions) {
conditions = conditions ? [...conditions] : [];
for (let key in ExportsCondition) {
if (this.#dep.packageConditions & ExportsCondition[key]) {
conditions.push(key);
}
}
}

return conditions;
}

get meta(): Meta {
return this.#dep.meta;
}
Expand Down
13 changes: 13 additions & 0 deletions packages/core/core/src/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,17 @@ export const Priority = {
lazy: 2,
};

// Must match package_json.rs in node-resolver-rs.
export const ExportsCondition = {
import: 1 << 0,
require: 1 << 1,
module: 1 << 2,
style: 1 << 12,
sass: 1 << 13,
less: 1 << 14,
stylus: 1 << 15,
};

export type Dependency = {|
id: string,
specifier: DependencySpecifier,
Expand All @@ -124,6 +135,8 @@ export type Dependency = {|
isOptional: boolean,
loc: ?InternalSourceLocation,
env: Environment,
packageConditions?: number,
customPackageConditions?: Array<string>,
meta: Meta,
resolverMeta?: ?Meta,
target: ?Target,
Expand Down
13 changes: 13 additions & 0 deletions packages/core/integration-tests/test/css.js
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,19 @@ describe('css', () => {
]);
});

it('should support the style package exports condition', async () => {
let b = await bundle(
path.join(__dirname, '/integration/css-exports/index.css'),
);

assertBundles(b, [
{
name: 'index.css',
assets: ['index.css', 'foo.css'],
},
]);
});

it('should support external CSS imports', async () => {
let b = await bundle(
path.join(__dirname, '/integration/css-external/a.css'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import 'npm:foo';

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import "foo";

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import "library"

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"private": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@import "foo";

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions packages/core/integration-tests/test/less.js
Original file line number Diff line number Diff line change
Expand Up @@ -285,4 +285,11 @@ describe('less', function () {
),
);
});

it('should support the less package exports condition', async function () {
await bundle(path.join(__dirname, '/integration/less-exports/index.less'));

let css = await outputFS.readFile(path.join(distDir, 'index.css'), 'utf8');
assert(css.includes('.a'));
});
});
16 changes: 16 additions & 0 deletions packages/core/integration-tests/test/sass.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,4 +269,20 @@ describe('sass', function () {
let css = await outputFS.readFile(path.join(distDir, 'index.css'), 'utf8');
assert(css.includes('.included'));
});

it('should support package.json exports', async function () {
let b = await bundle(
path.join(__dirname, '/integration/sass-exports/index.sass'),
);

assertBundles(b, [
{
name: 'index.css',
assets: ['index.sass'],
},
]);

let css = await outputFS.readFile(path.join(distDir, 'index.css'), 'utf8');
assert(css.includes('.external'));
});
});
9 changes: 9 additions & 0 deletions packages/core/integration-tests/test/stylus.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,13 @@ describe('stylus', function () {
assert(css.includes('.foo'));
assert(css.includes('.bar'));
});

it('should support the stylus package exports condition', async function () {
await bundle(
path.join(__dirname, '/integration/stylus-exports/index.styl'),
);

let css = await outputFS.readFile(path.join(distDir, 'index.css'), 'utf8');
assert(css.includes('.a'));
});
});
36 changes: 35 additions & 1 deletion packages/core/types/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,13 @@ export type DependencyOptions = {|
+loc?: SourceLocation,
/** The environment of the dependency. */
+env?: EnvironmentOptions,
/**
* A list of custom conditions to use when resolving package.json "exports" and "imports".
* This is combined with the conditions from the environment. However, it overrides the
* default "import" and "require" conditions inferred from the specifierType. To include those
* in addition to custom conditions, explicitly add them to this list.
*/
+packageConditions?: Array<string>,
/** Plugin-specific metadata for the dependency. */
+meta?: Meta,
/** The pipeline defined in .parcelrc that the dependency should be processed with. */
Expand Down Expand Up @@ -589,6 +596,13 @@ export interface Dependency {
+loc: ?SourceLocation;
/** The environment of the dependency. */
+env: Environment;
/**
* A list of custom conditions to use when resolving package.json "exports" and "imports".
* This is combined with the conditions from the environment. However, it overrides the
* default "import" and "require" conditions inferred from the specifierType. To include those
* in addition to custom conditions, explicitly add them to this list.
*/
+packageConditions: ?Array<string>;
/** Plugin-specific metadata for the dependency. */
+meta: Meta;
/** If this is an entry, this is the target that is associated with that entry. */
Expand Down Expand Up @@ -959,7 +973,27 @@ export interface PluginLogger {
/**
* @section transformer
*/
export type ResolveFn = (from: FilePath, to: string) => Promise<FilePath>;
export type ResolveOptions = {|
/**
* How the specifier should be interpreted.
* - esm: An ES module specifier. It is parsed as a URL, but bare specifiers are treated as node_modules.
* - commonjs: A CommonJS specifier. It is not parsed as a URL.
* - url: A URL that works as in a browser. Bare specifiers are treated as relative URLs.
* - custom: A custom specifier. Must be handled by a custom resolver plugin.
*/
+specifierType?: SpecifierType,
/** A list of custom conditions to use when resolving package.json "exports" and "imports". */
+packageConditions?: Array<string>,
|};

/**
* @section transformer
*/
export type ResolveFn = (
from: FilePath,
to: string,
options?: ResolveOptions,
) => Promise<FilePath>;

/**
* @section validator
Expand Down
1 change: 1 addition & 0 deletions packages/resolvers/default/src/DefaultResolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export default (new Resolver({
env: dependency.env,
sourcePath: dependency.sourcePath,
loc: dependency.loc,
packageConditions: dependency.packageConditions,
});
},
}): Resolver);
Loading