@rspress/plugin-playground 1.40.2 → 1.41.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.
@@ -1,577 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res) => function __init() {
4
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
- };
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
-
11
- // ../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js
12
- function anyFactory(tests) {
13
- const checks = [];
14
- let index = -1;
15
- while (++index < tests.length) {
16
- checks[index] = convert(tests[index]);
17
- }
18
- return castFactory(any);
19
- function any(...parameters) {
20
- let index2 = -1;
21
- while (++index2 < checks.length) {
22
- if (checks[index2].call(this, ...parameters))
23
- return true;
24
- }
25
- return false;
26
- }
27
- }
28
- function propsFactory(check) {
29
- return castFactory(all);
30
- function all(node) {
31
- let key;
32
- for (key in check) {
33
- if (node[key] !== check[key])
34
- return false;
35
- }
36
- return true;
37
- }
38
- }
39
- function typeFactory(check) {
40
- return castFactory(type);
41
- function type(node) {
42
- return node && node.type === check;
43
- }
44
- }
45
- function castFactory(check) {
46
- return assertion;
47
- function assertion(node, ...parameters) {
48
- return Boolean(
49
- node && typeof node === "object" && "type" in node && // @ts-expect-error: fine.
50
- Boolean(check.call(this, node, ...parameters))
51
- );
52
- }
53
- }
54
- function ok() {
55
- return true;
56
- }
57
- var convert;
58
- var init_lib = __esm({
59
- "../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js"() {
60
- "use strict";
61
- convert = /**
62
- * @type {(
63
- * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &
64
- * ((test?: Test) => AssertAnything)
65
- * )}
66
- */
67
- /**
68
- * @param {Test} [test]
69
- * @returns {AssertAnything}
70
- */
71
- function(test) {
72
- if (test === void 0 || test === null) {
73
- return ok;
74
- }
75
- if (typeof test === "string") {
76
- return typeFactory(test);
77
- }
78
- if (typeof test === "object") {
79
- return Array.isArray(test) ? anyFactory(test) : propsFactory(test);
80
- }
81
- if (typeof test === "function") {
82
- return castFactory(test);
83
- }
84
- throw new Error("Expected function, string, or object as test");
85
- };
86
- }
87
- });
88
-
89
- // ../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js
90
- var init_unist_util_is = __esm({
91
- "../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js"() {
92
- "use strict";
93
- init_lib();
94
- }
95
- });
96
-
97
- // ../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js
98
- function color(d) {
99
- return "\x1B[33m" + d + "\x1B[39m";
100
- }
101
- var init_color = __esm({
102
- "../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js"() {
103
- "use strict";
104
- }
105
- });
106
-
107
- // ../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js
108
- function toResult(value) {
109
- if (Array.isArray(value)) {
110
- return value;
111
- }
112
- if (typeof value === "number") {
113
- return [CONTINUE, value];
114
- }
115
- return [value];
116
- }
117
- var CONTINUE, EXIT, SKIP, visitParents;
118
- var init_lib2 = __esm({
119
- "../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js"() {
120
- "use strict";
121
- init_unist_util_is();
122
- init_color();
123
- CONTINUE = true;
124
- EXIT = false;
125
- SKIP = "skip";
126
- visitParents = /**
127
- * @type {(
128
- * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &
129
- * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)
130
- * )}
131
- */
132
- /**
133
- * @param {Node} tree
134
- * @param {Test} test
135
- * @param {Visitor<Node>} visitor
136
- * @param {boolean | null | undefined} [reverse]
137
- * @returns {void}
138
- */
139
- function(tree, test, visitor, reverse) {
140
- if (typeof test === "function" && typeof visitor !== "function") {
141
- reverse = visitor;
142
- visitor = test;
143
- test = null;
144
- }
145
- const is2 = convert(test);
146
- const step = reverse ? -1 : 1;
147
- factory(tree, void 0, [])();
148
- function factory(node, index, parents) {
149
- const value = node && typeof node === "object" ? node : {};
150
- if (typeof value.type === "string") {
151
- const name = (
152
- // `hast`
153
- typeof value.tagName === "string" ? value.tagName : (
154
- // `xast`
155
- typeof value.name === "string" ? value.name : void 0
156
- )
157
- );
158
- Object.defineProperty(visit2, "name", {
159
- value: "node (" + color(node.type + (name ? "<" + name + ">" : "")) + ")"
160
- });
161
- }
162
- return visit2;
163
- function visit2() {
164
- let result = [];
165
- let subresult;
166
- let offset;
167
- let grandparents;
168
- if (!test || is2(node, index, parents[parents.length - 1] || null)) {
169
- result = toResult(visitor(node, parents));
170
- if (result[0] === EXIT) {
171
- return result;
172
- }
173
- }
174
- if (node.children && result[0] !== SKIP) {
175
- offset = (reverse ? node.children.length : -1) + step;
176
- grandparents = parents.concat(node);
177
- while (offset > -1 && offset < node.children.length) {
178
- subresult = factory(node.children[offset], offset, grandparents)();
179
- if (subresult[0] === EXIT) {
180
- return subresult;
181
- }
182
- offset = typeof subresult[1] === "number" ? subresult[1] : offset + step;
183
- }
184
- }
185
- return result;
186
- }
187
- }
188
- };
189
- }
190
- });
191
-
192
- // ../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js
193
- var init_unist_util_visit_parents = __esm({
194
- "../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js"() {
195
- "use strict";
196
- init_lib2();
197
- }
198
- });
199
-
200
- // ../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/lib/index.js
201
- var visit;
202
- var init_lib3 = __esm({
203
- "../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/lib/index.js"() {
204
- "use strict";
205
- init_unist_util_visit_parents();
206
- init_unist_util_visit_parents();
207
- visit = /**
208
- * @type {(
209
- * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &
210
- * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)
211
- * )}
212
- */
213
- /**
214
- * @param {Node} tree
215
- * @param {Test} test
216
- * @param {Visitor} visitor
217
- * @param {boolean | null | undefined} [reverse]
218
- * @returns {void}
219
- */
220
- function(tree, test, visitor, reverse) {
221
- if (typeof test === "function" && typeof visitor !== "function") {
222
- reverse = visitor;
223
- visitor = test;
224
- test = null;
225
- }
226
- visitParents(tree, test, overload, reverse);
227
- function overload(node, parents) {
228
- const parent = parents[parents.length - 1];
229
- return visitor(
230
- node,
231
- parent ? parent.children.indexOf(node) : null,
232
- parent
233
- );
234
- }
235
- };
236
- }
237
- });
238
-
239
- // ../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/index.js
240
- var unist_util_visit_exports = {};
241
- __export(unist_util_visit_exports, {
242
- CONTINUE: () => CONTINUE,
243
- EXIT: () => EXIT,
244
- SKIP: () => SKIP,
245
- visit: () => visit
246
- });
247
- var init_unist_util_visit = __esm({
248
- "../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/index.js"() {
249
- "use strict";
250
- init_lib3();
251
- }
252
- });
253
-
254
- // src/cli/index.ts
255
- import path2, { join as join2 } from "path";
256
-
257
- // src/web/constant.ts
258
- var DEFAULT_BABEL_URL = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js";
259
- var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
260
-
261
- // src/web/utils.ts
262
- function normalizeUrl(u) {
263
- return u.replace(/\/\//g, "/");
264
- }
265
-
266
- // src/cli/index.ts
267
- import { RspackVirtualModulePlugin } from "rspack-plugin-virtual-module";
268
-
269
- // src/cli/constant.ts
270
- import path from "path";
271
- var staticPath = path.join(__dirname, "../../../static");
272
-
273
- // src/cli/remarkPlugin.ts
274
- init_unist_util_visit();
275
- import { dirname, join, resolve } from "path";
276
- import fs from "@rspress/shared/fs-extra";
277
-
278
- // src/cli/utils.ts
279
- import oxc from "@oxidation-compiler/napi";
280
- var parseImports = (code, sourceExt) => {
281
- const parsed = oxc.parseSync(code, {
282
- sourceType: "module",
283
- sourceFilename: `index.${sourceExt}`
284
- });
285
- const ast = JSON.parse(parsed.program);
286
- const result = [];
287
- ast.body.forEach((statement) => {
288
- if (statement.type === "ImportDeclaration") {
289
- result.push(statement.source.value);
290
- }
291
- });
292
- return result;
293
- };
294
- var getNodeAttribute = (node, attrName) => {
295
- return node.attributes.find(
296
- (attr) => attr.name === attrName
297
- )?.value;
298
- };
299
- var getNodeMeta = (node, metaName) => {
300
- if (!node.meta) {
301
- return;
302
- }
303
- const meta = node.meta.split(" ");
304
- const item = meta.find(
305
- (x) => x.startsWith(metaName)
306
- );
307
- if (item?.startsWith(`${metaName}=`)) {
308
- return item.substring(metaName.length + 1);
309
- }
310
- return item;
311
- };
312
-
313
- // src/cli/remarkPlugin.ts
314
- function createPlaygroundNode(currentNode, attrs) {
315
- Object.assign(currentNode, {
316
- type: "mdxJsxFlowElement",
317
- name: "Playground",
318
- attributes: attrs.map((it) => ({
319
- type: "mdxJsxAttribute",
320
- name: it[0],
321
- value: it[1]
322
- }))
323
- });
324
- }
325
- var remarkPlugin = ({
326
- getRouteMeta,
327
- editorPosition,
328
- defaultRenderMode
329
- }) => {
330
- const routeMeta2 = getRouteMeta();
331
- return (tree, vfile) => {
332
- const route = routeMeta2.find(
333
- (meta) => resolve(meta.absolutePath) === resolve(vfile.path || vfile.history[0])
334
- );
335
- if (!route) {
336
- return;
337
- }
338
- visit(tree, "mdxJsxFlowElement", (node) => {
339
- if (node.name === "code") {
340
- const src = getNodeAttribute(node, "src");
341
- if (!src) {
342
- return;
343
- }
344
- const demoPath = join(dirname(route.absolutePath), src);
345
- if (!fs.existsSync(demoPath)) {
346
- return;
347
- }
348
- const direction = getNodeAttribute(node, "direction") || "";
349
- const code = fs.readFileSync(demoPath, {
350
- encoding: "utf8"
351
- });
352
- const language = src.substr(src.lastIndexOf(".") + 1);
353
- createPlaygroundNode(node, [
354
- ["code", code],
355
- ["language", language],
356
- ["direction", direction],
357
- ["editorPosition", editorPosition]
358
- ]);
359
- }
360
- });
361
- visit(tree, "code", (node) => {
362
- if (node.lang === "jsx" || node.lang === "tsx") {
363
- const hasPureMeta = node?.meta?.includes("pure");
364
- const hasPlaygroundMeta = node?.meta?.includes("playground");
365
- let noTransform;
366
- switch (defaultRenderMode) {
367
- case "pure":
368
- noTransform = !hasPlaygroundMeta;
369
- break;
370
- case "playground":
371
- noTransform = hasPureMeta;
372
- break;
373
- default:
374
- break;
375
- }
376
- if (noTransform) {
377
- return;
378
- }
379
- const direction = getNodeMeta(node, "direction") || "";
380
- createPlaygroundNode(node, [
381
- ["code", node.value],
382
- ["language", node.lang],
383
- ["direction", direction],
384
- ["editorPosition", editorPosition]
385
- ]);
386
- }
387
- });
388
- };
389
- };
390
-
391
- // src/cli/index.ts
392
- var routeMeta;
393
- function pluginPlayground(options) {
394
- const {
395
- render = "",
396
- include,
397
- defaultDirection = "horizontal",
398
- editorPosition = "left",
399
- babelUrl = DEFAULT_BABEL_URL,
400
- monacoLoader = {},
401
- monacoOptions = {},
402
- defaultRenderMode = "playground"
403
- } = options || {};
404
- const playgroundVirtualModule = new RspackVirtualModulePlugin({});
405
- const getRouteMeta = () => routeMeta;
406
- if (render && !/Playground\.(jsx?|tsx?)$/.test(render)) {
407
- throw new Error(
408
- "[Playground]: render should ends with Playground.(jsx?|tsx?)"
409
- );
410
- }
411
- const preloads = [];
412
- const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;
413
- preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));
414
- preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));
415
- return {
416
- name: "@rspress/plugin-playground",
417
- config(config, { removePlugin }) {
418
- config.markdown = config.markdown || {};
419
- config.markdown.mdxRs = false;
420
- removePlugin("@rspress/plugin-preview");
421
- return config;
422
- },
423
- async routeGenerated(routes) {
424
- const { default: fs2 } = await import("@rspress/shared/fs-extra");
425
- routeMeta = routes;
426
- const files = routes.map((route) => route.absolutePath);
427
- const imports = {};
428
- await Promise.all(
429
- files.map(async (filepath, _index) => {
430
- const isMdxFile = /\.mdx?$/.test(filepath);
431
- if (!isMdxFile) {
432
- return;
433
- }
434
- const { createProcessor } = await import("@mdx-js/mdx");
435
- const { visit: visit2 } = await Promise.resolve().then(() => (init_unist_util_visit(), unist_util_visit_exports));
436
- const { default: remarkGFM } = await import("remark-gfm");
437
- try {
438
- const processor = createProcessor({
439
- format: path2.extname(filepath).slice(1),
440
- remarkPlugins: [remarkGFM]
441
- });
442
- const source = await fs2.readFile(filepath, "utf-8");
443
- const ast = processor.parse(source);
444
- visit2(ast, "mdxJsxFlowElement", (node) => {
445
- if (node.name === "code") {
446
- const src = getNodeAttribute(node, "src");
447
- if (!src) {
448
- return;
449
- }
450
- const demoPath = join2(path2.dirname(filepath), src);
451
- if (!fs2.existsSync(demoPath)) {
452
- return;
453
- }
454
- const code2 = fs2.readFileSync(demoPath, {
455
- encoding: "utf8"
456
- });
457
- const thisImports = parseImports(code2, path2.extname(demoPath));
458
- thisImports.forEach((x) => {
459
- if (typeof imports[x] === "undefined") {
460
- imports[x] = x;
461
- }
462
- });
463
- }
464
- });
465
- visit2(ast, "code", (node) => {
466
- if (node.lang === "jsx" || node.lang === "tsx") {
467
- const { value, meta } = node;
468
- const hasPureMeta = meta?.includes("pure");
469
- const hasPlaygroundMeta = meta?.includes("playground");
470
- let noTransform;
471
- switch (defaultRenderMode) {
472
- case "pure":
473
- noTransform = !hasPlaygroundMeta;
474
- break;
475
- case "playground":
476
- noTransform = hasPureMeta;
477
- break;
478
- default:
479
- break;
480
- }
481
- if (noTransform) {
482
- return;
483
- }
484
- const thisImports = parseImports(value, node.lang);
485
- thisImports.forEach((x) => {
486
- if (typeof imports[x] === "undefined") {
487
- imports[x] = x;
488
- }
489
- });
490
- }
491
- });
492
- } catch (e) {
493
- console.error(e);
494
- throw e;
495
- }
496
- })
497
- );
498
- if (include) {
499
- include.forEach((item) => {
500
- if (typeof item === "string") {
501
- imports[item] = item;
502
- } else {
503
- imports[item[0]] = item[1];
504
- }
505
- });
506
- }
507
- if (!("react" in imports)) {
508
- imports.react = "react";
509
- }
510
- const importKeys = Object.keys(imports);
511
- const code = [
512
- ...importKeys.map(
513
- (x, index) => `import * as i_${index} from '${imports[x]}';`
514
- ),
515
- "const imports = new Map();",
516
- ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),
517
- "function getImport(name, getDefault) {",
518
- " if (!imports.has(name)) {",
519
- ' throw new Error("Module " + name + " not found");',
520
- " }",
521
- " const result = imports.get(name);",
522
- ' if (getDefault && typeof result === "object") {',
523
- " return result.default || result;",
524
- " }",
525
- " return result;",
526
- "}",
527
- "export { imports };",
528
- "export default getImport;"
529
- ].join("\n");
530
- playgroundVirtualModule.writeModule("_rspress_playground_imports", code);
531
- },
532
- builderConfig: {
533
- source: {
534
- define: {
535
- __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),
536
- __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),
537
- __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),
538
- __PLAYGROUND_BABEL_URL__: JSON.stringify(babelUrl)
539
- },
540
- include: [join2(__dirname, "..", "..", "..")]
541
- },
542
- html: {
543
- tags: preloads.map((url) => ({
544
- tag: "link",
545
- head: true,
546
- attrs: {
547
- rel: "preload",
548
- href: url,
549
- as: "script"
550
- }
551
- }))
552
- },
553
- tools: {
554
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error
555
- // @ts-ignore
556
- rspack: {
557
- plugins: [playgroundVirtualModule]
558
- }
559
- }
560
- },
561
- markdown: {
562
- remarkPlugins: [
563
- [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }]
564
- ],
565
- globalComponents: [
566
- render ? render : path2.join(staticPath, "global-components", "Playground.tsx")
567
- ]
568
- },
569
- globalStyles: path2.join(staticPath, "global-styles", "web.css")
570
- };
571
- }
572
- export {
573
- pluginPlayground,
574
- routeMeta
575
- };
576
-
577
- //# sourceMappingURL=index.js.map