Skip to content

Commit

Permalink
[dev-tool] Upgrade to rollup v3 (#27285)
Browse files Browse the repository at this point in the history
### Packages impacted by this PR
All libraries

### Issues associated with this PR
Fixes #26665

### Describe the problem that is addressed by this PR
We need to upgrade Rollup to v3 so our cjs bundles could import ES
modules among other goodness.

### What are the possible designs available to address the problem? If
there are more than one possible design, why was the one in this PR
chosen?
See the linked issue for discussion of the upgrade. Credit to @xirzec
for writing up the sourcemaps plugin in-house replacement!

### Are there test cases added in this PR? _(If not, why?)_
N/A

### Provide a list of related PRs _(if any)_
[N/A](#27258)

### Command used to generate this PR:**_(Applicable only to SDK release
request PRs)_

### Checklists
- [x] Added impacted package name to the issue description
- [ ] Does this PR needs any fixes in the SDK Generator?** _(If so,
create an Issue in the
[Autorest/typescript](https://github.com/Azure/autorest.typescript)
repository and link it here)_
- [ ] Added a changelog (if necessary)
  • Loading branch information
deyaaeldeen authored Sep 29, 2023
1 parent 3061d14 commit c86e72c
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 323 deletions.
34 changes: 17 additions & 17 deletions common/config/rush/pnpm-lock.yaml

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

9 changes: 4 additions & 5 deletions common/tools/dev-tool/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@
},
"devDependencies": {
"@microsoft/api-extractor": "^7.31.1",
"@rollup/plugin-commonjs": "^24.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-multi-entry": "^6.0.0",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-node-resolve": "^15.0.0",
"@types/chai": "^4.1.6",
"@types/chai-as-promised": "^7.1.0",
"@types/decompress": "^4.2.4",
Expand All @@ -87,9 +87,8 @@
"nyc": "^15.1.0",
"karma": "^6.3.9",
"rimraf": "^3.0.0",
"rollup": "^2.78.0",
"rollup": "^3.0.0",
"rollup-plugin-polyfill-node": "^0.12.0",
"rollup-plugin-sourcemaps": "^0.6.2",
"rollup-plugin-visualizer": "^5.5.2"
"rollup-plugin-visualizer": "^5.0.0"
}
}
51 changes: 0 additions & 51 deletions common/tools/dev-tool/src/ambient.d.ts

This file was deleted.

13 changes: 5 additions & 8 deletions common/tools/dev-tool/src/commands/run/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ import nodeBuiltins from "builtin-modules";

import nodeResolve from "@rollup/plugin-node-resolve";
import cjs from "@rollup/plugin-commonjs";
import sourcemaps from "rollup-plugin-sourcemaps";
import nodePolyfills from "rollup-plugin-polyfill-node";
import json from "@rollup/plugin-json";
import multiEntry from "@rollup/plugin-multi-entry";

import { leafCommand, makeCommandInfo } from "../../framework/command";
import { resolveProject, resolveRoot } from "../../util/resolveProject";
import { createPrinter } from "../../util/printer";
import { makeOnWarnForTesting, sourcemapsExtra } from "../../config/rollup.base.config";
import { makeOnWarnForTesting, sourcemaps } from "../../config/rollup.base.config";

const log = createPrinter("bundle");

