rsbuild-plugin-workspace-dev 0.0.0-chore-modify-hook-2025-12-16-20251216020145

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Rspack Contrib
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # rsbuild-plugin-workspace-dev
2
+
3
+ Start monorepo sub-projects in topological order.
4
+
5
+ `rsbuild-plugin-workspace-dev` is designed for monorepo development. It computes the dependency graph starting from the current project and starts sub-projects in topological order.
6
+
7
+ <p>
8
+ <a href="https://npmjs.com/package/rsbuild-plugin-workspace-dev">
9
+ <img src="https://img.shields.io/npm/v/rsbuild-plugin-workspace-dev?style=flat-square&colorA=564341&colorB=EDED91" alt="npm version" />
10
+ </a>
11
+ <img src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square&colorA=564341&colorB=EDED91" alt="license" />
12
+ </p>
13
+
14
+ English | [简体中文](./README.zh-CN.md)
15
+
16
+ ## Usage
17
+
18
+ Install:
19
+
20
+ ```bash
21
+ pnpm add rsbuild-plugin-workspace-dev -D
22
+ ```
23
+
24
+ Register the plugin in `rsbuild.config.ts`:
25
+
26
+ ```ts
27
+ // rsbuild.config.ts
28
+ import { pluginWorkspaceDev } from "rsbuild-plugin-workspace-dev";
29
+
30
+ export default {
31
+ plugins: [pluginWorkspaceDev()],
32
+ };
33
+ ```
34
+
35
+ ## Use Cases
36
+
37
+ In a monorepo, one project may depend on multiple sub-projects, and those sub-projects can also depend on each other.
38
+
39
+ For example, the monorepo contains an app and several lib packages:
40
+
41
+ ```ts
42
+ monorepo
43
+ ├── app
44
+ └── lib1
45
+ └── lib2
46
+ └── lib3
47
+ ```
48
+
49
+ Here, app is built with Rsbuild, and lib is built with Rslib. The app depends on lib1 and lib2:
50
+
51
+ ```json
52
+ {
53
+ "name": "app",
54
+ "dependencies": {
55
+ "lib1": "workspace:*",
56
+ "lib2": "workspace:*"
57
+ }
58
+ }
59
+ ```
60
+
61
+ lib2 depends on lib3:
62
+
63
+ ```json
64
+ {
65
+ "name": "lib2",
66
+ "dependencies": {
67
+ "lib3": "workspace:*"
68
+ }
69
+ }
70
+ ```
71
+
72
+ When you run `pnpm dev` under app, sub-projects start in topological order: first lib1 and lib3, then lib2, and finally app. Starting a lib refers to running its dev command, for example:
73
+
74
+ ```json
75
+ {
76
+ "scripts": {
77
+ "dev": "rslib build --watch"
78
+ }
79
+ }
80
+ ```
81
+
82
+ Whether a sub-project has finished starting is determined by matching sub-project logs. By default, logs from Rslib and tsup sub-projects are recognized. You can also provide a custom match function to determine when a sub-project is ready.
83
+
84
+ ## Options
85
+
86
+ ### projects
87
+ Configure how sub-projects are started and define custom log matching logic.
88
+
89
+ - Type:
90
+ ```
91
+ type projects = {
92
+ // The key is the name of the sub-project's package.json file.
93
+ [key: string]: Projects;
94
+ }
95
+
96
+ interface projects {
97
+ /**
98
+ * Custom sub-project start command. Default is `dev` (runs `npm run dev`).
99
+ */
100
+ command?: string;
101
+ /**
102
+ * Custom logic to detect when a sub-project has started.
103
+ * By default, logs from `Rsbuild` and `tsup` are supported.
104
+ */
105
+ match?: (stdout: string) => boolean;
106
+ /**
107
+ * Whether to skip starting the current sub-project. Default is `false`.
108
+ * Useful for sub-projects that do not need to be started.
109
+ */
110
+ skip?: boolean;
111
+ }
112
+
113
+
114
+ // For example, to configure lib1 sub-project to use build:watch command and match watch success log
115
+ pluginWorkspaceDev({
116
+ projects: {
117
+ lib1: {
118
+ command: 'build:watch',
119
+ match: (stdout) => stdout.includes('watch success'),
120
+ },
121
+ },
122
+ })
123
+ ```
124
+
125
+ ### startCurrent
126
+
127
+ - Type: `boolean`
128
+ - Default: `false`
129
+
130
+ Whether to also start the current project. The default is `false`. In most cases, you start the current project manually, so the plugin does not interfere.
131
+
132
+ Consider a scenario where docs and lib are in the same project, and docs needs to debug the output of lib. In this case, you want to run `pnpm doc` for the docs, while lib should run `pnpm dev`. After configuring this option in your Rspress config, starting `pnpm doc` will automatically run `pnpm dev` to start the lib sub-project.
133
+
134
+ ```
135
+ ├── docs
136
+ │ └── index.mdx
137
+ ├── package.json
138
+ ├── src
139
+ │ └── Button.tsx
140
+ ├── rslib.config.ts
141
+ ├── rspress.config.ts
142
+ ```
143
+
144
+ ```
145
+ "scripts": {
146
+ "dev": "rslib build --watch",
147
+ "doc": "rspress dev"
148
+ },
149
+ ```
150
+
151
+ ### cwd
152
+
153
+ - Type: `string`
154
+ - Default: `process.cwd()`
155
+
156
+ Set the current working directory. The default is the current project directory; usually no configuration is needed.
157
+
158
+ ### workspaceFileDir
159
+
160
+ - Type: `string`
161
+ - Default: `process.cwd()`
162
+
163
+ Set the directory where the workspace file resides. The default is the current project directory; usually no configuration is needed.
164
+
165
+ ## Frequently Asked Questions
166
+
167
+ ### Project startup stuck
168
+ Stuck may be due to slow sub-project builds, etc. The lack of log output is because, by default, sub-project logs are output all at once after startup (to avoid interleaving sub-project logs). You can enable debug mode by adding an environment variable, which will allow sub-project logs to be output in real time.
169
+
170
+ ```
171
+ DEBUG=rsbuild pnpm dev
172
+ ```
173
+
174
+ ### Some projects don't need to start
175
+
176
+ If some sub-projects don't need to start, simply configure `skip: true` for the specified project in `rsbuild.config.ts`.
177
+
178
+ ```ts
179
+ // rsbuild.config.ts
180
+ import { pluginWorkspaceDev } from "rsbuild-plugin-workspace-dev";
181
+
182
+ export default {
183
+ plugins: [
184
+ pluginWorkspaceDev({
185
+ projects: {
186
+ lib1: {
187
+ skip: true,
188
+ },
189
+ },
190
+ }),
191
+ ],
192
+ };
193
+ ```
194
+
195
+ ## License
196
+
197
+ [MIT](./LICENSE).
@@ -0,0 +1,188 @@
1
+ # rsbuild-plugin-workspace-dev
2
+
3
+ 提供按拓扑顺序启动 monorepo 子项目的能力。
4
+
5
+ `rsbuild-plugin-workspace-dev` 用于 monorepo 开发场景,它支持从当前项目开始计算依赖关系生成拓扑图,按拓扑顺序启动子项目。
6
+
7
+ <p>
8
+ <a href="https://npmjs.com/package/rsbuild-plugin-workspace-dev">
9
+ <img src="https://img.shields.io/npm/v/rsbuild-plugin-workspace-dev?style=flat-square&colorA=564341&colorB=EDED91" alt="npm version" />
10
+ </a>
11
+ <img src="https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square&colorA=564341&colorB=EDED91" alt="license" />
12
+ </p>
13
+
14
+ ## 使用
15
+
16
+ 安装:
17
+
18
+ ```bash
19
+ pnpm add rsbuild-plugin-workspace-dev -D
20
+ ```
21
+
22
+ 在 `rsbuild.config.ts` 里注册插件:
23
+
24
+ ```ts
25
+ // rsbuild.config.ts
26
+ import { pluginWorkspaceDev } from "rsbuild-plugin-workspace-dev";
27
+
28
+ export default {
29
+ plugins: [pluginWorkspaceDev()],
30
+ };
31
+ ```
32
+
33
+ ## 使用场景
34
+
35
+ 在 monorepo 中,一个项目可能依赖多个子项目,而子项目之间也可能存在依赖关系。
36
+
37
+ 比如 monorepo 中包含了一个 app 应用和多个 lib 包:
38
+
39
+ ```ts
40
+ monorepo
41
+ ├── app
42
+ └── lib1
43
+ └── lib2
44
+ └── lib3
45
+ ```
46
+
47
+ 其中,app 是基于 Rsbuild 构建的, lib 是基于 Rslib 构建的。app 依赖了 lib1 和 lib2:
48
+
49
+ ```json
50
+ {
51
+ "name": "app",
52
+ "dependencies": {
53
+ "lib1": "workspace:*",
54
+ "lib2": "workspace:*"
55
+ }
56
+ }
57
+ ```
58
+
59
+ lib2 依赖了 lib3:
60
+
61
+ ```json
62
+ {
63
+ "name": "lib2",
64
+ "dependencies": {
65
+ "lib3": "workspace:*"
66
+ }
67
+ }
68
+ ```
69
+ 此时在 app 下执行 `pnpm dev` 后,会按照拓扑顺序先启动 lib1 和 lib3,再启动 lib2,最后启动 app。此处启动 lib 指的是执行 lib 的 dev 命令
70
+ ```json
71
+ {
72
+ "scripts": {
73
+ "dev": "rslib build --watch"
74
+ }
75
+ }
76
+ ```
77
+ 识别子项目是否启动完成是通过匹配子项目日志实现的,默认支持匹配 Rslib、tsup 子项目,同时支持手动配置 match 匹配日志。
78
+
79
+ ## 选项
80
+
81
+ ### projects
82
+ 用于子项目的启动项配置和自定义日志匹配逻辑。
83
+
84
+ - **类型:**
85
+ ```
86
+ type projects = {
87
+ // key 为子项目 package.json name
88
+ [key: string]: Projects;
89
+ }
90
+
91
+ interface Projects {
92
+ /**
93
+ * 自定义子项目启动命令,默认值为 `dev`, 即执行 `npm run dev`。
94
+ */
95
+ command?: string;
96
+ /**
97
+ * 自定义子项目启动完成匹配逻辑,默认支持 `Rsbuild`、`tsup` 子项目的日志匹配逻辑。
98
+ */
99
+ match?: (stdout: string) => boolean;
100
+ /**
101
+ * 是否跳过当前子项目的启动,默认值为 `false`,通常用于跳过一些不需要启动的子项目。
102
+ */
103
+ skip?: boolean;
104
+ }
105
+
106
+ // 例如,配置 lib1 子项目,用 build:watch 命令启动,匹配 watch success 日志
107
+ pluginWorkspaceDev({
108
+ projects: {
109
+ lib1: {
110
+ command: 'build:watch',
111
+ match: (stdout) => stdout.includes('watch success'),
112
+ },
113
+ },
114
+ })
115
+ ```
116
+
117
+
118
+ ### startCurrent
119
+
120
+ - **类型:** `boolean`
121
+ - **默认值:** `false`
122
+
123
+ 插件是否同时启动当前项目,默认值为 `false`。通常无需手动配置,当前项目通常由用户手动执行 dev 启动,无需插件干预。
124
+
125
+ 考虑如下场景,docs 和 lib 是在同一个项目中,而 docs 需要调试 lib 的产物,此时需要启动 `pnpm doc` 命令,而 lib 则需要启动 `pnpm dev` 命令,配置该选项到 rspress 配置中后,启动 `pnpm doc` 时会自动执行 `pnpm dev` 命令,用于启动 lib 子项目。
126
+ ```
127
+ ├── docs
128
+ │ └── index.mdx
129
+ ├── package.json
130
+ ├── src
131
+ │ └── Button.tsx
132
+ ├── rslib.config.ts
133
+ ├── rspress.config.ts
134
+ ```
135
+ ```
136
+ "scripts": {
137
+ "dev": "rslib build --watch",
138
+ "doc": "rspress dev"
139
+ },
140
+ ```
141
+
142
+ ### cwd
143
+
144
+ - **类型:** `string`
145
+ - **默认值:** `process.cwd()`
146
+
147
+ 用于配置当前工作目录,默认值为当前项目目录,通常无需配置。
148
+
149
+ ### workspaceFileDir
150
+
151
+ - **类型:** `string`
152
+ - **默认值:** `process.cwd()`
153
+
154
+ 用于配置 workspace 文件目录,默认值为当前项目目录,通常无需配置。
155
+
156
+
157
+ ## 常见问题
158
+
159
+ ### 启动项目时卡住
160
+ 卡住可能是因为子项目构建过慢等原因,没有日志输出是因为默认情况下子项目日志是启动完成后一次性输出的(为了避免子项目日志混和在一起交错输出),可以通过添加环境变量来开启调试模式,这会让子项目的日志实时输出。
161
+ ```
162
+ DEBUG=rsbuild pnpm dev
163
+ ```
164
+
165
+ ### 某些项目无需启动
166
+ 如果某些子项目不需要启动,只需要在 `rsbuild.config.ts` 中给指定项目配置 `skip: true` 即可。
167
+
168
+ ```ts
169
+ // rsbuild.config.ts
170
+ import { pluginWorkspaceDev } from "rsbuild-plugin-workspace-dev";
171
+
172
+ export default {
173
+ plugins: [
174
+ pluginWorkspaceDev({
175
+ projects: {
176
+ lib1: {
177
+ skip: true,
178
+ },
179
+ },
180
+ }),
181
+ ],
182
+ };
183
+ ```
184
+
185
+
186
+ ## License
187
+
188
+ [MIT](./LICENSE).
@@ -0,0 +1,5 @@
1
+ export declare const PACKAGE_JSON = "package.json";
2
+ export declare const DEBUG_LOG_TITLE = "[Rsbuild Workspace Dev Plugin]: ";
3
+ export declare const RSLIB_READY_MESSAGE = "build complete, watching for changes";
4
+ export declare const MODERN_MODULE_READY_MESSAGE = "Watching for file changes";
5
+ export declare const TSUP_READY_MESSAGE = "Watching for changes in";
package/dist/index.cjs ADDED
@@ -0,0 +1,316 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ pluginWorkspaceDev: ()=>pluginWorkspaceDev,
37
+ WorkspaceDevRunner: ()=>WorkspaceDevRunner
38
+ });
39
+ const external_chalk_namespaceObject = require("chalk");
40
+ var external_chalk_default = /*#__PURE__*/ __webpack_require__.n(external_chalk_namespaceObject);
41
+ const PACKAGE_JSON = 'package.json';
42
+ const DEBUG_LOG_TITLE = '[Rsbuild Workspace Dev Plugin]: ';
43
+ const RSLIB_READY_MESSAGE = 'build complete, watching for changes';
44
+ const MODERN_MODULE_READY_MESSAGE = 'Watching for file changes';
45
+ const TSUP_READY_MESSAGE = 'Watching for changes in';
46
+ const external_fs_namespaceObject = require("fs");
47
+ var external_fs_default = /*#__PURE__*/ __webpack_require__.n(external_fs_namespaceObject);
48
+ const external_json5_namespaceObject = require("json5");
49
+ var external_json5_default = /*#__PURE__*/ __webpack_require__.n(external_json5_namespaceObject);
50
+ async function pathExists(path) {
51
+ return external_fs_default().promises.access(path).then(()=>true).catch(()=>false);
52
+ }
53
+ const readJson = async (jsonFileAbsPath)=>{
54
+ if (!await pathExists(jsonFileAbsPath)) return {};
55
+ const content = await external_fs_default().promises.readFile(jsonFileAbsPath, 'utf-8');
56
+ const json = external_json5_default().parse(content);
57
+ return json;
58
+ };
59
+ const readPackageJson = async (pkgJsonFilePath)=>readJson(pkgJsonFilePath);
60
+ const isDebug = 'rsbuild' === process.env.DEBUG || '*' === process.env.DEBUG;
61
+ function _define_property(obj, key, value) {
62
+ if (key in obj) Object.defineProperty(obj, key, {
63
+ value: value,
64
+ enumerable: true,
65
+ configurable: true,
66
+ writable: true
67
+ });
68
+ else obj[key] = value;
69
+ return obj;
70
+ }
71
+ const logMap = {
72
+ ["stdout"]: 'log',
73
+ ["stderr"]: 'error'
74
+ };
75
+ class Logger {
76
+ appendLog(type, log) {
77
+ this[type] += log;
78
+ }
79
+ emitLog(type) {
80
+ console[logMap[type]](this[type]);
81
+ }
82
+ emitLogOnce(type, log) {
83
+ const logWithName = `${external_chalk_default().hex('#808080').bold(this.name)}: ${log}`;
84
+ console[logMap[type]](logWithName);
85
+ }
86
+ reset(type) {
87
+ this[type] = '';
88
+ }
89
+ setBanner(name) {
90
+ const startBanner = `\n------------ ${external_chalk_default().hex('#c95ab3').bold('log start:')} ${external_chalk_default().green(name)} ${'-'.repeat(Math.max(50 - name.toString().length, 5))}`;
91
+ this.stdout = startBanner + this.stdout;
92
+ }
93
+ flushStdout() {
94
+ if (isDebug) return;
95
+ this.setBanner(this.name);
96
+ this.emitLog("stdout");
97
+ }
98
+ static setEndBanner() {
99
+ const endBanner = `------------ ${external_chalk_default().hex('#c95ab3').bold('log end:')} ${external_chalk_default().green('all sub project have been started.')} ------------\n`;
100
+ console.log(endBanner);
101
+ }
102
+ constructor({ name }){
103
+ _define_property(this, "stdout", void 0);
104
+ _define_property(this, "stderr", void 0);
105
+ _define_property(this, "name", void 0);
106
+ _define_property(this, "logTitle", void 0);
107
+ this.name = name;
108
+ this.stdout = '';
109
+ this.stderr = '';
110
+ this.logTitle = DEBUG_LOG_TITLE;
111
+ }
112
+ }
113
+ const debugLog = (msg, prefix = DEBUG_LOG_TITLE)=>{
114
+ if (isDebug) console.log(prefix + msg);
115
+ };
116
+ const get_packages_namespaceObject = require("@manypkg/get-packages");
117
+ const external_child_process_namespaceObject = require("child_process");
118
+ const external_graphlib_namespaceObject = require("graphlib");
119
+ var external_graphlib_default = /*#__PURE__*/ __webpack_require__.n(external_graphlib_namespaceObject);
120
+ const external_path_namespaceObject = require("path");
121
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
122
+ function workspace_dev_define_property(obj, key, value) {
123
+ if (key in obj) Object.defineProperty(obj, key, {
124
+ value: value,
125
+ enumerable: true,
126
+ configurable: true,
127
+ writable: true
128
+ });
129
+ else obj[key] = value;
130
+ return obj;
131
+ }
132
+ class WorkspaceDevRunner {
133
+ async init() {
134
+ this.metaData = await readPackageJson(external_path_default().join(this.cwd, PACKAGE_JSON));
135
+ this.buildDependencyGraph();
136
+ debugLog(`Dependency graph:\nnodes: ${this.getNodes().join(', ')}\nedges: ${this.getEdges().map((edge)=>`${edge.v} -> ${edge.w}`).join(', ')}\n`);
137
+ }
138
+ buildDependencyGraph() {
139
+ const { packages } = (0, get_packages_namespaceObject.getPackagesSync)(this.workspaceFileDir);
140
+ const currentPackage = packages.find((pkg)=>pkg.packageJson.name === this.metaData.name);
141
+ this.packages = packages;
142
+ const initNode = (pkg)=>{
143
+ const { packageJson, dir } = pkg;
144
+ const { name, dependencies, devDependencies, peerDependencies } = packageJson;
145
+ const node = {
146
+ name,
147
+ packageJson,
148
+ path: dir
149
+ };
150
+ this.graph.setNode(name, node);
151
+ this.visited[name] = false;
152
+ this.visiting[name] = false;
153
+ this.matched[name] = false;
154
+ const packageName = name;
155
+ const deps = {
156
+ ...dependencies,
157
+ ...devDependencies,
158
+ ...peerDependencies
159
+ };
160
+ for (const depName of Object.keys(deps)){
161
+ const isInternalDep = this.packages.some((p)=>p.packageJson.name === depName);
162
+ if (isInternalDep) {
163
+ this.graph.setEdge(packageName, depName);
164
+ this.checkGraph();
165
+ const depPackage = packages.find((pkg)=>pkg.packageJson.name === depName);
166
+ if (!this.getNode(depName)) initNode(depPackage);
167
+ }
168
+ }
169
+ };
170
+ initNode(currentPackage);
171
+ }
172
+ checkGraph() {
173
+ const cycles = external_graphlib_default().alg.findCycles(this.graph);
174
+ const nonSelfCycles = cycles.filter((c)=>1 !== c.length);
175
+ if (nonSelfCycles.length) console.log(external_chalk_default().red(`${DEBUG_LOG_TITLE} Cycle dependency graph found: ${cycles.join(', ')}, you should config projects in plugin options to skip them, or fix the cycle dependency. Otherwise, a loop of dev will occur.`));
176
+ }
177
+ async start() {
178
+ const promises = [];
179
+ const allNodes = this.getNodes();
180
+ const filterSelfNodes = allNodes.filter((node)=>node !== this.metaData.name);
181
+ const nodes = this.options.startCurrent ? allNodes : filterSelfNodes;
182
+ for (const node of nodes){
183
+ const dependencies = this.getDependencies(node) || [];
184
+ const canStart = dependencies.every((dep)=>{
185
+ const selfStart = node === dep;
186
+ const isVisiting = this.visiting[dep];
187
+ const isVisited = selfStart || this.visited[dep];
188
+ return isVisited && !isVisiting;
189
+ });
190
+ if (canStart && !this.visited[node] && !this.visiting[node]) {
191
+ debugLog(`Start visit node: ${node}`);
192
+ const visitPromise = this.visitNodes(node);
193
+ promises.push(visitPromise);
194
+ }
195
+ }
196
+ await Promise.all(promises);
197
+ }
198
+ visitNodes(node) {
199
+ return new Promise((resolve)=>{
200
+ const { name, path } = this.getNode(node);
201
+ const logger = new Logger({
202
+ name
203
+ });
204
+ const config = this.options?.projects?.[name];
205
+ if (config?.skip) {
206
+ this.visited[node] = true;
207
+ this.visiting[node] = false;
208
+ debugLog(`Skip visit node: ${node}`);
209
+ logger.emitLogOnce('stdout', `skip visit node: ${name}`);
210
+ return this.start().then(()=>resolve());
211
+ }
212
+ this.visiting[node] = true;
213
+ const child = (0, external_child_process_namespaceObject.spawn)('npm', [
214
+ 'run',
215
+ config?.command ? config.command : 'dev'
216
+ ], {
217
+ cwd: path,
218
+ env: {
219
+ ...process.env,
220
+ FORCE_COLOR: '3'
221
+ },
222
+ shell: true
223
+ });
224
+ child.stdout.on('data', async (data)=>{
225
+ const stdout = data.toString();
226
+ const content = data.toString().replace(/\n$/, '');
227
+ if (this.matched[node]) return void logger.emitLogOnce('stdout', content);
228
+ debugLog(content, `${name}: `);
229
+ logger.appendLog('stdout', stdout);
230
+ const match = config?.match;
231
+ const matchResult = match ? match(stdout) : stdout.match(RSLIB_READY_MESSAGE) || stdout.match(MODERN_MODULE_READY_MESSAGE) || stdout.match(TSUP_READY_MESSAGE);
232
+ if (matchResult) {
233
+ logger.flushStdout();
234
+ this.matched[node] = true;
235
+ this.visited[node] = true;
236
+ this.visiting[node] = false;
237
+ await this.start();
238
+ resolve();
239
+ }
240
+ });
241
+ child.stderr.on('data', (data)=>{
242
+ const stderr = data.toString();
243
+ logger.emitLogOnce('stderr', stderr);
244
+ });
245
+ child.on('close', ()=>{});
246
+ });
247
+ }
248
+ getDependencyGraph() {
249
+ return this.graph;
250
+ }
251
+ getNodes() {
252
+ return this.graph.nodes();
253
+ }
254
+ getEdges() {
255
+ return this.graph.edges();
256
+ }
257
+ getNode(name) {
258
+ return this.graph.node(name);
259
+ }
260
+ getDependents(packageName) {
261
+ return this.graph.predecessors(packageName);
262
+ }
263
+ getDependencies(packageName) {
264
+ return this.graph.successors(packageName);
265
+ }
266
+ constructor(options){
267
+ workspace_dev_define_property(this, "options", void 0);
268
+ workspace_dev_define_property(this, "cwd", void 0);
269
+ workspace_dev_define_property(this, "workspaceFileDir", void 0);
270
+ workspace_dev_define_property(this, "packages", []);
271
+ workspace_dev_define_property(this, "graph", void 0);
272
+ workspace_dev_define_property(this, "visited", void 0);
273
+ workspace_dev_define_property(this, "visiting", void 0);
274
+ workspace_dev_define_property(this, "matched", void 0);
275
+ workspace_dev_define_property(this, "metaData", void 0);
276
+ this.options = {
277
+ startCurrent: false,
278
+ ...options
279
+ };
280
+ this.cwd = options.cwd || process.cwd();
281
+ this.workspaceFileDir = options.workspaceFileDir || this.cwd;
282
+ this.packages = [];
283
+ this.visited = {};
284
+ this.visiting = {};
285
+ this.matched = {};
286
+ this.graph = new external_graphlib_namespaceObject.Graph({
287
+ directed: true
288
+ });
289
+ }
290
+ }
291
+ function pluginWorkspaceDev(options) {
292
+ return {
293
+ name: 'rsbuild-plugin-workspace-dev',
294
+ async setup (api) {
295
+ const rootPath = api.context.rootPath;
296
+ api.modifyRsbuildConfig(async ()=>{
297
+ const runner = new WorkspaceDevRunner({
298
+ cwd: rootPath,
299
+ ...options
300
+ });
301
+ await runner.init();
302
+ await runner.start();
303
+ Logger.setEndBanner();
304
+ });
305
+ }
306
+ };
307
+ }
308
+ exports.WorkspaceDevRunner = __webpack_exports__.WorkspaceDevRunner;
309
+ exports.pluginWorkspaceDev = __webpack_exports__.pluginWorkspaceDev;
310
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
311
+ "WorkspaceDevRunner",
312
+ "pluginWorkspaceDev"
313
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
314
+ Object.defineProperty(exports, '__esModule', {
315
+ value: true
316
+ });
@@ -0,0 +1,2 @@
1
+ export { pluginWorkspaceDev } from './plugin.js';
2
+ export { WorkspaceDevRunner, type WorkspaceDevRunnerOptions, } from './workspace-dev.js';
package/dist/index.js ADDED
@@ -0,0 +1,265 @@
1
+ import chalk from "chalk";
2
+ import fs from "fs";
3
+ import json5 from "json5";
4
+ import { getPackagesSync } from "@manypkg/get-packages";
5
+ import { spawn } from "child_process";
6
+ import graphlib, { Graph } from "graphlib";
7
+ import path_0 from "path";
8
+ const PACKAGE_JSON = 'package.json';
9
+ const DEBUG_LOG_TITLE = '[Rsbuild Workspace Dev Plugin]: ';
10
+ const RSLIB_READY_MESSAGE = 'build complete, watching for changes';
11
+ const MODERN_MODULE_READY_MESSAGE = 'Watching for file changes';
12
+ const TSUP_READY_MESSAGE = 'Watching for changes in';
13
+ async function pathExists(path) {
14
+ return fs.promises.access(path).then(()=>true).catch(()=>false);
15
+ }
16
+ const readJson = async (jsonFileAbsPath)=>{
17
+ if (!await pathExists(jsonFileAbsPath)) return {};
18
+ const content = await fs.promises.readFile(jsonFileAbsPath, 'utf-8');
19
+ const json = json5.parse(content);
20
+ return json;
21
+ };
22
+ const readPackageJson = async (pkgJsonFilePath)=>readJson(pkgJsonFilePath);
23
+ const isDebug = 'rsbuild' === process.env.DEBUG || '*' === process.env.DEBUG;
24
+ function _define_property(obj, key, value) {
25
+ if (key in obj) Object.defineProperty(obj, key, {
26
+ value: value,
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true
30
+ });
31
+ else obj[key] = value;
32
+ return obj;
33
+ }
34
+ const logMap = {
35
+ ["stdout"]: 'log',
36
+ ["stderr"]: 'error'
37
+ };
38
+ class Logger {
39
+ appendLog(type, log) {
40
+ this[type] += log;
41
+ }
42
+ emitLog(type) {
43
+ console[logMap[type]](this[type]);
44
+ }
45
+ emitLogOnce(type, log) {
46
+ const logWithName = `${chalk.hex('#808080').bold(this.name)}: ${log}`;
47
+ console[logMap[type]](logWithName);
48
+ }
49
+ reset(type) {
50
+ this[type] = '';
51
+ }
52
+ setBanner(name) {
53
+ const startBanner = `\n------------ ${chalk.hex('#c95ab3').bold('log start:')} ${chalk.green(name)} ${'-'.repeat(Math.max(50 - name.toString().length, 5))}`;
54
+ this.stdout = startBanner + this.stdout;
55
+ }
56
+ flushStdout() {
57
+ if (isDebug) return;
58
+ this.setBanner(this.name);
59
+ this.emitLog("stdout");
60
+ }
61
+ static setEndBanner() {
62
+ const endBanner = `------------ ${chalk.hex('#c95ab3').bold('log end:')} ${chalk.green('all sub project have been started.')} ------------\n`;
63
+ console.log(endBanner);
64
+ }
65
+ constructor({ name }){
66
+ _define_property(this, "stdout", void 0);
67
+ _define_property(this, "stderr", void 0);
68
+ _define_property(this, "name", void 0);
69
+ _define_property(this, "logTitle", void 0);
70
+ this.name = name;
71
+ this.stdout = '';
72
+ this.stderr = '';
73
+ this.logTitle = DEBUG_LOG_TITLE;
74
+ }
75
+ }
76
+ const debugLog = (msg, prefix = DEBUG_LOG_TITLE)=>{
77
+ if (isDebug) console.log(prefix + msg);
78
+ };
79
+ function workspace_dev_define_property(obj, key, value) {
80
+ if (key in obj) Object.defineProperty(obj, key, {
81
+ value: value,
82
+ enumerable: true,
83
+ configurable: true,
84
+ writable: true
85
+ });
86
+ else obj[key] = value;
87
+ return obj;
88
+ }
89
+ class WorkspaceDevRunner {
90
+ async init() {
91
+ this.metaData = await readPackageJson(path_0.join(this.cwd, PACKAGE_JSON));
92
+ this.buildDependencyGraph();
93
+ debugLog(`Dependency graph:\nnodes: ${this.getNodes().join(', ')}\nedges: ${this.getEdges().map((edge)=>`${edge.v} -> ${edge.w}`).join(', ')}\n`);
94
+ }
95
+ buildDependencyGraph() {
96
+ const { packages } = getPackagesSync(this.workspaceFileDir);
97
+ const currentPackage = packages.find((pkg)=>pkg.packageJson.name === this.metaData.name);
98
+ this.packages = packages;
99
+ const initNode = (pkg)=>{
100
+ const { packageJson, dir } = pkg;
101
+ const { name, dependencies, devDependencies, peerDependencies } = packageJson;
102
+ const node = {
103
+ name,
104
+ packageJson,
105
+ path: dir
106
+ };
107
+ this.graph.setNode(name, node);
108
+ this.visited[name] = false;
109
+ this.visiting[name] = false;
110
+ this.matched[name] = false;
111
+ const packageName = name;
112
+ const deps = {
113
+ ...dependencies,
114
+ ...devDependencies,
115
+ ...peerDependencies
116
+ };
117
+ for (const depName of Object.keys(deps)){
118
+ const isInternalDep = this.packages.some((p)=>p.packageJson.name === depName);
119
+ if (isInternalDep) {
120
+ this.graph.setEdge(packageName, depName);
121
+ this.checkGraph();
122
+ const depPackage = packages.find((pkg)=>pkg.packageJson.name === depName);
123
+ if (!this.getNode(depName)) initNode(depPackage);
124
+ }
125
+ }
126
+ };
127
+ initNode(currentPackage);
128
+ }
129
+ checkGraph() {
130
+ const cycles = graphlib.alg.findCycles(this.graph);
131
+ const nonSelfCycles = cycles.filter((c)=>1 !== c.length);
132
+ if (nonSelfCycles.length) console.log(chalk.red(`${DEBUG_LOG_TITLE} Cycle dependency graph found: ${cycles.join(', ')}, you should config projects in plugin options to skip them, or fix the cycle dependency. Otherwise, a loop of dev will occur.`));
133
+ }
134
+ async start() {
135
+ const promises = [];
136
+ const allNodes = this.getNodes();
137
+ const filterSelfNodes = allNodes.filter((node)=>node !== this.metaData.name);
138
+ const nodes = this.options.startCurrent ? allNodes : filterSelfNodes;
139
+ for (const node of nodes){
140
+ const dependencies = this.getDependencies(node) || [];
141
+ const canStart = dependencies.every((dep)=>{
142
+ const selfStart = node === dep;
143
+ const isVisiting = this.visiting[dep];
144
+ const isVisited = selfStart || this.visited[dep];
145
+ return isVisited && !isVisiting;
146
+ });
147
+ if (canStart && !this.visited[node] && !this.visiting[node]) {
148
+ debugLog(`Start visit node: ${node}`);
149
+ const visitPromise = this.visitNodes(node);
150
+ promises.push(visitPromise);
151
+ }
152
+ }
153
+ await Promise.all(promises);
154
+ }
155
+ visitNodes(node) {
156
+ return new Promise((resolve)=>{
157
+ const { name, path } = this.getNode(node);
158
+ const logger = new Logger({
159
+ name
160
+ });
161
+ const config = this.options?.projects?.[name];
162
+ if (config?.skip) {
163
+ this.visited[node] = true;
164
+ this.visiting[node] = false;
165
+ debugLog(`Skip visit node: ${node}`);
166
+ logger.emitLogOnce('stdout', `skip visit node: ${name}`);
167
+ return this.start().then(()=>resolve());
168
+ }
169
+ this.visiting[node] = true;
170
+ const child = spawn('npm', [
171
+ 'run',
172
+ config?.command ? config.command : 'dev'
173
+ ], {
174
+ cwd: path,
175
+ env: {
176
+ ...process.env,
177
+ FORCE_COLOR: '3'
178
+ },
179
+ shell: true
180
+ });
181
+ child.stdout.on('data', async (data)=>{
182
+ const stdout = data.toString();
183
+ const content = data.toString().replace(/\n$/, '');
184
+ if (this.matched[node]) return void logger.emitLogOnce('stdout', content);
185
+ debugLog(content, `${name}: `);
186
+ logger.appendLog('stdout', stdout);
187
+ const match = config?.match;
188
+ const matchResult = match ? match(stdout) : stdout.match(RSLIB_READY_MESSAGE) || stdout.match(MODERN_MODULE_READY_MESSAGE) || stdout.match(TSUP_READY_MESSAGE);
189
+ if (matchResult) {
190
+ logger.flushStdout();
191
+ this.matched[node] = true;
192
+ this.visited[node] = true;
193
+ this.visiting[node] = false;
194
+ await this.start();
195
+ resolve();
196
+ }
197
+ });
198
+ child.stderr.on('data', (data)=>{
199
+ const stderr = data.toString();
200
+ logger.emitLogOnce('stderr', stderr);
201
+ });
202
+ child.on('close', ()=>{});
203
+ });
204
+ }
205
+ getDependencyGraph() {
206
+ return this.graph;
207
+ }
208
+ getNodes() {
209
+ return this.graph.nodes();
210
+ }
211
+ getEdges() {
212
+ return this.graph.edges();
213
+ }
214
+ getNode(name) {
215
+ return this.graph.node(name);
216
+ }
217
+ getDependents(packageName) {
218
+ return this.graph.predecessors(packageName);
219
+ }
220
+ getDependencies(packageName) {
221
+ return this.graph.successors(packageName);
222
+ }
223
+ constructor(options){
224
+ workspace_dev_define_property(this, "options", void 0);
225
+ workspace_dev_define_property(this, "cwd", void 0);
226
+ workspace_dev_define_property(this, "workspaceFileDir", void 0);
227
+ workspace_dev_define_property(this, "packages", []);
228
+ workspace_dev_define_property(this, "graph", void 0);
229
+ workspace_dev_define_property(this, "visited", void 0);
230
+ workspace_dev_define_property(this, "visiting", void 0);
231
+ workspace_dev_define_property(this, "matched", void 0);
232
+ workspace_dev_define_property(this, "metaData", void 0);
233
+ this.options = {
234
+ startCurrent: false,
235
+ ...options
236
+ };
237
+ this.cwd = options.cwd || process.cwd();
238
+ this.workspaceFileDir = options.workspaceFileDir || this.cwd;
239
+ this.packages = [];
240
+ this.visited = {};
241
+ this.visiting = {};
242
+ this.matched = {};
243
+ this.graph = new Graph({
244
+ directed: true
245
+ });
246
+ }
247
+ }
248
+ function pluginWorkspaceDev(options) {
249
+ return {
250
+ name: 'rsbuild-plugin-workspace-dev',
251
+ async setup (api) {
252
+ const rootPath = api.context.rootPath;
253
+ api.modifyRsbuildConfig(async ()=>{
254
+ const runner = new WorkspaceDevRunner({
255
+ cwd: rootPath,
256
+ ...options
257
+ });
258
+ await runner.init();
259
+ await runner.start();
260
+ Logger.setEndBanner();
261
+ });
262
+ }
263
+ };
264
+ }
265
+ export { WorkspaceDevRunner, pluginWorkspaceDev };
@@ -0,0 +1,17 @@
1
+ export declare class Logger {
2
+ stdout: string;
3
+ stderr: string;
4
+ name: string;
5
+ logTitle: string;
6
+ constructor({ name, }: {
7
+ name: string;
8
+ });
9
+ appendLog(type: 'stdout' | 'stderr', log: string): void;
10
+ emitLog(type: 'stdout' | 'stderr'): void;
11
+ emitLogOnce(type: 'stdout' | 'stderr', log: string): void;
12
+ reset(type: 'stdout' | 'stderr'): void;
13
+ setBanner(name: string): void;
14
+ flushStdout(): void;
15
+ static setEndBanner(): void;
16
+ }
17
+ export declare const debugLog: (msg: string, prefix?: string) => void;
@@ -0,0 +1,3 @@
1
+ import type { RsbuildPlugin } from '@rsbuild/core';
2
+ import { type WorkspaceDevRunnerOptions } from './workspace-dev.js';
3
+ export declare function pluginWorkspaceDev(options?: WorkspaceDevRunnerOptions): RsbuildPlugin;
@@ -0,0 +1,4 @@
1
+ import type { Package } from '@manypkg/get-packages';
2
+ export declare const readJson: <T>(jsonFileAbsPath: string) => Promise<T>;
3
+ export declare const readPackageJson: (pkgJsonFilePath: string) => Promise<Package["packageJson"]>;
4
+ export declare const isDebug: boolean;
@@ -0,0 +1,34 @@
1
+ import graphlib from 'graphlib';
2
+ export interface WorkspaceDevRunnerOptions {
3
+ cwd?: string;
4
+ workspaceFileDir?: string;
5
+ projects?: Record<string, {
6
+ match?: (stdout: string) => boolean;
7
+ command?: string;
8
+ skip?: boolean;
9
+ }>;
10
+ startCurrent?: boolean;
11
+ }
12
+ export declare class WorkspaceDevRunner {
13
+ private options;
14
+ private cwd;
15
+ private workspaceFileDir;
16
+ private packages;
17
+ private graph;
18
+ private visited;
19
+ private visiting;
20
+ private matched;
21
+ private metaData;
22
+ constructor(options: WorkspaceDevRunnerOptions);
23
+ init(): Promise<void>;
24
+ buildDependencyGraph(): void;
25
+ checkGraph(): void;
26
+ start(): Promise<void>;
27
+ visitNodes(node: string): Promise<void>;
28
+ getDependencyGraph(): graphlib.Graph;
29
+ getNodes(): string[];
30
+ getEdges(): graphlib.Edge[];
31
+ getNode(name: string): any;
32
+ getDependents(packageName: string): void | string[];
33
+ getDependencies(packageName: string): void | string[];
34
+ }
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "rsbuild-plugin-workspace-dev",
3
+ "version": "0.0.0-chore-modify-hook-2025-12-16-20251216020145",
4
+ "description": "An Rsbuild plugin to provides workspace recursive dev functionality for Monorepo topologies.",
5
+ "repository": "https://github.com/rspack-contrib/rsbuild-plugin-workspace-dev",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ }
14
+ },
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.mjs",
17
+ "types": "./dist/index.d.ts",
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "simple-git-hooks": {
22
+ "pre-commit": "npx nano-staged"
23
+ },
24
+ "nano-staged": {
25
+ "*.{js,jsx,ts,tsx,mjs,cjs}": [
26
+ "biome check --write --no-errors-on-unmatched"
27
+ ]
28
+ },
29
+ "dependencies": {
30
+ "@manypkg/get-packages": "^3.1.0",
31
+ "chalk": "^5.6.2",
32
+ "graphlib": "^2.1.8",
33
+ "json5": "^2.2.3",
34
+ "yaml": "^2.8.1"
35
+ },
36
+ "devDependencies": {
37
+ "@biomejs/biome": "^2.3.3",
38
+ "@playwright/test": "^1.55.1",
39
+ "@rsbuild/core": "^1.6.1",
40
+ "@rsbuild/plugin-react": "^1.4.1",
41
+ "@rsbuild/plugin-type-check": "^1.3.0",
42
+ "@rslib/core": "^0.17.0",
43
+ "@rstest/core": "^0.6.6",
44
+ "@types/graphlib": "^2.1.12",
45
+ "@types/node": "^22.18.8",
46
+ "@types/react": "^19.1.16",
47
+ "@types/react-dom": "^19.1.9",
48
+ "playwright": "^1.55.1",
49
+ "react": "^19.1.1",
50
+ "react-dom": "^19.1.1",
51
+ "simple-git-hooks": "^2.13.1",
52
+ "typescript": "^5.9.3"
53
+ },
54
+ "peerDependencies": {
55
+ "@rsbuild/core": "1.x"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "@rsbuild/core": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "publishConfig": {
63
+ "access": "public",
64
+ "registry": "https://registry.npmjs.org/"
65
+ },
66
+ "scripts": {
67
+ "build": "rslib build",
68
+ "bump": "npx bumpp",
69
+ "dev": "rslib build --watch",
70
+ "lint": "biome check .",
71
+ "lint:write": "biome check . --write",
72
+ "test": "pnpm run test:unit && pnpm run test:e2e",
73
+ "test:e2e": "playwright test --config=./test/playwright.config.ts",
74
+ "test:unit": "rstest --config=./test/rstest.config.ts"
75
+ }
76
+ }