Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

22
node_modules/@nx/rollup/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2017-2026 Narwhal Technologies Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

68
node_modules/@nx/rollup/README.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
<p style="text-align: center;">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-dark.svg">
<img alt="Nx - Smart Monorepos · Fast Builds" src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-light.svg" width="100%">
</picture>
</p>
<div style="text-align: center;">
[![CircleCI](https://circleci.com/gh/nrwl/nx.svg?style=svg)](https://circleci.com/gh/nrwl/nx)
[![License](https://img.shields.io/npm/l/@nx/workspace.svg?style=flat-square)]()
[![NPM Version](https://badge.fury.io/js/nx.svg)](https://www.npmjs.com/package/nx)
[![Semantic Release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)]()
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
[![Join the chat at https://gitter.im/nrwl-nx/community](https://badges.gitter.im/nrwl-nx/community.svg)](https://gitter.im/nrwl-nx/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join us on the Official Nx Discord Server](https://img.shields.io/discord/1143497901675401286?label=discord)](https://go.nx.dev/community)
</div>
<hr>
# Nx: Smart Monorepos · Fast Builds
Get to green PRs in half the time. Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.
This package is a [Rollup plugin for Nx](https://nx.dev/nx-api/rollup).
## Getting Started
### Creating an Nx Workspace
**Using `npx`**
```bash
npx create-nx-workspace
```
**Using `npm init`**
```bash
npm init nx-workspace
```
**Using `yarn create`**
```bash
yarn create nx-workspace
```
### Adding Nx to an Existing Repository
Run:
```bash
npx nx@latest init
```
## Documentation & Resources
- [Nx.Dev: Documentation, Guides, Tutorials](https://nx.dev)
- [Intro to Nx](https://nx.dev/getting-started/intro)
- [Official Nx YouTube Channel](https://www.youtube.com/@NxDevtools)
- [Blog Posts About Nx](https://nx.dev/blog)
<p style="text-align: center;"><a href="https://nx.dev/#learning-materials" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-courses-and-videos.svg"
width="100%" alt="Nx - Smart Monorepos · Fast Builds"></a></p>

9
node_modules/@nx/rollup/executors.json generated vendored Normal file
View File

@@ -0,0 +1,9 @@
{
"executors": {
"rollup": {
"implementation": "./src/executors/rollup/rollup.impl",
"schema": "./src/executors/rollup/schema.json",
"description": "Bundle a package using Rollup."
}
}
}

24
node_modules/@nx/rollup/generators.json generated vendored Normal file
View File

@@ -0,0 +1,24 @@
{
"name": "Nx rollup",
"version": "0.1",
"generators": {
"init": {
"factory": "./src/generators/init/init#rollupInitGenerator",
"schema": "./src/generators/init/schema.json",
"description": "Initialize the `@nx/rollup` plugin.",
"aliases": ["ng-add"],
"hidden": true
},
"configuration": {
"aliases": ["rollup-project"],
"factory": "./src/generators/configuration/configuration",
"schema": "./src/generators/configuration/schema.json",
"description": "Add rollup configuration to a project."
},
"convert-to-inferred": {
"factory": "./src/generators/convert-to-inferred/convert-to-inferred",
"schema": "./src/generators/convert-to-inferred/schema.json",
"description": "Convert existing Rollup project(s) using `@nx/rollup:*` executors to use `@nx/rollup/plugin`."
}
}
}

8
node_modules/@nx/rollup/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { configurationGenerator } from './src/generators/configuration/configuration';
export { configurationGenerator };
/** @deprecated Use `configurationGenerator` instead. */
export declare const rollupProjectGenerator: typeof configurationGenerator;
export * from './src/generators/init/init';
export type { AssetGlobPattern, Globals, RollupExecutorOptions, } from './src/executors/rollup/schema';
export * from './src/executors/rollup/rollup.impl';
//# sourceMappingURL=index.d.ts.map

1
node_modules/@nx/rollup/index.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../packages/rollup/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EAAE,sBAAsB,EAAE,CAAC;AAGlC,wDAAwD;AACxD,eAAO,MAAM,sBAAsB,+BAAyB,CAAC;AAE7D,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACV,gBAAgB,EAChB,OAAO,EACP,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,cAAc,oCAAoC,CAAC"}

11
node_modules/@nx/rollup/index.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rollupProjectGenerator = exports.configurationGenerator = void 0;
const tslib_1 = require("tslib");
const configuration_1 = require("./src/generators/configuration/configuration");
Object.defineProperty(exports, "configurationGenerator", { enumerable: true, get: function () { return configuration_1.configurationGenerator; } });
// Exported for backwards compatibility in case a plugin is using the old name.
/** @deprecated Use `configurationGenerator` instead. */
exports.rollupProjectGenerator = configuration_1.configurationGenerator;
tslib_1.__exportStar(require("./src/generators/init/init"), exports);
tslib_1.__exportStar(require("./src/executors/rollup/rollup.impl"), exports);

4
node_modules/@nx/rollup/migrations.json generated vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"generators": {},
"packageJsonUpdates": {}
}

58
node_modules/@nx/rollup/package.json generated vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "@nx/rollup",
"version": "22.7.5",
"private": false,
"description": "The Nx Plugin for Rollup contains executors and generators that support building applications using Rollup.",
"repository": {
"type": "git",
"url": "https://github.com/nrwl/nx.git",
"directory": "packages/rollup"
},
"keywords": [
"Monorepo",
"Rollup",
"Web",
"CLI"
],
"main": "./index.js",
"type": "commonjs",
"types": "./index.d.ts",
"author": "Victor Savkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/nrwl/nx/issues"
},
"homepage": "https://nx.dev",
"generators": "./generators.json",
"executors": "./executors.json",
"ng-update": {
"requirements": {},
"migrations": "./migrations.json"
},
"dependencies": {
"@nx/devkit": "22.7.5",
"@nx/js": "22.7.5",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-image": "^3.0.3",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-typescript": "^12.1.0",
"autoprefixer": "^10.4.9",
"concat-with-sourcemaps": "^1.1.0",
"picocolors": "^1.1.0",
"picomatch": "4.0.4",
"postcss": "^8.4.38",
"postcss-modules": "^6.0.1",
"rollup": "^4.14.0",
"rollup-plugin-typescript2": "^0.36.0",
"tslib": "^2.3.0"
},
"devDependencies": {
"nx": "22.7.5",
"source-map-js": "^1.2.0"
},
"publishConfig": {
"access": "public"
}
}

2
node_modules/@nx/rollup/plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { createNodes, createNodesV2, RollupPluginOptions, } from './src/plugins/plugin';
//# sourceMappingURL=plugin.d.ts.map

1
node_modules/@nx/rollup/plugin.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../packages/rollup/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,aAAa,EACb,mBAAmB,GACpB,MAAM,sBAAsB,CAAC"}

6
node_modules/@nx/rollup/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNodesV2 = exports.createNodes = void 0;
var plugin_1 = require("./src/plugins/plugin");
Object.defineProperty(exports, "createNodes", { enumerable: true, get: function () { return plugin_1.createNodes; } });
Object.defineProperty(exports, "createNodesV2", { enumerable: true, get: function () { return plugin_1.createNodesV2; } });

View File

@@ -0,0 +1,9 @@
import { ExecutorContext } from '@nx/devkit';
import type { RollupExecutorOptions } from '../schema';
export interface NormalizedRollupExecutorOptions extends RollupExecutorOptions {
projectRoot: string;
rollupConfig: string[];
}
export declare function normalizeRollupExecutorOptions(options: RollupExecutorOptions, context: ExecutorContext): NormalizedRollupExecutorOptions;
export declare function normalizePluginPath(pluginPath: void | string, root: string): string;
//# sourceMappingURL=normalize.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/executors/rollup/lib/normalize.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAGvD,MAAM,WAAW,+BAAgC,SAAQ,qBAAqB;IAC5E,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,EAAE,CAAC;CACxB;AAED,wBAAgB,8BAA8B,CAC5C,OAAO,EAAE,qBAAqB,EAC9B,OAAO,EAAE,eAAe,GACvB,+BAA+B,CAajC;AAED,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,IAAI,GAAG,MAAM,EAAE,IAAI,EAAE,MAAM,UAS1E"}

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeRollupExecutorOptions = normalizeRollupExecutorOptions;
exports.normalizePluginPath = normalizePluginPath;
const path_1 = require("path");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
function normalizeRollupExecutorOptions(options, context) {
const { root } = context;
const skipTypeCheck = (0, ts_solution_setup_1.isUsingTsSolutionSetup)() ? true : options.skipTypeCheck;
return {
...options,
rollupConfig: []
.concat(options.rollupConfig)
.filter(Boolean)
.map((p) => normalizePluginPath(p, root)),
buildLibsFromSource: options.buildLibsFromSource ?? true,
projectRoot: context.projectGraph.nodes[context.projectName].data.root,
skipTypeCheck: skipTypeCheck || false,
};
}
function normalizePluginPath(pluginPath, root) {
if (!pluginPath) {
return '';
}
try {
return require.resolve(pluginPath);
}
catch {
return (0, path_1.resolve)(root, pluginPath);
}
}

View File

@@ -0,0 +1,8 @@
import * as rollup from 'rollup';
import { type ExecutorContext } from '@nx/devkit';
import { RollupExecutorOptions } from './schema';
import { NormalizedRollupExecutorOptions } from './lib/normalize';
export declare function rollupExecutor(rawOptions: RollupExecutorOptions, context: ExecutorContext): AsyncGenerator<unknown, any, any>;
export declare function createRollupOptions(options: NormalizedRollupExecutorOptions, context: ExecutorContext): Promise<rollup.RollupOptions | rollup.RollupOptions[]>;
export default rollupExecutor;
//# sourceMappingURL=rollup.impl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"rollup.impl.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/executors/rollup/rollup.impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AAEjC,OAAO,EAAE,KAAK,eAAe,EAAU,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EACL,+BAA+B,EAEhC,MAAM,iBAAiB,CAAC;AAOzB,wBAAuB,cAAc,CACnC,UAAU,EAAE,qBAAqB,EACjC,OAAO,EAAE,eAAe,qCAkEzB;AAID,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,+BAA+B,EACxC,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,aAAa,EAAE,CAAC,CAuDxD;AAWD,eAAe,cAAc,CAAC"}

View File

@@ -0,0 +1,123 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rollupExecutor = rollupExecutor;
exports.createRollupOptions = createRollupOptions;
const tslib_1 = require("tslib");
const rollup = tslib_1.__importStar(require("rollup"));
const path_1 = require("path");
const devkit_1 = require("@nx/devkit");
const normalize_1 = require("./lib/normalize");
const config_utils_1 = require("@nx/devkit/src/utils/config-utils");
const async_iterable_1 = require("@nx/devkit/src/utils/async-iterable");
const with_nx_1 = require("../../plugins/with-nx/with-nx");
const generate_package_json_1 = require("../../plugins/package-json/generate-package-json");
const buildable_libs_utils_1 = require("@nx/js/src/utils/buildable-libs-utils");
async function* rollupExecutor(rawOptions, context) {
process.env.NODE_ENV ??= 'production';
const options = (0, normalize_1.normalizeRollupExecutorOptions)(rawOptions, context);
const rollupOptions = await createRollupOptions(options, context);
const outfile = resolveOutfile(context, options);
if (options.watch) {
// region Watch build
return yield* (0, async_iterable_1.createAsyncIterable)(({ next }) => {
const watcher = rollup.watch(rollupOptions);
watcher.on('event', (data) => {
if (data.code === 'START') {
devkit_1.logger.info(`Bundling ${context.projectName}...`);
}
else if (data.code === 'END') {
devkit_1.logger.info('Bundle complete. Watching for file changes...');
next({ success: true, outfile });
}
else if (data.code === 'ERROR') {
devkit_1.logger.error(`Error during bundle: ${data.error.message}`);
next({ success: false });
}
});
const processExitListener = (signal) => () => {
watcher.close();
};
process.once('SIGTERM', processExitListener);
process.once('SIGINT', processExitListener);
process.once('SIGQUIT', processExitListener);
});
// endregion
}
else {
// region Single build
try {
devkit_1.logger.info(`Bundling ${context.projectName}...`);
const start = process.hrtime.bigint();
const allRollupOptions = Array.isArray(rollupOptions)
? rollupOptions
: [rollupOptions];
for (const opts of allRollupOptions) {
const bundle = await rollup.rollup(opts);
const output = Array.isArray(opts.output) ? opts.output : [opts.output];
for (const o of output) {
await bundle.write(o);
}
}
const end = process.hrtime.bigint();
const duration = `${(Number(end - start) / 1_000_000_000).toFixed(2)}s`;
devkit_1.logger.info(`⚡ Done in ${duration}`);
return { success: true, outfile };
}
catch (e) {
if (e.formatted) {
devkit_1.logger.info(e.formatted);
}
else if (e.message) {
devkit_1.logger.info(e.message);
}
devkit_1.logger.error(e);
devkit_1.logger.error(`Bundle failed: ${context.projectName}`);
return { success: false };
}
// endregion
}
}
// -----------------------------------------------------------------------------
async function createRollupOptions(options, context) {
const { dependencies } = (0, buildable_libs_utils_1.calculateProjectBuildableDependencies)(context.taskGraph, context.projectGraph, context.root, context.projectName, context.targetName, context.configurationName, true);
const rollupConfig = (0, with_nx_1.withNx)(options, {}, dependencies);
// `generatePackageJson` is a plugin rather than being embedded into @nx/rollup:rollup.
// Make sure the plugin is always present to keep the previous before of Nx < 19.4, where it was not a plugin.
const generatePackageJsonPlugin = Array.isArray(rollupConfig.plugins)
? rollupConfig.plugins.find((p) => p['name'] === generate_package_json_1.pluginName)
: null;
const userDefinedRollupConfigs = options.rollupConfig.map((plugin) => (0, config_utils_1.loadConfigFile)(plugin));
let finalConfig = rollupConfig;
for (const _config of userDefinedRollupConfigs) {
const config = await _config;
if (typeof config === 'function') {
finalConfig = config(finalConfig, options);
}
else {
finalConfig = {
...finalConfig,
...config,
plugins: [
...(Array.isArray(finalConfig.plugins) &&
finalConfig.plugins?.length > 0
? finalConfig.plugins
: []),
...(config.plugins?.length > 0 ? config.plugins : []),
],
};
}
}
if (generatePackageJsonPlugin &&
Array.isArray(finalConfig.plugins) &&
!finalConfig.plugins.some((p) => p['name'] === generate_package_json_1.pluginName)) {
finalConfig.plugins.push(generatePackageJsonPlugin);
}
return finalConfig;
}
function resolveOutfile(context, options) {
if (!options.format?.includes('cjs'))
return undefined;
const { name } = (0, path_1.parse)(options.outputFileName ?? options.main);
return (0, path_1.resolve)(context.root, options.outputPath, `${name}.cjs.js`);
}
exports.default = rollupExecutor;

View File

@@ -0,0 +1,38 @@
type Compiler = 'babel' | 'swc';
export interface AssetGlobPattern {
glob: string;
input: string;
output: string;
ignore?: string[];
}
export interface Globals {
moduleId: string;
global: string;
}
export interface RollupExecutorOptions {
outputPath: string;
tsConfig: string;
main: string;
additionalEntryPoints?: string[];
allowJs?: boolean;
assets?: any[];
babelUpwardRootMode?: boolean;
buildLibsFromSource?: boolean;
compiler?: 'babel' | 'tsc' | 'swc';
deleteOutputPath?: boolean;
external?: string[] | 'all' | 'none';
extractCss?: boolean | string;
format?: ('cjs' | 'esm')[];
generateExportsField?: boolean;
javascriptEnabled?: boolean;
project?: string;
outputFileName?: string;
rollupConfig?: string | string[];
skipTypeCheck?: boolean;
skipTypeField?: boolean;
useLegacyTypescriptPlugin?: boolean;
watch?: boolean;
}

View File

@@ -0,0 +1,195 @@
{
"version": 2,
"outputCapture": "direct-nodejs",
"title": "Web Library Rollup Target",
"description": "Packages a library for different web usages (ESM, CommonJS).",
"cli": "nx",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The path to package.json file."
},
"main": {
"type": "string",
"description": "The path to the entry file, relative to project.",
"alias": "entryFile",
"x-completion-type": "file",
"x-completion-glob": "**/*@(.js|.ts)",
"x-priority": "important"
},
"outputPath": {
"type": "string",
"description": "The output path of the generated files.",
"x-completion-type": "directory",
"x-priority": "important"
},
"outputFileName": {
"type": "string",
"description": "Name of the main output file. Defaults same basename as 'main' file."
},
"deleteOutputPath": {
"type": "boolean",
"description": "Delete the output path before building.",
"default": true
},
"tsConfig": {
"type": "string",
"description": "The path to tsconfig file.",
"x-completion-type": "file",
"x-completion-glob": "tsconfig.*.json",
"x-priority": "important"
},
"allowJs": {
"type": "boolean",
"description": "Allow JavaScript files to be compiled.",
"default": false
},
"format": {
"type": "array",
"description": "List of module formats to output. Defaults to matching format from tsconfig (e.g. CJS for CommonJS, and ESM otherwise).",
"alias": "f",
"items": {
"type": "string",
"enum": ["esm", "cjs"]
}
},
"external": {
"type": "array",
"description": "A list of external modules that will not be bundled (`react`, `react-dom`, etc.). Can also be set to `all` (bundle nothing) or `none` (bundle everything).",
"oneOf": [
{
"type": "string",
"enum": ["all", "none"]
},
{
"type": "array",
"items": {
"type": "string"
}
}
]
},
"watch": {
"type": "boolean",
"description": "Enable re-building when files change.",
"default": false
},
"rollupConfig": {
"oneOf": [
{
"type": "array",
"items": {
"type": "string",
"x-completion-type": "file",
"x-completion-glob": "rollup?(*)@(.js|.ts)"
}
},
{
"type": "string",
"x-completion-type": "file",
"x-completion-glob": "rollup?(*)@(.js|.ts)"
}
],
"description": "Path to a function which takes a rollup config and returns an updated rollup config."
},
"extractCss": {
"type": ["boolean", "string"],
"description": "CSS files will be extracted to the output folder. Alternatively custom filename can be provided (e.g. styles.css)",
"default": true
},
"assets": {
"type": "array",
"description": "List of static assets.",
"default": [],
"items": {
"$ref": "#/definitions/assetPattern"
}
},
"compiler": {
"type": "string",
"enum": ["babel", "swc", "tsc"],
"default": "babel",
"description": "Which compiler to use."
},
"babelUpwardRootMode": {
"type": "boolean",
"description": "Whether to set rootmode to upward. See https://babeljs.io/docs/en/options#rootmode",
"default": false
},
"javascriptEnabled": {
"type": "boolean",
"description": "Sets `javascriptEnabled` option for less loader",
"default": false
},
"generateExportsField": {
"type": "boolean",
"alias": "exports",
"description": "Update the output package.json file's 'exports' field. This field is used by Node and bundles.",
"default": false,
"x-priority": "important"
},
"additionalEntryPoints": {
"type": "array",
"description": "Additional entry-points to add to exports field in the package.json file.",
"items": {
"type": "string"
},
"x-priority": "important"
},
"buildLibsFromSource": {
"type": "boolean",
"description": "Read buildable libraries from source instead of building them separately.",
"default": true
},
"skipTypeCheck": {
"type": "boolean",
"description": "Whether to skip TypeScript type checking.",
"default": false
},
"skipTypeField": {
"type": "boolean",
"description": "Prevents 'type' field from being added to compiled package.json file. Use this if you are having an issue with this field.",
"default": false
},
"sourceMap": {
"description": "Output sourcemaps.",
"type": "boolean"
},
"useLegacyTypescriptPlugin": {
"type": "boolean",
"description": "Use rollup-plugin-typescript2 instead of @rollup/plugin-typescript.",
"default": false
}
},
"required": ["tsConfig", "main", "outputPath"],
"definitions": {
"assetPattern": {
"oneOf": [
{
"type": "object",
"properties": {
"glob": {
"type": "string",
"description": "The pattern to match."
},
"input": {
"type": "string",
"description": "The input directory path in which to apply `glob`. Defaults to the project root."
},
"output": {
"type": "string",
"description": "Relative path within the output folder."
}
},
"additionalProperties": false,
"required": ["glob", "input", "output"]
},
{
"type": "string"
}
]
}
},
"examplesFile": "../../../docs/rollup-examples.md"
}

View File

@@ -0,0 +1,5 @@
import { GeneratorCallback, Tree } from '@nx/devkit';
import { RollupProjectSchema } from './schema';
export declare function configurationGenerator(tree: Tree, options: RollupProjectSchema): Promise<GeneratorCallback>;
export default configurationGenerator;
//# sourceMappingURL=configuration.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"configuration.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/generators/configuration/configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,EAOjB,IAAI,EAIL,MAAM,YAAY,CAAC;AAkBpB,OAAO,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAI/C,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,mBAAmB,8BAmC7B;AAsPD,eAAe,sBAAsB,CAAC"}

View File

@@ -0,0 +1,226 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.configurationGenerator = configurationGenerator;
const devkit_1 = require("@nx/devkit");
const target_defaults_utils_1 = require("@nx/devkit/src/generators/target-defaults-utils");
const js_1 = require("@nx/js");
const get_import_path_1 = require("@nx/js/src/utils/get-import-path");
const ensure_typescript_1 = require("@nx/js/src/utils/typescript/ensure-typescript");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
const posix_1 = require("node:path/posix");
const devkit_internals_1 = require("nx/src/devkit-internals");
const ensure_dependencies_1 = require("../../utils/ensure-dependencies");
const has_plugin_1 = require("../../utils/has-plugin");
const init_1 = require("../init/init");
let ts;
async function configurationGenerator(tree, options) {
const tasks = [];
const nxJson = (0, devkit_1.readNxJson)(tree);
const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
nxJson.useInferencePlugins !== false;
options.addPlugin ??= addPluginDefault;
tasks.push(await (0, init_1.rollupInitGenerator)(tree, { ...options, skipFormat: true }));
if (!options.skipPackageJson) {
tasks.push((0, ensure_dependencies_1.ensureDependencies)(tree, options));
}
const isTsSolutionSetup = (0, ts_solution_setup_1.isUsingTsSolutionSetup)(tree);
let outputConfig;
if ((0, has_plugin_1.hasPlugin)(tree)) {
outputConfig = createRollupConfig(tree, options, isTsSolutionSetup);
}
else {
options.buildTarget ??= 'build';
checkForTargetConflicts(tree, options);
addBuildTarget(tree, options, isTsSolutionSetup);
}
updatePackageJson(tree, options, outputConfig, isTsSolutionSetup);
if (isTsSolutionSetup) {
updateTsConfig(tree, options);
}
if (!options.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
return (0, devkit_1.runTasksInSerial)(...tasks);
}
function createRollupConfig(tree, options, isTsSolutionSetup) {
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
const main = options.main
? `./${(0, posix_1.relative)(project.root, options.main)}`
: './src/index.ts';
const outputPath = isTsSolutionSetup
? './dist'
: (0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(project.root), 'dist', project.root === '.' ? project.name : project.root);
const buildOptions = {
outputPath,
compiler: options.compiler ?? 'babel',
main,
tsConfig: options.tsConfig
? `./${(0, posix_1.relative)(project.root, options.tsConfig)}`
: './tsconfig.lib.json',
};
tree.write((0, devkit_1.joinPathFragments)(project.root, 'rollup.config.cjs'), `const { withNx } = require('@nx/rollup/with-nx');
module.exports = withNx(
{
main: '${buildOptions.main}',
outputPath: '${buildOptions.outputPath}',
tsConfig: '${buildOptions.tsConfig}',
compiler: '${buildOptions.compiler}',
format: ${JSON.stringify(options.format ?? ['esm'])},${!isTsSolutionSetup
? `
assets: [{ input: '{projectRoot}', output: '.', glob:'*.md' }],`
: ''}
},
{
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
// e.g.
// output: { sourcemap: true },
}
);
`);
return {
main: (0, devkit_1.joinPathFragments)(project.root, main),
outputPath: (0, devkit_1.joinPathFragments)(project.root, outputPath),
};
}
function checkForTargetConflicts(tree, options) {
if (options.skipValidation)
return;
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
if (project.targets?.[options.buildTarget]) {
throw new Error(`Project "${options.project}" already has a ${options.buildTarget} target. Pass --skipValidation to ignore this error.`);
}
}
function updatePackageJson(tree, options, outputConfig, isTsSolutionSetup) {
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
const packageJsonPath = (0, posix_1.join)(project.root, 'package.json');
let packageJson;
if (tree.exists(packageJsonPath)) {
if (!isTsSolutionSetup) {
return;
}
packageJson = (0, devkit_1.readJson)(tree, packageJsonPath);
}
else {
packageJson = {
name: options.importPath || (0, get_import_path_1.getImportPath)(tree, options.project),
version: '0.0.1',
};
}
if (isTsSolutionSetup) {
let main;
let outputPath;
if (outputConfig) {
({ main, outputPath } = outputConfig);
}
else {
// target must exist if we don't receive an outputConfig
const projectTarget = project.targets[options.buildTarget];
const nxJson = (0, devkit_1.readNxJson)(tree);
const mergedTarget = (0, devkit_internals_1.mergeTargetConfigurations)(projectTarget, (projectTarget.executor
? nxJson.targetDefaults?.[projectTarget.executor]
: undefined) ?? nxJson.targetDefaults?.[options.buildTarget]);
({ main, outputPath } = mergedTarget.options);
}
packageJson = (0, js_1.getUpdatedPackageJsonContent)(packageJson, {
main,
outputPath,
projectRoot: project.root,
rootDir: (0, posix_1.dirname)(main),
generateExportsField: true,
packageJsonPath,
format: options.format ?? ['esm'],
outputFileExtensionForCjs: '.cjs.js',
outputFileExtensionForEsm: '.esm.js',
developmentConditionName: (0, ts_solution_setup_1.getDefinedCustomConditionName)(tree),
});
// rollup has a specific declaration file generation not handled by the util above,
// adjust accordingly
const typingsFile = (packageJson.module ?? packageJson.main).replace(/\.js$/, '.d.ts');
packageJson.types = typingsFile;
packageJson.exports['.'].types = typingsFile;
}
(0, devkit_1.writeJson)(tree, packageJsonPath, packageJson);
}
function addBuildTarget(tree, options, isTsSolutionSetup) {
(0, target_defaults_utils_1.addBuildTargetDefaults)(tree, '@nx/rollup:rollup', options.buildTarget, [
ts_solution_setup_1.TS_SOLUTION_SETUP_TSCONFIG_INPUT,
]);
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
const prevBuildOptions = project.targets?.[options.buildTarget]?.options;
options.tsConfig ??=
prevBuildOptions?.tsConfig ??
(0, devkit_1.joinPathFragments)(project.root, 'tsconfig.lib.json');
let outputPath = prevBuildOptions?.outputPath;
if (!outputPath) {
outputPath = isTsSolutionSetup
? (0, devkit_1.joinPathFragments)(project.root, 'dist')
: (0, devkit_1.joinPathFragments)('dist', project.root === '.' ? project.name : project.root);
}
const buildOptions = {
main: options.main ??
prevBuildOptions?.main ??
(0, devkit_1.joinPathFragments)(project.root, 'src/index.ts'),
outputPath,
tsConfig: options.tsConfig,
// TODO(leo): see if we can use this when updating the package.json for the new setup
// additionalEntryPoints: prevBuildOptions?.additionalEntryPoints,
// generateExportsField: prevBuildOptions?.generateExportsField,
compiler: options.compiler ?? 'babel',
project: `${project.root}/package.json`,
external: options.external,
format: (options.format ?? isTsSolutionSetup) ? ['esm'] : undefined,
};
if (options.rollupConfig) {
buildOptions.rollupConfig = options.rollupConfig;
}
if (!isTsSolutionSetup) {
buildOptions.additionalEntryPoints =
prevBuildOptions?.additionalEntryPoints;
buildOptions.generateExportsField = prevBuildOptions?.generateExportsField;
if (tree.exists((0, devkit_1.joinPathFragments)(project.root, 'README.md'))) {
buildOptions.assets = [
{
glob: `${project.root}/README.md`,
input: '.',
output: '.',
},
];
}
}
(0, devkit_1.updateProjectConfiguration)(tree, options.project, {
...project,
targets: {
...project.targets,
[options.buildTarget]: {
executor: '@nx/rollup:rollup',
outputs: ['{options.outputPath}'],
options: buildOptions,
},
},
});
}
function updateTsConfig(tree, options) {
const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
const tsconfigPath = options.tsConfig ?? (0, devkit_1.joinPathFragments)(project.root, 'tsconfig.lib.json');
if (!tree.exists(tsconfigPath)) {
throw new Error(`The '${tsconfigPath}' file doesn't exist. Provide the 'tsConfig' option with the correct path pointing to the tsconfig file to use for builds.`);
}
if (!ts) {
ts = (0, ensure_typescript_1.ensureTypescript)();
}
const parsedTsConfig = (0, js_1.readTsConfig)(tsconfigPath, {
...ts.sys,
readFile: (p) => tree.read(p, 'utf-8'),
fileExists: (p) => tree.exists(p),
});
(0, devkit_1.updateJson)(tree, tsconfigPath, (json) => {
if (parsedTsConfig.options.module === ts.ModuleKind.NodeNext) {
json.compilerOptions ??= {};
json.compilerOptions.module = 'esnext';
json.compilerOptions.moduleResolution = 'bundler';
}
return json;
});
}
exports.default = configurationGenerator;

View File

@@ -0,0 +1,15 @@
export interface RollupProjectSchema {
project: string;
main?: string;
tsConfig?: string;
compiler?: 'babel' | 'swc' | 'tsc';
skipFormat?: boolean;
skipPackageJson?: boolean;
skipValidation?: boolean;
importPath?: string;
external?: string[];
rollupConfig?: string;
buildTarget?: string;
format?: ('cjs' | 'esm')[];
addPlugin?: boolean;
}

View File

@@ -0,0 +1,86 @@
{
"$schema": "https://json-schema.org/schema",
"$id": "NxRollupProject",
"cli": "nx",
"title": "Add Rollup Configuration to a project",
"description": "Add Rollup Configuration to a project.",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The name of the project.",
"$default": {
"$source": "argv",
"index": 0
},
"x-dropdown": "project",
"x-prompt": "What is the name of the project to set up a rollup for?",
"x-priority": "important"
},
"compiler": {
"type": "string",
"enum": ["babel", "swc", "tsc"],
"description": "The compiler to use to build source.",
"default": "babel"
},
"main": {
"type": "string",
"description": "Path relative to the workspace root for the main entry file. Defaults to '<projectRoot>/src/index.ts'.",
"alias": "entryFile",
"x-priority": "important"
},
"tsConfig": {
"type": "string",
"description": "Path relative to the workspace root for the tsconfig file to build with. Defaults to '<projectRoot>/tsconfig.lib.json'.",
"x-priority": "important"
},
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false,
"x-priority": "internal"
},
"skipPackageJson": {
"type": "boolean",
"default": false,
"description": "Do not add dependencies to `package.json`.",
"x-priority": "internal"
},
"skipValidation": {
"type": "boolean",
"default": false,
"description": "Do not perform any validation on existing project.",
"x-priority": "internal"
},
"importPath": {
"type": "string",
"description": "The library name used to import it, like `@myorg/my-awesome-lib`."
},
"external": {
"type": "array",
"description": "A list of external modules that will not be bundled (`react`, `react-dom`, etc.).",
"items": {
"type": "string"
}
},
"rollupConfig": {
"type": "string",
"description": "Path relative to workspace root to a custom rollup file that takes a config object and returns an updated config."
},
"buildTarget": {
"description": "The build target to add.",
"type": "string",
"default": "build"
},
"format": {
"description": "The format to build the library (esm or cjs).",
"type": "array",
"items": {
"type": "string",
"enum": ["esm", "cjs"]
},
"default": ["esm"]
}
},
"required": []
}

View File

@@ -0,0 +1,8 @@
import { type Tree } from '@nx/devkit';
interface Schema {
project?: string;
skipFormat?: boolean;
}
export declare function convertToInferred(tree: Tree, options: Schema): Promise<void>;
export default convertToInferred;
//# sourceMappingURL=convert-to-inferred.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"convert-to-inferred.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/generators/convert-to-inferred/convert-to-inferred.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAQpB,UAAU,MAAM;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,iBAkGlE;AAED,eAAe,iBAAiB,CAAC"}

View File

@@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertToInferred = convertToInferred;
const devkit_1 = require("@nx/devkit");
const executor_options_utils_1 = require("@nx/devkit/src/generators/executor-options-utils");
const extract_rollup_config_from_executor_options_1 = require("./lib/extract-rollup-config-from-executor-options");
const add_plugin_registrations_1 = require("./lib/add-plugin-registrations");
const executor_to_plugin_migrator_1 = require("@nx/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator");
async function convertToInferred(tree, options) {
const migratedProjects = new Map();
let projects = (0, devkit_1.getProjects)(tree);
(0, executor_options_utils_1.forEachExecutorOptions)(tree, '@nx/rollup:rollup', (_, projectName, targetName, configurationName) => {
if (options.project && projectName !== options.project)
return;
const project = projects.get(projectName);
const target = project.targets[targetName];
// We'll handle configurations when dealing with default options.
if (configurationName)
return;
// Since targetDefaults for '@nx/rollup:rollup' will no longer apply, we want to copy them to the target options.
const nxJson = (0, devkit_1.readNxJson)(tree);
const defaults = nxJson.targetDefaults['@nx/rollup:rollup'];
if (defaults) {
for (const [key, value] of Object.entries(defaults)) {
target[key] ??= value;
}
}
const extractedPluginOptions = (0, extract_rollup_config_from_executor_options_1.extractRollupConfigFromExecutorOptions)(tree, target.options, target.configurations, project.root);
// If rollup is not an external dependency, add it
if (target.inputs &&
!target.inputs.some((i) => Array.isArray(i['externalDependencies']) &&
i['externalDependencies'].includes('rollup'))) {
const idx = target.inputs.findIndex((i) => Array.isArray(i['externalDependencies']));
if (idx === -1) {
target.inputs.push({ externalDependencies: ['rollup'] });
}
else {
target.inputs[idx]['externalDependencies'].push('rollup');
}
}
// Clean up the target now that it is inferred
delete target.executor;
if (target.outputs &&
target.outputs.length === 1 &&
// "{projectRoot}/{options.outputPath}" is an invalid output for Rollup since
// there would be a mismatch between where the executor outputs to and where Nx caches.
// If users have this set erroneously, then it will continue to not work.
(target.outputs[0] === '{options.outputPath}' ||
target.outputs[0] === '{workspaceRoot}/{options.outputPath}')) {
// If only the default `options.outputPath` is set as output, remove it and use path inferred from `rollup.config.cjs`.
delete target.outputs;
}
else {
// Otherwise, replace `options.outputPath` with what is inferred from `rollup.config.cjs`.
target.outputs = target.outputs.map((output) =>
// Again, "{projectRoot}/{options.outputPath}" is an invalid output for Rollup.
output === '{options.outputPath}' ||
output === '{workspaceRoot}/{options.outputPath}'
? `{projectRoot}/${extractedPluginOptions.outputPath}`
: output);
}
if (Object.keys(target.options).length === 0)
delete target.options;
if (Object.keys(target).length === 0)
delete project.targets[targetName];
(0, devkit_1.updateProjectConfiguration)(tree, projectName, project);
migratedProjects.set(projectName, { buildTargetName: targetName });
});
if (migratedProjects.size === 0) {
throw new executor_to_plugin_migrator_1.NoTargetsToMigrateError();
}
projects = (0, devkit_1.getProjects)(tree);
await (0, add_plugin_registrations_1.addPluginRegistrations)(tree, migratedProjects, projects, '@nx/rollup/plugin');
if (!options.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
}
exports.default = convertToInferred;

View File

@@ -0,0 +1,3 @@
import { type ProjectConfiguration, type Tree } from '@nx/devkit';
export declare function addPluginRegistrations<T>(tree: Tree, projectTargets: Map<string, T>, projects: Map<string, ProjectConfiguration>, pluginPath: string): Promise<void>;
//# sourceMappingURL=add-plugin-registrations.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"add-plugin-registrations.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/generators/convert-to-inferred/lib/add-plugin-registrations.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,oBAAoB,EACzB,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAGpB,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,EAC9B,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,EAC3C,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAiDf"}

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addPluginRegistrations = addPluginRegistrations;
const devkit_1 = require("@nx/devkit");
const picomatch = require("picomatch");
async function addPluginRegistrations(tree, projectTargets, projects, pluginPath) {
const nxJson = (0, devkit_1.readNxJson)(tree);
for (const [project, options] of projectTargets.entries()) {
const existingPlugin = nxJson.plugins?.find((plugin) => typeof plugin !== 'string' &&
plugin.plugin === pluginPath &&
Object.keys(options).every((key) => plugin.options[key] === options[key]));
const projectIncludeGlob = `${projects.get(project).root}/**/*`;
if (!existingPlugin) {
nxJson.plugins ??= [];
const plugin = {
plugin: pluginPath,
options,
include: [projectIncludeGlob],
};
nxJson.plugins.push(plugin);
}
else if (existingPlugin.include) {
if (!existingPlugin.include.some((include) => picomatch(include)(projectIncludeGlob))) {
existingPlugin.include.push(projectIncludeGlob);
}
}
}
if (!areProjectsUsingTheExecutorLeft(projects)) {
// all projects have been migrated, if there's only one plugin registration
// left, remove its "include" property
const pluginRegistrations = nxJson.plugins?.filter((plugin) => typeof plugin !== 'string' && plugin.plugin === pluginPath);
if (pluginRegistrations?.length === 1) {
for (const plugin of pluginRegistrations) {
delete plugin.include;
}
}
}
(0, devkit_1.updateNxJson)(tree, nxJson);
}
function areProjectsUsingTheExecutorLeft(projects) {
return Array.from(projects.values()).some((project) => Object.values(project.targets ?? {}).some((target) => target.executor === '@nx/rollup:rollup'));
}

View File

@@ -0,0 +1,4 @@
import { Tree } from '@nx/devkit';
import { RollupExecutorOptions } from '../../../executors/rollup/schema';
export declare function extractRollupConfigFromExecutorOptions(tree: Tree, options: RollupExecutorOptions, configurations: Record<string, Partial<RollupExecutorOptions>>, projectRoot: string): Record<string, unknown>;
//# sourceMappingURL=extract-rollup-config-from-executor-options.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"extract-rollup-config-from-executor-options.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/generators/convert-to-inferred/lib/extract-rollup-config-from-executor-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmC,IAAI,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AASzE,wBAAgB,sCAAsC,CACpD,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,qBAAqB,EAC9B,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,qBAAqB,CAAC,CAAC,EAC9D,WAAW,EAAE,MAAM,2BAoHpB"}

View File

@@ -0,0 +1,151 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractRollupConfigFromExecutorOptions = extractRollupConfigFromExecutorOptions;
const devkit_1 = require("@nx/devkit");
const normalize_path_options_1 = require("./normalize-path-options");
const aliases = {
entryFile: 'main',
exports: 'generateExportsField',
f: 'format',
};
function extractRollupConfigFromExecutorOptions(tree, options, configurations, projectRoot) {
(0, normalize_path_options_1.normalizePathOptions)(projectRoot, options);
const hasConfigurations = !!configurations && Object.keys(configurations).length > 0;
const oldRollupConfig = Array.isArray(options.rollupConfig)
? options.rollupConfig
: options.rollupConfig
? [options.rollupConfig]
: [];
delete options.rollupConfig;
// Resolve conflict with rollup.config.cjs or rollup.config.js if they exist.
for (let i = 0; i < oldRollupConfig.length; i++) {
const file = oldRollupConfig[i];
if (file === './rollup.config.cjs') {
tree.rename((0, devkit_1.joinPathFragments)(projectRoot, 'rollup.config.cjs'), (0, devkit_1.joinPathFragments)(projectRoot, `rollup.migrated.config.cjs`));
oldRollupConfig.splice(i, 1, './rollup.migrated.config.cjs');
}
if (file === './rollup.config.js') {
tree.rename((0, devkit_1.joinPathFragments)(projectRoot, 'rollup.config.js'), (0, devkit_1.joinPathFragments)(projectRoot, `rollup.migrated.config.js`));
oldRollupConfig.splice(i, 1, './rollup.migrated.config.js');
}
}
const defaultOptions = {};
for (const [key, value] of Object.entries(options)) {
if (key === 'watch')
continue;
delete options[key];
if (aliases[key]) {
defaultOptions[aliases[key]] = value;
}
else {
defaultOptions[key] = value;
}
}
let configurationOptions;
if (hasConfigurations) {
configurationOptions = {};
for (const [key, value] of Object.entries(configurations)) {
let newConfigFileName;
let oldRollupConfigForConfiguration;
for (const [optionKey, optionValue] of Object.entries(value)) {
if (optionKey === 'watch')
continue;
/**
* If a configuration lists rollupConfig as an option
* Collect the options and set up a new file to point to
* Set the `--config` option to the new file
*/
if (optionKey === 'rollupConfig') {
oldRollupConfigForConfiguration = Array.isArray(optionValue)
? optionValue
: optionValue
? [optionValue]
: [];
newConfigFileName = `rollup.${key}.config.js`;
for (let i = 0; i < oldRollupConfigForConfiguration.length; i++) {
const file = oldRollupConfigForConfiguration[i];
if (file === newConfigFileName) {
tree.rename((0, devkit_1.joinPathFragments)(projectRoot, newConfigFileName), (0, devkit_1.joinPathFragments)(projectRoot, `rollup.${key}.migrated.config.js`));
oldRollupConfigForConfiguration.splice(i, 1, `./rollup.${key}.migrated.config.js`);
}
}
delete value[optionKey];
value['config'] = newConfigFileName;
continue;
}
delete value[optionKey];
configurationOptions[key] ??= {};
configurationOptions[key][optionKey] = optionValue;
}
/**
* Only if we encountered a rollupConfig in the current configuration
* should we write a new config file, containing all the config values
*/
if (newConfigFileName) {
tree.write((0, devkit_1.joinPathFragments)(projectRoot, newConfigFileName), createNewRollupConfig(oldRollupConfigForConfiguration, defaultOptions, configurationOptions[key], true));
}
}
}
tree.write((0, devkit_1.joinPathFragments)(projectRoot, `rollup.config.cjs`), createNewRollupConfig(oldRollupConfig, defaultOptions, configurationOptions));
return defaultOptions;
}
function createNewRollupConfig(oldRollupConfig, defaultOptions, configurationOptions, singleConfiguration = false) {
if (configurationOptions) {
return (0, devkit_1.stripIndents) `
const { withNx } = require('@nx/rollup/with-nx');
// These options were migrated by @nx/rollup:convert-to-inferred from project.json
const configValues = ${JSON.stringify(singleConfiguration
? {
...defaultOptions,
...configurationOptions,
}
: {
default: defaultOptions,
...configurationOptions,
}, null, 2)};
// Determine the correct configValue to use based on the configuration
const nxConfiguration = process.env.NX_TASK_TARGET_CONFIGURATION ?? 'default';
const options = {
...configValues.default,
...configValues[nxConfiguration],
};
${oldRollupConfig.length > 0 ? 'let' : 'const'} config = withNx(options, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
// e.g.
// output: { sourcemap: true },
});
${oldRollupConfig
// Normalize path
.map((s) => `config = require('${s}')(config, options);`)
.join('\n')}
module.exports = config;
`;
}
else {
return (0, devkit_1.stripIndents) `
const { withNx } = require('@nx/rollup/with-nx');
// These options were migrated by @nx/rollup:convert-to-inferred from project.json
const options = ${JSON.stringify(defaultOptions, null, 2)};
${oldRollupConfig.length > 0 ? 'let' : 'const'} config = withNx(options, {
// Provide additional rollup configuration here. See: https://rollupjs.org/configuration-options
// e.g.
// output: { sourcemap: true },
});
${oldRollupConfig
// Normalize path
.map((s) => `config = require('${s}')(config, options);`)
.join('\n')}
module.exports = config;
`;
}
}

View File

@@ -0,0 +1,3 @@
import { RollupExecutorOptions } from '../../../executors/rollup/schema';
export declare function normalizePathOptions(projectRoot: string, options: RollupExecutorOptions): void;
//# sourceMappingURL=normalize-path-options.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"normalize-path-options.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/generators/convert-to-inferred/lib/normalize-path-options.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAWzE,wBAAgB,oBAAoB,CAClC,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,qBAAqB,GAC7B,IAAI,CAmBN"}

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePathOptions = normalizePathOptions;
const devkit_1 = require("@nx/devkit");
const executorPathFieldsToMigrate = [
'tsConfig',
'project',
'main',
'outputPath',
'rollupConfig',
'additionalEntryPoints',
];
function normalizePathOptions(projectRoot, options) {
for (const [key, value] of Object.entries(options)) {
if (!executorPathFieldsToMigrate.includes(key))
continue;
if (Array.isArray(value)) {
options[key] = value.map((v) => normalizeValue(projectRoot, key, v));
}
else {
options[key] = normalizeValue(projectRoot, key, value);
}
}
}
function normalizeValue(projectRoot, key, value) {
// Logic matches `@nx/rollup:rollup` in `normalizePluginPath` function.
if (!value)
return value;
if (key === 'rollupConfig') {
try {
// If this can load as npm module, keep as is.
require.resolve(value);
return value;
}
catch {
// Otherwise continue below convert to relative path from project.
}
}
if (value.startsWith(`${projectRoot}/`)) {
return value.replace(new RegExp(`^${projectRoot}/`), './');
}
else {
return (0, devkit_1.joinPathFragments)((0, devkit_1.offsetFromRoot)(projectRoot), value);
}
}

View File

@@ -0,0 +1,19 @@
{
"$schema": "https://json-schema.org/schema",
"$id": "NxRollupConvertToInferred",
"description": "Convert existing Rollup project(s) using `@nx/rollup:rollup` executor to use `@nx/rollup/plugin`. Defaults to migrating all projects. Pass '--project' to migrate only one target.",
"title": "Convert Rollup project from executor to plugin",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "The project to convert from using the `@nx/rollup:rollup` executor to use `@nx/rollup/plugin`.",
"x-priority": "important"
},
"skipFormat": {
"type": "boolean",
"description": "Whether to format files at the end of the migration.",
"default": false
}
}
}

View File

@@ -0,0 +1,5 @@
import { GeneratorCallback, Tree } from '@nx/devkit';
import { Schema } from './schema';
export declare function rollupInitGenerator(tree: Tree, schema: Schema): Promise<GeneratorCallback>;
export default rollupInitGenerator;
//# sourceMappingURL=init.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/generators/init/init.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,iBAAiB,EAEjB,IAAI,EACL,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAIlC,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,8BAkDnE;AAED,eAAe,mBAAmB,CAAC"}

42
node_modules/@nx/rollup/src/generators/init/init.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rollupInitGenerator = rollupInitGenerator;
const devkit_1 = require("@nx/devkit");
const versions_1 = require("../../utils/versions");
const add_plugin_1 = require("@nx/devkit/src/utils/add-plugin");
const plugin_1 = require("../../plugins/plugin");
async function rollupInitGenerator(tree, schema) {
let task = () => { };
const nxJson = (0, devkit_1.readNxJson)(tree);
schema.addPlugin ??=
process.env.NX_ADD_PLUGINS !== 'false' &&
nxJson.useInferencePlugins !== false;
if (!schema.skipPackageJson) {
const devDependencies = { '@nx/rollup': versions_1.nxVersion };
if (schema.addPlugin) {
// Ensure user can run Rollup CLI.
devDependencies['rollup'] = versions_1.rollupVersion;
}
task = (0, devkit_1.addDependenciesToPackageJson)(tree, {}, devDependencies, undefined, schema.keepExistingVersions);
}
if (schema.addPlugin) {
await (0, add_plugin_1.addPlugin)(tree, await (0, devkit_1.createProjectGraphAsync)(), '@nx/rollup/plugin', plugin_1.createNodesV2, {
buildTargetName: ['build', 'rollup:build', 'rollup-build'],
buildDepsTargetName: [
'build-deps',
'rollup:build-deps',
'rollup-build-deps',
],
watchDepsTargetName: [
'watch-deps',
'rollup:watch-deps',
'rollup-watch-deps',
],
}, schema.updatePackageScripts);
}
if (!schema.skipFormat) {
await (0, devkit_1.formatFiles)(tree);
}
return task;
}
exports.default = rollupInitGenerator;

View File

@@ -0,0 +1,7 @@
export interface Schema {
skipFormat?: boolean;
skipPackageJson?: boolean;
keepExistingVersions?: boolean;
updatePackageScripts?: boolean;
addPlugin?: boolean;
}

View File

@@ -0,0 +1,33 @@
{
"$schema": "https://json-schema.org/schema",
"$id": "NxWebpackInit",
"cli": "nx",
"title": "Init Webpack Plugin",
"description": "Init Webpack Plugin.",
"type": "object",
"properties": {
"skipFormat": {
"description": "Skip formatting files.",
"type": "boolean",
"default": false
},
"skipPackageJson": {
"description": "Do not add dependencies to `package.json`.",
"type": "boolean",
"default": false
},
"keepExistingVersions": {
"type": "boolean",
"x-priority": "internal",
"description": "Keep existing dependencies versions",
"default": false
},
"updatePackageScripts": {
"type": "boolean",
"x-priority": "internal",
"description": "Update `package.json` scripts with inferred targets",
"default": false
}
},
"required": []
}

5
node_modules/@nx/rollup/src/plugins/analyze.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
export declare function analyze(): {
name: string;
renderChunk(source: any, chunk: any): void;
};
//# sourceMappingURL=analyze.d.ts.map

1
node_modules/@nx/rollup/src/plugins/analyze.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../../../../../packages/rollup/src/plugins/analyze.ts"],"names":[],"mappings":"AAYA,wBAAgB,OAAO;;;EAStB"}

25
node_modules/@nx/rollup/src/plugins/analyze.js generated vendored Normal file
View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.analyze = analyze;
const tslib_1 = require("tslib");
const pc = tslib_1.__importStar(require("picocolors"));
const devkit_1 = require("@nx/devkit");
const formatBytes = (bytes) => {
if (bytes === 0)
return '0 Byte';
const k = 1000;
const dm = 3;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
function analyze() {
return {
name: 'rollup-plugin-nx-analyzer',
renderChunk(source, chunk) {
const sourceBytes = formatBytes(source.length);
const fileName = chunk.fileName;
devkit_1.logger.info(` ${pc.bold(fileName)} ${pc.cyan(sourceBytes)}`);
},
};
}

View File

@@ -0,0 +1,6 @@
import type { Plugin } from 'rollup';
export interface DeleteOutputOptions {
dirs: string[];
}
export declare function deleteOutput(options: DeleteOutputOptions): Plugin;
//# sourceMappingURL=delete-output.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"delete-output.d.ts","sourceRoot":"","sources":["../../../../../packages/rollup/src/plugins/delete-output.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGrC,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB;AAED,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,MAAM,CAMjE"}

10
node_modules/@nx/rollup/src/plugins/delete-output.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteOutput = deleteOutput;
const fs_1 = require("../utils/fs");
function deleteOutput(options) {
return {
name: 'rollup-plugin-nx-delete-output',
buildStart: () => options.dirs.forEach((dir) => (0, fs_1.deleteOutputDir)(process.cwd(), dir)),
};
}

View File

@@ -0,0 +1,24 @@
import type { Plugin } from 'rollup';
import { AssetGlob } from '@nx/js/src/utils/assets/assets';
export interface NxCopyAssetsPluginOptions {
assets: (string | AssetGlob)[];
outputPath: string;
projectRoot: string;
}
/**
* Splits a glob into its literal directory prefix and the remaining pattern.
* CopyAssetsHandler expects input to be a directory and glob to be a pattern
* within it (e.g., input: 'docs', glob: '**\/*.md'), not combined paths.
*
* 'libs/mylib/README.md' => { prefix: 'libs/mylib', glob: 'README.md' }
* 'docs/*.md' => { prefix: 'docs', glob: '*.md' }
* '**\/*.md' => { prefix: '.', glob: '**\/*.md' }
*
* @visibleForTesting
*/
export declare function extractGlobLiteralPrefix(glob: string): {
prefix: string;
glob: string;
};
export declare function nxCopyAssetsPlugin(options: NxCopyAssetsPluginOptions): Plugin;
//# sourceMappingURL=nx-copy-assets.plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nx-copy-assets.plugin.d.ts","sourceRoot":"","sources":["../../../../../packages/rollup/src/plugins/nx-copy-assets.plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,MAAM,gCAAgC,CAAC;AAG3D,MAAM,WAAW,yBAAyB;IACxC,MAAM,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,CAAC;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG;IACtD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;CACd,CAiBA;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,yBAAyB,GAAG,MAAM,CAqD7E"}

View File

@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractGlobLiteralPrefix = extractGlobLiteralPrefix;
exports.nxCopyAssetsPlugin = nxCopyAssetsPlugin;
const node_path_1 = require("node:path");
const devkit_1 = require("@nx/devkit");
const copy_assets_handler_1 = require("@nx/js/src/utils/assets/copy-assets-handler");
/**
* Splits a glob into its literal directory prefix and the remaining pattern.
* CopyAssetsHandler expects input to be a directory and glob to be a pattern
* within it (e.g., input: 'docs', glob: '**\/*.md'), not combined paths.
*
* 'libs/mylib/README.md' => { prefix: 'libs/mylib', glob: 'README.md' }
* 'docs/*.md' => { prefix: 'docs', glob: '*.md' }
* '**\/*.md' => { prefix: '.', glob: '**\/*.md' }
*
* @visibleForTesting
*/
function extractGlobLiteralPrefix(glob) {
const parts = glob.split('/');
const isGlobPart = (p) => p.includes('*') || p.includes('?') || p.includes('[') || p.includes('{');
const firstGlobIndex = parts.findIndex(isGlobPart);
const hasGlob = firstGlobIndex !== -1;
const prefixParts = hasGlob
? parts.slice(0, firstGlobIndex)
: parts.slice(0, -1);
const globParts = hasGlob ? parts.slice(firstGlobIndex) : parts.slice(-1);
return {
prefix: prefixParts.join('/') || '.',
glob: globParts.join('/'),
};
}
function nxCopyAssetsPlugin(options) {
let handler;
let dispose;
if (global.NX_GRAPH_CREATION)
return { name: 'nx-copy-assets-plugin' };
const relativeProjectRoot = (0, node_path_1.relative)(devkit_1.workspaceRoot, options.projectRoot);
return {
name: 'nx-copy-assets-plugin',
async buildStart() {
// Input must be relative to rootDir because CopyAssetsHandler computes
// destination paths using path.relative(input, globResult), and glob
// returns paths relative to rootDir.
const assets = options.assets.map((a) => {
if (typeof a === 'string') {
return (0, node_path_1.join)(relativeProjectRoot, a);
}
else {
// relative() returns '' when paths are equal, normalize to '.'
const relativeInput = (0, node_path_1.relative)(devkit_1.workspaceRoot, a.input) || '.';
const { prefix: globPrefix, glob: normalizedGlob } = extractGlobLiteralPrefix(a.glob);
return {
...a,
input: (0, node_path_1.join)(relativeInput, globPrefix),
glob: normalizedGlob,
};
}
});
const outputDir = (0, node_path_1.isAbsolute)(options.outputPath)
? options.outputPath
: (0, node_path_1.join)(devkit_1.workspaceRoot, options.outputPath);
handler = new copy_assets_handler_1.CopyAssetsHandler({
rootDir: devkit_1.workspaceRoot,
projectDir: options.projectRoot,
outputDir,
assets,
});
if (this.meta.watchMode && (0, devkit_1.isDaemonEnabled)()) {
dispose = await handler.watchAndProcessOnAssetChange();
}
},
async writeBundle() {
await handler.processAllAssetsOnce();
},
closeWatcher() {
dispose?.();
},
};
}

View File

@@ -0,0 +1,14 @@
import type { Plugin } from 'rollup';
import type { PackageJson } from 'nx/src/utils/package-json';
export interface GeneratePackageJsonOptions {
outputPath: string;
main: string;
format: string[];
generateExportsField?: boolean;
skipTypeField?: boolean;
outputFileName?: string;
additionalEntryPoints?: string[];
}
export declare const pluginName = "rollup-plugin-nx-generate-package-json";
export declare function generatePackageJson(options: GeneratePackageJsonOptions, packageJson: PackageJson): Plugin;
//# sourceMappingURL=generate-package-json.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"generate-package-json.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/plugins/package-json/generate-package-json.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAG7D,MAAM,WAAW,0BAA0B;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;CAClC;AAED,eAAO,MAAM,UAAU,2CAA2C,CAAC;AAEnE,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,0BAA0B,EACnC,WAAW,EAAE,WAAW,GACvB,MAAM,CAOR"}

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pluginName = void 0;
exports.generatePackageJson = generatePackageJson;
const update_package_json_1 = require("./update-package-json");
exports.pluginName = 'rollup-plugin-nx-generate-package-json';
function generatePackageJson(options, packageJson) {
return {
name: exports.pluginName,
writeBundle: () => {
(0, update_package_json_1.updatePackageJson)(options, packageJson);
},
};
}

View File

@@ -0,0 +1,11 @@
import { PackageJson } from 'nx/src/utils/package-json';
export declare function updatePackageJson(options: {
outputPath: string;
main: string;
format: string[];
generateExportsField?: boolean;
skipTypeField?: boolean;
outputFileName?: string;
additionalEntryPoints?: string[];
}, packageJson: PackageJson): void;
//# sourceMappingURL=update-package-json.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"update-package-json.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/plugins/package-json/update-package-json.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAGxD,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE;IACP,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;CAClC,EACD,WAAW,EAAE,WAAW,QA0GzB"}

View File

@@ -0,0 +1,104 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePackageJson = updatePackageJson;
const path_1 = require("path");
const fileutils_1 = require("nx/src/utils/fileutils");
const fs_1 = require("fs");
const devkit_1 = require("@nx/devkit");
function updatePackageJson(options, packageJson) {
const jsFileRegex = /(\.cjs|\.mjs|\.esm\.js|\.cjs\.js|\.mjs\.js|\.js)$/;
const hasEsmFormat = options.format.includes('esm');
const hasCjsFormat = options.format.includes('cjs');
if (options.generateExportsField) {
packageJson.exports =
typeof packageJson.exports === 'string' ? {} : { ...packageJson.exports };
packageJson.exports['./package.json'] = './package.json';
}
if (hasEsmFormat) {
const esmExports = getExports({
...options,
fileExt: '.esm.js',
});
packageJson.module = esmExports['.'];
if (!hasCjsFormat) {
if (!options.skipTypeField)
packageJson.type = 'module';
packageJson.main ??= esmExports['.'];
}
if (options.generateExportsField) {
for (const [exportEntry, filePath] of Object.entries(esmExports)) {
packageJson.exports[exportEntry] =
// If CJS format is used, make sure `import` (from Node) points to same instance of the package.
// Otherwise, packages that are required to be singletons (like React, RxJS, etc.) will break.
// Reserve `module` entry for bundlers to accommodate tree-shaking.
{
[hasCjsFormat ? 'module' : 'import']: filePath,
types: filePath.replace(jsFileRegex, '.d.ts'),
};
}
}
}
if (hasCjsFormat) {
const cjsExports = getExports({
...options,
fileExt: '.cjs.js',
});
packageJson.main = cjsExports['.'];
if (!hasEsmFormat && !options.skipTypeField) {
packageJson.type = 'commonjs';
}
if (options.generateExportsField) {
for (const [exportEntry, filePath] of Object.entries(cjsExports)) {
if (hasEsmFormat) {
// If ESM format used, make sure `import` (from Node) points to a wrapped
// version of CJS file to ensure the package remains a singleton.
// TODO(jack): This can be made into a rollup plugin to re-use in Vite.
const relativeFile = (0, path_1.parse)(filePath).base;
const fauxEsmFilePath = filePath.replace(/\.cjs\.js$/, '.cjs.mjs');
packageJson.exports[exportEntry]['import'] ??= fauxEsmFilePath;
packageJson.exports[exportEntry]['default'] ??= filePath;
// Set `types` field only if it's not already set as the preferred ESM Format.
packageJson.exports[exportEntry]['types'] ??= filePath.replace(/\.js$/, '.d.ts');
// Re-export from relative CJS file, and Node will synthetically export it as ESM.
// Make sure both ESM and CJS point to same instance of the package because libs like React, RxJS, etc. requires it.
// Also need a special .cjs.default.js file that re-exports the `default` from CJS, or else
// default import in Node will not work.
(0, fs_1.writeFileSync)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, filePath.replace(/\.cjs\.js$/, '.cjs.default.js')), `exports._default = require('./${(0, path_1.parse)(filePath).base}').default;`);
(0, fs_1.writeFileSync)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, fauxEsmFilePath),
// Re-export from relative CJS file, and Node will synthetically export it as ESM.
(0, devkit_1.stripIndents) `
export * from './${relativeFile}';
export { _default as default } from './${relativeFile.replace(/\.cjs\.js$/, '.cjs.default.js')}';
`);
}
else {
packageJson.exports[exportEntry] = filePath;
}
}
}
}
if (packageJson.module) {
packageJson.types ??= packageJson.module.replace(jsFileRegex, '.d.ts');
}
else {
packageJson.types ??= packageJson.main.replace(jsFileRegex, '.d.ts');
}
(0, fileutils_1.writeJsonFile)((0, path_1.join)(devkit_1.workspaceRoot, options.outputPath, 'package.json'), packageJson);
}
function getExports(options) {
const exports = {};
// Users may provide custom input option and skip the main field.
if (options.main) {
const mainFile = options.outputFileName
? options.outputFileName.replace(/\.[tj]s$/, '')
: (0, path_1.basename)(options.main).replace(/\.[tj]s$/, '');
exports['.'] = './' + mainFile + options.fileExt;
}
if (options.additionalEntryPoints) {
for (const file of options.additionalEntryPoints) {
const { name: fileName } = (0, path_1.parse)(file);
exports['./' + fileName] = './' + fileName + options.fileExt;
}
}
return exports;
}

13
node_modules/@nx/rollup/src/plugins/plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { type CreateDependencies, CreateNodesV2 } from '@nx/devkit';
/**
* @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.
*/
export declare const createDependencies: CreateDependencies;
export interface RollupPluginOptions {
buildTargetName?: string;
buildDepsTargetName?: string;
watchDepsTargetName?: string;
}
export declare const createNodes: CreateNodesV2<RollupPluginOptions>;
export declare const createNodesV2: CreateNodesV2<RollupPluginOptions>;
//# sourceMappingURL=plugin.d.ts.map

1
node_modules/@nx/rollup/src/plugins/plugin.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../../packages/rollup/src/plugins/plugin.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,kBAAkB,EAGvB,aAAa,EAOd,MAAM,YAAY,CAAC;AA+BpB;;GAEG;AACH,eAAO,MAAM,kBAAkB,EAAE,kBAEhC,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAClC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,eAAO,MAAM,WAAW,EAAE,aAAa,CAAC,mBAAmB,CAkC1D,CAAC;AAEF,eAAO,MAAM,aAAa,oCAAc,CAAC"}

166
node_modules/@nx/rollup/src/plugins/plugin.js generated vendored Normal file
View File

@@ -0,0 +1,166 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNodesV2 = exports.createNodes = exports.createDependencies = void 0;
const cache_directory_1 = require("nx/src/utils/cache-directory");
const path_1 = require("path");
const fs_1 = require("fs");
const devkit_1 = require("@nx/devkit");
const calculate_hash_for_create_nodes_1 = require("@nx/devkit/src/utils/calculate-hash-for-create-nodes");
const js_1 = require("@nx/js");
const get_named_inputs_1 = require("@nx/devkit/src/utils/get-named-inputs");
const file_hasher_1 = require("nx/src/hasher/file-hasher");
const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
const util_1 = require("@nx/js/src/plugins/typescript/util");
function readTargetsCache(cachePath) {
try {
return process.env.NX_CACHE_PROJECT_GRAPH !== 'false'
? (0, devkit_1.readJsonFile)(cachePath)
: {};
}
catch {
return {};
}
}
function writeTargetsToCache(cachePath, results) {
(0, devkit_1.writeJsonFile)(cachePath, results);
}
/**
* @deprecated The 'createDependencies' function is now a no-op. This functionality is included in 'createNodesV2'.
*/
const createDependencies = () => {
return [];
};
exports.createDependencies = createDependencies;
const rollupConfigGlob = '**/rollup.config.{js,cjs,mjs,ts,cts,mts}';
exports.createNodes = [
rollupConfigGlob,
async (configFilePaths, options, context) => {
const normalizedOptions = normalizeOptions(options);
const optionsHash = (0, file_hasher_1.hashObject)(normalizedOptions);
const cachePath = (0, path_1.join)(cache_directory_1.workspaceDataDirectory, `rollup-${optionsHash}.hash`);
const targetsCache = readTargetsCache(cachePath);
const isTsSolutionSetup = (0, ts_solution_setup_1.isUsingTsSolutionSetup)();
const pmc = (0, devkit_1.getPackageManagerCommand)((0, devkit_1.detectPackageManager)(context.workspaceRoot));
try {
return await (0, devkit_1.createNodesFromFiles)((configFile, _, context) => createNodesInternal(configFile, normalizedOptions, context, targetsCache, isTsSolutionSetup, pmc), configFilePaths, normalizedOptions, context);
}
finally {
writeTargetsToCache(cachePath, targetsCache);
}
},
];
exports.createNodesV2 = exports.createNodes;
async function createNodesInternal(configFilePath, options, context, targetsCache, isTsSolutionSetup, pmc) {
const projectRoot = (0, path_1.dirname)(configFilePath);
const fullyQualifiedProjectRoot = (0, path_1.join)(context.workspaceRoot, projectRoot);
// Do not create a project if package.json and project.json do not exist
const siblingFiles = (0, fs_1.readdirSync)(fullyQualifiedProjectRoot);
if (!siblingFiles.includes('package.json') &&
!siblingFiles.includes('project.json')) {
return {};
}
const hash = await (0, calculate_hash_for_create_nodes_1.calculateHashForCreateNodes)(projectRoot, options, context, [(0, js_1.getLockFileName)((0, devkit_1.detectPackageManager)(context.workspaceRoot))]);
targetsCache[hash] ??= await buildRollupTarget(configFilePath, projectRoot, options, context, isTsSolutionSetup, pmc);
return {
projects: {
[projectRoot]: {
root: projectRoot,
targets: targetsCache[hash],
},
},
};
}
async function buildRollupTarget(configFilePath, projectRoot, options, context, isTsSolutionSetup, pmc) {
let loadConfigFile;
try {
// Try to load the workspace version of rollup first (it should already exist).
// Using the workspace rollup ensures that the config file is compatible with the `loadConfigFile` function.
// e.g. rollup@2 supports having `require` calls in rollup config, but rollup@4 does not.
const m = require(require.resolve('rollup/loadConfigFile', {
paths: [(0, path_1.dirname)(configFilePath)],
}));
// Rollup 2 has this has default export, but it is named in 3 and 4.
// See: https://www.unpkg.com/browse/rollup@2.79.1/dist/loadConfigFile.js
loadConfigFile = typeof m === 'function' ? m : m.loadConfigFile;
}
catch {
// Fallback to our own if needed.
loadConfigFile = require('rollup/loadConfigFile').loadConfigFile;
}
const isTsConfig = configFilePath.endsWith('ts');
const tsConfigPlugin = '@rollup/plugin-typescript';
const namedInputs = (0, get_named_inputs_1.getNamedInputs)(projectRoot, context);
const rollupConfig = (await loadConfigFile((0, devkit_1.joinPathFragments)(context.workspaceRoot, configFilePath), isTsConfig ? { configPlugin: tsConfigPlugin } : {}, true // Enable watch mode so that rollup properly reloads config files without reusing a cached version
)).options;
const outputs = getOutputs(rollupConfig, projectRoot);
const targets = {};
targets[options.buildTargetName] = {
command: `rollup -c ${(0, path_1.basename)(configFilePath)}${isTsConfig
? ` --configPlugin typescript={tsconfig:\\'tsconfig.lib.json\\'}`
: ''}`,
options: { cwd: projectRoot },
cache: true,
dependsOn: [`^${options.buildTargetName}`],
inputs: [
...('production' in namedInputs
? ['production', '^production']
: ['default', '^default']),
{ externalDependencies: ['rollup'] },
ts_solution_setup_1.TS_SOLUTION_SETUP_TSCONFIG_INPUT,
],
outputs,
metadata: {
technologies: ['rollup'],
description: 'Run Rollup',
help: {
command: `${pmc.exec} rollup --help`,
example: {
options: {
sourcemap: true,
watch: true,
},
},
},
},
};
if (isTsSolutionSetup) {
targets[options.buildTargetName].syncGenerators = [
'@nx/js:typescript-sync',
];
}
(0, util_1.addBuildAndWatchDepsTargets)(context.workspaceRoot, projectRoot, targets, options, pmc);
return targets;
}
function getOutputs(rollupConfigs, projectRoot) {
const outputs = new Set();
for (const rollupConfig of rollupConfigs) {
if (rollupConfig.output) {
const rollupConfigOutputs = [];
if (Array.isArray(rollupConfig.output)) {
rollupConfigOutputs.push(...rollupConfig.output);
}
else {
rollupConfigOutputs.push(rollupConfig.output);
}
for (const output of rollupConfigOutputs) {
const outputPathFromConfig = output.dir
? output.dir
: output.file
? (0, path_1.dirname)(output.file)
: 'dist';
const outputPath = projectRoot === '.'
? (0, devkit_1.joinPathFragments)(`{workspaceRoot}`, outputPathFromConfig)
: (0, devkit_1.joinPathFragments)(`{workspaceRoot}`, projectRoot, outputPathFromConfig);
outputs.add(outputPath);
}
}
}
return Array.from(outputs);
}
function normalizeOptions(options) {
return {
buildTargetName: options.buildTargetName ?? 'build',
buildDepsTargetName: options.buildDepsTargetName ?? 'build-deps',
watchDepsTargetName: options.watchDepsTargetName ?? 'watch-deps',
};
}

16
node_modules/@nx/rollup/src/plugins/postcss/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* @nx/rollup PostCSS plugin
*
* An inlined, simplified version of rollup-plugin-postcss that:
* - Processes CSS files through PostCSS
* - Supports CSS preprocessors (Sass, Less, Stylus)
* - Supports CSS Modules
* - Can inject CSS into DOM or extract to separate files
*
* This replaces the external rollup-plugin-postcss dependency to avoid
* peer dependency conflicts and maintenance issues.
*/
export { postcss } from './postcss-plugin';
export { postcss as default } from './postcss-plugin';
export type { PostCSSPluginOptions, PostCSSModulesOptions, FilterPattern, UseOptions, LessOptions, SassOptions, StylusOptions, } from './options';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/plugins/postcss/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAEtD,YAAY,EACV,oBAAoB,EACpB,qBAAqB,EACrB,aAAa,EACb,UAAU,EACV,WAAW,EACX,WAAW,EACX,aAAa,GACd,MAAM,WAAW,CAAC"}

19
node_modules/@nx/rollup/src/plugins/postcss/index.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
"use strict";
/**
* @nx/rollup PostCSS plugin
*
* An inlined, simplified version of rollup-plugin-postcss that:
* - Processes CSS files through PostCSS
* - Supports CSS preprocessors (Sass, Less, Stylus)
* - Supports CSS Modules
* - Can inject CSS into DOM or extract to separate files
*
* This replaces the external rollup-plugin-postcss dependency to avoid
* peer dependency conflicts and maintenance issues.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = exports.postcss = void 0;
var postcss_plugin_1 = require("./postcss-plugin");
Object.defineProperty(exports, "postcss", { enumerable: true, get: function () { return postcss_plugin_1.postcss; } });
var postcss_plugin_2 = require("./postcss-plugin");
Object.defineProperty(exports, "default", { enumerable: true, get: function () { return postcss_plugin_2.postcss; } });

View File

@@ -0,0 +1,38 @@
import type { LoaderContext, LoaderResult, PostCSSLoaderOptions } from './types';
import type { UseOptions } from '../options';
export * from './types';
export { createPostCSSLoader } from './postcss-loader';
export { createLessLoader } from './less-loader';
export { createSassLoader } from './sass-loader';
export { createStylusLoader } from './stylus-loader';
interface LoadersOptions {
/** PostCSS loader options */
postcss: PostCSSLoaderOptions;
/** Preprocessor options */
use: UseOptions;
}
/**
* Manages the chain of CSS loaders (preprocessors + PostCSS)
*/
export declare class Loaders {
private loaders;
constructor(options: LoadersOptions);
/**
* Register preprocessor loaders based on the 'use' option
*/
private registerPreprocessors;
/**
* Check if any loader can process the given file
*/
isSupported(filepath: string): boolean;
/**
* Check if a file matches a loader's test
*/
private matchesLoader;
/**
* Process a file through the loader chain
* Preprocessors run first (if matching), then PostCSS always runs
*/
process(code: string, context: LoaderContext): Promise<LoaderResult>;
}
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACb,YAAY,EACZ,oBAAoB,EAIrB,MAAM,SAAS,CAAC;AAKjB,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,UAAU,cAAc;IACtB,6BAA6B;IAC7B,OAAO,EAAE,oBAAoB,CAAC;IAC9B,2BAA2B;IAC3B,GAAG,EAAE,UAAU,CAAC;CACjB;AAED;;GAEG;AACH,qBAAa,OAAO;IAClB,OAAO,CAAC,OAAO,CAAgB;gBAEnB,OAAO,EAAE,cAAc;IASnC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAuB7B;;OAEG;IACH,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAItC;;OAEG;IACH,OAAO,CAAC,aAAa;IAOrB;;;OAGG;IACG,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;CAwB3E"}

View File

@@ -0,0 +1,90 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Loaders = exports.createStylusLoader = exports.createSassLoader = exports.createLessLoader = exports.createPostCSSLoader = void 0;
const tslib_1 = require("tslib");
const postcss_loader_1 = require("./postcss-loader");
const less_loader_1 = require("./less-loader");
const sass_loader_1 = require("./sass-loader");
const stylus_loader_1 = require("./stylus-loader");
tslib_1.__exportStar(require("./types"), exports);
var postcss_loader_2 = require("./postcss-loader");
Object.defineProperty(exports, "createPostCSSLoader", { enumerable: true, get: function () { return postcss_loader_2.createPostCSSLoader; } });
var less_loader_2 = require("./less-loader");
Object.defineProperty(exports, "createLessLoader", { enumerable: true, get: function () { return less_loader_2.createLessLoader; } });
var sass_loader_2 = require("./sass-loader");
Object.defineProperty(exports, "createSassLoader", { enumerable: true, get: function () { return sass_loader_2.createSassLoader; } });
var stylus_loader_2 = require("./stylus-loader");
Object.defineProperty(exports, "createStylusLoader", { enumerable: true, get: function () { return stylus_loader_2.createStylusLoader; } });
/**
* Manages the chain of CSS loaders (preprocessors + PostCSS)
*/
class Loaders {
constructor(options) {
this.loaders = [];
// Register preprocessor loaders based on 'use' options
// These are registered first and process files before PostCSS
this.registerPreprocessors(options.use);
// Register the PostCSS loader last - it always processes
this.loaders.push((0, postcss_loader_1.createPostCSSLoader)(options.postcss));
}
/**
* Register preprocessor loaders based on the 'use' option
*/
registerPreprocessors(use) {
// Less loader
if (use.less !== false) {
const lessOptions = typeof use.less === 'object' ? use.less : {};
this.loaders.push((0, less_loader_1.createLessLoader)(lessOptions));
}
// Sass loader
if (use.sass !== false) {
const sassOptions = typeof use.sass === 'object' ? use.sass : {};
this.loaders.push((0, sass_loader_1.createSassLoader)(sassOptions));
}
// Stylus loader
if (use.stylus !== false) {
const stylusOptions = typeof use.stylus === 'object' ? use.stylus : {};
this.loaders.push((0, stylus_loader_1.createStylusLoader)(stylusOptions));
}
}
/**
* Check if any loader can process the given file
*/
isSupported(filepath) {
return this.loaders.some((loader) => this.matchesLoader(loader, filepath));
}
/**
* Check if a file matches a loader's test
*/
matchesLoader(loader, filepath) {
if (typeof loader.test === 'function') {
return loader.test(filepath);
}
return loader.test.test(filepath);
}
/**
* Process a file through the loader chain
* Preprocessors run first (if matching), then PostCSS always runs
*/
async process(code, context) {
let result = { code };
// Process through each loader in order
for (const loader of this.loaders) {
// Skip non-matching loaders unless they always process
if (!loader.alwaysProcess && !this.matchesLoader(loader, context.id)) {
continue;
}
// Process with this loader
const loaderResult = await loader.process(result.code, context);
// Merge the result
result = {
...result,
...loaderResult,
// Preserve the map from the latest loader that produced one
map: loaderResult.map ?? result.map,
};
}
return result;
}
}
exports.Loaders = Loaders;

View File

@@ -0,0 +1,7 @@
import type { Loader, LessLoaderOptions } from './types';
/**
* Less preprocessor loader
* Compiles .less files to CSS
*/
export declare function createLessLoader(options?: LessLoaderOptions): Loader;
//# sourceMappingURL=less-loader.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"less-loader.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/less-loader.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,MAAM,EAGN,iBAAiB,EAClB,MAAM,SAAS,CAAC;AAwCjB;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CA2CxE"}

View File

@@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLessLoader = createLessLoader;
const util_1 = require("util");
const utils_1 = require("../utils");
let less;
/**
* Less preprocessor loader
* Compiles .less files to CSS
*/
function createLessLoader(options = {}) {
return {
name: 'less',
test: /\.less$/,
async process(code, context) {
if (!less) {
less = (0, utils_1.requireModule)('less', 'Less');
}
const render = (0, util_1.promisify)(less.render.bind(less));
const result = await render(code, {
...options,
filename: context.id,
sourceMap: context.sourceMap
? {
outputSourceFiles: true,
}
: undefined,
});
// Track dependencies
if (result.imports) {
for (const dep of result.imports) {
context.dependencies.add(dep);
}
}
let map;
if (result.map) {
map = JSON.parse(result.map);
if (map && map.sources) {
map.sources = map.sources.map(utils_1.humanizePath);
}
}
return {
code: result.css,
map,
};
},
};
}

View File

@@ -0,0 +1,7 @@
import type { Loader, PostCSSLoaderOptions } from './types';
/**
* PostCSS loader - processes CSS through PostCSS plugins
* This loader always runs last in the chain
*/
export declare function createPostCSSLoader(options: PostCSSLoaderOptions): Loader;
//# sourceMappingURL=postcss-loader.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"postcss-loader.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/postcss-loader.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,MAAM,EAGN,oBAAoB,EACrB,MAAM,SAAS,CAAC;AAejB;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,oBAAoB,GAAG,MAAM,CAsHzE"}

View File

@@ -0,0 +1,173 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPostCSSLoader = createPostCSSLoader;
const tslib_1 = require("tslib");
const path_1 = require("path");
const postcss_1 = tslib_1.__importDefault(require("postcss"));
const utils_1 = require("../utils");
/**
* Check if a file should use CSS modules based on its filename
*/
function shouldUseCSSModules(filepath, autoModules) {
if (!autoModules) {
return false;
}
// Check for .module.xxx pattern
const filename = (0, path_1.basename)(filepath);
return /\.module\.[a-z]+$/i.test(filename);
}
/**
* PostCSS loader - processes CSS through PostCSS plugins
* This loader always runs last in the chain
*/
function createPostCSSLoader(options) {
return {
name: 'postcss',
test: /\.(css|sss|pcss|sass|scss|less|styl|stylus)$/,
alwaysProcess: true,
async process(code, context) {
const { plugins, modules, autoModules, extract, inject } = options;
// Determine if CSS modules should be used
const shouldUseModules = modules || shouldUseCSSModules(context.id, autoModules);
// Collect CSS module exports
let cssModuleExports;
// Build the PostCSS plugins array
const postcssPlugins = [...plugins];
// Add CSS modules plugin if needed
if (shouldUseModules) {
try {
const postcssModules = require('postcss-modules');
const modulesOptions = typeof modules === 'object' ? modules : {};
postcssPlugins.unshift(postcssModules({
...modulesOptions,
getJSON(_cssFilename, json, _outputFilename) {
cssModuleExports = json;
},
}));
}
catch {
throw new Error('You need to install "postcss-modules" package in order to use CSS Modules.');
}
}
// Process with PostCSS
const processOptions = {
from: context.id,
to: context.id,
map: context.sourceMap
? {
inline: context.sourceMap === 'inline',
annotation: false,
sourcesContent: true,
}
: false,
};
const result = await (0, postcss_1.default)(postcssPlugins).process(code, processOptions);
// Track dependencies from PostCSS messages
for (const message of result.messages) {
if (message.type === 'dependency') {
context.dependencies.add(message.file);
}
}
// Emit warnings
for (const warning of result.warnings()) {
context.warn(warning.toString());
}
// Get the source map
let map;
if (result.map) {
map = result.map.toJSON();
if (map?.sources) {
map.sources = map.sources.map(utils_1.humanizePath);
}
}
// If extracting CSS, return the extracted content
if (extract) {
return {
code: generateModuleCode(cssModuleExports),
map: undefined,
extracted: {
code: result.css,
map,
},
exports: cssModuleExports,
};
}
// If injecting CSS, return code that injects at runtime
if (inject) {
return {
code: generateInjectCode(result.css, context.id, inject, cssModuleExports),
map: undefined,
exports: cssModuleExports,
};
}
// Otherwise return the CSS as a string export
return {
code: generateModuleCode(cssModuleExports, result.css),
map,
exports: cssModuleExports,
};
},
};
}
/**
* Generate JavaScript module code for CSS exports
*/
function generateModuleCode(exports, css) {
const lines = [];
if (exports && Object.keys(exports).length > 0) {
// Export each class name
for (const [key, value] of Object.entries(exports)) {
const safeName = (0, utils_1.safeIdentifier)(key);
lines.push(`export var ${safeName} = ${JSON.stringify(value)};`);
}
// Default export is the full exports object
lines.push(`export default ${JSON.stringify(exports)};`);
}
else if (css !== undefined) {
// Export the CSS string as default
lines.push(`export default ${JSON.stringify(css)};`);
}
else {
// Empty export
lines.push(`export default {};`);
}
return lines.join('\n');
}
/**
* Generate JavaScript code that injects CSS at runtime
*/
function generateInjectCode(css, id, inject, exports) {
const lines = [];
// Import style-inject
lines.push(`import styleInject from '${utils_1.STYLE_INJECT_PATH}';`);
lines.push('');
// CSS string variable
lines.push(`var css = ${JSON.stringify(css)};`);
lines.push('');
// Inject the CSS
if (typeof inject === 'function') {
// Custom inject function
lines.push(`(${inject.toString()})(css, ${JSON.stringify(id)});`);
}
else if (typeof inject === 'object') {
// Inject with options
lines.push(`styleInject(css, ${JSON.stringify(inject)});`);
}
else {
// Default inject
lines.push(`styleInject(css);`);
}
lines.push('');
// Export CSS module classes if any
if (exports && Object.keys(exports).length > 0) {
for (const [key, value] of Object.entries(exports)) {
const safeName = (0, utils_1.safeIdentifier)(key);
lines.push(`export var ${safeName} = ${JSON.stringify(value)};`);
}
lines.push(`export default ${JSON.stringify(exports)};`);
}
else {
lines.push(`export default css;`);
}
return lines.join('\n');
}

View File

@@ -0,0 +1,7 @@
import type { Loader, SassLoaderOptions } from './types';
/**
* Sass/SCSS preprocessor loader
* Compiles .sass and .scss files to CSS
*/
export declare function createSassLoader(options?: SassLoaderOptions): Loader;
//# sourceMappingURL=sass-loader.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"sass-loader.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/sass-loader.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,MAAM,EAGN,iBAAiB,EAClB,MAAM,SAAS,CAAC;AA4IjB;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CAuGxE"}

View File

@@ -0,0 +1,164 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSassLoader = createSassLoader;
const path_1 = require("path");
const utils_1 = require("../utils");
let sassModule;
let isModernSass = false;
/**
* Get the sass module, trying modern sass first, then node-sass
*/
function getSassModule() {
if (sassModule) {
return sassModule;
}
// Try modern sass first
const modernSass = (0, utils_1.loadModule)('sass');
if (modernSass && typeof modernSass.compile === 'function') {
sassModule = modernSass;
isModernSass = true;
return sassModule;
}
// Try legacy sass (or node-sass)
const legacySass = (0, utils_1.loadModule)('sass') || (0, utils_1.loadModule)('node-sass');
if (legacySass && typeof legacySass.render === 'function') {
sassModule = legacySass;
isModernSass = false;
return sassModule;
}
throw new Error('You need to install "sass" or "node-sass" package in order to process Sass files.');
}
/**
* Resolve a module import (handles ~ prefix for node_modules)
*/
function resolveModuleImport(url, prev) {
if (!url.startsWith('~')) {
return null;
}
const modulePath = url.slice(1);
const prevDir = (0, path_1.dirname)(prev);
// Try to resolve from node_modules
const paths = [
(0, path_1.join)(prevDir, 'node_modules', modulePath),
(0, path_1.join)(process.cwd(), 'node_modules', modulePath),
];
// Also try partial file (with underscore prefix)
const dir = (0, path_1.dirname)(modulePath);
const file = (0, path_1.basename)(modulePath);
const partialPaths = [
(0, path_1.join)(prevDir, 'node_modules', dir, `_${file}`),
(0, path_1.join)(process.cwd(), 'node_modules', dir, `_${file}`),
];
// Try all paths with various extensions
const extensions = ['', '.scss', '.sass', '.css'];
for (const basePath of [...partialPaths, ...paths]) {
for (const ext of extensions) {
const fullPath = basePath + ext;
try {
require.resolve(fullPath);
return fullPath;
}
catch {
// Continue trying
}
}
}
return null;
}
/**
* Sass/SCSS preprocessor loader
* Compiles .sass and .scss files to CSS
*/
function createSassLoader(options = {}) {
return {
name: 'sass',
test: /\.(sass|scss)$/,
async process(code, context) {
const sass = getSassModule();
const { implementation: _, ...sassOptions } = options;
if (isModernSass) {
// Modern sass (Dart Sass) with compile API
const modernSass = sass;
const result = modernSass.compileString(code, {
...sassOptions,
loadPaths: [(0, path_1.dirname)(context.id), process.cwd(), 'node_modules'],
sourceMap: !!context.sourceMap,
importers: [
{
findFileUrl(url) {
const resolved = resolveModuleImport(url, context.id);
if (resolved) {
return new URL(`file://${(0, path_1.resolve)(resolved)}`);
}
return null;
},
},
],
});
// Track dependencies
for (const loadedUrl of result.loadedUrls) {
if (loadedUrl.protocol === 'file:') {
context.dependencies.add(loadedUrl.pathname);
}
}
let map;
if (result.sourceMap) {
map = result.sourceMap;
if (map?.sources) {
map.sources = map.sources.map(utils_1.humanizePath);
}
}
return {
code: result.css,
map,
};
}
else {
// Legacy sass/node-sass with render API
const legacySass = sass;
return new Promise((resolvePromise, reject) => {
legacySass.render({
...sassOptions,
data: code,
file: context.id,
includePaths: [(0, path_1.dirname)(context.id), process.cwd()],
sourceMap: !!context.sourceMap,
outFile: context.id,
sourceMapContents: true,
importer: (url, prev, done) => {
const resolved = resolveModuleImport(url, prev);
if (resolved) {
done({ file: resolved });
}
else {
done(null);
}
},
}, (error, result) => {
if (error) {
reject(error);
return;
}
// Track dependencies
if (result.stats.includedFiles) {
for (const dep of result.stats.includedFiles) {
context.dependencies.add(dep);
}
}
let map;
if (result.map) {
map = JSON.parse(result.map.toString());
if (map?.sources) {
map.sources = map.sources.map(utils_1.humanizePath);
}
}
resolvePromise({
code: result.css.toString(),
map,
});
});
});
}
},
};
}

View File

@@ -0,0 +1,7 @@
import type { Loader, StylusLoaderOptions } from './types';
/**
* Stylus preprocessor loader
* Compiles .styl and .stylus files to CSS
*/
export declare function createStylusLoader(options?: StylusLoaderOptions): Loader;
//# sourceMappingURL=stylus-loader.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"stylus-loader.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/stylus-loader.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,MAAM,EAGN,mBAAmB,EACpB,MAAM,SAAS,CAAC;AAqBjB;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,MAAM,CA0D5E"}

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createStylusLoader = createStylusLoader;
const path_1 = require("path");
const utils_1 = require("../utils");
let stylus;
/**
* Stylus preprocessor loader
* Compiles .styl and .stylus files to CSS
*/
function createStylusLoader(options = {}) {
return {
name: 'stylus',
test: /\.(styl|stylus)$/,
async process(code, context) {
if (!stylus) {
stylus = (0, utils_1.requireModule)('stylus', 'Stylus');
}
const renderer = stylus(code);
// Set options
renderer.set('filename', context.id);
renderer.set('paths', [(0, path_1.dirname)(context.id), process.cwd()]);
if (context.sourceMap) {
renderer.set('sourcemap', {
comment: false,
inline: false,
basePath: process.cwd(),
});
}
// Apply additional options
for (const [key, value] of Object.entries(options)) {
renderer.set(key, value);
}
return new Promise((resolve, reject) => {
renderer.render((error, css) => {
if (error) {
reject(error);
return;
}
// Track dependencies
const deps = renderer.deps();
for (const dep of deps) {
context.dependencies.add(dep);
}
let map;
if (renderer.sourcemap) {
map = renderer.sourcemap;
if (map?.sources) {
map.sources = map.sources.map(utils_1.humanizePath);
}
}
resolve({
code: css,
map,
});
});
});
},
};
}

View File

@@ -0,0 +1,88 @@
import type { RawSourceMap } from 'source-map-js';
import type { PostCSSModulesOptions } from '../options';
import type { AcceptedPlugin } from 'postcss';
/**
* Context passed to each loader during processing
*/
export interface LoaderContext {
/** Absolute path to the file being processed */
id: string;
/** Whether source maps are enabled */
sourceMap: boolean | 'inline';
/** Set of file dependencies (for watch mode) */
dependencies: Set<string>;
/** Function to emit warnings */
warn: (message: string) => void;
}
/**
* Result returned from a loader
*/
export interface LoaderResult {
/** Processed CSS/code */
code: string;
/** Source map (if generated) */
map?: RawSourceMap;
/** Extracted CSS content (for extraction mode) */
extracted?: {
/** CSS content */
code: string;
/** CSS source map */
map?: RawSourceMap;
};
/** CSS module exports (class name mappings) */
exports?: Record<string, string>;
}
/**
* Interface for CSS loaders (preprocessors and PostCSS)
*/
export interface Loader {
/** Unique name for this loader */
name: string;
/** Test to determine if this loader should process a file */
test: RegExp | ((filepath: string) => boolean);
/** Whether this loader should always process files (like postcss-loader) */
alwaysProcess?: boolean;
/** Process the file and return the result */
process(code: string, context: LoaderContext, options?: Record<string, unknown>): Promise<LoaderResult>;
}
/**
* Options for the PostCSS loader
*/
export interface PostCSSLoaderOptions {
/** PostCSS plugins to apply */
plugins: AcceptedPlugin[];
/** CSS modules options */
modules: boolean | PostCSSModulesOptions;
/** Auto-detect CSS modules from .module.xxx files */
autoModules: boolean;
/** Extract CSS to separate file instead of injecting */
extract: boolean | string;
/** Inject CSS into DOM */
inject: boolean | Record<string, unknown> | ((cssVar: string, id: string) => string);
}
/**
* Options for the Less loader
*/
export interface LessLoaderOptions {
/** Enable inline JavaScript in Less files */
javascriptEnabled?: boolean;
/** Additional Less options */
[key: string]: unknown;
}
/**
* Options for the Sass loader
*/
export interface SassLoaderOptions {
/** Sass implementation to use */
implementation?: string;
/** Additional Sass options */
[key: string]: unknown;
}
/**
* Options for the Stylus loader
*/
export interface StylusLoaderOptions {
/** Additional Stylus options */
[key: string]: unknown;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/loaders/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,gDAAgD;IAChD,EAAE,EAAE,MAAM,CAAC;IACX,sCAAsC;IACtC,SAAS,EAAE,OAAO,GAAG,QAAQ,CAAC;IAC9B,gDAAgD;IAChD,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,gCAAgC;IAChC,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,yBAAyB;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,GAAG,CAAC,EAAE,YAAY,CAAC;IACnB,kDAAkD;IAClD,SAAS,CAAC,EAAE;QACV,kBAAkB;QAClB,IAAI,EAAE,MAAM,CAAC;QACb,qBAAqB;QACrB,GAAG,CAAC,EAAE,YAAY,CAAC;KACpB,CAAC;IACF,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB,kCAAkC;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,6DAA6D;IAC7D,IAAI,EAAE,MAAM,GAAG,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;IAC/C,4EAA4E;IAC5E,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,6CAA6C;IAC7C,OAAO,CACL,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAChC,OAAO,CAAC,YAAY,CAAC,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,+BAA+B;IAC/B,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,0BAA0B;IAC1B,OAAO,EAAE,OAAO,GAAG,qBAAqB,CAAC;IACzC,qDAAqD;IACrD,WAAW,EAAE,OAAO,CAAC;IACrB,wDAAwD;IACxD,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC;IAC1B,0BAA0B;IAC1B,MAAM,EACF,OAAO,GACP,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvB,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;CAC9C;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,6CAA6C;IAC7C,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,8BAA8B;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,iCAAiC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8BAA8B;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,gCAAgC;IAChC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB"}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,111 @@
import type { AcceptedPlugin } from 'postcss';
export type FilterPattern = string | RegExp | (string | RegExp)[];
export interface PostCSSModulesOptions {
/** Generate scoped names */
generateScopedName?: string | ((name: string, filename: string, css: string) => string);
/** Scope behaviour */
scopeBehaviour?: 'global' | 'local';
/** Global module paths */
globalModulePaths?: RegExp[];
/** Export globals */
exportGlobals?: boolean;
/** Hash prefix */
hashPrefix?: string;
/** Locate imports */
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly';
}
export interface LessOptions {
/** Enable inline JavaScript in Less files */
javascriptEnabled?: boolean;
/** Additional Less options */
[key: string]: unknown;
}
export interface SassOptions {
/** Sass implementation to use ('sass' or 'node-sass') */
implementation?: string;
/** Additional Sass options */
[key: string]: unknown;
}
export interface StylusOptions {
/** Additional Stylus options */
[key: string]: unknown;
}
export interface UseOptions {
sass?: SassOptions | false;
less?: LessOptions | false;
stylus?: StylusOptions | false;
}
export interface PostCSSPluginOptions {
/**
* Inject CSS as <style> tag to <head>
* @default true
*/
inject?: boolean | Record<string, unknown> | ((cssVar: string, id: string) => string);
/**
* Extract CSS to a separate file
* - `true`: Extract to `[name].css`
* - `string`: Extract to the specified path
* @default false
*/
extract?: boolean | string;
/**
* Automatically enable CSS modules for `.module.xxx` files
* @default false
*/
autoModules?: boolean;
/**
* Enable CSS modules
* - `true`: Enable with default options
* - `object`: Enable with custom options
* @default false
*/
modules?: boolean | PostCSSModulesOptions;
/**
* PostCSS plugins to apply
*/
plugins?: AcceptedPlugin[];
/**
* Preprocessor options
*/
use?: UseOptions;
/**
* Files to include
* @default [/\.css$/, /\.sss$/, /\.pcss$/]
*/
include?: FilterPattern;
/**
* Files to exclude
* @default /node_modules/
*/
exclude?: FilterPattern;
/**
* Generate source maps
* - `true`: Generate external source maps
* - `'inline'`: Generate inline source maps
* @default false
*/
sourceMap?: boolean | 'inline';
/**
* File extensions to process
* @default ['.css', '.sss', '.pcss']
*/
extensions?: string[];
}
/**
* Internal options after normalization
*/
export interface NormalizedPostCSSOptions extends PostCSSPluginOptions {
inject: boolean | Record<string, unknown> | ((cssVar: string, id: string) => string);
extract: boolean | string;
autoModules: boolean;
modules: boolean | PostCSSModulesOptions;
plugins: AcceptedPlugin[];
use: UseOptions;
extensions: string[];
sourceMap: boolean | 'inline';
}
/**
* Normalize plugin options with defaults
*/
export declare function normalizeOptions(options?: PostCSSPluginOptions): NormalizedPostCSSOptions;
//# sourceMappingURL=options.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"options.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/plugins/postcss/options.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAC;AAElE,MAAM,WAAW,qBAAqB;IACpC,4BAA4B;IAC5B,kBAAkB,CAAC,EACf,MAAM,GACN,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;IAC9D,sBAAsB;IACtB,cAAc,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC;IACpC,0BAA0B;IAC1B,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,qBAAqB;IACrB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,kBAAkB;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,qBAAqB;IACrB,gBAAgB,CAAC,EAAE,WAAW,GAAG,eAAe,GAAG,QAAQ,GAAG,YAAY,CAAC;CAC5E;AAED,MAAM,WAAW,WAAW;IAC1B,6CAA6C;IAC7C,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,8BAA8B;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,WAAW;IAC1B,yDAAyD;IACzD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,8BAA8B;IAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,aAAa;IAC5B,gCAAgC;IAChC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,UAAU;IACzB,IAAI,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC;IAC3B,IAAI,CAAC,EAAE,WAAW,GAAG,KAAK,CAAC;IAC3B,MAAM,CAAC,EAAE,aAAa,GAAG,KAAK,CAAC;CAChC;AAED,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,MAAM,CAAC,EACH,OAAO,GACP,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvB,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;IAE7C;;;;;OAKG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAE3B;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,qBAAqB,CAAC;IAE1C;;OAEG;IACH,OAAO,CAAC,EAAE,cAAc,EAAE,CAAC;IAE3B;;OAEG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;IAEjB;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC;IAExB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAE/B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,wBAAyB,SAAQ,oBAAoB;IACpE,MAAM,EACF,OAAO,GACP,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACvB,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,MAAM,CAAC,CAAC;IAC7C,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC;IAC1B,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,OAAO,GAAG,qBAAqB,CAAC;IACzC,OAAO,EAAE,cAAc,EAAE,CAAC;IAC1B,GAAG,EAAE,UAAU,CAAC;IAChB,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,SAAS,EAAE,OAAO,GAAG,QAAQ,CAAC;CAC/B;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,GAAE,oBAAyB,GACjC,wBAAwB,CAY1B"}

19
node_modules/@nx/rollup/src/plugins/postcss/options.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeOptions = normalizeOptions;
/**
* Normalize plugin options with defaults
*/
function normalizeOptions(options = {}) {
return {
...options,
inject: options.inject ?? true,
extract: options.extract ?? false,
autoModules: options.autoModules ?? false,
modules: options.modules ?? false,
plugins: options.plugins ?? [],
use: options.use ?? {},
extensions: options.extensions ?? ['.css', '.sss', '.pcss'],
sourceMap: options.sourceMap ?? false,
};
}

View File

@@ -0,0 +1,10 @@
import type { Plugin } from 'rollup';
import type { PostCSSPluginOptions } from './options';
/**
* PostCSS Rollup plugin
*
* Processes CSS files through PostCSS and optional preprocessors (Sass, Less, Stylus).
* Supports CSS injection into the DOM or extraction to separate files.
*/
export declare function postcss(pluginOptions?: PostCSSPluginOptions): Plugin;
//# sourceMappingURL=postcss-plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"postcss-plugin.d.ts","sourceRoot":"","sources":["../../../../../../packages/rollup/src/plugins/postcss/postcss-plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAiC,MAAM,QAAQ,CAAC;AACpE,OAAO,KAAK,EACV,oBAAoB,EAGrB,MAAM,WAAW,CAAC;AAsHnB;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,aAAa,GAAE,oBAAyB,GAAG,MAAM,CA2OxE"}

View File

@@ -0,0 +1,275 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.postcss = postcss;
const path_1 = require("path");
const options_1 = require("./options");
const loaders_1 = require("./loaders");
const utils_1 = require("./utils");
// Use require for modules that don't have proper ES module exports
const Concat = require('concat-with-sourcemaps');
const picomatch = require('picomatch');
/**
* Convert a source map from loader format to Rollup format
*/
function toRollupSourceMap(map) {
if (!map)
return undefined;
// Rollup expects version as number, but source-map-js uses string
// Convert to Rollup-compatible format
return {
...map,
version: typeof map.version === 'string' ? parseInt(map.version, 10) : map.version,
};
}
/**
* Create a file filter from include/exclude patterns
*/
function createFilter(include, exclude) {
const includeMatchers = include
? (Array.isArray(include) ? include : [include]).map((p) => typeof p === 'string' ? picomatch(p) : (id) => p.test(id))
: [];
const excludeMatchers = exclude
? (Array.isArray(exclude) ? exclude : [exclude]).map((p) => typeof p === 'string' ? picomatch(p) : (id) => p.test(id))
: [];
return (id) => {
const normalizedId = (0, utils_1.normalizePath)(id);
// If exclude matches, reject
if (excludeMatchers.length > 0 &&
excludeMatchers.some((m) => m(normalizedId))) {
return false;
}
// If include is specified, only accept if it matches
if (includeMatchers.length > 0) {
return includeMatchers.some((m) => m(normalizedId));
}
// Default: accept all
return true;
};
}
/**
* Get the output filename for extracted CSS
*/
function getExtractedFilename(extract, chunkName) {
if (typeof extract === 'string') {
return extract;
}
return `${chunkName}.css`;
}
/**
* Recursively get the import order for CSS files
* This ensures CSS is concatenated in the correct dependency order
*/
function getRecursiveImportOrder(id, moduleGraph, visited = new Set()) {
if (visited.has(id)) {
return [];
}
visited.add(id);
const imports = moduleGraph.get(id);
if (!imports) {
return [id];
}
const result = [];
for (const importId of imports) {
result.push(...getRecursiveImportOrder(importId, moduleGraph, visited));
}
result.push(id);
return result;
}
/**
* PostCSS Rollup plugin
*
* Processes CSS files through PostCSS and optional preprocessors (Sass, Less, Stylus).
* Supports CSS injection into the DOM or extraction to separate files.
*/
function postcss(pluginOptions = {}) {
const options = (0, options_1.normalizeOptions)(pluginOptions);
// Create file filter
const defaultExtensions = [
'.css',
'.sss',
'.pcss', // CSS formats
'.scss',
'.sass', // Sass
'.less', // Less
'.styl',
'.stylus', // Stylus
];
const extensions = options.extensions ?? defaultExtensions;
const filter = createFilter(options.include ?? extensions.map((ext) => `**/*${ext}`), options.exclude ?? /node_modules/);
// Initialize the loaders
const loaders = new loaders_1.Loaders({
postcss: {
plugins: options.plugins,
modules: options.modules,
autoModules: options.autoModules,
extract: options.extract,
inject: options.inject,
},
use: options.use,
});
// Storage for extracted CSS (when extract is enabled)
const extracted = new Map();
// Track module dependencies for correct CSS ordering
const moduleGraph = new Map();
return {
name: 'postcss',
/**
* Resolve the virtual style-inject module
*/
resolveId(source) {
if (source === utils_1.STYLE_INJECT_PATH) {
return utils_1.STYLE_INJECT_ID;
}
return null;
},
/**
* Load the virtual style-inject module
*/
load(id) {
if (id === utils_1.STYLE_INJECT_ID) {
return utils_1.styleInjectCode;
}
return null;
},
/**
* Transform CSS files
*/
async transform(code, id) {
// Skip non-CSS files
if (!filter(id)) {
return null;
}
const ext = (0, path_1.extname)(id);
if (!extensions.includes(ext)) {
return null;
}
// Track dependencies for this module
const deps = new Set();
moduleGraph.set(id, deps);
// Process through the loader chain
const result = await loaders.process(code, {
id,
sourceMap: options.sourceMap,
dependencies: deps,
warn: (message) => this.warn(message),
});
// Add watch dependencies
for (const dep of deps) {
this.addWatchFile(dep);
}
// Store extracted CSS if in extract mode
if (result.extracted) {
extracted.set(id, {
id,
code: result.extracted.code,
map: result.extracted.map,
});
}
return {
code: result.code,
map: toRollupSourceMap(result.map) ?? { mappings: '' },
};
},
/**
* Include extracted CSS in chunk hash
*/
augmentChunkHash(chunk) {
if (!options.extract || extracted.size === 0) {
return;
}
// Find CSS files that belong to this chunk
const chunkCSS = [];
for (const moduleId of Object.keys(chunk.modules)) {
const css = extracted.get(moduleId);
if (css) {
chunkCSS.push(css.code);
}
}
if (chunkCSS.length > 0) {
return chunkCSS.join(':');
}
},
/**
* Generate the extracted CSS files
*/
async generateBundle(outputOptions, bundle) {
if (!options.extract || extracted.size === 0) {
return;
}
// Group extracted CSS by chunk
const cssPerChunk = new Map();
for (const [chunkId, chunk] of Object.entries(bundle)) {
if (chunk.type !== 'chunk') {
continue;
}
const chunkModules = Object.keys(chunk.modules);
const cssForChunk = [];
// Get the import order for CSS files in this chunk
const orderedModules = [];
for (const moduleId of chunkModules) {
orderedModules.push(...getRecursiveImportOrder(moduleId, moduleGraph));
}
// Remove duplicates while preserving order
const seen = new Set();
const uniqueModules = orderedModules.filter((id) => {
if (seen.has(id))
return false;
seen.add(id);
return true;
});
// Collect CSS in dependency order
for (const moduleId of uniqueModules) {
const css = extracted.get(moduleId);
if (css) {
cssForChunk.push(css);
}
}
if (cssForChunk.length > 0) {
cssPerChunk.set(chunkId, cssForChunk);
}
}
// Emit CSS files for each chunk
for (const [chunkId, cssFiles] of cssPerChunk) {
const chunk = bundle[chunkId];
if (chunk.type !== 'chunk')
continue;
// Use the actual chunk filename to derive CSS filename
// This preserves patterns like index.esm.js -> index.esm.css
const chunkFileName = chunk.fileName;
const chunkBaseName = (0, path_1.basename)(chunkFileName, (0, path_1.extname)(chunkFileName));
const cssFilename = getExtractedFilename(options.extract, chunkBaseName);
// Concatenate CSS files with source maps
const concat = new Concat(!!options.sourceMap, cssFilename, '\n');
for (const css of cssFiles) {
const relativePath = (0, path_1.relative)(process.cwd(), css.id);
concat.add(relativePath, css.code, css.map ? JSON.stringify(css.map) : undefined);
}
// Emit the CSS file
const cssContent = concat.content.toString();
const cssMap = concat.sourceMap;
// Determine if source map should be inline or separate
let finalCSS = cssContent;
if (options.sourceMap === 'inline' && cssMap) {
const mapBase64 = Buffer.from(cssMap).toString('base64');
finalCSS += `\n/*# sourceMappingURL=data:application/json;base64,${mapBase64} */`;
}
else if (options.sourceMap && cssMap) {
// Add source map reference
finalCSS += `\n/*# sourceMappingURL=${cssFilename}.map */`;
// Emit source map file
this.emitFile({
type: 'asset',
fileName: `${cssFilename}.map`,
source: cssMap,
});
}
// Emit CSS file
this.emitFile({
type: 'asset',
fileName: cssFilename,
source: finalCSS,
});
}
},
};
}

View File

@@ -0,0 +1,29 @@
declare module 'concat-with-sourcemaps' {
class Concat {
constructor(
generateSourceMap: boolean,
outputFileName: string,
separator?: string
);
/**
* Add a file to the output
* @param filePath - Relative path to the file
* @param content - File content
* @param sourceMap - Source map JSON string (optional)
*/
add(filePath: string, content: string | Buffer, sourceMap?: string): void;
/**
* The concatenated content
*/
readonly content: Buffer;
/**
* The combined source map (as JSON string)
*/
readonly sourceMap: string | undefined;
}
export = Concat;
}

View File

@@ -0,0 +1,5 @@
export { normalizePath, humanizePath } from './normalize-path';
export { loadModule, requireModule } from './load-module';
export { safeIdentifier, escapeClassNameDashes } from './safe-identifier';
export { styleInjectCode, STYLE_INJECT_ID, STYLE_INJECT_PATH, } from './style-inject';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1E,OAAO,EACL,eAAe,EACf,eAAe,EACf,iBAAiB,GAClB,MAAM,gBAAgB,CAAC"}

View File

@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.STYLE_INJECT_PATH = exports.STYLE_INJECT_ID = exports.styleInjectCode = exports.escapeClassNameDashes = exports.safeIdentifier = exports.requireModule = exports.loadModule = exports.humanizePath = exports.normalizePath = void 0;
var normalize_path_1 = require("./normalize-path");
Object.defineProperty(exports, "normalizePath", { enumerable: true, get: function () { return normalize_path_1.normalizePath; } });
Object.defineProperty(exports, "humanizePath", { enumerable: true, get: function () { return normalize_path_1.humanizePath; } });
var load_module_1 = require("./load-module");
Object.defineProperty(exports, "loadModule", { enumerable: true, get: function () { return load_module_1.loadModule; } });
Object.defineProperty(exports, "requireModule", { enumerable: true, get: function () { return load_module_1.requireModule; } });
var safe_identifier_1 = require("./safe-identifier");
Object.defineProperty(exports, "safeIdentifier", { enumerable: true, get: function () { return safe_identifier_1.safeIdentifier; } });
Object.defineProperty(exports, "escapeClassNameDashes", { enumerable: true, get: function () { return safe_identifier_1.escapeClassNameDashes; } });
var style_inject_1 = require("./style-inject");
Object.defineProperty(exports, "styleInjectCode", { enumerable: true, get: function () { return style_inject_1.styleInjectCode; } });
Object.defineProperty(exports, "STYLE_INJECT_ID", { enumerable: true, get: function () { return style_inject_1.STYLE_INJECT_ID; } });
Object.defineProperty(exports, "STYLE_INJECT_PATH", { enumerable: true, get: function () { return style_inject_1.STYLE_INJECT_PATH; } });

View File

@@ -0,0 +1,11 @@
/**
* Load a module with fallback to loading from cwd
* This allows preprocessors like sass, less, stylus to be loaded from
* either the plugin's node_modules or the project's node_modules
*/
export declare function loadModule<T = unknown>(moduleId: string): T | undefined;
/**
* Load a module and throw an error if it's not found
*/
export declare function requireModule<T = unknown>(moduleId: string, feature: string): T;
//# sourceMappingURL=load-module.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"load-module.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/utils/load-module.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,CAAC,GAAG,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAavE;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,CAAC,GAAG,OAAO,EACvC,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,GACd,CAAC,CAQH"}

View File

@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadModule = loadModule;
exports.requireModule = requireModule;
const path_1 = require("path");
/**
* Load a module with fallback to loading from cwd
* This allows preprocessors like sass, less, stylus to be loaded from
* either the plugin's node_modules or the project's node_modules
*/
function loadModule(moduleId) {
try {
// First try to load from the plugin's node_modules
return require(moduleId);
}
catch {
// If that fails, try to load from the current working directory
try {
const modulePath = (0, path_1.resolve)(process.cwd(), 'node_modules', moduleId);
return require(modulePath);
}
catch {
return undefined;
}
}
}
/**
* Load a module and throw an error if it's not found
*/
function requireModule(moduleId, feature) {
const module = loadModule(moduleId);
if (!module) {
throw new Error(`You need to install "${moduleId}" package in order to process ${feature} files.`);
}
return module;
}

View File

@@ -0,0 +1,10 @@
/**
* Normalize file path to use forward slashes (POSIX style)
* This ensures consistent path handling across Windows and Unix systems
*/
export declare function normalizePath(path: string | undefined): string;
/**
* Convert an absolute path to a human-readable relative path from cwd
*/
export declare function humanizePath(filepath: string): string;
//# sourceMappingURL=normalize-path.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"normalize-path.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/utils/normalize-path.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAK9D;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGrD"}

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePath = normalizePath;
exports.humanizePath = humanizePath;
/**
* Normalize file path to use forward slashes (POSIX style)
* This ensures consistent path handling across Windows and Unix systems
*/
function normalizePath(path) {
if (!path) {
return '';
}
return path.replace(/\\+/g, '/');
}
/**
* Convert an absolute path to a human-readable relative path from cwd
*/
function humanizePath(filepath) {
const { relative } = require('path');
return normalizePath(relative(process.cwd(), filepath));
}

View File

@@ -0,0 +1,14 @@
/**
* Convert a CSS class name to a valid JavaScript identifier
* This is used when generating exports for CSS modules
*/
/**
* Escape dashes in class names to make them valid JS identifiers
* e.g., "my-class" -> "myClass"
*/
export declare function escapeClassNameDashes(name: string): string;
/**
* Convert a CSS class name to a safe JavaScript identifier
*/
export declare function safeIdentifier(name: string): string;
//# sourceMappingURL=safe-identifier.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"safe-identifier.d.ts","sourceRoot":"","sources":["../../../../../../../packages/rollup/src/plugins/postcss/utils/safe-identifier.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA4DH;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAkBnD"}

Some files were not shown because too many files have changed in this diff Show More