@rspress/plugin-playground 0.0.0-next-20230925114748

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.
@@ -0,0 +1,338 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/web/index.ts
30
+ var web_exports = {};
31
+ __export(web_exports, {
32
+ Editor: () => Editor,
33
+ MonacoEditor: () => import_react3.default,
34
+ MonacoEditorLoader: () => import_react3.loader,
35
+ MonacoEditorProps: () => import_react3.EditorProps,
36
+ Runner: () => Runner
37
+ });
38
+ module.exports = __toCommonJS(web_exports);
39
+ var import_react3 = __toESM(require("@monaco-editor/react"));
40
+
41
+ // src/web/editor.tsx
42
+ var import_react = __toESM(require("@monaco-editor/react"));
43
+
44
+ // src/web/constant.ts
45
+ var DEFAULT_BABEL_URL = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.22.20/babel.min.js";
46
+ var DEFAULT_MONACO_URL = "https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.43.0/min/vs";
47
+
48
+ // src/web/editor.tsx
49
+ var import_jsx_runtime = require("react/jsx-runtime");
50
+ function initLoader() {
51
+ let loaderConfig = {
52
+ paths: {
53
+ vs: DEFAULT_MONACO_URL
54
+ }
55
+ };
56
+ try {
57
+ const keys = Object.keys(__PLAYGROUND_MONACO_LOADER__);
58
+ if (keys.length > 0) {
59
+ loaderConfig = __PLAYGROUND_MONACO_LOADER__;
60
+ }
61
+ } catch (e) {
62
+ }
63
+ import_react.loader.config(loaderConfig);
64
+ }
65
+ initLoader();
66
+ function getMonacoOptions() {
67
+ try {
68
+ return __PLAYGROUND_MONACO_OPTIONS__;
69
+ } catch (e) {
70
+ }
71
+ return {};
72
+ }
73
+ function Editor(props) {
74
+ const { options, className = "", ...rest } = props || {};
75
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: `rspress-playground-editor ${className}`, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
76
+ import_react.default,
77
+ {
78
+ ...rest,
79
+ theme: "light",
80
+ options: {
81
+ minimap: {
82
+ enabled: true,
83
+ autohide: true
84
+ },
85
+ fontSize: 14,
86
+ lineNumbersMinChars: 7,
87
+ scrollBeyondLastLine: false,
88
+ automaticLayout: true,
89
+ wordBasedSuggestions: true,
90
+ quickSuggestions: true,
91
+ scrollbar: {
92
+ verticalScrollbarSize: 8,
93
+ horizontalScrollbarSize: 8
94
+ },
95
+ scrollPredominantAxis: false,
96
+ ...getMonacoOptions(),
97
+ ...options
98
+ }
99
+ }
100
+ ) });
101
+ }
102
+
103
+ // src/web/runner.tsx
104
+ var import_react2 = __toESM(require("react"));
105
+
106
+ // src/web/ast.ts
107
+ function createVariableDeclaration(id, init) {
108
+ return {
109
+ type: "VariableDeclaration",
110
+ declarations: [
111
+ {
112
+ type: "VariableDeclarator",
113
+ id: typeof id === "string" ? {
114
+ type: "Identifier",
115
+ name: id
116
+ } : id,
117
+ init
118
+ }
119
+ ],
120
+ kind: "const"
121
+ };
122
+ }
123
+ function createObjectPattern(names) {
124
+ return {
125
+ type: "ObjectPattern",
126
+ properties: names.map((name) => ({
127
+ type: "ObjectProperty",
128
+ key: {
129
+ type: "Identifier",
130
+ name
131
+ },
132
+ computed: false,
133
+ method: false,
134
+ shorthand: true,
135
+ value: {
136
+ type: "Identifier",
137
+ name
138
+ }
139
+ }))
140
+ };
141
+ }
142
+ function createGetImport(name, getDefault) {
143
+ return {
144
+ type: "CallExpression",
145
+ callee: {
146
+ type: "Identifier",
147
+ name: "__get_import"
148
+ },
149
+ arguments: [
150
+ {
151
+ type: "StringLiteral",
152
+ value: name
153
+ },
154
+ {
155
+ type: "BooleanLiteral",
156
+ value: Boolean(getDefault)
157
+ }
158
+ ]
159
+ };
160
+ }
161
+
162
+ // src/web/utils.ts
163
+ var loadingMap = /* @__PURE__ */ new Map();
164
+ function loadScript(url) {
165
+ const exists = loadingMap.get(url);
166
+ if (exists) {
167
+ return exists;
168
+ }
169
+ const n = new Promise((resolve) => {
170
+ const e = document.createElement("script");
171
+ e.src = url;
172
+ e.onload = () => resolve();
173
+ document.body.appendChild(e);
174
+ });
175
+ loadingMap.set(url, n);
176
+ return n;
177
+ }
178
+
179
+ // src/web/babel.ts
180
+ async function getBabel() {
181
+ if (!window.Babel) {
182
+ let babelUrl = DEFAULT_BABEL_URL;
183
+ try {
184
+ const u = __PLAYGROUND_BABEL_URL__;
185
+ if (u) {
186
+ babelUrl = u;
187
+ }
188
+ } catch (e) {
189
+ }
190
+ await loadScript(babelUrl);
191
+ }
192
+ return window.Babel;
193
+ }
194
+
195
+ // src/web/runner.tsx
196
+ var import_jsx_runtime2 = require("react/jsx-runtime");
197
+ var Runner = class extends import_react2.Component {
198
+ constructor(props) {
199
+ super(props);
200
+ this.state = {
201
+ error: void 0,
202
+ comp: null
203
+ };
204
+ this.doCompile = this.doCompile.bind(this);
205
+ this.waitCompile = this.waitCompile.bind(this);
206
+ }
207
+ static getDerivedStateFromError(error) {
208
+ return {
209
+ error,
210
+ comp: null
211
+ };
212
+ }
213
+ waitCompile(targetCode) {
214
+ if (this.timer) {
215
+ clearTimeout(this.timer);
216
+ }
217
+ this.timer = setTimeout(() => {
218
+ this.timer = null;
219
+ this.doCompile(targetCode);
220
+ }, 600);
221
+ }
222
+ async doCompile(targetCode) {
223
+ const { language, getImport } = this.props;
224
+ const babel = await getBabel();
225
+ try {
226
+ const presets = [
227
+ [babel.availablePresets.react],
228
+ [babel.availablePresets.env, { modules: "commonjs" }]
229
+ ];
230
+ if (language === "tsx" || language === "ts") {
231
+ presets.unshift([
232
+ babel.availablePresets.typescript,
233
+ {
234
+ allExtensions: true,
235
+ isTSX: language === "tsx"
236
+ }
237
+ ]);
238
+ }
239
+ const result = babel.transform(targetCode, {
240
+ sourceType: "module",
241
+ presets,
242
+ plugins: [
243
+ {
244
+ visitor: {
245
+ ImportDeclaration(path) {
246
+ const pkg = path.node.source.value;
247
+ const code = [];
248
+ for (const specifier of path.node.specifiers) {
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
+ code.push(
267
+ createVariableDeclaration(
268
+ createObjectPattern([specifier.local.name]),
269
+ createGetImport(pkg)
270
+ )
271
+ );
272
+ }
273
+ }
274
+ path.replaceWithMultiple(code);
275
+ }
276
+ }
277
+ }
278
+ ]
279
+ });
280
+ if (targetCode !== this.props.code || !result || !result.code) {
281
+ return;
282
+ }
283
+ const runExports = {};
284
+ const func = new Function("__get_import", "exports", result.code);
285
+ func(getImport, runExports);
286
+ if (runExports.default) {
287
+ this.setState({
288
+ error: void 0,
289
+ comp: import_react2.default.createElement(runExports.default)
290
+ });
291
+ return;
292
+ }
293
+ this.setState({
294
+ error: new Error("No default export"),
295
+ comp: null
296
+ });
297
+ } catch (e) {
298
+ if (targetCode !== this.props.code) {
299
+ return;
300
+ }
301
+ console.error(e);
302
+ this.setState({
303
+ error: e,
304
+ comp: null
305
+ });
306
+ }
307
+ }
308
+ componentDidCatch(error, errorInfo) {
309
+ console.error(error);
310
+ console.error(errorInfo);
311
+ }
312
+ componentDidMount() {
313
+ this.doCompile(this.props.code);
314
+ }
315
+ componentDidUpdate(prevProps) {
316
+ if (prevProps.code !== this.props.code) {
317
+ this.waitCompile(this.props.code);
318
+ }
319
+ }
320
+ render() {
321
+ const { className = "", code, language, getImport, ...rest } = this.props;
322
+ const { error, comp } = this.state;
323
+ if (error) {
324
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `rspress-playground-runner ${className}`, ...rest, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { color: "red" }, children: error.message }) });
325
+ }
326
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("div", { className: `rspress-playground-runner ${className}`, ...rest, children: comp });
327
+ }
328
+ };
329
+ // Annotate the CommonJS export names for ESM import in node:
330
+ 0 && (module.exports = {
331
+ Editor,
332
+ MonacoEditor,
333
+ MonacoEditorLoader,
334
+ MonacoEditorProps,
335
+ Runner
336
+ });
337
+
338
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAIO;;;ACHP,mBAGO;;;ACJA,IAAM,oBACX;AAEK,IAAM,qBACX;;;A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AAK,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,QAAI,OAAO;AACT,aACE,6CAAC,SAAI,WAAW,6BAA6B,aAAc,GAAG,MAC5D,uDAAC,UAAK,OAAO,EAAE,OAAO,MAAM,GAAI,gBAAM,SAAQ,GAChD;AAAA,IAEJ;AAEA,WACE,6CAAC,SAAI,WAAW,6BAA6B,aAAc,GAAG,MAC3D,gBACH;AAAA,EAEJ;AACF;","names":[],"sources":["../../../src/web/index.ts","../../../src/web/editor.tsx","../../../src/web/constant.ts","../../../src/web/runner.tsx","../../../src/web/ast.ts","../../../src/web/utils.ts","../../../src/web/babel.ts"],"sourcesContent":["export {\n default as MonacoEditor,\n loader as MonacoEditorLoader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nexport { Editor } from './editor';\nexport { Runner } from './runner';\n","import React from 'react';\nimport MonacoEditor, {\n loader,\n EditorProps as MonacoEditorProps,\n} from '@monaco-editor/react';\nimport { DEFAULT_MONACO_URL } from './constant';\n\n// inject by builder in cli/index.ts\n// see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\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 = '', ...rest } = props || {};\n\n return (\n <div className={`rspress-playground-editor ${className}`}>\n <MonacoEditor\n {...rest}\n theme=\"light\"\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, 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\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 }, 600);\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 presets,\n plugins: [\n {\n visitor: {\n ImportDeclaration(path) {\n const pkg = path.node.source.value;\n const code: Node[] = [];\n for (const specifier of path.node.specifiers) {\n // import X from 'xxx'\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 'xxx'\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 'xxx'\n if (specifier.type === 'ImportSpecifier') {\n // const {${specifier.local.name}} = __get_import()\n code.push(\n createVariableDeclaration(\n createObjectPattern([specifier.local.name]),\n createGetImport(pkg),\n ),\n );\n }\n }\n path.replaceWithMultiple(code);\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 comp: null,\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 comp: null,\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 if (error) {\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n <span style={{ color: 'red' }}>{error.message}</span>\n </div>\n );\n }\n\n return (\n <div className={`rspress-playground-runner ${className}`} {...rest}>\n {comp}\n </div>\n );\n }\n}\n\nexport { Runner };\n","import type {\n CallExpression,\n Expression,\n ObjectPattern,\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\nexport function createObjectPattern(names: string[]): ObjectPattern {\n return {\n type: 'ObjectPattern',\n properties: names.map(name => ({\n type: 'ObjectProperty',\n key: {\n type: 'Identifier',\n name,\n },\n computed: false,\n method: false,\n shorthand: true,\n value: {\n type: 'Identifier',\n name,\n },\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","const loadingMap = new Map<string, Promise<void>>();\n\nexport function loadScript(url: string): Promise<void> {\n const exists = loadingMap.get(url);\n if (exists) {\n return exists;\n }\n const n: Promise<void> = new Promise(resolve => {\n const e = document.createElement('script');\n e.src = url;\n e.onload = () => resolve();\n document.body.appendChild(e);\n });\n loadingMap.set(url, n);\n return n;\n}\n\nexport function normalizeUrl(u: string) {\n return u.replace(/\\/\\//g, '/');\n}\n","import type babel from '@babel/standalone';\nimport { DEFAULT_BABEL_URL } from './constant';\nimport { loadScript } from './utils';\n\ndeclare global {\n // inject by builder in cli/index.ts\n // see: https://modernjs.dev/builder/api/config-source.html#sourcedefine\n const __PLAYGROUND_BABEL_URL__: any;\n interface Window {\n Babel: typeof babel;\n }\n}\n\nasync function getBabel() {\n if (!window.Babel) {\n let babelUrl = DEFAULT_BABEL_URL;\n try {\n const u = __PLAYGROUND_BABEL_URL__;\n if (u) {\n babelUrl = u;\n }\n } catch (e) {\n // ignore\n }\n await loadScript(babelUrl);\n }\n return window.Babel;\n}\n\nexport { getBabel };\n"]}
@@ -0,0 +1,36 @@
1
+ import { EditorProps as EditorProps$1 } from '@monaco-editor/react';
2
+ export { default as MonacoEditor, loader as MonacoEditorLoader, EditorProps as MonacoEditorProps } from '@monaco-editor/react';
3
+ import React, { Component, HTMLAttributes } from 'react';
4
+
5
+ declare global {
6
+ const __PLAYGROUND_MONACO_LOADER__: any;
7
+ const __PLAYGROUND_MONACO_OPTIONS__: any;
8
+ }
9
+ type EditorProps = Partial<EditorProps$1>;
10
+ declare function Editor(props: EditorProps): JSX.Element;
11
+
12
+ interface RunnerProps extends HTMLAttributes<HTMLDivElement> {
13
+ code: string;
14
+ language: string;
15
+ getImport: (name: string, getDefault?: boolean) => void;
16
+ }
17
+ interface RunnerState {
18
+ error?: Error;
19
+ comp: any;
20
+ }
21
+ declare class Runner extends Component<RunnerProps, RunnerState> {
22
+ static getDerivedStateFromError(error: Error): {
23
+ error: Error;
24
+ comp: null;
25
+ };
26
+ timer: any;
27
+ constructor(props: RunnerProps);
28
+ waitCompile(targetCode: string): void;
29
+ doCompile(targetCode: string): Promise<void>;
30
+ componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void;
31
+ componentDidMount(): void;
32
+ componentDidUpdate(prevProps: RunnerProps): void;
33
+ render(): JSX.Element;
34
+ }
35
+
36
+ export { Editor, Runner };