@tomjs/vite-plugin-vscode 2.3.0 → 2.4.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/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  > Use `vue`/`react` to develop [vscode extension webview](https://code.visualstudio.com/api/references/vscode-api#WebviewPanel), supporting `esm` and `cjs`.
8
8
 
9
- In development mode, inject the code of [@tomjs/vscode-extension-webview](https://github.com/tomjs/vscode-extension-webview) into `vscode extension code` and `web page code`, use To support `HMR`; during production build, the final generated `index.html` code is injected into `vscode extension code` to reduce the workload.
9
+ In development mode, inject the same code of [@tomjs/vscode-extension-webview](https://github.com/tomjs/vscode-extension-webview) into `vscode extension code` and `web page code`, use To support `HMR`; during production build, the final generated `index.html` code is injected into `vscode extension code` to reduce the workload.
10
10
 
11
11
  ## Features
12
12
 
@@ -27,7 +27,7 @@ pnpm add @tomjs/vite-plugin-vscode -D
27
27
  yarn add @tomjs/vite-plugin-vscode -D
28
28
 
29
29
  # npm
30
- npm i @tomjs/vite-plugin-vscode --save-dev
30
+ npm i @tomjs/vite-plugin-vscode -D
31
31
  ```
32
32
 
33
33
  ## Usage
package/README.zh_CN.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  > 用 `vue`/`react` 来开发 [vscode extension webview](https://code.visualstudio.com/api/references/vscode-api#WebviewPanel) ,支持 `esm` 和 `cjs`。
8
8
 
9
- 在开发模式时,给 `vscode 扩展代码` 和 `web 页面代码`中注入 [@tomjs/vscode-extension-webview](https://github.com/tomjs/vscode-extension-webview) 的代码,用来支持 `HMR`;生产构建时,将最终生成的`index.html` 代码注入到 `vscode 扩展代码` 中,减少工作量。
9
+ 在开发模式时,给 `vscode 扩展代码` 和 `web 页面代码`中注入 [@tomjs/vscode-extension-webview](https://github.com/tomjs/vscode-extension-webview) 相同的代码,用来支持 `HMR`;生产构建时,将最终生成的`index.html` 代码注入到 `vscode 扩展代码` 中,减少工作量。
10
10
 
11
11
  ## 特性
12
12
 
@@ -27,7 +27,7 @@ pnpm add @tomjs/vite-plugin-vscode -D
27
27
  yarn add @tomjs/vite-plugin-vscode -D
28
28
 
29
29
  # npm
30
- npm i @tomjs/vite-plugin-vscode --save-dev
30
+ npm i @tomjs/vite-plugin-vscode -D
31
31
  ```
32
32
 
33
33
  ## 使用说明
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ (() => {
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __commonJS = (cb, mod) => function __require() {
5
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
6
+ };
7
+
8
+ // src/webview/client.ts
9
+ var require_client = __commonJS({
10
+ "src/webview/client.ts"() {
11
+ if (window.top === window.self) {
12
+ return;
13
+ }
14
+ var TAG = "[@tomjs:vscode:client] ";
15
+ patchAcquireVsCodeApi();
16
+ function onDomReady(callback) {
17
+ if (document.readyState === "interactive" || document.readyState === "complete") {
18
+ callback();
19
+ } else {
20
+ document.addEventListener("DOMContentLoaded", callback);
21
+ }
22
+ }
23
+ function setStateData(data) {
24
+ localStorage.setItem("vscode.state", JSON.stringify(data));
25
+ }
26
+ function getStateData() {
27
+ try {
28
+ const v = localStorage.getItem("vscode.state");
29
+ return v ? JSON.parse(v) : v;
30
+ } catch (e) {
31
+ }
32
+ return;
33
+ }
34
+ function patchInitData(data) {
35
+ const { state, style, body, root } = data;
36
+ setStateData(state);
37
+ document.documentElement.style.cssText = root.cssText;
38
+ document.body.className = body.className;
39
+ Object.keys(body.dataset).forEach((key) => {
40
+ document.body.dataset[key] = body.dataset[key];
41
+ });
42
+ const defaultStyles = document.createElement("style");
43
+ defaultStyles.id = "_defaultStyles";
44
+ defaultStyles.textContent = style;
45
+ document.head.appendChild(defaultStyles);
46
+ }
47
+ function patchAcquireVsCodeApi() {
48
+ class AcquireVsCodeApi {
49
+ postMessage(message) {
50
+ console.log(TAG + " acquireVsCodeApi.postMessage:", message);
51
+ window.parent.postMessage({ type: "[vscode:client]:postMessage", data: message }, "*");
52
+ }
53
+ getState() {
54
+ console.log(TAG + " acquireVsCodeApi.getState");
55
+ return getStateData();
56
+ }
57
+ setState(newState) {
58
+ console.log(TAG + " acquireVsCodeApi.setState:", newState);
59
+ setStateData(newState);
60
+ window.parent.postMessage({ type: "[vscode:client]:setSate", data: newState }, "*");
61
+ }
62
+ }
63
+ console.log(TAG + "patch acquireVsCodeApi");
64
+ let api;
65
+ window.acquireVsCodeApi = () => {
66
+ if (!api) {
67
+ api = new AcquireVsCodeApi();
68
+ return api;
69
+ } else {
70
+ return api;
71
+ }
72
+ };
73
+ }
74
+ var INIT_TYPE = "[vscode:extension]:init";
75
+ var GET_STATE_TYPE = "[vscode:extension]:state";
76
+ window.addEventListener("message", (e) => {
77
+ const { type, data } = e.data || {};
78
+ if (!e.origin.startsWith("vscode-webview://") || ![INIT_TYPE, GET_STATE_TYPE].includes(type)) {
79
+ return;
80
+ }
81
+ onDomReady(function() {
82
+ if (type === INIT_TYPE) {
83
+ patchInitData(data);
84
+ } else if (type === GET_STATE_TYPE) {
85
+ localStorage.setItem("vscode.state", JSON.stringify(data));
86
+ }
87
+ });
88
+ });
89
+ }
90
+ });
91
+ require_client();
92
+ })();
package/dist/index.js CHANGED
@@ -1,16 +1,17 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/index.ts
2
2
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
3
+ var _os = require('os'); var _os2 = _interopRequireDefault(_os);
3
4
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
4
5
  var _process = require('process');
5
6
  var _lodashclonedeep = require('lodash.clonedeep'); var _lodashclonedeep2 = _interopRequireDefault(_lodashclonedeep);
6
7
  var _lodashmerge = require('lodash.merge'); var _lodashmerge2 = _interopRequireDefault(_lodashmerge);
7
8
  var _nodehtmlparser = require('node-html-parser');
8
9
  var _tsup = require('tsup');
10
+ var _node = require('@tomjs/node');
9
11
 
10
12
  // src/constants.ts
11
13
  var PLUGIN_NAME = "tomjs:vscode";
12
14
  var PACKAGE_NAME = "@tomjs/vite-plugin-vscode";
13
- var WEBVIEW_PACKAGE_NAME = "@tomjs/vscode-extension-webview";
14
15
  var WEBVIEW_METHOD_NAME = "__getWebviewHtml__";
15
16
 
16
17
  // src/logger.ts
@@ -56,22 +57,6 @@ var createLogger = (tag) => {
56
57
  };
57
58
 
58
59
  // src/utils.ts
59
- var _child_process = require('child_process');
60
-
61
- var _module = require('module');
62
-
63
-
64
- function readJson(path3) {
65
- if (_fs2.default.existsSync(path3)) {
66
- return JSON.parse(_fs2.default.readFileSync(path3, "utf8"));
67
- }
68
- }
69
- function emptyPath(dest) {
70
- if (_fs2.default.existsSync(dest)) {
71
- _fs2.default.rmSync(dest, { recursive: true });
72
- }
73
- _fs2.default.mkdirSync(dest, { recursive: true });
74
- }
75
60
  function resolveHostname(hostname) {
76
61
  const loopbackHosts = /* @__PURE__ */ new Set([
77
62
  "localhost",
@@ -91,46 +76,11 @@ function resolveServerUrl(server) {
91
76
  const options = server.config.server;
92
77
  const protocol = options.https ? "https" : "http";
93
78
  const devBase = server.config.base;
94
- const path3 = typeof options.open === "string" ? options.open : devBase;
95
- const url = path3.startsWith("http") ? path3 : `${protocol}://${hostname}:${port}${path3}`;
79
+ const path2 = typeof options.open === "string" ? options.open : devBase;
80
+ const url = path2.startsWith("http") ? path2 : `${protocol}://${hostname}:${port}${path2}`;
96
81
  return url;
97
82
  }
98
83
  }
99
- function getWebviewNpmPath() {
100
- let npmPath = _path2.default.join(_process.cwd.call(void 0, ), "node_modules", WEBVIEW_PACKAGE_NAME);
101
- if (!_fs2.default.existsSync(npmPath)) {
102
- try {
103
- const res = _child_process.spawnSync.call(void 0,
104
- process.platform === "win32" ? "pnpm.cmd" : "pnpm",
105
- ["list", "--dev", "--depth=1", "--json"],
106
- {
107
- // stdio: ['inherit', 'ignore'],
108
- cwd: process.cwd(),
109
- encoding: "utf-8"
110
- }
111
- );
112
- if (res.status === 0 && res.stdout) {
113
- const list = JSON.parse(res.stdout.trim());
114
- if (list.length === 0) {
115
- return;
116
- }
117
- const self = (list[0].devDependencies || {})[PACKAGE_NAME];
118
- if (!self) {
119
- return;
120
- }
121
- const dep = self.dependencies[WEBVIEW_PACKAGE_NAME];
122
- if (dep) {
123
- npmPath = dep.path;
124
- }
125
- }
126
- } catch (e) {
127
- npmPath = "";
128
- }
129
- if (npmPath) {
130
- return _path2.default.join(npmPath, "dist");
131
- }
132
- }
133
- }
134
84
 
135
85
  // src/index.ts
136
86
  var isDev = process.env.NODE_ENV === "development";
@@ -140,7 +90,7 @@ function getPkg() {
140
90
  if (!_fs2.default.existsSync(pkgFile)) {
141
91
  throw new Error("Main file is not specified, and no package.json found");
142
92
  }
143
- const pkg = readJson(pkgFile);
93
+ const pkg = _node.readJsonSync.call(void 0, pkgFile);
144
94
  if (!pkg.main) {
145
95
  throw new Error("Main file is not specified, please check package.json");
146
96
  }
@@ -183,9 +133,7 @@ function preMergeOptions(options) {
183
133
  } else {
184
134
  opt.minify ??= true;
185
135
  }
186
- opt.external = ["vscode", WEBVIEW_PACKAGE_NAME].concat(
187
- _nullishCoalesce(opt.external, () => ( []))
188
- );
136
+ opt.external = ["vscode"].concat(_nullishCoalesce(opt.external, () => ( [])));
189
137
  if (!opt.skipNodeModulesBundle) {
190
138
  opt.noExternal = Object.keys(pkg.dependencies || {}).concat(
191
139
  Object.keys(pkg.peerDependencies || {})
@@ -205,7 +153,7 @@ var prodCachePkgName = `${PACKAGE_NAME}-inject`;
205
153
  function genProdWebviewCode(cache, webview) {
206
154
  webview = Object.assign({}, webview);
207
155
  const prodCacheFolder = _path2.default.join(_process.cwd.call(void 0, ), "node_modules", prodCachePkgName);
208
- emptyPath(prodCacheFolder);
156
+ _node.emptyDirSync.call(void 0, prodCacheFolder);
209
157
  const destFile = _path2.default.join(prodCacheFolder, "index.ts");
210
158
  function handleHtmlCode(html) {
211
159
  const root = _nodehtmlparser.parse.call(void 0, html);
@@ -263,7 +211,13 @@ export default function getWebviewHtml(webview: Webview, context: ExtensionConte
263
211
  `
264
212
  );
265
213
  _fs2.default.writeFileSync(destFile, code, { encoding: "utf8" });
266
- return destFile.replaceAll("\\", "/");
214
+ return fixWindowsPath(destFile);
215
+ }
216
+ function fixWindowsPath(webviewPath) {
217
+ if (_os2.default.platform() === "win32") {
218
+ webviewPath = webviewPath.replaceAll("\\", "/");
219
+ }
220
+ return webviewPath;
267
221
  }
268
222
  function useVSCodePlugin(options) {
269
223
  const opts = preMergeOptions(options);
@@ -297,21 +251,9 @@ function useVSCodePlugin(options) {
297
251
  }
298
252
  };
299
253
  };
300
- let webviewClient;
301
- let webviewNpmPath;
254
+ let devWebviewClient;
302
255
  if (opts.webview) {
303
- webviewNpmPath = getWebviewNpmPath();
304
- if (!webviewNpmPath || !_fs2.default.existsSync(webviewNpmPath)) {
305
- logger.warn(`[${WEBVIEW_PACKAGE_NAME}] is not installed, please install it first!`);
306
- } else {
307
- const fileName = "client.global.js";
308
- const clientFile = _path2.default.join(webviewNpmPath, fileName);
309
- if (!_fs2.default.existsSync(clientFile)) {
310
- logger.warn(`[${fileName}] is does not exist, please update the package!`);
311
- } else {
312
- webviewClient = _fs2.default.readFileSync(clientFile, "utf-8");
313
- }
314
- }
256
+ devWebviewClient = _node.readFileSync.call(void 0, _path2.default.join(__dirname, "client.global.js"));
315
257
  }
316
258
  let buildConfig;
317
259
  const prodHtmlCache = {};
@@ -349,7 +291,7 @@ function useVSCodePlugin(options) {
349
291
  const file = _fs2.default.readFileSync(args.path, "utf-8");
350
292
  if (file.includes(`${webview.name}(`)) {
351
293
  return {
352
- contents: `import ${webview.name} from '@tomjs/vscode-extension-webview';
294
+ contents: `import ${webview.name} from '${PACKAGE_NAME}/webview';
353
295
  ` + file,
354
296
  loader: "ts"
355
297
  };
@@ -374,10 +316,10 @@ function useVSCodePlugin(options) {
374
316
  });
375
317
  },
376
318
  transformIndexHtml(html) {
377
- if (!opts.webview || !webviewClient) {
319
+ if (!opts.webview) {
378
320
  return html;
379
321
  }
380
- return html.replace(/<\/title>/i, `</title><script>${webviewClient}</script>`);
322
+ return html.replace(/<\/title>/i, `</title><script>${devWebviewClient}</script>`);
381
323
  }
382
324
  },
383
325
  {
package/dist/index.mjs CHANGED
@@ -1,16 +1,24 @@
1
+ // node_modules/.pnpm/tsup@7.2.0_@swc+core@1.3.100_postcss@8.4.32_typescript@5.3.3/node_modules/tsup/assets/esm_shims.js
2
+ import { fileURLToPath } from "url";
3
+ import path from "path";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+
1
8
  // src/index.ts
2
- import fs2 from "fs";
9
+ import fs from "fs";
10
+ import os from "os";
3
11
  import path2 from "path";
4
- import { cwd as cwd2 } from "process";
12
+ import { cwd } from "process";
5
13
  import cloneDeep from "lodash.clonedeep";
6
14
  import merge from "lodash.merge";
7
15
  import { parse as htmlParser } from "node-html-parser";
8
16
  import { build as tsupBuild } from "tsup";
17
+ import { emptyDirSync, readFileSync, readJsonSync } from "@tomjs/node";
9
18
 
10
19
  // src/constants.ts
11
20
  var PLUGIN_NAME = "tomjs:vscode";
12
21
  var PACKAGE_NAME = "@tomjs/vite-plugin-vscode";
13
- var WEBVIEW_PACKAGE_NAME = "@tomjs/vscode-extension-webview";
14
22
  var WEBVIEW_METHOD_NAME = "__getWebviewHtml__";
15
23
 
16
24
  // src/logger.ts
@@ -56,21 +64,6 @@ var createLogger = (tag) => {
56
64
  };
57
65
 
58
66
  // src/utils.ts
59
- import { spawnSync } from "child_process";
60
- import fs from "fs";
61
- import path from "path";
62
- import { cwd } from "process";
63
- function readJson(path3) {
64
- if (fs.existsSync(path3)) {
65
- return JSON.parse(fs.readFileSync(path3, "utf8"));
66
- }
67
- }
68
- function emptyPath(dest) {
69
- if (fs.existsSync(dest)) {
70
- fs.rmSync(dest, { recursive: true });
71
- }
72
- fs.mkdirSync(dest, { recursive: true });
73
- }
74
67
  function resolveHostname(hostname) {
75
68
  const loopbackHosts = /* @__PURE__ */ new Set([
76
69
  "localhost",
@@ -95,51 +88,16 @@ function resolveServerUrl(server) {
95
88
  return url;
96
89
  }
97
90
  }
98
- function getWebviewNpmPath() {
99
- let npmPath = path.join(cwd(), "node_modules", WEBVIEW_PACKAGE_NAME);
100
- if (!fs.existsSync(npmPath)) {
101
- try {
102
- const res = spawnSync(
103
- process.platform === "win32" ? "pnpm.cmd" : "pnpm",
104
- ["list", "--dev", "--depth=1", "--json"],
105
- {
106
- // stdio: ['inherit', 'ignore'],
107
- cwd: process.cwd(),
108
- encoding: "utf-8"
109
- }
110
- );
111
- if (res.status === 0 && res.stdout) {
112
- const list = JSON.parse(res.stdout.trim());
113
- if (list.length === 0) {
114
- return;
115
- }
116
- const self = (list[0].devDependencies || {})[PACKAGE_NAME];
117
- if (!self) {
118
- return;
119
- }
120
- const dep = self.dependencies[WEBVIEW_PACKAGE_NAME];
121
- if (dep) {
122
- npmPath = dep.path;
123
- }
124
- }
125
- } catch {
126
- npmPath = "";
127
- }
128
- if (npmPath) {
129
- return path.join(npmPath, "dist");
130
- }
131
- }
132
- }
133
91
 
134
92
  // src/index.ts
135
93
  var isDev = process.env.NODE_ENV === "development";
136
94
  var logger = createLogger();
137
95
  function getPkg() {
138
96
  const pkgFile = path2.resolve(process.cwd(), "package.json");
139
- if (!fs2.existsSync(pkgFile)) {
97
+ if (!fs.existsSync(pkgFile)) {
140
98
  throw new Error("Main file is not specified, and no package.json found");
141
99
  }
142
- const pkg = readJson(pkgFile);
100
+ const pkg = readJsonSync(pkgFile);
143
101
  if (!pkg.main) {
144
102
  throw new Error("Main file is not specified, please check package.json");
145
103
  }
@@ -182,9 +140,7 @@ function preMergeOptions(options) {
182
140
  } else {
183
141
  opt.minify ??= true;
184
142
  }
185
- opt.external = ["vscode", WEBVIEW_PACKAGE_NAME].concat(
186
- opt.external ?? []
187
- );
143
+ opt.external = ["vscode"].concat(opt.external ?? []);
188
144
  if (!opt.skipNodeModulesBundle) {
189
145
  opt.noExternal = Object.keys(pkg.dependencies || {}).concat(
190
146
  Object.keys(pkg.peerDependencies || {})
@@ -203,8 +159,8 @@ function preMergeOptions(options) {
203
159
  var prodCachePkgName = `${PACKAGE_NAME}-inject`;
204
160
  function genProdWebviewCode(cache, webview) {
205
161
  webview = Object.assign({}, webview);
206
- const prodCacheFolder = path2.join(cwd2(), "node_modules", prodCachePkgName);
207
- emptyPath(prodCacheFolder);
162
+ const prodCacheFolder = path2.join(cwd(), "node_modules", prodCachePkgName);
163
+ emptyDirSync(prodCacheFolder);
208
164
  const destFile = path2.join(prodCacheFolder, "index.ts");
209
165
  function handleHtmlCode(html) {
210
166
  const root = htmlParser(html);
@@ -261,8 +217,14 @@ export default function getWebviewHtml(webview: Webview, context: ExtensionConte
261
217
  }
262
218
  `
263
219
  );
264
- fs2.writeFileSync(destFile, code, { encoding: "utf8" });
265
- return destFile.replaceAll("\\", "/");
220
+ fs.writeFileSync(destFile, code, { encoding: "utf8" });
221
+ return fixWindowsPath(destFile);
222
+ }
223
+ function fixWindowsPath(webviewPath) {
224
+ if (os.platform() === "win32") {
225
+ webviewPath = webviewPath.replaceAll("\\", "/");
226
+ }
227
+ return webviewPath;
266
228
  }
267
229
  function useVSCodePlugin(options) {
268
230
  const opts = preMergeOptions(options);
@@ -296,21 +258,9 @@ function useVSCodePlugin(options) {
296
258
  }
297
259
  };
298
260
  };
299
- let webviewClient;
300
- let webviewNpmPath;
261
+ let devWebviewClient;
301
262
  if (opts.webview) {
302
- webviewNpmPath = getWebviewNpmPath();
303
- if (!webviewNpmPath || !fs2.existsSync(webviewNpmPath)) {
304
- logger.warn(`[${WEBVIEW_PACKAGE_NAME}] is not installed, please install it first!`);
305
- } else {
306
- const fileName = "client.global.js";
307
- const clientFile = path2.join(webviewNpmPath, fileName);
308
- if (!fs2.existsSync(clientFile)) {
309
- logger.warn(`[${fileName}] is does not exist, please update the package!`);
310
- } else {
311
- webviewClient = fs2.readFileSync(clientFile, "utf-8");
312
- }
313
- }
263
+ devWebviewClient = readFileSync(path2.join(__dirname, "client.global.js"));
314
264
  }
315
265
  let buildConfig;
316
266
  const prodHtmlCache = {};
@@ -345,10 +295,10 @@ function useVSCodePlugin(options) {
345
295
  name: "@tomjs:vscode:inject",
346
296
  setup(build) {
347
297
  build.onLoad({ filter: /\.ts$/ }, async (args) => {
348
- const file = fs2.readFileSync(args.path, "utf-8");
298
+ const file = fs.readFileSync(args.path, "utf-8");
349
299
  if (file.includes(`${webview.name}(`)) {
350
300
  return {
351
- contents: `import ${webview.name} from '@tomjs/vscode-extension-webview';
301
+ contents: `import ${webview.name} from '${PACKAGE_NAME}/webview';
352
302
  ` + file,
353
303
  loader: "ts"
354
304
  };
@@ -373,10 +323,10 @@ function useVSCodePlugin(options) {
373
323
  });
374
324
  },
375
325
  transformIndexHtml(html) {
376
- if (!opts.webview || !webviewClient) {
326
+ if (!opts.webview) {
377
327
  return html;
378
328
  }
379
- return html.replace(/<\/title>/i, `</title><script>${webviewClient}</script>`);
329
+ return html.replace(/<\/title>/i, `</title><script>${devWebviewClient}</script>`);
380
330
  }
381
331
  },
382
332
  {
@@ -403,7 +353,7 @@ function useVSCodePlugin(options) {
403
353
  if (webview) {
404
354
  webviewPath = genProdWebviewCode(prodHtmlCache, webview);
405
355
  }
406
- let outDir = buildConfig.build.outDir.replace(cwd2(), "").replaceAll("\\", "/");
356
+ let outDir = buildConfig.build.outDir.replace(cwd(), "").replaceAll("\\", "/");
407
357
  if (outDir.startsWith("/")) {
408
358
  outDir = outDir.substring(1);
409
359
  }
@@ -422,7 +372,7 @@ function useVSCodePlugin(options) {
422
372
  name: "@tomjs:vscode:inject",
423
373
  setup(build) {
424
374
  build.onLoad({ filter: /\.ts$/ }, async (args) => {
425
- const file = fs2.readFileSync(args.path, "utf-8");
375
+ const file = fs.readFileSync(args.path, "utf-8");
426
376
  if (file.includes(`${webview.name}(`)) {
427
377
  return {
428
378
  contents: `import ${webview.name} from \`${webviewPath}\`;
@@ -0,0 +1,13 @@
1
+ interface WebviewHtmlDevOptions {
2
+ /**
3
+ * local server url
4
+ */
5
+ serverUrl: string;
6
+ }
7
+ /**
8
+ *
9
+ * @param options serverUrl string or object options
10
+ */
11
+ declare function getHtml(options: string | WebviewHtmlDevOptions): string;
12
+
13
+ export { WebviewHtmlDevOptions, getHtml as default, getHtml };
@@ -0,0 +1,13 @@
1
+ interface WebviewHtmlDevOptions {
2
+ /**
3
+ * local server url
4
+ */
5
+ serverUrl: string;
6
+ }
7
+ /**
8
+ *
9
+ * @param options serverUrl string or object options
10
+ */
11
+ declare function getHtml(options: string | WebviewHtmlDevOptions): string;
12
+
13
+ export { WebviewHtmlDevOptions, getHtml as default, getHtml };
@@ -0,0 +1,165 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/webview/template.html
2
+ var template_default = `<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8
+ <style>
9
+ html,
10
+ body {
11
+ width: 100%;
12
+ height: 100%;
13
+ margin: 0;
14
+ padding: 0;
15
+ overflow: hidden;
16
+ }
17
+
18
+ #webview-patch-iframe {
19
+ width: 100%;
20
+ height: 100%;
21
+ border: none;
22
+ }
23
+
24
+ .outer {
25
+ width: 100%;
26
+ height: 100%;
27
+ overflow: hidden;
28
+ }
29
+ </style>
30
+
31
+ <script type="module" id="webview-patch">
32
+ const TAG = '[@tomjs:vscode:extension] ';
33
+
34
+ function onDomReady(callback) {
35
+ if (document.readyState === 'interactive' || document.readyState === 'complete') {
36
+ callback();
37
+ } else {
38
+ document.addEventListener('DOMContentLoaded', callback);
39
+ }
40
+ }
41
+
42
+ let vsCodeApi;
43
+
44
+ function getApi() {
45
+ if (vsCodeApi) return vsCodeApi;
46
+ return (vsCodeApi = acquireVsCodeApi());
47
+ }
48
+
49
+ function sendInitData(iframe) {
50
+ console.log(TAG + 'init data');
51
+ const dataset = {};
52
+ Object.keys(document.body.dataset).forEach(key => {
53
+ dataset[key] = document.body.dataset[key];
54
+ });
55
+
56
+ iframe.contentWindow.postMessage(
57
+ {
58
+ type: '[vscode:extension]:init',
59
+ data: {
60
+ state: getApi().getState(),
61
+ style: document.getElementById('_defaultStyles').innerHTML,
62
+ root: {
63
+ cssText: document.documentElement.style.cssText,
64
+ },
65
+ body: {
66
+ dataset: dataset,
67
+ className: document.body.className,
68
+ role: document.body.getAttribute('role'),
69
+ },
70
+ },
71
+ },
72
+ '*',
73
+ );
74
+ }
75
+
76
+ function addListeners(iframe) {
77
+ window.addEventListener('message', function (e) {
78
+ if (e.origin.startsWith('vscode-webview://')) {
79
+ iframe.contentWindow.postMessage(e.data, '*');
80
+ } else if ('{{serverUrl}}'.startsWith(e.origin)) {
81
+ const { type, data } = e.data;
82
+ if (type === '[vscode:client]:postMessage') {
83
+ getApi().postMessage(data);
84
+ } else if (type === '[vscode:client]:getState') {
85
+ iframe.contentWindow.postMessage(
86
+ {
87
+ type: '[vscode:extension]:getState',
88
+ data: getApi().getState(),
89
+ },
90
+ '*',
91
+ );
92
+ } else if (type === '[vscode:client]:setState') {
93
+ getApi().setState(data);
94
+ }
95
+ }
96
+ });
97
+ }
98
+
99
+ function observeAttributeChanges(element, attributeName, callback) {
100
+ const observer = new MutationObserver(function (mutationsList) {
101
+ for (let mutation of mutationsList) {
102
+ if (mutation.type === 'attributes' && mutation.attributeName === attributeName) {
103
+ callback(mutation.target.getAttribute(attributeName));
104
+ }
105
+ }
106
+ });
107
+ observer.observe(element, { attributes: true });
108
+ return observer;
109
+ }
110
+
111
+ onDomReady(function () {
112
+ const iframe = document.getElementById('webview-patch-iframe');
113
+ observeAttributeChanges(document.body, 'class', function (className) {
114
+ sendInitData(iframe);
115
+ });
116
+ iframe.addEventListener('load', function (e) {
117
+ let interval = setInterval(() => {
118
+ try {
119
+ if (document.getElementById('_defaultStyles')) {
120
+ sendInitData(iframe);
121
+ addListeners(iframe);
122
+ clearInterval(interval);
123
+ return;
124
+ }
125
+ } catch (e) {
126
+ clearInterval(interval);
127
+ console.error(e);
128
+ }
129
+ }, 10);
130
+ });
131
+ });
132
+ </script>
133
+ </head>
134
+
135
+ <body>
136
+ <div class="outer">
137
+ <iframe
138
+ id="webview-patch-iframe"
139
+ frameborder="0"
140
+ sandbox="allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-downloads"
141
+ allow="cross-origin-isolated; autoplay; clipboard-read; clipboard-write"
142
+ src="{{serverUrl}}"
143
+ ></iframe>
144
+ </div>
145
+ </body>
146
+ </html>
147
+ `;
148
+
149
+ // src/webview/webview.ts
150
+ function getHtml(options) {
151
+ const opts = {
152
+ serverUrl: ""
153
+ };
154
+ if (typeof options === "string") {
155
+ opts.serverUrl = options;
156
+ } else {
157
+ Object.assign(opts, options);
158
+ }
159
+ return template_default.replace(new RegExp("{{serverUrl}}", "g"), opts.serverUrl);
160
+ }
161
+ var webview_default = getHtml;
162
+
163
+
164
+
165
+ exports.default = webview_default; exports.getHtml = getHtml;
@@ -0,0 +1,165 @@
1
+ // src/webview/template.html
2
+ var template_default = `<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
8
+ <style>
9
+ html,
10
+ body {
11
+ width: 100%;
12
+ height: 100%;
13
+ margin: 0;
14
+ padding: 0;
15
+ overflow: hidden;
16
+ }
17
+
18
+ #webview-patch-iframe {
19
+ width: 100%;
20
+ height: 100%;
21
+ border: none;
22
+ }
23
+
24
+ .outer {
25
+ width: 100%;
26
+ height: 100%;
27
+ overflow: hidden;
28
+ }
29
+ </style>
30
+
31
+ <script type="module" id="webview-patch">
32
+ const TAG = '[@tomjs:vscode:extension] ';
33
+
34
+ function onDomReady(callback) {
35
+ if (document.readyState === 'interactive' || document.readyState === 'complete') {
36
+ callback();
37
+ } else {
38
+ document.addEventListener('DOMContentLoaded', callback);
39
+ }
40
+ }
41
+
42
+ let vsCodeApi;
43
+
44
+ function getApi() {
45
+ if (vsCodeApi) return vsCodeApi;
46
+ return (vsCodeApi = acquireVsCodeApi());
47
+ }
48
+
49
+ function sendInitData(iframe) {
50
+ console.log(TAG + 'init data');
51
+ const dataset = {};
52
+ Object.keys(document.body.dataset).forEach(key => {
53
+ dataset[key] = document.body.dataset[key];
54
+ });
55
+
56
+ iframe.contentWindow.postMessage(
57
+ {
58
+ type: '[vscode:extension]:init',
59
+ data: {
60
+ state: getApi().getState(),
61
+ style: document.getElementById('_defaultStyles').innerHTML,
62
+ root: {
63
+ cssText: document.documentElement.style.cssText,
64
+ },
65
+ body: {
66
+ dataset: dataset,
67
+ className: document.body.className,
68
+ role: document.body.getAttribute('role'),
69
+ },
70
+ },
71
+ },
72
+ '*',
73
+ );
74
+ }
75
+
76
+ function addListeners(iframe) {
77
+ window.addEventListener('message', function (e) {
78
+ if (e.origin.startsWith('vscode-webview://')) {
79
+ iframe.contentWindow.postMessage(e.data, '*');
80
+ } else if ('{{serverUrl}}'.startsWith(e.origin)) {
81
+ const { type, data } = e.data;
82
+ if (type === '[vscode:client]:postMessage') {
83
+ getApi().postMessage(data);
84
+ } else if (type === '[vscode:client]:getState') {
85
+ iframe.contentWindow.postMessage(
86
+ {
87
+ type: '[vscode:extension]:getState',
88
+ data: getApi().getState(),
89
+ },
90
+ '*',
91
+ );
92
+ } else if (type === '[vscode:client]:setState') {
93
+ getApi().setState(data);
94
+ }
95
+ }
96
+ });
97
+ }
98
+
99
+ function observeAttributeChanges(element, attributeName, callback) {
100
+ const observer = new MutationObserver(function (mutationsList) {
101
+ for (let mutation of mutationsList) {
102
+ if (mutation.type === 'attributes' && mutation.attributeName === attributeName) {
103
+ callback(mutation.target.getAttribute(attributeName));
104
+ }
105
+ }
106
+ });
107
+ observer.observe(element, { attributes: true });
108
+ return observer;
109
+ }
110
+
111
+ onDomReady(function () {
112
+ const iframe = document.getElementById('webview-patch-iframe');
113
+ observeAttributeChanges(document.body, 'class', function (className) {
114
+ sendInitData(iframe);
115
+ });
116
+ iframe.addEventListener('load', function (e) {
117
+ let interval = setInterval(() => {
118
+ try {
119
+ if (document.getElementById('_defaultStyles')) {
120
+ sendInitData(iframe);
121
+ addListeners(iframe);
122
+ clearInterval(interval);
123
+ return;
124
+ }
125
+ } catch (e) {
126
+ clearInterval(interval);
127
+ console.error(e);
128
+ }
129
+ }, 10);
130
+ });
131
+ });
132
+ </script>
133
+ </head>
134
+
135
+ <body>
136
+ <div class="outer">
137
+ <iframe
138
+ id="webview-patch-iframe"
139
+ frameborder="0"
140
+ sandbox="allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-downloads"
141
+ allow="cross-origin-isolated; autoplay; clipboard-read; clipboard-write"
142
+ src="{{serverUrl}}"
143
+ ></iframe>
144
+ </div>
145
+ </body>
146
+ </html>
147
+ `;
148
+
149
+ // src/webview/webview.ts
150
+ function getHtml(options) {
151
+ const opts = {
152
+ serverUrl: ""
153
+ };
154
+ if (typeof options === "string") {
155
+ opts.serverUrl = options;
156
+ } else {
157
+ Object.assign(opts, options);
158
+ }
159
+ return template_default.replace(new RegExp("{{serverUrl}}", "g"), opts.serverUrl);
160
+ }
161
+ var webview_default = getHtml;
162
+ export {
163
+ webview_default as default,
164
+ getHtml
165
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomjs/vite-plugin-vscode",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Use vue/react to develop 'vscode extension webview', supporting esm/cjs",
5
5
  "keywords": [
6
6
  "vite",
@@ -23,10 +23,27 @@
23
23
  "types": "./dist/index.d.ts",
24
24
  "exports": {
25
25
  ".": {
26
- "require": "./dist/index.js",
27
- "import": "./dist/index.mjs",
28
- "types": "./dist/index.d.ts"
29
- }
26
+ "require": {
27
+ "default": "./dist/index.js",
28
+ "types": "./dist/index.d.ts"
29
+ },
30
+ "import": {
31
+ "default": "./dist/index.mjs",
32
+ "types": "./dist/index.d.mts"
33
+ }
34
+ },
35
+ "./webview": {
36
+ "require": {
37
+ "default": "./dist/webview.js",
38
+ "types": "./dist/webview.d.ts"
39
+ },
40
+ "import": {
41
+ "default": "./dist/webview.mjs",
42
+ "types": "./dist/webview.d.mts"
43
+ }
44
+ },
45
+ "./client": "./dist/client.global.js",
46
+ "./env": "./env.d.ts"
30
47
  },
31
48
  "files": [
32
49
  "dist",
@@ -44,8 +61,10 @@
44
61
  "url": "git+https://github.com/tomjs/vite-plugin-vscode.git"
45
62
  },
46
63
  "dependencies": {
64
+ "@tomjs/node": "^2.2.0",
47
65
  "@tomjs/vscode-extension-webview": "^1.2.0",
48
66
  "dayjs": "^1.11.10",
67
+ "execa": "^5.1.1",
49
68
  "kolorist": "^1.8.0",
50
69
  "lodash.clonedeep": "^4.5.0",
51
70
  "lodash.merge": "^4.6.2",
@@ -77,8 +96,9 @@
77
96
  "vite": ">=2"
78
97
  },
79
98
  "scripts": {
80
- "dev": "tsup --watch",
81
- "build": "tsup",
99
+ "dev": "pnpm clean && tsup --watch",
100
+ "build": "pnpm clean && tsup",
101
+ "clean": "rimraf ./dist",
82
102
  "lint": "run-s lint:eslint lint:stylelint lint:prettier",
83
103
  "lint:eslint": "eslint \"{src,scripts,examples}/**/*.ts\" *.{js,cjs,ts} --fix --cache",
84
104
  "lint:stylelint": "stylelint \"examples/**/*.{css,scss,less,vue,html}\" --fix --cache",