@rspress/plugin-playground 2.0.0-beta.0 → 2.0.0-beta.2

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.
@@ -4,218 +4,13 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__ from "@rspress/shared/node-utils";
6
6
  import * as __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__ from "rspack-plugin-virtual-module";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__ from "unist-util-visit";
7
8
  import * as __WEBPACK_EXTERNAL_MODULE__oxidation_compiler_napi_5e24345a__ from "@oxidation-compiler/napi";
8
- var __webpack_modules__ = {
9
- "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
10
- __webpack_require__.d(__webpack_exports__, {
11
- Vn: ()=>lib_visit
12
- });
13
- const convert = function(test) {
14
- if (null == test) return ok;
15
- if ('function' == typeof test) return castFactory(test);
16
- if ('object' == typeof test) return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
17
- if ('string' == typeof test) return typeFactory(test);
18
- throw new Error('Expected function, string, or object as test');
19
- };
20
- function anyFactory(tests) {
21
- const checks = [];
22
- let index = -1;
23
- while(++index < tests.length)checks[index] = convert(tests[index]);
24
- return castFactory(any);
25
- function any(...parameters) {
26
- let index = -1;
27
- while(++index < checks.length)if (checks[index].apply(this, parameters)) return true;
28
- return false;
29
- }
30
- }
31
- function propsFactory(check) {
32
- const checkAsRecord = check;
33
- return castFactory(all);
34
- function all(node) {
35
- const nodeAsRecord = node;
36
- let key;
37
- for(key in check)if (nodeAsRecord[key] !== checkAsRecord[key]) return false;
38
- return true;
39
- }
40
- }
41
- function typeFactory(check) {
42
- return castFactory(type);
43
- function type(node) {
44
- return node && node.type === check;
45
- }
46
- }
47
- function castFactory(testFunction) {
48
- return check;
49
- function check(value, index, parent) {
50
- return Boolean(looksLikeANode(value) && testFunction.call(this, value, 'number' == typeof index ? index : void 0, parent || void 0));
51
- }
52
- }
53
- function ok() {
54
- return true;
55
- }
56
- function looksLikeANode(value) {
57
- return null !== value && 'object' == typeof value && 'type' in value;
58
- }
59
- function color(d) {
60
- return '\u001B[33m' + d + '\u001B[39m';
61
- }
62
- const empty = [];
63
- const CONTINUE = true;
64
- const EXIT = false;
65
- const SKIP = 'skip';
66
- function visitParents(tree, test, visitor, reverse) {
67
- let check;
68
- if ('function' == typeof test && 'function' != typeof visitor) {
69
- reverse = visitor;
70
- visitor = test;
71
- } else check = test;
72
- const is = convert(check);
73
- const step = reverse ? -1 : 1;
74
- factory(tree, void 0, [])();
75
- function factory(node, index, parents) {
76
- const value = node && 'object' == typeof node ? node : {};
77
- if ('string' == typeof value.type) {
78
- const name = 'string' == typeof value.tagName ? value.tagName : 'string' == typeof value.name ? value.name : void 0;
79
- Object.defineProperty(visit, 'name', {
80
- value: 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'
81
- });
82
- }
83
- return visit;
84
- function visit() {
85
- let result = empty;
86
- let subresult;
87
- let offset;
88
- let grandparents;
89
- if (!test || is(node, index, parents[parents.length - 1] || void 0)) {
90
- result = toResult(visitor(node, parents));
91
- if (result[0] === EXIT) return result;
92
- }
93
- if ('children' in node && node.children) {
94
- const nodeAsParent = node;
95
- if (nodeAsParent.children && result[0] !== SKIP) {
96
- offset = (reverse ? nodeAsParent.children.length : -1) + step;
97
- grandparents = parents.concat(nodeAsParent);
98
- while(offset > -1 && offset < nodeAsParent.children.length){
99
- const child = nodeAsParent.children[offset];
100
- subresult = factory(child, offset, grandparents)();
101
- if (subresult[0] === EXIT) return subresult;
102
- offset = 'number' == typeof subresult[1] ? subresult[1] : offset + step;
103
- }
104
- }
105
- }
106
- return result;
107
- }
108
- }
109
- }
110
- function toResult(value) {
111
- if (Array.isArray(value)) return value;
112
- if ('number' == typeof value) return [
113
- CONTINUE,
114
- value
115
- ];
116
- return null == value ? empty : [
117
- value
118
- ];
119
- }
120
- function lib_visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
121
- let reverse;
122
- let test;
123
- let visitor;
124
- if ('function' == typeof testOrVisitor && 'function' != typeof visitorOrReverse) {
125
- test = void 0;
126
- visitor = testOrVisitor;
127
- reverse = visitorOrReverse;
128
- } else {
129
- test = testOrVisitor;
130
- visitor = visitorOrReverse;
131
- reverse = maybeReverse;
132
- }
133
- visitParents(tree, test, overload, reverse);
134
- function overload(node, parents) {
135
- const parent = parents[parents.length - 1];
136
- const index = parent ? parent.children.indexOf(node) : void 0;
137
- return visitor(node, index, parent);
138
- }
139
- }
140
- }
141
- };
142
- var __webpack_module_cache__ = {};
143
- function __webpack_require__(moduleId) {
144
- var cachedModule = __webpack_module_cache__[moduleId];
145
- if (void 0 !== cachedModule) return cachedModule.exports;
146
- var module = __webpack_module_cache__[moduleId] = {
147
- exports: {}
148
- };
149
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
150
- return module.exports;
151
- }
152
- __webpack_require__.m = __webpack_modules__;
153
- (()=>{
154
- __webpack_require__.d = (exports, definition)=>{
155
- for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
156
- enumerable: true,
157
- get: definition[key]
158
- });
159
- };
160
- })();
161
- (()=>{
162
- __webpack_require__.f = {};
163
- __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
164
- __webpack_require__.f[key](chunkId, promises);
165
- return promises;
166
- }, []));
167
- })();
168
- (()=>{
169
- __webpack_require__.u = (chunkId)=>"" + chunkId + ".mjs";
170
- })();
171
- (()=>{
172
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
173
- })();
174
- (()=>{
175
- var installedChunks = {
176
- 980: 0
177
- };
178
- var installChunk = (data)=>{
179
- var __webpack_ids__ = data.__webpack_ids__;
180
- var __webpack_modules__ = data.__webpack_modules__;
181
- var __webpack_runtime__ = data.__webpack_runtime__;
182
- var moduleId, chunkId, i = 0;
183
- for(moduleId in __webpack_modules__)if (__webpack_require__.o(__webpack_modules__, moduleId)) __webpack_require__.m[moduleId] = __webpack_modules__[moduleId];
184
- if (__webpack_runtime__) __webpack_runtime__(__webpack_require__);
185
- for(; i < __webpack_ids__.length; i++){
186
- chunkId = __webpack_ids__[i];
187
- if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
188
- installedChunks[__webpack_ids__[i]] = 0;
189
- }
190
- };
191
- __webpack_require__.f.j = function(chunkId, promises) {
192
- var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
193
- if (0 !== installedChunkData) if (installedChunkData) promises.push(installedChunkData[1]);
194
- else {
195
- var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, (e)=>{
196
- if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
197
- throw e;
198
- });
199
- var promise = Promise.race([
200
- promise,
201
- new Promise((resolve)=>{
202
- installedChunkData = installedChunks[chunkId] = [
203
- resolve
204
- ];
205
- })
206
- ]);
207
- promises.push(installedChunkData[1] = promise);
208
- }
209
- };
210
- })();
211
9
  const DEFAULT_BABEL_URL = 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';
