@modern-js/plugin-devtools 2.52.0 → 2.54.0

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/dist/cli.d.ts CHANGED
@@ -1,9 +1,11 @@
1
- import type { AppTools, CliPlugin } from '@modern-js/app-tools';
1
+ import { type AppTools, type CliPlugin } from '@modern-js/app-tools';
2
2
  import { ClientDefinition } from '@modern-js/devtools-kit/node';
3
3
  import { DevtoolsPluginOptions } from './options';
4
+ import { Plugin } from './types';
4
5
  export type { DevtoolsPluginOptions };
5
6
  export type DevtoolsPlugin = CliPlugin<AppTools> & {
6
7
  setClientDefinition: (def: ClientDefinition) => void;
7
8
  };
9
+ export declare const BUILTIN_PLUGINS: Plugin[];
8
10
  export declare const devtoolsPlugin: (inlineOptions?: DevtoolsPluginOptions) => DevtoolsPlugin;
9
11
  export default devtoolsPlugin;
package/dist/cli.js CHANGED
@@ -28,259 +28,150 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var cli_exports = {};
30
30
  __export(cli_exports, {
31
+ BUILTIN_PLUGINS: () => BUILTIN_PLUGINS,
31
32
  default: () => cli_default,
32
33
  devtoolsPlugin: () => devtoolsPlugin
33
34
  });
34
35
  module.exports = __toCommonJS(cli_exports);
35
- var import_http = __toESM(require("http"));
36
- var import_path = __toESM(require("path"));
37
- var import_assert = __toESM(require("assert"));
38
- var import_url = require("url");
39
- var import_lodash = __toESM(require("@modern-js/utils/lodash"));
36
+ var import_app_tools = require("@modern-js/app-tools");
40
37
  var import_utils = require("@modern-js/utils");
41
- var import_hono = require("hono");
42
- var import_node_server = require("@hono/node-server");
43
- var import_serve_static = require("@hono/node-server/serve-static");
44
- var import_node = require("@modern-js/devtools-kit/node");
38
+ var import_p_defer = __toESM(require("p-defer"));
39
+ var import_hookable = require("hookable");
45
40
  var import_valtio = require("valtio");
46
41
  var import_options = require("./options");
