@rspress/plugin-playground 1.40.2 → 1.40.3-cannary-20250126
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/cjs/301.js +14 -0
- package/dist/cli/cjs/index.js +479 -591
- package/dist/cli/esm/301.mjs +13 -0
- package/dist/cli/esm/index.d.ts +28 -24
- package/dist/cli/esm/index.mjs +471 -0
- package/dist/web/cjs/index.js +289 -355
- package/dist/web/esm/index.d.ts +45 -37
- package/dist/web/esm/index.mjs +269 -0
- package/package.json +8 -7
- package/dist/cli/cjs/index.js.map +0 -1
- package/dist/cli/esm/index.js +0 -577
- package/dist/cli/esm/index.js.map +0 -1
- package/dist/web/cjs/index.js.map +0 -1
- package/dist/web/esm/index.js +0 -354
- package/dist/web/esm/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,UAAU;AAAG,eAAO;AAAA,IACtD;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,aAAa,OAAO;AAC3B,SAAO,YAAY,GAAG;AAMtB,WAAS,IAAI,MAAM;AAEjB,QAAI;AAEJ,SAAK,OAAO,OAAO;AAEjB,UAAI,KAAK,GAAG,MAAM,MAAM,GAAG;AAAG,eAAO;AAAA,IACvC;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,YAAY,OAAO;AAC1B,SAAO,YAAY,IAAI;AAKvB,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AAK,UAAU,YAAY;AAAA,UACzD,+BAA+B,KAAK,UAAU,aAAa;AAAA,UAC3D,0BAA0B,KAAK,UAAU,QAAQ;AAAA,QACnD;AAAA,QACA,SAAS,CAACE,MAAK,WAAW,MAAM,MAAM,IAAI,CAAC;AAAA,MAC7C;AAAA,MACA,MAAM;AAAA,QACJ,MAAM,SAAS,IAAI,UAAQ;AAAA,UACzB,KAAK;AAAA,UACL,MAAM;AAAA,UACN,OAAO;AAAA,YACL,KAAK;AAAA,YACL,MAAM;AAAA,YACN,IAAI;AAAA,UACN;AAAA,QACF,EAAE;AAAA,MACJ;AAAA,MACA,OAAO;AAAA;AAAA;AAAA,QAGL,QAAQ;AAAA,UACN,SAAS,CAAC,uBAAuB;AAAA,QACnC;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb,CAAC,cAAc,EAAE,cAAc,gBAAgB,kBAAkB,CAAC;AAAA,MACpE;AAAA,MACA,kBAAkB;AAAA,QAChB,SACI,SACAD,MAAK,KAAK,YAAY,qBAAqB,gBAAgB;AAAA,MACjE;AAAA,IACF;AAAA,IACA,cAAcA,MAAK,KAAK,YAAY,iBAAiB,SAAS;AAAA,EAChE;AACF","names":["index","init_lib","is","visit","path","join","routeMeta","fs","code"],"ignoreList":[],"sources":["../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/lib/index.js","../../../../../node_modules/.pnpm/unist-util-visit@4.1.2/node_modules/unist-util-visit/index.js","../../../src/cli/index.ts","../../../src/web/constant.ts","../../../src/web/utils.ts","../../../src/cli/constant.ts","../../../src/cli/remarkPlugin.ts","../../../src/cli/utils.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n */\n\n/**\n * Check if `Child` can be a child of `Ancestor`.\n *\n * Returns the ancestor when `Child` can be a child of `Ancestor`, or returns\n * `never`.\n *\n * @template {Node} Ancestor\n * Node type.\n * @template {Node} Child\n * Node type.\n * @typedef {(\n * Ancestor extends Parent\n * ? Child extends Ancestor['children'][number]\n * ? Ancestor\n * : never\n * : never\n * )} ParentsOf\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform `parent`.\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of `parent` still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Visited extends Node ? number | null : never} index\n * Index of `node` in `parent`.\n * @param {Ancestor extends Node ? Ancestor | null : never} parent\n * Parent of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * Build a typed `Visitor` function from a node and all possible parents.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n *\n * @template {Node} Visited\n * Node type.\n * @template {Parent} Ancestor\n * Parent type.\n * @typedef {Visitor<Visited, ParentsOf<Ancestor, Visited>>} BuildVisitorFromMatch\n */\n\n/**\n * Build a typed `Visitor` function from a list of descendants and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n *\n * @template {Node} Descendant\n * Node type.\n * @template {Test} Check\n * Test type.\n * @typedef {(\n * BuildVisitorFromMatch<\n * import('unist-util-visit-parents/complex-types.js').Matches<Descendant, Check>,\n * Extract<Descendant, Parent>\n * >\n * )} BuildVisitorFromDescendants\n */\n\n/**\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parent`.\n *\n * @template {Node} [Tree=Node]\n * Node type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {(\n * BuildVisitorFromDescendants<\n * import('unist-util-visit-parents/complex-types.js').InclusiveDescendant<Tree>,\n * Check\n * >\n * )} BuildVisitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit nodes.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visit} from './lib/index.js'\n","import path, { join } from 'node:path';\nimport { DEFAULT_BABEL_URL, DEFAULT_MONACO_URL } from '@/web/constant';\nimport { normalizeUrl } from '@/web/utils';\nimport type {\n EditorProps as MonacoEditorProps,\n loader,\n} from '@monaco-editor/react';\nimport type { RouteMeta, RspressPlugin } from '@rspress/shared';\nimport type { Code } from 'mdast';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport { staticPath } from './constant';\nimport { remarkPlugin } from './remarkPlugin';\nimport { getNodeAttribute, parseImports } from './utils';\n\ninterface PlaygroundOptions {\n render: string;\n include: Array<string | [string, string]>;\n\n defaultDirection: 'horizontal' | 'vertical';\n editorPosition: 'left' | 'right';\n\n babelUrl: string;\n\n monacoLoader: Parameters<typeof loader.config>[0];\n monacoOptions: MonacoEditorProps['options'];\n /**\n * determine how to handle a internal code block without meta\n * @default 'playground'\n */\n defaultRenderMode?: 'pure' | 'playground';\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPlayground(\n options?: Partial<PlaygroundOptions>,\n): RspressPlugin {\n const {\n render = '',\n include,\n defaultDirection = 'horizontal',\n editorPosition = 'left',\n babelUrl = DEFAULT_BABEL_URL,\n monacoLoader = {},\n monacoOptions = {},\n defaultRenderMode = 'playground',\n } = options || {};\n\n const playgroundVirtualModule = new RspackVirtualModulePlugin({});\n const getRouteMeta = () => routeMeta;\n\n if (render && !/Playground\\.(jsx?|tsx?)$/.test(render)) {\n throw new Error(\n '[Playground]: render should ends with Playground.(jsx?|tsx?)',\n );\n }\n\n const preloads: string[] = [];\n const monacoPrefix = monacoLoader.paths?.vs || DEFAULT_MONACO_URL;\n preloads.push(normalizeUrl(`${monacoPrefix}/loader.js`));\n preloads.push(normalizeUrl(`${monacoPrefix}/editor/editor.main.js`));\n\n return {\n name: '@rspress/plugin-playground',\n config(config, { removePlugin }) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n // The preview and playground plugin are mutually conflicting.\n removePlugin('@rspress/plugin-preview');\n return config;\n },\n async routeGenerated(routes: RouteMeta[]) {\n const { default: fs } = await import('@rspress/shared/fs-extra');\n\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n\n const imports: Record<string, string> = {};\n\n // scan all demos, and generate imports\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: remarkGFM } = await import('remark-gfm');\n try {\n const processor = createProcessor({\n format: path.extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(path.dirname(filepath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n\n const thisImports = parseImports(code, path.extname(demoPath));\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n\n visit(ast, 'code', (node: Code) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value, meta } = node;\n const hasPureMeta = meta?.includes('pure');\n const hasPlaygroundMeta = meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const thisImports = parseImports(value, node.lang);\n thisImports.forEach(x => {\n if (typeof imports[x] === 'undefined') {\n imports[x] = x;\n }\n });\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n\n if (include) {\n include.forEach(item => {\n if (typeof item === 'string') {\n imports[item] = item;\n } else {\n imports[item[0]] = item[1];\n }\n });\n }\n\n if (!('react' in imports)) {\n imports.react = 'react';\n }\n\n const importKeys = Object.keys(imports);\n const code = [\n ...importKeys.map(\n (x, index) => `import * as i_${index} from '${imports[x]}';`,\n ),\n 'const imports = new Map();',\n ...importKeys.map((x, index) => `imports.set('${x}', i_${index});`),\n 'function getImport(name, getDefault) {',\n ' if (!imports.has(name)) {',\n ' throw new Error(\"Module \" + name + \" not found\");',\n ' }',\n ' const result = imports.get(name);',\n ' if (getDefault && typeof result === \"object\") {',\n ' return result.default || result;',\n ' }',\n ' return result;',\n '}',\n 'export { imports };',\n 'export default getImport;',\n ].join('\\n');\n\n // console.log('playground-imports', code);\n\n playgroundVirtualModule.writeModule('_rspress_playground_imports', code);\n },\n builderConfig: {\n source: {\n define: {\n __PLAYGROUND_DIRECTION__: JSON.stringify(defaultDirection),\n __PLAYGROUND_MONACO_LOADER__: JSON.stringify(monacoLoader),\n __PLAYGROUND_MONACO_OPTIONS__: JSON.stringify(monacoOptions),\n __PLAYGROUND_BABEL_URL__: JSON.stringify(babelUrl),\n },\n include: [join(__dirname, '..', '..', '..')],\n },\n html: {\n tags: preloads.map(url => ({\n tag: 'link',\n head: true,\n attrs: {\n rel: 'preload',\n href: url,\n as: 'script',\n },\n })),\n },\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [playgroundVirtualModule],\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [remarkPlugin, { getRouteMeta, editorPosition, defaultRenderMode }],\n ],\n globalComponents: [\n render\n ? render\n : path.join(staticPath, 'global-components', 'Playground.tsx'),\n ],\n },\n globalStyles: path.join(staticPath, 'global-styles', 'web.css'),\n };\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","export function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import path from 'node:path';\n\nexport const staticPath = path.join(__dirname, '../../../static');\n","import { dirname, join, resolve } from 'node:path';\nimport type { RouteMeta } from '@rspress/shared';\nimport fs from '@rspress/shared/fs-extra';\nimport type { Root } from 'mdast';\nimport type { Plugin } from 'unified';\nimport { visit } from 'unist-util-visit';\nimport { getNodeAttribute, getNodeMeta } from './utils';\n\nfunction createPlaygroundNode(\n currentNode: any,\n attrs: Array<[string, string]>,\n) {\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Playground',\n attributes: attrs.map(it => ({\n type: 'mdxJsxAttribute',\n name: it[0],\n value: it[1],\n })),\n });\n}\n\ninterface RemarkPluginProps {\n getRouteMeta: () => RouteMeta[];\n editorPosition: 'left' | 'right';\n defaultRenderMode: 'pure' | 'playground';\n}\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkPlugin: Plugin<[RemarkPluginProps], Root> = ({\n getRouteMeta,\n editorPosition,\n defaultRenderMode,\n}) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const route = routeMeta.find(\n meta =>\n resolve(meta.absolutePath) === resolve(vfile.path || vfile.history[0]),\n );\n if (!route) {\n return;\n }\n\n // 1. External demo , use <code src=\"foo\" /> to declare demo\n visit(tree, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = getNodeAttribute(node, 'src');\n if (!src) {\n return;\n }\n const demoPath = join(dirname(route.absolutePath), src);\n if (!fs.existsSync(demoPath)) {\n return;\n }\n const direction = getNodeAttribute(node, 'direction') || '';\n const code = fs.readFileSync(demoPath, {\n encoding: 'utf8',\n });\n const language = src.substr(src.lastIndexOf('.') + 1);\n createPlaygroundNode(node, [\n ['code', code],\n ['language', language],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const hasPureMeta = node?.meta?.includes('pure');\n const hasPlaygroundMeta = node?.meta?.includes('playground');\n\n let noTransform;\n switch (defaultRenderMode) {\n case 'pure':\n noTransform = !hasPlaygroundMeta;\n break;\n case 'playground':\n noTransform = hasPureMeta;\n break;\n default:\n break;\n }\n\n // do not anything for pure mode\n if (noTransform) {\n return;\n }\n\n const direction = getNodeMeta(node, 'direction') || '';\n\n createPlaygroundNode(node, [\n ['code', node.value],\n ['language', node.lang],\n ['direction', direction],\n ['editorPosition', editorPosition],\n ]);\n }\n });\n };\n};\n","/* eslint-disable consistent-return */\nimport type { Program } from '@babel/types';\nimport oxc from '@oxidation-compiler/napi';\n\nexport const parseImports = (code: string, sourceExt: string) => {\n const parsed = oxc.parseSync(code, {\n sourceType: 'module',\n sourceFilename: `index.${sourceExt}`,\n });\n\n const ast = JSON.parse(parsed.program) as Program;\n\n const result: string[] = [];\n\n // oxc didn't have \"traverse\", so it currently only scans the first level\n // (generally, demos are not too complicated, right?)\n ast.body.forEach(statement => {\n if (statement.type === 'ImportDeclaration') {\n result.push(statement.source.value);\n }\n });\n\n return result;\n};\n\nexport const getNodeAttribute = (\n node: any,\n attrName: string,\n): string | undefined => {\n return node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === attrName,\n )?.value;\n};\n\nexport const getNodeMeta = (\n node: any,\n metaName: string,\n): string | undefined => {\n if (!node.meta) {\n return;\n }\n const meta: string[] = node.meta.split(' ');\n const item: string | undefined = meta.find((x: string) =>\n x.startsWith(metaName),\n );\n if (item?.startsWith(`${metaName}=`)) {\n return item.substring(metaName.length + 1);\n }\n return item;\n};\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBAIO;;;ACJP,mBAGO;AACP,qBAAwB;AACxB,IAAAA,gBAA+B;;;ACFxB,IAAM,qBACX;;;ADwDI;AA7CN,SAAS,aAAa;AACpB,MAAI,eAAe;AAAA,IACjB,OAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AAEA,MAAI;AACF,UAAM,OAAO,OAAO,KAAK,4BAA4B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SAAS,IAAK,GAAG,MAC3D;AAAA;AAAA,MACA,SACC,6CAAC,SAAI,WAAU,4BAA4B,gBAAM,SAAQ;AAAA,OAE7D;AAAA,EAEJ;AACF","names":["import_react","MonacoEditor","module","require","import_jsx_runtime","React"],"ignoreList":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n type EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import MonacoEditor, {\n loader,\n type EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport React, { useMemo } from 'react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/config/source/define\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, type HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: (string | [string, string])[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'foo'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'foo'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'foo'\n if (specifier.type === 'ImportSpecifier') {\n if (\n 'name' in specifier.imported &&\n specifier.imported.name !== specifier.local.name\n ) {\n // const {${specifier.imported.name}: ${specifier.local.name}} = __get_import()\n specifiers.push([\n specifier.imported.name,\n specifier.local.name,\n ]);\n } else {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n Identifier,\n ObjectPattern,\n ObjectProperty,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nfunction createIdentifier(name: string): Identifier {\n return {\n type: 'Identifier',\n name,\n };\n}\n\nfunction createObjectProperty(key: string, value: string): ObjectProperty {\n return {\n type: 'ObjectProperty',\n key: createIdentifier(key),\n computed: false,\n shorthand: key === value,\n value: createIdentifier(value),\n };\n}\n\nexport function createObjectPattern(\n names: (string | [string, string])[],\n): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name =>\n Array.isArray(name)\n ? createObjectProperty(name[0], name[1])\n : createObjectProperty(name, name),\n ),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n const __PLAYGROUND_BABEL_URL__: string;\n}\n\n// see https://github.com/web-infra-dev/rspress/issues/876\nasync function loadUmdBabelModule(): Promise<Babel> {\n const data = await fetch(__PLAYGROUND_BABEL_URL__);\n\n const umdSourceCode = await data.text();\n\n const run = new Function(\n 'exports',\n 'module',\n 'require',\n `with(exports, module, require) {${umdSourceCode}}`,\n );\n\n const exports: Babel = {} as unknown as Babel;\n const module = { exports };\n const require = () => {};\n\n run(exports, module, require);\n\n return exports;\n}\n\nlet loadBabelPromise: null | Promise<Babel> = null;\n\nasync function getBabel(): Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n if (loadBabelPromise) {\n return loadBabelPromise;\n }\n\n loadBabelPromise = loadUmdBabelModule();\n try {\n const Babel = await loadBabelPromise;\n window.Babel = Babel;\n return Babel;\n } catch (e) {\n loadBabelPromise = null;\n throw e;\n }\n}\n\nexport { getBabel };\n"]}
|
package/dist/web/esm/index.js
DELETED
|
@@ -1,354 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
-
var __publicField = (obj, key, value) => {
|
|
4
|
-
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
5
|
-
return value;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
// src/web/index.ts
|
|
9
|
-
import {
|
|
10
|
-
default as default2,
|
|
11
|
-
loader as loader2
|
|
12
|
-
} from "@monaco-editor/react";
|
|
13
|
-
|
|
14
|
-
// src/web/editor.tsx
|
|
15
|
-
import MonacoEditor, {
|
|
16
|
-
loader
|
|
17
|
-
} from "@monaco-editor/react";
|
|
18
|
-
import { useDark } from "@rspress/core/runtime";
|
|
19
|
-
import { useMemo } from "react";
|
|
20
|
-
|
|
21
|
-
// src/web/constant.ts
|
|
22
|
-
var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
|
|
23
|
-
|
|
24
|
-
// src/web/editor.tsx
|
|
25
|
-
import { jsx } from "react/jsx-runtime";
|
|
26
|
-
function initLoader() {
|
|
27
|
-
let loaderConfig = {
|
|
28
|
-
paths: {
|
|
29
|
-
vs: DEFAULT_MONACO_URL
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
try {
|
|
33
|
-
const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
|
|
34
|
-
if (keys.length > 0) {
|
|
35
|
-
loaderConfig = __PLAYGROUND_MONACO_LOADER__;
|
|
36
|
-
}
|
|
37
|
-
} catch (e) {
|
|
38
|
-
}
|
|
39
|
-
loader.config(loaderConfig);
|
|
40
|
-
}
|
|
41
|
-
initLoader();
|
|
42
|
-
function getMonacoOptions() {
|
|
43
|
-
try {
|
|
44
|
-
return __PLAYGROUND_MONACO_OPTIONS__;
|
|
45
|
-
} catch (e) {
|
|
46
|
-
}
|
|
47
|
-
return {};
|
|
48
|
-
}
|
|
49
|
-
function Editor(props) {
|
|
50
|
-
const { options, className = "", theme: themeProp, ...rest } = props || {};
|
|
51
|
-
const dark = useDark();
|
|
52
|
-
const theme = useMemo(() => {
|
|
53
|
-
if (themeProp) {
|
|
54
|
-
return themeProp;
|
|
55
|
-
}
|
|
56
|
-
return dark ? "vs-dark" : "light";
|
|
57
|
-
}, [themeProp, dark]);
|
|
58
|
-
return /* @__PURE__ */ jsx("div", { className: `rspress-playground-editor ${className}`, children: /* @__PURE__ */ jsx(
|
|
59
|
-
MonacoEditor,
|
|
60
|
-
{
|
|
61
|
-
...rest,
|
|
62
|
-
theme,
|
|
63
|
-
options: {
|
|
64
|
-
minimap: {
|
|
65
|
-
enabled: true,
|
|
66
|
-
autohide: true
|
|
67
|
-
},
|
|
68
|
-
fontSize: 14,
|
|
69
|
-
lineNumbersMinChars: 7,
|
|
70
|
-
scrollBeyondLastLine: false,
|
|
71
|
-
automaticLayout: true,
|
|
72
|
-
wordBasedSuggestions: true,
|
|
73
|
-
quickSuggestions: true,
|
|
74
|
-
scrollbar: {
|
|
75
|
-
verticalScrollbarSize: 8,
|
|
76
|
-
horizontalScrollbarSize: 8
|
|
77
|
-
},
|
|
78
|
-
scrollPredominantAxis: false,
|
|
79
|
-
...getMonacoOptions(),
|
|
80
|
-
...options
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
) });
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// src/web/runner.tsx
|
|
87
|
-
import React2, { Component } from "react";
|
|
88
|
-
|
|
89
|
-
// src/web/ast.ts
|
|
90
|
-
function createVariableDeclaration(id, init) {
|
|
91
|
-
return {
|
|
92
|
-
type: "VariableDeclaration",
|
|
93
|
-
declarations: [
|
|
94
|
-
{
|
|
95
|
-
type: "VariableDeclarator",
|
|
96
|
-
id: typeof id === "string" ? {
|
|
97
|
-
type: "Identifier",
|
|
98
|
-
name: id
|
|
99
|
-
} : id,
|
|
100
|
-
init
|
|
101
|
-
}
|
|
102
|
-
],
|
|
103
|
-
kind: "const"
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
function createIdentifier(name) {
|
|
107
|
-
return {
|
|
108
|
-
type: "Identifier",
|
|
109
|
-
name
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
function createObjectProperty(key, value) {
|
|
113
|
-
return {
|
|
114
|
-
type: "ObjectProperty",
|
|
115
|
-
key: createIdentifier(key),
|
|
116
|
-
computed: false,
|
|
117
|
-
shorthand: key === value,
|
|
118
|
-
value: createIdentifier(value)
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
function createObjectPattern(names) {
|
|
122
|
-
return {
|
|
123
|
-
type: "ObjectPattern",
|
|
124
|
-
properties: names.map(
|
|
125
|
-
(name) => Array.isArray(name) ? createObjectProperty(name[0], name[1]) : createObjectProperty(name, name)
|
|
126
|
-
)
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
function createGetImport(name, getDefault) {
|
|
130
|
-
return {
|
|
131
|
-
type: "CallExpression",
|
|
132
|
-
callee: {
|
|
133
|
-
type: "Identifier",
|
|
134
|
-
name: "__get_import"
|
|
135
|
-
},
|
|
136
|
-
arguments: [
|
|
137
|
-
{
|
|
138
|
-
type: "StringLiteral",
|
|
139
|
-
value: name
|
|
140
|
-
},
|
|
141
|
-
{
|
|
142
|
-
type: "BooleanLiteral",
|
|
143
|
-
value: Boolean(getDefault)
|
|
144
|
-
}
|
|
145
|
-
]
|
|
146
|
-
};
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
// src/web/babel.ts
|
|
150
|
-
async function loadUmdBabelModule() {
|
|
151
|
-
const data = await fetch(__PLAYGROUND_BABEL_URL__);
|
|
152
|
-
const umdSourceCode = await data.text();
|
|
153
|
-
const run = new Function(
|
|
154
|
-
"exports",
|
|
155
|
-
"module",
|
|
156
|
-
"require",
|
|
157
|
-
`with(exports, module, require) {${umdSourceCode}}`
|
|
158
|
-
);
|
|
159
|
-
const exports = {};
|
|
160
|
-
const module = { exports };
|
|
161
|
-
const require2 = () => {
|
|
162
|
-
};
|
|
163
|
-
run(exports, module, require2);
|
|
164
|
-
return exports;
|
|
165
|
-
}
|
|
166
|
-
var loadBabelPromise = null;
|
|
167
|
-
async function getBabel() {
|
|
168
|
-
if (window.Babel) {
|
|
169
|
-
return window.Babel;
|
|
170
|
-
}
|
|
171
|
-
if (loadBabelPromise) {
|
|
172
|
-
return loadBabelPromise;
|
|
173
|
-
}
|
|
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
|
-
|
|
185
|
-
// src/web/runner.tsx
|
|
186
|
-
import { jsx as jsx2, jsxs } from "react/jsx-runtime";
|
|
187
|
-
var DEBOUNCE_TIME = 800;
|
|
188
|
-
var Runner = class extends Component {
|
|
189
|
-
constructor(props) {
|
|
190
|
-
super(props);
|
|
191
|
-
__publicField(this, "timer");
|
|
192
|
-
this.state = {
|
|
193
|
-
error: void 0,
|
|
194
|
-
comp: null
|
|
195
|
-
};
|
|
196
|
-
this.doCompile = this.doCompile.bind(this);
|
|
197
|
-
this.waitCompile = this.waitCompile.bind(this);
|
|
198
|
-
}
|
|
199
|
-
static getDerivedStateFromError(error) {
|
|
200
|
-
return {
|
|
201
|
-
error,
|
|
202
|
-
comp: null
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
waitCompile(targetCode) {
|
|
206
|
-
if (this.timer) {
|
|
207
|
-
clearTimeout(this.timer);
|
|
208
|
-
}
|
|
209
|
-
this.timer = setTimeout(() => {
|
|
210
|
-
this.timer = null;
|
|
211
|
-
this.doCompile(targetCode);
|
|
212
|
-
}, DEBOUNCE_TIME);
|
|
213
|
-
}
|
|
214
|
-
async doCompile(targetCode) {
|
|
215
|
-
const { language, getImport } = this.props;
|
|
216
|
-
const babel = await getBabel();
|
|
217
|
-
try {
|
|
218
|
-
const presets = [
|
|
219
|
-
[babel.availablePresets.react],
|
|
220
|
-
[babel.availablePresets.env, { modules: "commonjs" }]
|
|
221
|
-
];
|
|
222
|
-
if (language === "tsx" || language === "ts") {
|
|
223
|
-
presets.unshift([
|
|
224
|
-
babel.availablePresets.typescript,
|
|
225
|
-
{
|
|
226
|
-
allExtensions: true,
|
|
227
|
-
isTSX: language === "tsx"
|
|
228
|
-
}
|
|
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 (specifier.local.name === "React") {
|
|
247
|
-
this.hasReactImported = true;
|
|
248
|
-
}
|
|
249
|
-
if (specifier.type === "ImportDefaultSpecifier") {
|
|
250
|
-
code.push(
|
|
251
|
-
createVariableDeclaration(
|
|
252
|
-
specifier.local.name,
|
|
253
|
-
createGetImport(pkg, true)
|
|
254
|
-
)
|
|
255
|
-
);
|
|
256
|
-
}
|
|
257
|
-
if (specifier.type === "ImportNamespaceSpecifier") {
|
|
258
|
-
code.push(
|
|
259
|
-
createVariableDeclaration(
|
|
260
|
-
specifier.local.name,
|
|
261
|
-
createGetImport(pkg)
|
|
262
|
-
)
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
if (specifier.type === "ImportSpecifier") {
|
|
266
|
-
if ("name" in specifier.imported && specifier.imported.name !== specifier.local.name) {
|
|
267
|
-
specifiers.push([
|
|
268
|
-
specifier.imported.name,
|
|
269
|
-
specifier.local.name
|
|
270
|
-
]);
|
|
271
|
-
} else {
|
|
272
|
-
specifiers.push(specifier.local.name);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
if (specifiers.length > 0) {
|
|
277
|
-
code.push(
|
|
278
|
-
createVariableDeclaration(
|
|
279
|
-
createObjectPattern(specifiers),
|
|
280
|
-
createGetImport(pkg)
|
|
281
|
-
)
|
|
282
|
-
);
|
|
283
|
-
}
|
|
284
|
-
path.replaceWithMultiple(code);
|
|
285
|
-
}
|
|
286
|
-
},
|
|
287
|
-
post(file) {
|
|
288
|
-
if (!this.hasReactImported) {
|
|
289
|
-
file.ast.program.body.unshift(
|
|
290
|
-
createVariableDeclaration(
|
|
291
|
-
"React",
|
|
292
|
-
createGetImport("react", true)
|
|
293
|
-
)
|
|
294
|
-
);
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
]
|
|
299
|
-
});
|
|
300
|
-
if (targetCode !== this.props.code || !result || !result.code) {
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
const runExports = {};
|
|
304
|
-
const func = new Function("__get_import", "exports", result.code);
|
|
305
|
-
func(getImport, runExports);
|
|
306
|
-
if (runExports.default) {
|
|
307
|
-
this.setState({
|
|
308
|
-
error: void 0,
|
|
309
|
-
comp: React2.createElement(runExports.default)
|
|
310
|
-
});
|
|
311
|
-
return;
|
|
312
|
-
}
|
|
313
|
-
this.setState({
|
|
314
|
-
error: new Error("No default export")
|
|
315
|
-
});
|
|
316
|
-
} catch (e) {
|
|
317
|
-
if (targetCode !== this.props.code) {
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
console.error(e);
|
|
321
|
-
this.setState({
|
|
322
|
-
error: e
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
componentDidCatch(error, errorInfo) {
|
|
327
|
-
console.error(error);
|
|
328
|
-
console.error(errorInfo);
|
|
329
|
-
}
|
|
330
|
-
componentDidMount() {
|
|
331
|
-
this.doCompile(this.props.code);
|
|
332
|
-
}
|
|
333
|
-
componentDidUpdate(prevProps) {
|
|
334
|
-
if (prevProps.code !== this.props.code) {
|
|
335
|
-
this.waitCompile(this.props.code);
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
render() {
|
|
339
|
-
const { className = "", code, language, getImport, ...rest } = this.props;
|
|
340
|
-
const { error, comp } = this.state;
|
|
341
|
-
return /* @__PURE__ */ jsxs("div", { className: `rspress-playground-runner ${className}`, ...rest, children: [
|
|
342
|
-
comp,
|
|
343
|
-
error && /* @__PURE__ */ jsx2("pre", { className: "rspress-playground-error", children: error.message })
|
|
344
|
-
] });
|
|
345
|
-
}
|
|
346
|
-
};
|
|
347
|
-
export {
|
|
348
|
-
Editor,
|
|
349
|
-
default2 as MonacoEditor,
|
|
350
|
-
loader2 as MonacoEditorLoader,
|
|
351
|
-
Runner
|
|
352
|
-
};
|
|
353
|
-
|
|
354
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;AAAA;AAAA,EACa,WAAXA;AAAA,EACU,UAAVC;AAAA,OAEK;;;ACJP,OAAO;AAAA,EACL;AAAA,OAEK;AACP,SAAS,eAAe;AACxB,SAAgB,eAAe;;;ACFxB,IAAM,qBACX;;;ADwDI;AA7CN,SAAS,aAAa;AACpB,MAAI,eAAe;AAAA,IACjB,OAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AAEA,MAAI;AACF,UAAM,OAAO,OAAO,KAAK,4BAA4B;AAErD,QAAI,KAAK,SAAS,GAAG;AACnB,qBAAe;AAAA,IACjB;AAAA,EACF,SAAS,GAAG;AAAA,EAEZ;AAEA,SAAO,OAAO,YAAY;AAC5B;AACA,WAAW;AAEX,SAAS,mBAAmB;AAC1B,MAAI;AACF,WAAO;AAAA,EACT,SAAS,GAAG;AAAA,EAEZ;AACA,SAAO,CAAC;AACV;AAIO,SAAS,OAAO,OAAoB;AACzC,QAAM,EAAE,SAAS,YAAY,IAAI,OAAO,WAAW,GAAG,KAAK,IAAI,SAAS,CAAC;AAEzE,QAAM,OAAO,QAAQ;AACrB,QAAM,QAAQ,QAAQ,MAAM;AAC1B,QAAI,WAAW;AACb,aAAO;AAAA,IACT;AACA,WAAO,OAAO,YAAY;AAAA,EAC5B,GAAG,CAAC,WAAW,IAAI,CAAC;AAEpB,SACE,oBAAC,SAAI,WAAW,6BAA6B,SAAS,IACpD;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA,MACA,SAAS;AAAA,QACP,SAAS;AAAA,UACP,SAAS;AAAA,UACT,UAAU;AAAA,QAC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CAAC;AACf,WAAK,SAAS;AAAA,QACZ,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,kBAAkB,OAAc,WAA4B;AAC1D,YAAQ,MAAM,KAAK;AACnB,YAAQ,MAAM,SAAS;AAAA,EACzB;AAAA,EAEA,oBAAoB;AAClB,SAAK,UAAU,KAAK,MAAM,IAAI;AAAA,EAChC;AAAA,EAEA,mBAAmB,WAAwB;AACzC,QAAI,UAAU,SAAS,KAAK,MAAM,MAAM;AACtC,WAAK,YAAY,KAAK,MAAM,IAAI;AAAA,IAClC;AAAA,EACF;AAAA,EAEA,SAAS;AACP,UAAM,EAAE,YAAY,IAAI,MAAM,UAAU,WAAW,GAAG,KAAK,IAAI,KAAK;AACpE,UAAM,EAAE,OAAO,KAAK,IAAI,KAAK;AAE7B,WACE,qBAAC,SAAI,WAAW,6BAA6B,SAAS,IAAK,GAAG,MAC3D;AAAA;AAAA,MACA,SACC,gBAAAE,KAAC,SAAI,WAAU,4BAA4B,gBAAM,SAAQ;AAAA,OAE7D;AAAA,EAEJ;AACF","names":["default","loader","React","require","jsx"],"ignoreList":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n type EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import MonacoEditor, {\n loader,\n type EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { useDark } from '@rspress/core/runtime';\nimport React, { useMemo } from 'react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by Rsbuild in cli/index.ts\n// see: https://rsbuild.dev/config/source/define\ndeclare global {\n const __PLAYGROUND_MONACO_LOADER__: any;\n const __PLAYGROUND_MONACO_OPTIONS__: any;\n}\n\nfunction initLoader() {\n let loaderConfig = {\n paths: {\n vs: DEFAULT_MONACO_URL,\n },\n };\n\n try {\n const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);\n\n if (keys.length > 0) {\n loaderConfig = __PLAYGROUND_MONACO_LOADER__;\n }\n } catch (e) {\n // ignore\n }\n\n loader.config(loaderConfig);\n}\ninitLoader();\n\nfunction getMonacoOptions() {\n try {\n return __PLAYGROUND_MONACO_OPTIONS__;\n } catch (e) {\n // ignore\n }\n return {};\n}\n\nexport type EditorProps = Partial<MonacoEditorProps>;\n\nexport function Editor(props: EditorProps) {\n const { options, className = '', theme: themeProp, ...rest } = props || {};\n\n const dark = useDark();\n const theme = useMemo(() => {\n if (themeProp) {\n return themeProp;\n }\n return dark ? 'vs-dark' : 'light';\n }, [themeProp, dark]);\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme={theme}\n options={{\n minimap: {\n enabled: true,\n autohide: true,\n },\n fontSize: 14,\n lineNumbersMinChars: 7,\n scrollBeyondLastLine: false,\n automaticLayout: true,\n wordBasedSuggestions: true,\n quickSuggestions: true,\n scrollbar: {\n verticalScrollbarSize: 8,\n horizontalScrollbarSize: 8,\n },\n scrollPredominantAxis: false,\n ...getMonacoOptions(),\n ...options,\n }}\n />\n </div>\n );\n}\n","export const DEFAULT_BABEL_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js';\n\nexport const DEFAULT_MONACO_URL =\n 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs';\n","import type { Node } from '@babel/types';\nimport React, { Component, type HTMLAttributes } from 'react';\nimport {\n createGetImport,\n createObjectPattern,\n createVariableDeclaration,\n} from './ast';\nimport { getBabel } from './babel';\n\ninterface RunnerProps extends HTMLAttributes<HTMLDivElement> {\n code: string;\n language: string;\n getImport: (name: string, getDefault?: boolean) => void;\n}\n\ninterface RunnerState {\n error?: Error;\n comp: any;\n}\n\nconst DEBOUNCE_TIME = 800;\n\nclass Runner extends Component<RunnerProps, RunnerState> {\n static getDerivedStateFromError(error: Error) {\n return {\n error,\n comp: null,\n };\n }\n\n timer: any;\n\n constructor(props: RunnerProps) {\n super(props);\n\n this.state = {\n error: undefined,\n comp: null,\n };\n\n this.doCompile = this.doCompile.bind(this);\n this.waitCompile = this.waitCompile.bind(this);\n }\n\n waitCompile(targetCode: string) {\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => {\n this.timer = null;\n this.doCompile(targetCode);\n }, DEBOUNCE_TIME);\n }\n\n async doCompile(targetCode: string) {\n const { language, getImport } = this.props;\n const babel = await getBabel();\n try {\n const presets = [\n [babel.availablePresets.react],\n [babel.availablePresets.env, { modules: 'commonjs' }],\n ];\n if (language === 'tsx' || language === 'ts') {\n presets.unshift([\n babel.availablePresets.typescript,\n {\n allExtensions: true,\n isTSX: language === 'tsx',\n },\n ]);\n }\n const result = babel.transform(targetCode, {\n sourceType: 'module',\n sourceMaps: 'inline',\n presets,\n plugins: [\n {\n pre() {\n this.hasReactImported = false;\n },\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n const specifiers: (string | [string, string])[] = [];\n for (const specifier of path.node.specifiers) {\n if (specifier.local.name === 'React') {\n this.hasReactImported = true;\n }\n // import X from 'foo'\n if (specifier.type === 'ImportDefaultSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg, true),\n ),\n );\n }\n // import * as X from 'foo'\n if (specifier.type === 'ImportNamespaceSpecifier') {\n // const ${specifier.local.name} = __get_import()\n code.push(\n createVariableDeclaration(\n specifier.local.name,\n createGetImport(pkg),\n ),\n );\n }\n // import { a, b, c } from 'foo'\n if (specifier.type === 'ImportSpecifier') {\n if (\n 'name' in specifier.imported &&\n specifier.imported.name !== specifier.local.name\n ) {\n // const {${specifier.imported.name}: ${specifier.local.name}} = __get_import()\n specifiers.push([\n specifier.imported.name,\n specifier.local.name,\n ]);\n } else {\n // const {${specifier.local.name}} = __get_import()\n specifiers.push(specifier.local.name);\n }\n }\n }\n if (specifiers.length > 0) {\n code.push(\n createVariableDeclaration(\n createObjectPattern(specifiers),\n createGetImport(pkg),\n ),\n );\n }\n path.replaceWithMultiple(code);\n },\n },\n post(file) {\n // Auto import React\n if (!this.hasReactImported) {\n file.ast.program.body.unshift(\n createVariableDeclaration(\n 'React',\n createGetImport('react', true),\n ),\n );\n }\n },\n },\n ],\n });\n\n // Code has been updated\n if (targetCode !== this.props.code || !result || !result.code) {\n return;\n }\n\n const runExports: any = {};\n // eslint-disable-next-line @typescript-eslint/no-implied-eval, no-new-func\n const func = new Function('__get_import', 'exports', result.code);\n func(getImport, runExports);\n\n if (runExports.default) {\n this.setState({\n error: undefined,\n comp: React.createElement(runExports.default),\n });\n return;\n }\n\n this.setState({\n error: new Error('No default export'),\n });\n } catch (e) {\n // Code has been updated\n if (targetCode !== this.props.code) {\n return;\n }\n console.error(e);\n this.setState({\n error: e as Error,\n });\n }\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {\n console.error(error);\n console.error(errorInfo);\n }\n\n componentDidMount() {\n this.doCompile(this.props.code);\n }\n\n componentDidUpdate(prevProps: RunnerProps) {\n if (prevProps.code !== this.props.code) {\n this.waitCompile(this.props.code);\n }\n }\n\n render() {\n const { className = '', code, language, getImport, ...rest } = this.props;\n const { error, comp } = this.state;\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n {error && (\n <pre className=\"rspress-playground-error\">{error.message}</pre>\n )}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n Identifier,\n ObjectPattern,\n ObjectProperty,\n VariableDeclaration,\n} from '@babel/types';\n\nexport function createVariableDeclaration(\n id: string | ObjectPattern,\n init: Expression,\n): VariableDeclaration {\n return {\n type: 'VariableDeclaration',\n declarations: [\n {\n type: 'VariableDeclarator',\n id:\n typeof id === 'string'\n ? {\n type: 'Identifier',\n name: id,\n }\n : id,\n init,\n },\n ],\n kind: 'const',\n };\n}\n\nfunction createIdentifier(name: string): Identifier {\n return {\n type: 'Identifier',\n name,\n };\n}\n\nfunction createObjectProperty(key: string, value: string): ObjectProperty {\n return {\n type: 'ObjectProperty',\n key: createIdentifier(key),\n computed: false,\n shorthand: key === value,\n value: createIdentifier(value),\n };\n}\n\nexport function createObjectPattern(\n names: (string | [string, string])[],\n): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name =>\n Array.isArray(name)\n ? createObjectProperty(name[0], name[1])\n : createObjectProperty(name, name),\n ),\n };\n}\n\nexport function createGetImport(\n name: string,\n getDefault?: boolean,\n): CallExpression {\n return {\n type: 'CallExpression',\n callee: {\n type: 'Identifier',\n name: '__get_import',\n },\n arguments: [\n {\n type: 'StringLiteral',\n value: name,\n },\n {\n type: 'BooleanLiteral',\n value: Boolean(getDefault),\n },\n ],\n };\n}\n","import type babel from '@babel/standalone';\n\ntype Babel = typeof babel;\n\ndeclare global {\n interface Window {\n Babel: Babel;\n }\n const __PLAYGROUND_BABEL_URL__: string;\n}\n\n// see https://github.com/web-infra-dev/rspress/issues/876\nasync function loadUmdBabelModule(): Promise<Babel> {\n const data = await fetch(__PLAYGROUND_BABEL_URL__);\n\n const umdSourceCode = await data.text();\n\n const run = new Function(\n 'exports',\n 'module',\n 'require',\n `with(exports, module, require) {${umdSourceCode}}`,\n );\n\n const exports: Babel = {} as unknown as Babel;\n const module = { exports };\n const require = () => {};\n\n run(exports, module, require);\n\n return exports;\n}\n\nlet loadBabelPromise: null | Promise<Babel> = null;\n\nasync function getBabel(): Promise<Babel> {\n if (window.Babel) {\n return window.Babel;\n }\n if (loadBabelPromise) {\n return loadBabelPromise;\n }\n\n loadBabelPromise = loadUmdBabelModule();\n try {\n const Babel = await loadBabelPromise;\n window.Babel = Babel;\n return Babel;\n } catch (e) {\n loadBabelPromise = null;\n throw e;\n }\n}\n\nexport { getBabel };\n"]}
|