Expand Down Expand Up @@ -104,23 +103,21 @@ export default leafCommand(commandInfo, async (options) => {
[pnpmStore, name.split("/").join("+"), "@*", "**/*.js"].join("/");

const browserTestConfig = {
input: {
include: [[basePath, "test", "**", "*.spec.js"].join("/")],
exclude: [[basePath, "test", "**", "node", "**"].join("/")],
},
input: path.join(basePath, "test", "**", "*.spec.js"),
preserveSymlinks: false,
plugins: [
multiEntry({ exports: false }),
multiEntry({ exports: false, exclude: ["**/test/**/node/**/*.js"] }),
nodeResolve({
mainFields: ["module", "browser"],
preferBuiltins: false,
browser: true,
}),
...(options["polyfill-node"] ? [nodePolyfills({ sourceMap: true })] : []),
cjs({
dynamicRequireTargets: [globFromStore("chai")],
}),
json(),
sourcemapsExtra(),
sourcemaps(),
],
onwarn: makeOnWarnForTesting(),
// Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0,
Expand Down
106 changes: 53 additions & 53 deletions common/tools/dev-tool/src/config/rollup.base.config.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import { PluginContext, RollupWarning, WarningHandler } from "rollup";
import {
LoadResult,
PluginContext,
RollupOptions,
RollupWarning,
WarningHandlerWithDefault,
} from "rollup";

import nodeResolve from "@rollup/plugin-node-resolve";
import cjs from "@rollup/plugin-commonjs";
import sourcemaps from "rollup-plugin-sourcemaps";
import multiEntry from "@rollup/plugin-multi-entry";
import json from "@rollup/plugin-json";
import * as path from "path";
import { readFile } from "node:fs/promises";

import nodeBuiltins from "builtin-modules";
import { createPrinter } from "../util/printer";
Expand All @@ -22,44 +28,6 @@ interface PackageJson {
devDependencies: Record<string, string>;
}

/**
* The default sourcemaps plugin does not provide very much information in warnings, so this shim allows us to capture
* the active sourcemaps loading context.
*
* This allows us to selectively disable warnings about missing source maps, for example in core-asynciterator-polyfill.
*/
export function sourcemapsExtra() {
const _sourcemaps = sourcemaps();

const load = _sourcemaps.load;

if (!load) return _sourcemaps;

return Object.assign(_sourcemaps, {
load(this: PluginContext, id: string) {
const shim = new Proxy(this, {
get(context, p, ...rest) {
if (p === "warn") {
const warn = context.warn;
return (warning: unknown) => {
const warningObject = (
typeof warning === "string" ? { message: warning } : warning
) as RollupWarning;

warningObject.id = id;

warn(warningObject);
};
}
return Reflect.get(context, p, ...rest);
},
});

return load instanceof Function ? load.call(shim, id) : load.handler.call(shim, id);
},
});
}

// #region Warning Handler

/**
Expand All @@ -83,14 +51,14 @@ function ignoreNiseSinonEval(warning: RollupWarning): boolean {
function ignoreChaiCircularDependency(warning: RollupWarning): boolean {
return (
warning.code === "CIRCULAR_DEPENDENCY" &&
matchesPathSegments(warning.importer, ["node_modules", "chai"])
matchesPathSegments(warning.ids?.[0], ["node_modules", "chai"])
);
}

function ignoreRheaPromiseCircularDependency(warning: RollupWarning): boolean {
return (
warning.code === "CIRCULAR_DEPENDENCY" &&
matchesPathSegments(warning.importer, ["node_modules", "rhea-promise"])
matchesPathSegments(warning.ids?.[0], ["node_modules", "rhea-promise"])
);
}

Expand Down Expand Up @@ -125,44 +93,76 @@ const warningInhibitors: Array<(warning: RollupWarning) => boolean> = [
* Construct a warning handler for the shared rollup configuration
* that ignores certain warnings that are not relevant to testing.
*/
export function makeOnWarnForTesting(): (warning: RollupWarning, warn: WarningHandler) => void {
export function makeOnWarnForTesting(): (
warning: RollupWarning,
warn: WarningHandlerWithDefault
) => void {
return (warning, warn) => {
if (!warningInhibitors.some((inhibited) => inhibited(warning))) {
debug("Warning:", warning.code, warning.id, warning.loc);
warn(warning);
warn(warning, console.warn);
}
};
}

export function sourcemaps() {
return {
name: "load-source-maps",
async load(this: PluginContext, id: string): Promise<LoadResult> {
if (!id.endsWith(".js")) {
return null;
}
try {
const code = await readFile(id, "utf8");
if (code.includes("sourceMappingURL")) {
const basePath = path.dirname(id);
const mapPath = code.match(/sourceMappingURL=(.*)/)?.[1];
if (!mapPath) {
this.warn({ message: "Could not find map path in file " + id, id });
return null;
}
const absoluteMapPath = path.join(basePath, mapPath);
const map = JSON.parse(await readFile(absoluteMapPath, "utf8"));
debug("got map for file ", id);
return { code, map };
}
debug("no map for file ", id);
return { code, map: null };
} catch (e) {
function toString(error: any): string {
return error instanceof Error ? error.stack ?? error.toString() : JSON.stringify(error);
}
this.warn({ message: toString(e), id });
return null;
}
},
};
}

// #endregion

export function makeBrowserTestConfig(pkg: PackageJson): RollupOptions {
// ./dist-esm/src/index.js -> ./dist-esm
// ./dist-esm/keyvault-keys/src/index.js -> ./dist-esm/keyvault-keys
const module = pkg["module"] ?? "dist-esm/src/index.js";
const basePath = path.dirname(path.parse(module).dir);

const config: RollupOptions = {
input: {
include: [path.join(basePath, "test", "**", "*.spec.js")],
exclude: [path.join(basePath, "test", "**", "node", "**")],
},
input: path.join(basePath, "test", "**", "*.spec.js"),
output: {
file: `dist-test/index.browser.js`,
format: "umd",
sourcemap: true,
},
preserveSymlinks: false,
plugins: [
multiEntry({ exports: false }),
multiEntry({ exports: false, exclude: ["**/test/**/node/**/*.js"] }),
nodeResolve({
mainFields: ["module", "browser"],
preferBuiltins: false,
browser: true,
}),
cjs(),
json(),
sourcemapsExtra(),
//viz({ filename: "dist-test/browser-stats.html", sourcemap: true })
sourcemaps(),
],
onwarn: makeOnWarnForTesting(),
// Disable tree-shaking of test code. In rollup-plugin-node-resolve@5.0.0,
Expand Down
Loading

0 comments on commit c86e72c

Please sign in to comment.