47
- var import_rpc = require("./rpc");
48
- var import_socket = require("./utils/socket");
49
- var import_config = require("./utils/config");
42
+ var import_debug = require("./plugins/debug");
43
+ var import_http = require("./plugins/http");
44
+ var import_state = require("./plugins/state");
45
+ var import_watcher = require("./plugins/watcher");
46
+ var import_service_worker = require("./plugins/service-worker");
47
+ var import_html = require("./plugins/html");
48
+ var import_rpc = require("./plugins/rpc");
49
+ var import_cleanup = require("./plugins/cleanup");
50
+ var import_settle = require("./plugins/settle");
51
+ var import_manifest = require("./plugins/manifest");
52
+ const BUILTIN_PLUGINS = [
53
+ import_debug.pluginDebug,
54
+ import_watcher.pluginWatcher,
55
+ import_service_worker.pluginServiceWorker,
56
+ import_html.pluginHtml,
57
+ // --- //
58
+ import_state.pluginState,
59
+ import_http.pluginHttp,
60
+ import_rpc.pluginRpc,
61
+ import_settle.pluginSettleState,
62
+ import_manifest.pluginManifest,
63
+ // --- //
64
+ import_cleanup.pluginCleanup
65
+ ];
50
66
  const devtoolsPlugin = (inlineOptions = {}) => {
51
67
  const ctx = (0, import_valtio.proxy)((0, import_options.resolveContext)(inlineOptions));
52
- let watcher = null;
53
- const closeWatcher = () => {
54
- if (!watcher)
55
- return;
56
- watcher.close();
57
- watcher = null;
68
+ const setupBuilder = (0, import_p_defer.default)();
69
+ const setupFramework = (0, import_p_defer.default)();
70
+ const _sharedVars = {};
71
+ const api = {
72
+ builderHooks: (0, import_hookable.createHooks)(),
73
+ frameworkHooks: (0, import_hookable.createHooks)(),
74
+ hooks: (0, import_hookable.createHooks)(),
75
+ setupBuilder: () => setupBuilder.promise,
76
+ setupFramework: () => setupFramework.promise,
77
+ get context() {
78
+ return ctx;
79
+ },
80
+ get vars() {
81
+ return _sharedVars;
82
+ }
58
83
  };
84
+ api.hooks.hook("cleanup", () => {
85
+ setupBuilder.reject(new Error("Devtools Plugin is disabled"));
86
+ setupFramework.reject(new Error("Devtools Plugin is disabled"));
87
+ });
88
+ for (const plugin of BUILTIN_PLUGINS) {
89
+ plugin.setup(api);
90
+ }
59
91
  return {
60
92
  name: "@modern-js/plugin-devtools",
61
93
  usePlugins: [],
62
94
  setClientDefinition(def) {
63
95
  Object.assign(ctx.def, def);
64
96
  },
65
- async setup(api) {
97
+ async setup(frameworkApi) {
66
98
  if (!ctx.enable)
67
99
  return {};
68
- const httpServer = await setupHttpServer();
69
- const socketServer = new import_socket.SocketServer({
70
- server: httpServer.instance,
71
- path: "/rpc"
72
- });
73
- const rpc = await (0, import_rpc.setupClientConnection)({
74
- api,
75
- ctx,
76
- server: socketServer
77
- });
100
+ setupFramework.resolve(frameworkApi);
78
101
  return {
79
102
  async prepare() {
80
- await rpc.hooks.prepare();
81
- const appConfig = api.useConfigContext();
82
- const appCtx = api.useAppContext();
83
- const { devtools: options = {} } = appConfig;
84
- (0, import_options.updateContext)(ctx, options);
85
- const basename = `${ctx.def.name.shortName}.runtime.json`;
86
- const watcher2 = import_utils.chokidar.watch((0, import_config.getConfigFilenames)(basename), {
87
- cwd: appCtx.appDirectory,
88
- ignorePermissionErrors: true
89
- });
90
- const refreshStoragePreset = async () => {
91
- const configs = await (0, import_config.loadConfigFiles)(basename, appCtx.appDirectory);
92
- if (!configs)
93
- return;
94
- ctx.storagePresets = [];
95
- (0, import_options.updateContext)(ctx, ...configs);
96
- };
97
- watcher2.on("add", refreshStoragePreset);
98
- watcher2.on("change", refreshStoragePreset);
99
- watcher2.on("unlink", refreshStoragePreset);
103
+ await api.frameworkHooks.callHook("prepare");
104
+ },
105
+ async modifyFileSystemRoutes(params) {
106
+ await api.frameworkHooks.callHook("modifyFileSystemRoutes", params);
107
+ return params;
108
+ },
109
+ async afterCreateCompiler(params) {
110
+ await api.frameworkHooks.callHook("afterCreateCompiler", params);
100
111
  },
101
- modifyFileSystemRoutes: rpc.hooks.modifyFileSystemRoutes,
102
- afterCreateCompiler: rpc.hooks.afterCreateCompiler,
103
- beforeRestart() {
104
- closeWatcher();
105
- return new Promise((resolve, reject) => httpServer.instance.close((err) => err ? reject(err) : resolve()));
112
+ async modifyServerRoutes(params) {
113
+ await api.frameworkHooks.callHook("modifyServerRoutes", params);
114
+ return params;
115
+ },
116
+ async beforeRestart() {
117
+ await api.frameworkHooks.callHook("beforeRestart");
106
118
  },
107
119
  beforeExit() {
108
- closeWatcher();
120
+ api.frameworkHooks.callHookWith((hooks) => hooks.forEach((hook) => hook()), "beforeExit");
109
121
  },
110
- modifyServerRoutes({ routes }) {
111
- routes.push({
112
- urlPath: "/sw-proxy.js",
113
- isSPA: true,
114
- isSSR: false,
115
- entryPath: "public/sw-proxy.js"
116
- });
117
- return {
118
- routes
119
- };
122
+ async afterDev(params) {
123
+ await api.frameworkHooks.callHook("afterDev", params);
124
+ },
125
+ async afterBuild(params) {
126
+ api.frameworkHooks.callHook("afterBuild", params);
120
127
  },
121
128
  async config() {
122
129
  import_utils.logger.info(`${ctx.def.name.formalName} DevTools is enabled`);
123
- const swProxyEntry = require.resolve("@modern-js/devtools-client/sw-proxy");
124
- const clientOptions = import_lodash.default.pick(ctx, [
125
- "def",
126
- "endpoint",
127
- "dataSource"
128
- ]);
129
- Object.assign(clientOptions, {
130
- __keep: true
131
- });
132
- const serializedOptions = JSON.stringify(clientOptions);
133
- const tags = [
134
- {
135
- tag: "script",
136
- children: `window.__MODERN_JS_DEVTOOLS_OPTIONS__ = ${serializedOptions};`,
137
- head: true,
138
- append: false
139
- }
140
- ];
141
- const styles = [];
142
- const manifest = require("@modern-js/devtools-client/manifest");
143
- for (const src of manifest.routeAssets.mount.assets) {
144
- (0, import_assert.default)(typeof src === "string");
145
- if (src.endsWith(".js")) {
146
- tags.push({
147
- tag: "script",
148
- attrs: {
149
- src
150
- },
151
- head: true,
152
- append: false
130
+ const configs = await api.frameworkHooks.callHookParallel("config");
131
+ const builderPlugin = {
132
+ name: "builder-plugin-devtools",
133
+ setup(builderApi) {
134
+ setupBuilder.resolve(builderApi);
135
+ builderApi.modifyBundlerChain(async (options, utils) => {
136
+ await api.builderHooks.callHook("modifyBundlerChain", options, utils);
137
+ });
138
+ builderApi.modifyWebpackConfig(async (config, utils) => {
139
+ await api.builderHooks.callHook("modifyWebpackConfig", config, utils);
140
+ });
141
+ builderApi.modifyRspackConfig(async (config, utils) => {
142
+ await api.builderHooks.callHook("modifyRspackConfig", config, utils);
143
+ });
144
+ builderApi.onBeforeCreateCompiler(async (params) => {
145
+ await api.builderHooks.callHook("onBeforeCreateCompiler", params);
146
+ });
147
+ builderApi.onAfterCreateCompiler(async (params) => {
148
+ await api.builderHooks.callHook("onAfterCreateCompiler", params);
149
+ });
150
+ builderApi.onDevCompileDone(async (params) => {
151
+ await api.builderHooks.callHook("onDevCompileDone", params);
152
+ });
153
+ builderApi.onAfterBuild(async (params) => {
154
+ await api.builderHooks.callHook("onAfterBuild", params);
155
+ });
156
+ builderApi.onExit(() => {
157
+ api.builderHooks.callHookWith((hooks) => hooks.forEach((hook) => hook()), "onExit");
153
158
  });
154
- } else if (src.endsWith(".css")) {
155
- styles.push(src);
156
- }
157
- }
158
- tags.push({
159
- tag: "template",
160
- attrs: {
161
- id: "_modern_js_devtools_styles"
162
- },
163
- append: true,
164
- head: false,
165
- children: styles.map((src) => `<link rel="stylesheet" href="${src}">`).join("")
166
- });
167
- return {
168
- builderPlugins: [
169
- rpc.builderPlugin
170
- ],
171
- source: {},
172
- output: {
173
- copy: [
174
- {
175
- from: swProxyEntry,
176
- to: "public"
177
- }
178
- ]
179
- },
180
- html: {
181
- tags
182
- },
183
- tools: {
184
- devServer: {
185
- proxy: {
186
- [import_node.ROUTE_BASENAME]: {
187
- target: `http://127.0.0.1:${httpServer.port}`,
188
- pathRewrite: {
189
- [`^${import_node.ROUTE_BASENAME}`]: ""
190
- },
191
- ws: true,
192
- onProxyReq(proxyReq, req) {
193
- const addrInfo = req.socket.address();
194
- if ("address" in addrInfo) {
195
- const { address } = addrInfo;
196
- proxyReq.setHeader("X-Forwarded-For", address);
197
- } else {
198
- proxyReq.removeHeader("X-Forwarded-For");
199
- }
200
- }
201
- }
202
- }
203
- }
204
159
  }
205
160
  };
161
+ configs.push({
162
+ builderPlugins: [
163
+ builderPlugin
164
+ ]
165
+ });
166
+ return (0, import_app_tools.mergeConfig)(configs);
206
167
  }
207
168
  };
208
169
  }
209
170
  };
210
171
  };
211
172
  var cli_default = devtoolsPlugin;
212
- const setupHttpServer = async () => {
213
- const app = new import_hono.Hono();
214
- const port = await (0, import_utils.getPort)(8782, {
215
- slient: true
216
- });
217
- const clientServeDir = import_path.default.resolve(require.resolve("@modern-js/devtools-client/package.json"), "../dist");
218
- const handleCookieApi = async (c) => {
219
- const raw = c.req.header("Cookie");
220
- const { parse } = await import("cookie-es");
221
- const cookies = raw ? parse(raw) : {};
222
- const body = await c.req.json().catch(() => null);
223
- if (body === null || body === void 0 ? void 0 : body.setCookies) {
224
- const { setCookies } = body;
225
- (0, import_assert.default)(typeof setCookies === "object", "setCookies should be object");
226
- for (const [k, v] of Object.entries(setCookies)) {
227
- (0, import_assert.default)(typeof v === "string");
228
- const expires = new Date(Date.now() + 30 * 24 * 36e5).toUTCString();
229
- cookies[k] = v;
230
- c.header("Set-Cookie", `${k}=${v}; Expires=${expires}; Path=/`, {
231
- append: true
232
- });
233
- }
234
- }
235
- return c.json({
236
- cookies
237
- });
238
- };
239
- app.get("/api/cookies", handleCookieApi);
240
- app.post("/api/cookies", handleCookieApi);
241
- app.use(
242
- "/static/*",
243
- // Workaround for https://github.com/honojs/node-server/blob/dd0e0cd160b0b8f18abbcb28c5f5c39b72105d98/src/serve-static.ts#L56
244
- (0, import_serve_static.serveStatic)({
245
- root: import_path.default.relative(process.cwd(), clientServeDir)
246
- })
247
- );
248
- app.get(":filename{.+\\.hot-update\\.\\w+$}", async (c) => {
249
- if (process.env.NODE_ENV !== "development") {
250
- return c.text("Not found", 404);
251
- }
252
- const filename = c.req.param("filename");
253
- const target = new import_url.URL(filename, "http://127.0.0.1:8780");
254
- const { body, headers, status } = await fetch(target.href);
255
- const newResp = c.newResponse(body, {
256
- headers,
257
- status
258
- });
259
- if (newResp.headers.get("content-encoding") === "gzip") {
260
- newResp.headers.delete("content-encoding");
261
- }
262
- return newResp;
263
- });
264
- app.get("*", async (c) => {
265
- const filename = import_path.default.resolve(clientServeDir, "html/client/index.html");
266
- const content = await import_utils.fs.readFile(filename, "utf-8");
267
- return c.html(content);
268
- });
269
- const instance = (0, import_node_server.serve)({
270
- fetch: app.fetch,
271
- port,
272
- hostname: "127.0.0.1",
273
- serverOptions: {
274
- allowHTTP1: true
275
- }
276
- });
277
- (0, import_assert.default)(instance instanceof import_http.default.Server, "instance should be http.Server");
278
- return {
279
- instance,
280
- port
281
- };
282
- };
283
173
  // Annotate the CommonJS export names for ESM import in node:
284
174
  0 && (module.exports = {
175
+ BUILTIN_PLUGINS,
285
176
  devtoolsPlugin
286
177
  });
package/dist/options.js CHANGED
@@ -25,19 +25,13 @@ module.exports = __toCommonJS(options_exports);
25
25
  var import_node = require("@modern-js/devtools-kit/node");
26
26
  const resolveContext = (...sources) => {
27
27
  const ret = {
28
- enable: process.env.NODE_ENV === "development",
29
- dataSource: `${import_node.ROUTE_BASENAME}/rpc`,
30
- endpoint: import_node.ROUTE_BASENAME,
28
+ enable: true,
31
29
  def: new import_node.ClientDefinition(),
32
30
  storagePresets: []
33
31
  };
34
32
  for (const opts of sources) {
35
33
  var _opts_enable;
36
34
  ret.enable = (_opts_enable = opts.enable) !== null && _opts_enable !== void 0 ? _opts_enable : ret.enable;
37
- var _opts_dataSource;
38
- ret.dataSource = (_opts_dataSource = opts.dataSource) !== null && _opts_dataSource !== void 0 ? _opts_dataSource : ret.dataSource;
39
- var _opts_endpoint;
40
- ret.endpoint = (_opts_endpoint = opts.endpoint) !== null && _opts_endpoint !== void 0 ? _opts_endpoint : ret.endpoint;
41
35
  var _opts_def;
42
36
  ret.def = (_opts_def = opts.def) !== null && _opts_def !== void 0 ? _opts_def : ret.def;
43
37
  opts.storagePresets && ret.storagePresets.push(...opts.storagePresets);
@@ -0,0 +1,2 @@
1
+ import { Plugin } from '../types';
2
+ export declare const pluginCleanup: Plugin;
@@ -16,21 +16,24 @@ var __copyProps = (to, from, except, desc) => {
16
16
  return to;
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var state_exports = {};
20
- __export(state_exports, {
21
- $resolvers: () => $resolvers,
22
- $serverExportedState: () => $serverExportedState,
23
- $state: () => $state
19
+ var cleanup_exports = {};
20
+ __export(cleanup_exports, {
21
+ pluginCleanup: () => pluginCleanup
24
22
  });
25
- module.exports = __toCommonJS(state_exports);
26
- var import_valtio = require("valtio");
27
- var import_node = require("@modern-js/devtools-kit/node");
28
- const $serverExportedState = (0, import_node.createServerExportedState)();
29
- const $resolvers = $serverExportedState.resolvers;
30
- const $state = (0, import_valtio.proxy)($serverExportedState.state);
23
+ module.exports = __toCommonJS(cleanup_exports);
24
+ const pluginCleanup = {
25
+ async setup(api) {
26
+ let _done = false;
27
+ const cleanup = async () => {
28
+ !_done && await api.hooks.callHook("cleanup");
29
+ _done = true;
30
+ };
31
+ api.frameworkHooks.hook("beforeExit", cleanup);
32
+ api.frameworkHooks.hook("beforeRestart", cleanup);
33
+ api.frameworkHooks.hook("afterBuild", cleanup);
34
+ }
35
+ };
31
36
  // Annotate the CommonJS export names for ESM import in node:
32
37
  0 && (module.exports = {
33
- $resolvers,
34
- $serverExportedState,
35
- $state
38
+ pluginCleanup
36
39
  });
@@ -0,0 +1,2 @@
1
+ import { Plugin } from '../types';
2
+ export declare const pluginDebug: Plugin;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var debug_exports = {};
20
+ __export(debug_exports, {
21
+ pluginDebug: () => pluginDebug
22
+ });
23
+ module.exports = __toCommonJS(debug_exports);
24
+ var import_utils = require("@modern-js/utils");
25
+ const logger = (0, import_utils.createLogger)({
26
+ level: process.env.LOG_LEVEL || "info"
27
+ });
28
+ const pluginDebug = {
29
+ async setup(api) {
30
+ await api.setupFramework();
31
+ logger.debug("setup framework api");
32
+ await api.setupBuilder();
33
+ logger.debug("setup builder api");
34
+ api.builderHooks.beforeEach((e) => {
35
+ logger.debug("after builder hook:", e.name);
36
+ });
37
+ api.frameworkHooks.beforeEach((e) => {
38
+ logger.debug("after framework hook:", e.name);
39
+ });
40
+ api.hooks.beforeEach((e) => {
41
+ logger.debug("after hook:", e.name);
42
+ });
43
+ }
44
+ };
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ pluginDebug
48
+ });
@@ -0,0 +1,2 @@
1
+ import { Plugin } from '../types';
2
+ export declare const pluginHtml: Plugin;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var html_exports = {};
30
+ __export(html_exports, {
31
+ pluginHtml: () => pluginHtml
32
+ });
33
+ module.exports = __toCommonJS(html_exports);
34
+ const pluginHtml = {
35
+ async setup(api) {
36
+ api.frameworkHooks.hook("config", async () => {
37
+ const clientOptions = {
38
+ def: api.context.def,
39
+ src: "/__devtools"
40
+ };
41
+ Object.assign(clientOptions, {
42
+ __keep: true
43
+ });
44
+ const config = {
45
+ source: {
46
+ preEntry: [
47
+ require.resolve("../runtime")
48
+ ],
49
+ globalVars: {
50
+ "process.env.__USE_MODERNJS_DEVTOOLS__": "/__devtools/manifest"
51
+ }
52
+ }
53
+ };
54
+ return config;
55
+ });
56
+ }
57
+ };
58
+ // Annotate the CommonJS export names for ESM import in node:
59
+ 0 && (module.exports = {
60
+ pluginHtml
61
+ });
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ import http from 'http';
3
+ import { Plugin } from '../types';
4
+ declare global {
5
+ interface DevtoolsPluginVars {
6
+ http: http.Server;
7
+ }
8
+ }
9
+ export declare const pluginHttp: Plugin;