212
10
  const DEFAULT_MONACO_URL = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';
213
11
  function normalizeUrl(u) {
214
12
  return u.replace(/\/\//g, '/');
215
13
  }
216
- var constant_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
217
- const staticPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(constant_dirname, '../../../static');
218
- var lib = __webpack_require__("../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js");
219
14
  const parseImports = (code, sourceExt)=>{
220
15
  const parsed = __WEBPACK_EXTERNAL_MODULE__oxidation_compiler_napi_5e24345a__["default"].parseSync(code, {
221
16
  sourceType: 'module',
@@ -232,7 +27,7 @@ const getNodeMeta = (node, metaName)=>{
232
27
  if (!node.meta) return;
233
28
  const meta = node.meta.split(' ');
234
29
  const item = meta.find((x)=>x.startsWith(metaName));
235
- if (null == item ? void 0 : item.startsWith(`${metaName}=`)) return item.slice(metaName.length + 1);
30
+ if (item?.startsWith(`${metaName}=`)) return item.slice(metaName.length + 1);
236
31
  return item;
237
32
  };
238
33
  function createPlaygroundNode(currentNode, attrs) {
@@ -251,7 +46,7 @@ const remarkPlugin = ({ getRouteMeta, editorPosition, defaultRenderMode })=>{
251
46
  return (tree, vfile)=>{
252
47
  const route = routeMeta.find((meta)=>(0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.resolve)(meta.absolutePath) === (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.resolve)(vfile.path || vfile.history[0]));
253
48
  if (!route) return;
254
- (0, lib.Vn)(tree, 'mdxJsxFlowElement', (node)=>{
49
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'mdxJsxFlowElement', (node)=>{
255
50
  if ('code' === node.name) {
256
51
  const src = (0, __WEBPACK_EXTERNAL_MODULE__rspress_shared_node_utils_78947ce6__.getNodeAttribute)(node, 'src');
257
52
  if ('string' != typeof src) return;
@@ -282,11 +77,10 @@ const remarkPlugin = ({ getRouteMeta, editorPosition, defaultRenderMode })=>{
282
77
  ]);
283
78
  }
284
79
  });
285
- (0, lib.Vn)(tree, 'code', (node)=>{
80
+ (0, __WEBPACK_EXTERNAL_MODULE_unist_util_visit_555e002a__.visit)(tree, 'code', (node)=>{
286
81
  if ('jsx' === node.lang || 'tsx' === node.lang) {
287
- var _node_meta, _node_meta1;
288
- const hasPureMeta = null == (_node_meta = node.meta) ? void 0 : _node_meta.includes('pure');
289
- const hasPlaygroundMeta = null == (_node_meta1 = node.meta) ? void 0 : _node_meta1.includes('playground');
82
+ const hasPureMeta = node.meta?.includes('pure');
83
+ const hasPlaygroundMeta = node.meta?.includes('playground');
290
84
  let noTransform;
291
85
  switch(defaultRenderMode){
292
86
  case 'pure':
@@ -323,22 +117,22 @@ const remarkPlugin = ({ getRouteMeta, editorPosition, defaultRenderMode })=>{
323
117
  };
324
118
  };
325
119
  var cli_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
120
+ const pkgRootPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(cli_dirname, '../../');
121
+ const staticPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(pkgRootPath, 'static');
326
122
  let cli_routeMeta;
327
123
  function pluginPlayground(options) {
328
- var _monacoLoader_paths;
329
124
  const { render = '', include, defaultDirection = 'horizontal', editorPosition = 'left', babelUrl = DEFAULT_BABEL_URL, monacoLoader = {}, monacoOptions = {}, defaultRenderMode = 'playground' } = options || {};
330
125
  const playgroundVirtualModule = new __WEBPACK_EXTERNAL_MODULE_rspack_plugin_virtual_module_609978fd__.RspackVirtualModulePlugin({});
331
126
  const getRouteMeta = ()=>cli_routeMeta;
332
127
  if (render && !/Playground\.(jsx?|tsx?)$/.test(render)) throw new Error('[Playground]: render should ends with Playground.(jsx?|tsx?)');
333
128
  const preloads = [];
334
- const monacoPrefix = (null == (_monacoLoader_paths = monacoLoader.paths) ? void 0 : _monacoLoader_paths.vs) || DEFAULT_MONACO_URL;
129
+ const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;
335
130
  preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));
336
131
  preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));
337
132
  return {
338
133
  name: '@rspress/plugin-playground',
339
134
  config (config, { removePlugin }) {
340
135
  config.markdown = config.markdown || {};
341
- config.markdown.mdxRs = false;
342
136
  removePlugin('@rspress/plugin-preview');
343
137
  return config;
344
138
  },
@@ -350,7 +144,7 @@ function pluginPlayground(options) {
350
144
  const isMdxFile = /\.mdx?$/.test(filepath);
351
145
  if (!isMdxFile) return;
352
146
  const { createProcessor } = await import("@mdx-js/mdx");
353
- const { visit } = await __webpack_require__.e("52").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/index.js"));
147
+ const { visit } = await import("unist-util-visit");
354
148
  const { default: remarkGFM } = await import("remark-gfm");
355
149
  try {
356
150
  const processor = createProcessor({
@@ -379,8 +173,8 @@ function pluginPlayground(options) {
379
173
  visit(ast, 'code', (node)=>{
380
174
  if ('jsx' === node.lang || 'tsx' === node.lang) {
381
175
  const { value, meta } = node;
382
- const hasPureMeta = null == meta ? void 0 : meta.includes('pure');
383
- const hasPlaygroundMeta = null == meta ? void 0 : meta.includes('playground');
176
+ const hasPureMeta = meta?.includes('pure');
177
+ const hasPlaygroundMeta = meta?.includes('playground');
384
178
  let noTransform;
385
179
  switch(defaultRenderMode){
386
180
  case 'pure':
@@ -438,7 +232,7 @@ function pluginPlayground(options) {
438
232
  __PLAYGROUND_BABEL_URL__: JSON.stringify(babelUrl)
439
233
  },
440
234
  include: [
441
- (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join)(cli_dirname, '..', '..', '..')
235
+ pkgRootPath
442
236
  ]
443
237
  },
444
238
  html: {
@@ -141,16 +141,6 @@ async function getBabel() {
141
141
  throw e;
142
142
  }
143
143
  }
144
- function _define_property(obj, key, value) {
145
- if (key in obj) Object.defineProperty(obj, key, {
146
- value: value,
147
- enumerable: true,
148
- configurable: true,
149
- writable: true
150
- });
151
- else obj[key] = value;
152
- return obj;
153
- }
154
144
  const DEBOUNCE_TIME = 800;
155
145
  class Runner extends __WEBPACK_EXTERNAL_MODULE_react__.Component {
156
146
  static getDerivedStateFromError(error) {
@@ -159,6 +149,16 @@ class Runner extends __WEBPACK_EXTERNAL_MODULE_react__.Component {
159
149
  comp: null
160
150
  };
161
151
  }
152
+ timer = null;
153
+ constructor(props){
154
+ super(props);
155
+ this.state = {
156
+ error: void 0,
157
+ comp: null
158
+ };
159
+ this.doCompile = this.doCompile.bind(this);
160
+ this.waitCompile = this.waitCompile.bind(this);
161
+ }
162
162
  waitCompile(targetCode) {
163
163
  if (this.timer) clearTimeout(this.timer);
164
164
  this.timer = window.setTimeout(()=>{
@@ -266,15 +266,6 @@ class Runner extends __WEBPACK_EXTERNAL_MODULE_react__.Component {
266
266
  ]
267
267
  });
268
268
  }
269
- constructor(props){
270
- super(props), _define_property(this, "timer", null);
271
- this.state = {
272
- error: void 0,
273
- comp: null
274
- };
275
- this.doCompile = this.doCompile.bind(this);
276
- this.waitCompile = this.waitCompile.bind(this);
277
- }
278
269
  }
279
270
  var __webpack_exports__MonacoEditor = __WEBPACK_EXTERNAL_MODULE__monaco_editor_react_be42f315__["default"];
280
271
  var __webpack_exports__MonacoEditorLoader = __WEBPACK_EXTERNAL_MODULE__monaco_editor_react_be42f315__.loader;
package/package.json CHANGED
@@ -1,29 +1,27 @@
1
1
  {
2
2
  "name": "@rspress/plugin-playground",
3
- "version": "2.0.0-beta.0",
3
+ "version": "2.0.0-beta.2",
4
4
  "description": "A plugin for rspress to preview the code block in markdown/mdx file.",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "https://github.com/web-infra-dev/rspress",
8
+ "url": "git+https://github.com/web-infra-dev/rspress.git",
9
9
  "directory": "packages/plugin-preview"
10
10
  },
11
11
  "license": "MIT",
12
+ "type": "module",
12
13
  "exports": {
13
14
  ".": {
14
- "types": "./dist/cli/esm/index.d.ts",
15
- "import": "./dist/cli/esm/index.mjs",
16
- "default": "./dist/cli/cjs/index.js"
15
+ "types": "./dist/cli/index.d.ts",
16
+ "default": "./dist/cli/index.js"
17
17
  },
18
18
  "./web": {
19
- "types": "./dist/web/esm/index.d.ts",
20
- "import": "./dist/web/esm/index.mjs",
21
- "default": "./dist/web/cjs/index.js"
19
+ "types": "./dist/web/index.d.ts",
20
+ "default": "./dist/web/index.js"
22
21
  }
23
22
  },
24
- "main": "./dist/cli/cjs/index.js",
25
- "module": "./dist/cli/esm/index.js",
26
- "types": "./dist/cli/esm/index.d.ts",
23
+ "module": "./dist/cli/index.js",
24
+ "types": "./dist/cli/index.d.ts",
27
25
  "files": [
28
26
  "dist",
29
27
  "static"
@@ -34,7 +32,8 @@
34
32
  "@oxidation-compiler/napi": "^0.2.0",
35
33
  "remark-gfm": "^4.0.1",
36
34
  "rspack-plugin-virtual-module": "0.1.13",
37
- "@rspress/shared": "2.0.0-beta.0"
35
+ "unist-util-visit": "^5.0.0",
36
+ "@rspress/shared": "2.0.0-beta.2"
38
37
  },
39
38
  "devDependencies": {
40
39
  "@babel/types": "^7.27.0",
@@ -51,17 +50,18 @@
51
50
  "react": "^19.1.0",
52
51
  "react-dom": "^19.1.0",
53
52
  "react-router-dom": "^6.29.0",
53
+ "rsbuild-plugin-publint": "^0.3.0",
54
54
  "typescript": "^5.8.2",
55
55
  "unified": "^11.0.5",
56
- "unist-util-visit": "^5.0.0"
56
+ "@rspress/plugin-playground": "2.0.0-beta.2"
57
57
  },
58
58
  "peerDependencies": {
59
- "@rspress/core": "^2.0.0-beta.0",
60
- "react": ">=17.0.0",
59
+ "@rspress/core": "^2.0.0-beta.2",
60
+ "react": ">=18.0.0",
61
61
  "react-router-dom": "^6.8.1"
62
62
  },
63
63
  "engines": {
64
- "node": ">=14.17.6"
64
+ "node": ">=18.0.0"
65
65
  },
66
66
  "publishConfig": {
67
67
  "access": "public",
@@ -1,4 +1,5 @@
1
1
  import { usePageData } from '@rspress/core/runtime';
2
+ import { Editor, Runner } from '@rspress/plugin-playground/web';
2
3
  // @ts-ignore Cannot find module _rspress_playground_imports
3
4
  import getImport from '_rspress_playground_imports';
4
5
  import React, {
@@ -7,7 +8,6 @@ import React, {
7
8
  useCallback,
8
9
  useState,
9
10
  } from 'react';
10
- import { Editor, Runner } from '../../dist/web/esm';
11
11
 
12
12
  // inject by builder in cli/index.ts
13
13
  declare global {
@@ -1,12 +0,0 @@
1
- "use strict";
2
- exports.ids = [
3
- '52'
4
- ];
5
- exports.modules = {
6
- "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
7
- __webpack_require__.d(__webpack_exports__, {
8
- visit: ()=>_lib_index_js__WEBPACK_IMPORTED_MODULE_0__.Vn
9
- });
10
- var _lib_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js");
11
- }
12
- };
@@ -1,503 +0,0 @@
1
- "use strict";
2
- var __webpack_modules__ = {
3
- "@mdx-js/mdx": function(module) {
4
- module.exports = import("@mdx-js/mdx").then(function(module) {
5
- return module;
6
- });
7
- },
8
- "remark-gfm": function(module) {
9
- module.exports = import("remark-gfm").then(function(module) {
10
- return module;
11
- });
12
- },
13
- "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
14
- __webpack_require__.d(__webpack_exports__, {
15
- Vn: ()=>lib_visit
16
- });
17
- const convert = function(test) {
18
- if (null == test) return ok;
19
- if ('function' == typeof test) return castFactory(test);
20
- if ('object' == typeof test) return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
21
- if ('string' == typeof test) return typeFactory(test);
22
- throw new Error('Expected function, string, or object as test');
23
- };
24
- function anyFactory(tests) {
25
- const checks = [];
26
- let index = -1;
27
- while(++index < tests.length)checks[index] = convert(tests[index]);
28
- return castFactory(any);
29
- function any(...parameters) {
30
- let index = -1;
31
- while(++index < checks.length)if (checks[index].apply(this, parameters)) return true;
32
- return false;
33
- }
34
- }
35
- function propsFactory(check) {
36
- const checkAsRecord = check;
37
- return castFactory(all);
38
- function all(node) {
39
- const nodeAsRecord = node;
40
- let key;
41
- for(key in check)if (nodeAsRecord[key] !== checkAsRecord[key]) return false;
42
- return true;
43
- }
44
- }
45
- function typeFactory(check) {
46
- return castFactory(type);
47
- function type(node) {
48
- return node && node.type === check;
49
- }
50
- }
51
- function castFactory(testFunction) {
52
- return check;
53
- function check(value, index, parent) {
54
- return Boolean(looksLikeANode(value) && testFunction.call(this, value, 'number' == typeof index ? index : void 0, parent || void 0));
55
- }
56
- }
57
- function ok() {
58
- return true;
59
- }
60
- function looksLikeANode(value) {
61
- return null !== value && 'object' == typeof value && 'type' in value;
62
- }
63
- function color(d) {
64
- return '\u001B[33m' + d + '\u001B[39m';
65
- }
66
- const empty = [];
67
- const CONTINUE = true;
68
- const EXIT = false;
69
- const SKIP = 'skip';
70
- function visitParents(tree, test, visitor, reverse) {
71
- let check;
72
- if ('function' == typeof test && 'function' != typeof visitor) {
73
- reverse = visitor;
74
- visitor = test;
75
- } else check = test;
76
- const is = convert(check);
77
- const step = reverse ? -1 : 1;
78
- factory(tree, void 0, [])();
79
- function factory(node, index, parents) {
80
- const value = node && 'object' == typeof node ? node : {};
81
- if ('string' == typeof value.type) {
82
- const name = 'string' == typeof value.tagName ? value.tagName : 'string' == typeof value.name ? value.name : void 0;
83
- Object.defineProperty(visit, 'name', {
84
- value: 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'
85
- });
86
- }
87
- return visit;
88
- function visit() {
89
- let result = empty;
90
- let subresult;
91
- let offset;
92
- let grandparents;
93
- if (!test || is(node, index, parents[parents.length - 1] || void 0)) {
94
- result = toResult(visitor(node, parents));
95
- if (result[0] === EXIT) return result;
96
- }
97
- if ('children' in node && node.children) {
98
- const nodeAsParent = node;
99
- if (nodeAsParent.children && result[0] !== SKIP) {
100
- offset = (reverse ? nodeAsParent.children.length : -1) + step;
101
- grandparents = parents.concat(nodeAsParent);
102
- while(offset > -1 && offset < nodeAsParent.children.length){
103
- const child = nodeAsParent.children[offset];
104
- subresult = factory(child, offset, grandparents)();
105
- if (subresult[0] === EXIT) return subresult;
106
- offset = 'number' == typeof subresult[1] ? subresult[1] : offset + step;
107
- }
108
- }
109
- }
110
- return result;
111
- }
112
- }
113
- }
114
- function toResult(value) {
115
- if (Array.isArray(value)) return value;
116
- if ('number' == typeof value) return [
117
- CONTINUE,
118
- value
119
- ];
120
- return null == value ? empty : [
121
- value
122
- ];
123
- }
124
- function lib_visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
125
- let reverse;
126
- let test;
127
- let visitor;
128
- if ('function' == typeof testOrVisitor && 'function' != typeof visitorOrReverse) {
129
- test = void 0;
130
- visitor = testOrVisitor;
131
- reverse = visitorOrReverse;
132
- } else {
133
- test = testOrVisitor;
134
- visitor = visitorOrReverse;
135
- reverse = maybeReverse;
136
- }
137
- visitParents(tree, test, overload, reverse);
138
- function overload(node, parents) {
139
- const parent = parents[parents.length - 1];
140
- const index = parent ? parent.children.indexOf(node) : void 0;
141
- return visitor(node, index, parent);
142
- }
143
- }
144
- }
145
- };
146
- var __webpack_module_cache__ = {};
147
- function __webpack_require__(moduleId) {
148
- var cachedModule = __webpack_module_cache__[moduleId];
149
- if (void 0 !== cachedModule) return cachedModule.exports;
150
- var module = __webpack_module_cache__[moduleId] = {
151
- exports: {}
152
- };
153
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
154
- return module.exports;
155
- }
156
- __webpack_require__.m = __webpack_modules__;
157
- (()=>{
158
- __webpack_require__.n = (module)=>{
159
- var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
160
- __webpack_require__.d(getter, {
161
- a: getter
162
- });
163
- return getter;
164
- };
165
- })();
166
- (()=>{
167
- __webpack_require__.d = (exports1, definition)=>{
168
- for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
169
- enumerable: true,
170
- get: definition[key]
171
- });
172
- };
173
- })();
174
- (()=>{
175
- __webpack_require__.f = {};
176
- __webpack_require__.e = (chunkId)=>Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key)=>{
177
- __webpack_require__.f[key](chunkId, promises);
178
- return promises;
179
- }, []));
180
- })();
181
- (()=>{
182
- __webpack_require__.u = (chunkId)=>"" + chunkId + ".js";
183
- })();
184
- (()=>{
185
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
186
- })();
187
- (()=>{
188
- __webpack_require__.r = (exports1)=>{
189
- if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
190
- value: 'Module'
191
- });
192
- Object.defineProperty(exports1, '__esModule', {
193
- value: true
194
- });
195
- };
196
- })();
197
- (()=>{
198
- var installedChunks = {
199
- 980: 1
200
- };
201
- var installChunk = (chunk)=>{
202
- var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;
203
- for(var moduleId in moreModules)if (__webpack_require__.o(moreModules, moduleId)) __webpack_require__.m[moduleId] = moreModules[moduleId];
204
- if (runtime) runtime(__webpack_require__);
205
- for(var i = 0; i < chunkIds.length; i++)installedChunks[chunkIds[i]] = 1;
206
- };
207
- __webpack_require__.f.require = (chunkId, promises)=>{
208
- if (!installedChunks[chunkId]) installChunk(require("./" + __webpack_require__.u(chunkId)));
209
- };
210
- })();
211
- var __webpack_exports__ = {};
212
- (()=>{
213
- __webpack_require__.r(__webpack_exports__);
214
- __webpack_require__.d(__webpack_exports__, {
215
- pluginPlayground: ()=>pluginPlayground,
216
- routeMeta: ()=>cli_routeMeta
217
- });
218
- const external_node_fs_namespaceObject = require("node:fs");
219
- var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
220
- const external_node_path_namespaceObject = require("node:path");
221
- var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
222
- const node_utils_namespaceObject = require("@rspress/shared/node-utils");
223
- const external_rspack_plugin_virtual_module_namespaceObject = require("rspack-plugin-virtual-module");
224
- const DEFAULT_BABEL_URL = 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';
225
- const DEFAULT_MONACO_URL = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';
226
- function normalizeUrl(u) {
227
- return u.replace(/\/\//g, '/');
228
- }
229
- const staticPath = external_node_path_default().join(__dirname, '../../../static');
230
- var lib = __webpack_require__("../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js");
231
- const napi_namespaceObject = require("@oxidation-compiler/napi");
232
- var napi_default = /*#__PURE__*/ __webpack_require__.n(napi_namespaceObject);
233
- const parseImports = (code, sourceExt)=>{
234
- const parsed = napi_default().parseSync(code, {
235
- sourceType: 'module',
236
- sourceFilename: `index.${sourceExt}`
237
- });
238
- const ast = JSON.parse(parsed.program);
239
- const result = [];
240
- ast.body.forEach((statement)=>{
241
- if ('ImportDeclaration' === statement.type) result.push(statement.source.value);
242
- });
243
- return result;
244
- };
245
- const getNodeMeta = (node, metaName)=>{
246
- if (!node.meta) return;
247
- const meta = node.meta.split(' ');
248
- const item = meta.find((x)=>x.startsWith(metaName));
249
- if (null == item ? void 0 : item.startsWith(`${metaName}=`)) return item.slice(metaName.length + 1);
250
- return item;
251
- };
252
- function createPlaygroundNode(currentNode, attrs) {
253
- Object.assign(currentNode, {
254
- type: 'mdxJsxFlowElement',
255
- name: 'Playground',
256
- attributes: attrs.map((it)=>({
257
- type: 'mdxJsxAttribute',
258
- name: it[0],
259
- value: it[1]
260
- }))
261
- });
262
- }
263
- const remarkPlugin = ({ getRouteMeta, editorPosition, defaultRenderMode })=>{
264
- const routeMeta = getRouteMeta();
265
- return (tree, vfile)=>{
266
- const route = routeMeta.find((meta)=>(0, external_node_path_namespaceObject.resolve)(meta.absolutePath) === (0, external_node_path_namespaceObject.resolve)(vfile.path || vfile.history[0]));
267
- if (!route) return;
268
- (0, lib.Vn)(tree, 'mdxJsxFlowElement', (node)=>{
269
- if ('code' === node.name) {
270
- const src = (0, node_utils_namespaceObject.getNodeAttribute)(node, 'src');
271
- if ('string' != typeof src) return;
272
- const demoPath = (0, external_node_path_namespaceObject.join)((0, external_node_path_namespaceObject.dirname)(route.absolutePath), src);
273
- if (!external_node_fs_default().existsSync(demoPath)) return;
274
- const direction = (0, node_utils_namespaceObject.getNodeAttribute)(node, 'direction') || '';
275
- const code = external_node_fs_default().readFileSync(demoPath, {
276
- encoding: 'utf8'
277
- });
278
- const language = src.slice(src.lastIndexOf('.') + 1);
279
- createPlaygroundNode(node, [
280
- [
281
- 'code',
282
- code
283
- ],
284
- [
285
- 'language',
286
- language
287
- ],
288
- [
289
- 'direction',
290
- direction
291
- ],
292
- [
293
- 'editorPosition',
294
- editorPosition
295
- ]
296
- ]);
297
- }
298
- });
299
- (0, lib.Vn)(tree, 'code', (node)=>{
300
- if ('jsx' === node.lang || 'tsx' === node.lang) {
301
- var _node_meta, _node_meta1;
302
- const hasPureMeta = null == (_node_meta = node.meta) ? void 0 : _node_meta.includes('pure');
303
- const hasPlaygroundMeta = null == (_node_meta1 = node.meta) ? void 0 : _node_meta1.includes('playground');
304
- let noTransform;
305
- switch(defaultRenderMode){
306
- case 'pure':
307
- noTransform = !hasPlaygroundMeta;
308
- break;
309
- case 'playground':
310
- noTransform = hasPureMeta;
311
- break;
312
- default:
313
- break;
314
- }
315
- if (noTransform) return;
316
- const direction = getNodeMeta(node, 'direction') || '';
317
- createPlaygroundNode(node, [
318
- [
319
- 'code',
320
- node.value
321
- ],
322
- [
323
- 'language',
324
- node.lang
325
- ],
326
- [
327
- 'direction',
328
- direction
329
- ],
330
- [
331
- 'editorPosition',
332
- editorPosition
333
- ]
334
- ]);
335
- }
336
- });
337
- };
338
- };
339
- let cli_routeMeta;
340
- function pluginPlayground(options) {
341
- var _monacoLoader_paths;
342
- const { render = '', include, defaultDirection = 'horizontal', editorPosition = 'left', babelUrl = DEFAULT_BABEL_URL, monacoLoader = {}, monacoOptions = {}, defaultRenderMode = 'playground' } = options || {};
343
- const playgroundVirtualModule = new external_rspack_plugin_virtual_module_namespaceObject.RspackVirtualModulePlugin({});
344
- const getRouteMeta = ()=>cli_routeMeta;
345
- if (render && !/Playground\.(jsx?|tsx?)$/.test(render)) throw new Error('[Playground]: render should ends with Playground.(jsx?|tsx?)');
346
- const preloads = [];
347
- const monacoPrefix = (null == (_monacoLoader_paths = monacoLoader.paths) ? void 0 : _monacoLoader_paths.vs) || DEFAULT_MONACO_URL;
348
- preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));
349
- preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));
350
- return {
351
- name: '@rspress/plugin-playground',
352
- config (config, { removePlugin }) {
353
- config.markdown = config.markdown || {};
354
- config.markdown.mdxRs = false;
355
- removePlugin('@rspress/plugin-preview');
356
- return config;
357
- },
358
- async routeGenerated (routes) {
359
- cli_routeMeta = routes;
360
- const files = routes.map((route)=>route.absolutePath);
361
- const imports = {};
362
- await Promise.all(files.map(async (filepath, _index)=>{
363
- const isMdxFile = /\.mdx?$/.test(filepath);
364
- if (!isMdxFile) return;
365
- const { createProcessor } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "@mdx-js/mdx"));
366
- const { visit } = await __webpack_require__.e("52").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/index.js"));
367
- const { default: remarkGFM } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "remark-gfm"));
368
- try {
369
- const processor = createProcessor({
370
- format: external_node_path_default().extname(filepath).slice(1),
371
- remarkPlugins: [
372
- remarkGFM
373
- ]
374
- });
375
- const source = await external_node_fs_default().promises.readFile(filepath, 'utf-8');
376
- const ast = processor.parse(source);
377
- visit(ast, 'mdxJsxFlowElement', (node)=>{
378
- if ('code' === node.name) {
379
- const src = (0, node_utils_namespaceObject.getNodeAttribute)(node, 'src');
380
- if ('string' != typeof src) return;
381
- const demoPath = (0, external_node_path_namespaceObject.join)(external_node_path_default().dirname(filepath), src);
382
- if (!external_node_fs_default().existsSync(demoPath)) return;
383
- const code = external_node_fs_default().readFileSync(demoPath, {
384
- encoding: 'utf8'
385
- });
386
- const thisImports = parseImports(code, external_node_path_default().extname(demoPath));
387
- thisImports.forEach((x)=>{
388
- if (void 0 === imports[x]) imports[x] = x;
389
- });
390
- }
391
- });
392
- visit(ast, 'code', (node)=>{
393
- if ('jsx' === node.lang || 'tsx' === node.lang) {
394
- const { value, meta } = node;
395
- const hasPureMeta = null == meta ? void 0 : meta.includes('pure');
396
- const hasPlaygroundMeta = null == meta ? void 0 : meta.includes('playground');
397
- let noTransform;
398
- switch(defaultRenderMode){
399
- case 'pure':
400
- noTransform = !hasPlaygroundMeta;
401
- break;
402
- case 'playground':
403
- noTransform = hasPureMeta;
404
- break;
405
- default:
406
- break;
407
- }
408
- if (noTransform) return;
409
- const thisImports = parseImports(value, node.lang);
410
- thisImports.forEach((x)=>{
411
- if (void 0 === imports[x]) imports[x] = x;
412
- });
413
- }
414
- });
415
- } catch (e) {
416
- console.error(e);
417
- throw e;
418
- }
419
- }));
420
- if (include) include.forEach((item)=>{
421
- if ('string' == typeof item) imports[item] = item;
422
- else imports[item[0]] = item[1];
423
- });
424
- if (!('react' in imports)) imports.react = 'react';
425
- const importKeys = Object.keys(imports);
426
- const code = [
427
- ...importKeys.map((x, index)=>`import * as i_${index} from '${imports[x]}';`),
428
- 'const imports = new Map();',
429
- ...importKeys.map((x, index)=>`imports.set('${x}', i_${index});`),
430
- 'function getImport(name, getDefault) {',
431
- ' if (!imports.has(name)) {',
432
- ' throw new Error("Module " + name + " not found");',
433
- ' }',
434
- ' const result = imports.get(name);',
435
- ' if (getDefault && typeof result === "object") {',
436
- ' return result.default || result;',
437
- ' }',
438
- ' return result;',
439
- '}',
440
- 'export { imports };',
441
- 'export default getImport;'
442
- ].join('\n');
443
- playgroundVirtualModule.writeModule('_rspress_playground_imports', code);
444
- },
445
- builderConfig: {
446
- source: {
447
- define: {
448
- __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),
449
- __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),
450
- __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),
451
- __PLAYGROUND_BABEL_URL__: JSON.stringify(babelUrl)
452
- },
453
- include: [
454
- (0, external_node_path_namespaceObject.join)(__dirname, '..', '..', '..')
455
- ]
456
- },
457
- html: {
458
- tags: preloads.map((url)=>({
459
- tag: 'link',
460
- head: true,
461
- attrs: {
462
- rel: 'preload',
463
- href: url,
464
- as: "script"
465
- }
466
- }))
467
- },
468
- tools: {
469
- rspack: {
470
- plugins: [
471
- playgroundVirtualModule
472
- ]
473
- }
474
- }
475
- },
476
- markdown: {
477
- remarkPlugins: [
478
- [
479
- remarkPlugin,
480
- {
481
- getRouteMeta,
482
- editorPosition,
483
- defaultRenderMode
484
- }
485
- ]
486
- ],
487
- globalComponents: [
488
- render ? render : external_node_path_default().join(staticPath, 'global-components', 'Playground.tsx')
489
- ]
490
- },
491
- globalStyles: external_node_path_default().join(staticPath, 'global-styles', 'web.css')
492
- };
493
- }
494
- })();
495
- exports.pluginPlayground = __webpack_exports__.pluginPlayground;
496
- exports.routeMeta = __webpack_exports__.routeMeta;
497
- for(var __webpack_i__ in __webpack_exports__)if (-1 === [
498
- "pluginPlayground",
499
- "routeMeta"
500
- ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
501
- Object.defineProperty(exports, '__esModule', {
502
- value: true
503
- });
@@ -1,11 +0,0 @@
1
- export const __webpack_ids__ = [
2
- '52'
3
- ];
4
- export const __webpack_modules__ = {
5
- "../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/index.js": function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
6
- __webpack_require__.d(__webpack_exports__, {
7
- visit: ()=>_lib_index_js__WEBPACK_IMPORTED_MODULE_0__.Vn
8
- });
9
- var _lib_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js");
10
- }
11
- };
@@ -1,326 +0,0 @@
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
- MonacoEditor: ()=>react_default(),
37
- Editor: ()=>Editor,
38
- MonacoEditorLoader: ()=>react_namespaceObject.loader,
39
- Runner: ()=>Runner
40
- });
41
- const react_namespaceObject = require("@monaco-editor/react");
42
- var react_default = /*#__PURE__*/ __webpack_require__.n(react_namespaceObject);
43
- const runtime_namespaceObject = require("@rspress/core/runtime");
44
- const external_react_namespaceObject = require("react");
45
- var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
46
- const DEFAULT_MONACO_URL = 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';
47
- function initLoader() {
48
- let loaderConfig = {
49
- paths: {
50
- vs: DEFAULT_MONACO_URL
51
- }
52
- };
53
- try {
54
- const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
55
- if (keys.length > 0) loaderConfig = __PLAYGROUND_MONACO_LOADER__;
56
- } catch (_e) {}
57
- react_namespaceObject.loader.config(loaderConfig);
58
- }
59
- initLoader();
60
- function getMonacoOptions() {
61
- try {
62
- return __PLAYGROUND_MONACO_OPTIONS__;
63
- } catch (_e) {}
64
- return {};
65
- }
66
- function Editor(props) {
67
- const { options, className = '', theme: themeProp, ...rest } = props || {};
68
- const dark = (0, runtime_namespaceObject.useDark)();
69
- const theme = (0, external_react_namespaceObject.useMemo)(()=>{
70
- if (themeProp) return themeProp;
71
- return dark ? 'vs-dark' : 'light';
72
- }, [
73
- themeProp,
74
- dark
75
- ]);
76
- return /*#__PURE__*/ React.createElement("div", {
77
- className: `rspress-playground-editor ${className}`
78
- }, /*#__PURE__*/ React.createElement(react_default(), {
79
- ...rest,
80
- theme: theme,
81
- options: {
82
- minimap: {
83
- enabled: true,
84
- autohide: true
85
- },
86
- fontSize: 14,
87
- lineNumbersMinChars: 7,
88
- scrollBeyondLastLine: false,
89
- automaticLayout: true,
90
- wordBasedSuggestions: true,
91
- quickSuggestions: true,
92
- scrollbar: {
93
- verticalScrollbarSize: 8,
94
- horizontalScrollbarSize: 8
95
- },
96
- scrollPredominantAxis: false,
97
- ...getMonacoOptions(),
98
- ...options
99
- }
100
- }));
101
- }
102
- function createVariableDeclaration(id, init) {
103
- return {
104
- type: 'VariableDeclaration',
105
- declarations: [
106
- {
107
- type: 'VariableDeclarator',
108
- id: 'string' == typeof id ? {
109
- type: 'Identifier',
110
- name: id
111
- } : id,
112
- init
113
- }
114
- ],
115
- kind: 'const'
116
- };
117
- }
118
- function createIdentifier(name) {
119
- return {
120
- type: 'Identifier',
121
- name
122
- };
123
- }
124
- function createObjectProperty(key, value) {
125
- return {
126
- type: 'ObjectProperty',
127
- key: createIdentifier(key),
128
- computed: false,
129
- shorthand: key === value,
130
- value: createIdentifier(value)
131
- };
132
- }
133
- function createObjectPattern(names) {
134
- return {
135
- type: 'ObjectPattern',
136
- properties: names.map((name)=>Array.isArray(name) ? createObjectProperty(name[0], name[1]) : createObjectProperty(name, name))
137
- };
138
- }
139
- function createGetImport(name, getDefault) {
140
- return {
141
- type: 'CallExpression',
142
- callee: {
143
- type: 'Identifier',
144
- name: '__get_import'
145
- },
146
- arguments: [
147
- {
148
- type: 'StringLiteral',
149
- value: name
150
- },
151
- {
152
- type: 'BooleanLiteral',
153
- value: Boolean(getDefault)
154
- }
155
- ]
156
- };
157
- }
158
- async function loadUmdBabelModule() {
159
- const data = await fetch(__PLAYGROUND_BABEL_URL__);
160
- const umdSourceCode = await data.text();
161
- const run = new Function('exports', 'module', 'require', `with(exports, module, require) {${umdSourceCode}}`);
162
- const exports1 = {};
163
- const module = {
164
- exports: exports1
165
- };
166
- const require1 = ()=>{};
167
- run(exports1, module, require1);
168
- return exports1;
169
- }
170
- let loadBabelPromise = null;
171
- async function getBabel() {
172
- if (window.Babel) return window.Babel;
173
- if (loadBabelPromise) return loadBabelPromise;
174
- loadBabelPromise = loadUmdBabelModule();
175
- try {
176
- const Babel = await loadBabelPromise;
177
- window.Babel = Babel;
178
- return Babel;
179
- } catch (e) {
180
- loadBabelPromise = null;
181
- throw e;
182
- }
183
- }
184
- function _define_property(obj, key, value) {
185
- if (key in obj) Object.defineProperty(obj, key, {
186
- value: value,
187
- enumerable: true,
188
- configurable: true,
189
- writable: true
190
- });
191
- else obj[key] = value;
192
- return obj;
193
- }
194
- const DEBOUNCE_TIME = 800;
195
- class Runner extends external_react_namespaceObject.Component {
196
- static getDerivedStateFromError(error) {
197
- return {
198
- error,
199
- comp: null
200
- };
201
- }
202
- waitCompile(targetCode) {
203
- if (this.timer) clearTimeout(this.timer);
204
- this.timer = window.setTimeout(()=>{
205
- this.timer = null;
206
- this.doCompile(targetCode);
207
- }, DEBOUNCE_TIME);
208
- }
209
- async doCompile(targetCode) {
210
- const { language, getImport } = this.props;
211
- const babel = await getBabel();
212
- try {
213
- const presets = [
214
- [
215
- babel.availablePresets.react
216
- ],
217
- [
218
- babel.availablePresets.env,
219
- {
220
- modules: 'commonjs'
221
- }
222
- ]
223
- ];
224
- if ('tsx' === language || 'ts' === language) presets.unshift([
225
- babel.availablePresets.typescript,
226
- {
227
- allExtensions: true,
228
- isTSX: 'tsx' === language
229
- }
230
- ]);
231
- const result = babel.transform(targetCode, {
232
- sourceType: 'module',
233
- sourceMaps: 'inline',
234
- presets,
235
- plugins: [
236
- {
237
- pre () {
238
- this.hasReactImported = false;
239
- },
240
- visitor: {
241
- ImportDeclaration (path) {
242
- const pkg = path.node.source.value;
243
- const code = [];
244
- const specifiers = [];
245
- for (const specifier of path.node.specifiers){
246
- if ('React' === specifier.local.name) this.hasReactImported = true;
247
- if ('ImportDefaultSpecifier' === specifier.type) code.push(createVariableDeclaration(specifier.local.name, createGetImport(pkg, true)));
248
- if ('ImportNamespaceSpecifier' === specifier.type) code.push(createVariableDeclaration(specifier.local.name, createGetImport(pkg)));
249
- if ('ImportSpecifier' === specifier.type) if ('name' in specifier.imported && specifier.imported.name !== specifier.local.name) specifiers.push([
250
- specifier.imported.name,
251
- specifier.local.name
252
- ]);
253
- else specifiers.push(specifier.local.name);
254
- }
255
- if (specifiers.length > 0) code.push(createVariableDeclaration(createObjectPattern(specifiers), createGetImport(pkg)));
256
- path.replaceWithMultiple(code);
257
- }
258
- },
259
- post (file) {
260
- if (!this.hasReactImported) file.ast.program.body.unshift(createVariableDeclaration('React', createGetImport('react', true)));
261
- }
262
- }
263
- ]
264
- });
265
- if (targetCode !== this.props.code || !result || !result.code) return;
266
- const runExports = {};
267
- const func = new Function('__get_import', 'exports', result.code);
268
- func(getImport, runExports);
269
- if (runExports.default) return void this.setState({
270
- error: void 0,
271
- comp: /*#__PURE__*/ external_react_default().createElement(runExports.default)
272
- });
273
- this.setState({
274
- error: new Error('No default export')
275
- });
276
- } catch (e) {
277
- if (targetCode !== this.props.code) return;
278
- console.error(e);
279
- this.setState({
280
- error: e
281
- });
282
- }
283
- }
284
- componentDidCatch(error, errorInfo) {
285
- console.error(error);
286
- console.error(errorInfo);
287
- }
288
- componentDidMount() {
289
- this.doCompile(this.props.code);
290
- }
291
- componentDidUpdate(prevProps) {
292
- if (prevProps.code !== this.props.code) this.waitCompile(this.props.code);
293
- }
294
- render() {
295
- const { className = '', code, language, getImport, ...rest } = this.props;
296
- const { error, comp } = this.state;
297
- return /*#__PURE__*/ external_react_default().createElement("div", {
298
- className: `rspress-playground-runner ${className}`,
299
- ...rest
300
- }, comp, error && /*#__PURE__*/ external_react_default().createElement("pre", {
301
- className: "rspress-playground-error"
302
- }, error.message));
303
- }
304
- constructor(props){
305
- super(props), _define_property(this, "timer", null);
306
- this.state = {
307
- error: void 0,
308
- comp: null
309
- };
310
- this.doCompile = this.doCompile.bind(this);
311
- this.waitCompile = this.waitCompile.bind(this);
312
- }
313
- }
314
- exports.Editor = __webpack_exports__.Editor;
315
- exports.MonacoEditor = __webpack_exports__.MonacoEditor;
316
- exports.MonacoEditorLoader = __webpack_exports__.MonacoEditorLoader;
317
- exports.Runner = __webpack_exports__.Runner;
318
- for(var __webpack_i__ in __webpack_exports__)if (-1 === [
319
- "Editor",
320
- "MonacoEditor",
321
- "MonacoEditorLoader",
322
- "Runner"
323
- ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
324
- Object.defineProperty(exports, '__esModule', {
325
- value: true
326
- });
File without changes
File without changes