dumi 2.4.38-beta.0 → 2.4.38-beta.1

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,52 +1,11 @@
1
1
  function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
3
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
4
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
5
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
6
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
7
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
8
2
  import { SP_ROUTE_PREFIX } from "../../../constants";
9
3
  import { useAppData, useDemo, useSiteData } from 'dumi';
10
- import React, { createElement, useEffect, useRef, useState } from 'react';
4
+ import React, { createElement } from 'react';
11
5
  import Previewer from 'dumi/theme/builtins/Previewer';
12
6
  import { useRenderer } from "../useRenderer";
13
7
  import DemoErrorBoundary from "./DemoErrorBoundary";
14
- var LazyDemoPlaceholder = function LazyDemoPlaceholder(_ref) {
15
- var id = _ref.id,
16
- onVisible = _ref.onVisible;
17
- var ref = useRef(null);
18
- useEffect(function () {
19
- if (typeof IntersectionObserver === 'undefined') {
20
- onVisible();
21
- return;
22
- }
23
- var observer = new IntersectionObserver(function (_ref2) {
24
- var _ref3 = _slicedToArray(_ref2, 1),
25
- entry = _ref3[0];
26
- if (entry.isIntersecting) {
27
- observer.disconnect();
28
- onVisible();
29
- }
30
- }, {
31
- rootMargin: '1000px 0px'
32
- });
33
- if (ref.current) {
34
- observer.observe(ref.current);
35
- }
36
- return function () {
37
- return observer.disconnect();
38
- };
39
- }, [onVisible]);
40
- return /*#__PURE__*/React.createElement("div", {
41
- id: id,
42
- ref: ref,
43
- "data-dumi-demo-lazy": true,
44
- style: {
45
- minHeight: 160
46
- }
47
- });
48
- };
49
- var LoadedDumiDemo = function LoadedDumiDemo(props) {
8
+ var InternalDumiDemo = function InternalDumiDemo(props) {
50
9
  var _useSiteData = useSiteData(),
51
10
  historyType = _useSiteData.historyType;
52
11
  var _useAppData = useAppData(),
@@ -84,25 +43,9 @@ var LoadedDumiDemo = function LoadedDumiDemo(props) {
84
43
  "".concat(isHashRoute ? "#" : '').concat(basename).concat(SP_ROUTE_PREFIX, "demos/").concat(props.demo.id).concat(routeQuery)
85
44
  }, props.previewerProps), props.previewerProps.iframe ? null : demoNode);
86
45
  };
87
- var InternalDumiDemo = function InternalDumiDemo(props) {
88
- var shouldLazyLoad = process.env.NODE_ENV !== 'production' && Boolean(props.demo.loader) && !props.demo.inline;
89
- var _useState = useState(!shouldLazyLoad),
90
- _useState2 = _slicedToArray(_useState, 2),
91
- visible = _useState2[0],
92
- setVisible = _useState2[1];
93
- if (!visible) {
94
- return /*#__PURE__*/React.createElement(LazyDemoPlaceholder, {
95
- id: props.demo.id,
96
- onVisible: function onVisible() {
97
- return setVisible(true);
98
- }
99
- });
100
- }
101
- return /*#__PURE__*/React.createElement(LoadedDumiDemo, props);
102
- };
103
46
  export var DumiDemo = /*#__PURE__*/React.memo(InternalDumiDemo, function (prev, next) {
104
47
  // compare length for performance
105
- return prev.demo.id === next.demo.id && prev.demo.inline === next.demo.inline && prev.demo.version === next.demo.version && JSON.stringify(prev.previewerProps).length === JSON.stringify(next.previewerProps).length;
48
+ return JSON.stringify(prev).length === JSON.stringify(next).length;
106
49
  });
107
50
  if (process.env.NODE_ENV !== 'production') {
108
51
  InternalDumiDemo.displayName = 'DumiDemo';
@@ -117,97 +117,7 @@ function toRequireRef(found) {
117
117
  const modRef = `require(${JSON.stringify(found.modulePath)})`;
118
118
  return found.exportName === "module.exports" ? modRef : `(${modRef})[${JSON.stringify(found.exportName)}]`;
119
119
  }
120
- function createTechStackMockApi(onRegister) {
121
- const api = {
122
- cwd: process.cwd(),
123
- config: {},
124
- userConfig: {},
125
- pkg: {},
126
- paths: {},
127
- service: {},
128
- registerTechStack: onRegister,
129
- register(opts) {
130
- if ((opts == null ? void 0 : opts.key) === "registerTechStack" && typeof opts.fn === "function") {
131
- onRegister(opts.fn);
132
- }
133
- }
134
- };
135
- return new Proxy(api, {
136
- get(target, key) {
137
- if (key in target) {
138
- return target[key];
139
- }
140
- return () => {
141
- };
142
- }
143
- });
144
- }
145
- function isSameTechStack(a, b) {
146
- return a === b || a.name === b.name && a.constructor.name === b.constructor.name;
147
- }
148
- function collectTechStacksFromPlugin(plugin) {
149
- if (typeof plugin !== "function")
150
- return [];
151
- const ret = [];
152
- const api = createTechStackMockApi((fn) => {
153
- try {
154
- const techStack = fn();
155
- if (techStack)
156
- ret.push(techStack);
157
- } catch {
158
- }
159
- });
160
- try {
161
- plugin(api);
162
- } catch {
163
- }
164
- return ret;
165
- }
166
- function findTechStackPluginInModule(target, mod) {
167
- const exp = mod.exports;
168
- if (!exp)
169
- return null;
170
- const candidates = [
171
- ["module.exports", exp],
172
- ["default", exp == null ? void 0 : exp.default],
173
- ...Object.entries(exp)
174
- ];
175
- for (const [exportName, plugin] of candidates) {
176
- const techStacks = collectTechStacksFromPlugin(plugin);
177
- if (techStacks.some((techStack) => isSameTechStack(techStack, target))) {
178
- return { modulePath: mod.filename, exportName };
179
- }
180
- }
181
- return null;
182
- }
183
- function findTechStackPluginInSourceFiles(target, sourceFiles) {
184
- import_utils.register.register({ implementor: import_esbuild.default });
185
- import_utils.register.clearFiles();
186
- try {
187
- for (const file of sourceFiles) {
188
- try {
189
- require(file);
190
- const mod = require.cache[file];
191
- if (!(mod == null ? void 0 : mod.exports))
192
- continue;
193
- const found = findTechStackPluginInModule(target, mod);
194
- if (found)
195
- return found;
196
- } catch {
197
- }
198
- }
199
- return null;
200
- } finally {
201
- for (const file of import_utils.register.getFiles()) {
202
- delete require.cache[file];
203
- }
204
- for (const file of sourceFiles) {
205
- delete require.cache[file];
206
- }
207
- import_utils.register.restore();
208
- }
209
- }
210
- function toTechStackRefs(techStacks, sourceFiles = []) {
120
+ function toTechStackRefs(techStacks) {
211
121
  const refs = [];
212
122
  for (const ts of techStacks) {
213
123
  const ctor = ts.constructor;
@@ -223,18 +133,12 @@ function toTechStackRefs(techStacks, sourceFiles = []) {
223
133
  ref = toRequireRef(found);
224
134
  }
225
135
  }
226
- if (!ref) {
227
- const found = findTechStackPluginInSourceFiles(ts, sourceFiles);
228
- if (found) {
229
- ref = `...loadTechStacksFromPlugin(${toRequireRef(found)})`;
230
- }
231
- }
232
136
  if (ref) {
233
137
  refs.push(ref);
234
138
  } else {
235
139
  const name = ts.constructor.name ? ` (${ts.constructor.name})` : "";
236
140
  console.warn(
237
- `[dumi] Utoopack markdown loader cannot serialize tech stack "${ts.name}"${name}. Please export the tech stack class or register it from an exported dumi plugin.`
141
+ `[dumi] Utoopack markdown loader cannot serialize tech stack "${ts.name}"${name}. Please export the tech stack class from a module.`
238
142
  );
239
143
  }
240
144
  }
@@ -266,7 +170,7 @@ function toPluginRefs(plugins = [], sourceFiles = []) {
266
170
  }).join(", ")}]`;
267
171
  }
268
172
  function buildLoaderContextContent(techStacks, builtins = {}, routes = {}, extraRemarkPlugins = [], extraRehypePlugins = [], sourceFiles = []) {
269
- const refs = toTechStackRefs(techStacks, sourceFiles);
173
+ const refs = toTechStackRefs(techStacks);
270
174
  return `'use strict';
271
175
  try {
272
176
  require(${JSON.stringify(
@@ -277,42 +181,6 @@ try {
277
181
  } catch (e) {
278
182
  console.warn('[dumi] failed to register TS require hook for utoopack loader context:', e);
279
183
  }
280
- function loadTechStacksFromPlugin(plugin) {
281
- if (typeof plugin !== 'function') return [];
282
- const techStacks = [];
283
- const registerTechStack = (fn) => {
284
- try {
285
- const techStack = fn();
286
- if (techStack) techStacks.push(techStack);
287
- } catch (e) {
288
- console.warn('[dumi] failed to register tech stack from utoopack loader context:', e);
289
- }
290
- };
291
- const api = new Proxy({
292
- cwd: process.cwd(),
293
- config: {},
294
- userConfig: {},
295
- pkg: {},
296
- paths: {},
297
- service: {},
298
- registerTechStack,
299
- register(opts) {
300
- if (opts && opts.key === 'registerTechStack' && typeof opts.fn === 'function') {
301
- registerTechStack(opts.fn);
302
- }
303
- },
304
- }, {
305
- get(target, key) {
306
- return key in target ? target[key] : () => {};
307
- },
308
- });
309
- try {
310
- plugin(api);
311
- } catch (e) {
312
- console.warn('[dumi] failed to load tech stack plugin in utoopack loader context:', e);
313
- }
314
- return techStacks;
315
- }
316
184
  exports.techStacks = [${refs.join(", ")}];
317
185
  exports.builtins = ${JSON.stringify(builtins)};
318
186
  exports.routes = ${JSON.stringify(routes)};
@@ -464,7 +332,7 @@ var getUtoopackRules = (api, config = api.config) => {
464
332
  },
465
333
  // compile inline demo code blocks
466
334
  {
467
- condition: { query: /^\?type=demo(?:&.*)?$/ },
335
+ condition: { query: /^\?type=demo$/ },
468
336
  loaders: [
469
337
  {
470
338
  loader: mdLoaderPath,
@@ -23,5 +23,9 @@ interface IMdLoaderTextModeOptions extends Omit<IMdLoaderDefaultModeOptions, 'bu
23
23
  mode: 'text';
24
24
  }
25
25
  export type IMdLoaderOptions = IMdLoaderDefaultModeOptions | IMdLoaderDemosModeOptions | IMdLoaderDemoModeOptions | IMdLoaderFrontmatterModeOptions | IMdLoaderTextModeOptions | IMdLoaderDemoIndexModeOptions;
26
+ type MdLoaderCache = {
27
+ getSync: (key: string, defaultValue: any) => any;
28
+ };
29
+ export declare function getMdLoaderCacheSync<T>(cache: MdLoaderCache, key: string, defaultValue: T): T;
26
30
  export default function mdLoader(this: any, content: string): void;
27
31
  export {};
@@ -29,7 +29,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  // src/loaders/markdown/index.ts
30
30
  var markdown_exports = {};
31
31
  __export(markdown_exports, {
32
- default: () => mdLoader
32
+ default: () => mdLoader,
33
+ getMdLoaderCacheSync: () => getMdLoaderCacheSync
33
34
  });
34
35
  module.exports = __toCommonJS(markdown_exports);
35
36
  var import_utoopackLoaders = require("../../features/compile/utoopackLoaders");
@@ -40,6 +41,20 @@ var import_path = __toESM(require("path"));
40
41
  var import_plugin_utils = require("umi/plugin-utils");
41
42
  var import_transformer = __toESM(require("./transformer"));
42
43
  var import_rehypeText = require("./transformer/rehypeText");
44
+ function isMalformedCacheError(err) {
45
+ return err instanceof SyntaxError || err instanceof Error && /Unexpected end of JSON input|Unterminated string in JSON/.test(
46
+ err.message
47
+ );
48
+ }
49
+ function getMdLoaderCacheSync(cache, key, defaultValue) {
50
+ try {
51
+ return cache.getSync(key, defaultValue);
52
+ } catch (err) {
53
+ if (isMalformedCacheError(err))
54
+ return defaultValue;
55
+ throw err;
56
+ }
57
+ }
43
58
  function getDemoSourceFiles(demos = []) {
44
59
  return demos.reduce((ret, demo) => {
45
60
  if ("resolveMap" in demo) {
@@ -50,13 +65,6 @@ function getDemoSourceFiles(demos = []) {
50
65
  return ret;
51
66
  }, []);
52
67
  }
53
- function getDemoIdFromQuery(resourceQuery = "") {
54
- return new URLSearchParams(resourceQuery.replace(/^\?/, "")).get("demoId");
55
- }
56
- function filterDemosByQuery(demos, resourceQuery) {
57
- const demoId = getDemoIdFromQuery(resourceQuery);
58
- return demoId ? demos == null ? void 0 : demos.filter((demo) => demo.id === demoId) : demos;
59
- }
60
68
  function isRelativePath(path2) {
61
69
  return /^\.{1,2}(?!\w)/.test(path2);
62
70
  }
@@ -112,7 +120,7 @@ function DumiMarkdownContent() {
112
120
  export default DumiMarkdownContent;`;
113
121
  }
114
122
  function emitDemo(opts, ret) {
115
- const demos = filterDemosByQuery(ret.meta.demos, this.resourceQuery);
123
+ const { demos } = ret.meta;
116
124
  const shareDepsMap = {};
117
125
  const demoDepsMap = {};
118
126
  const relativeDepsMap = {};
@@ -313,12 +321,9 @@ function emitText(opts, ret) {
313
321
  }
314
322
  function emit(opts, ret) {
315
323
  const { demos, embeds } = ret.meta;
316
- const dependencyDemos = opts.mode === "demo" ? filterDemosByQuery(demos, this.resourceQuery) : demos;
317
324
  embeds.forEach((file) => this.addDependency(file));
318
325
  if (opts.mode !== "demo-index") {
319
- getDemoSourceFiles(dependencyDemos).forEach(
320
- (file) => this.addDependency(file)
321
- );
326
+ getDemoSourceFiles(demos).forEach((file) => this.addDependency(file));
322
327
  }
323
328
  if (this.resourceQuery.includes("watch=parent"))
324
329
  return null;
@@ -382,7 +387,7 @@ function mdLoader(content) {
382
387
  baseCacheKey,
383
388
  getDepsCacheKey(depsMapping[this.resourcePath])
384
389
  ].join(":");
385
- const cacheRet = cache.getSync(cacheKey, "");
390
+ const cacheRet = getMdLoaderCacheSync(cache, cacheKey, "");
386
391
  if (cacheRet) {
387
392
  cb(null, emit.call(this, opts, cacheRet));
388
393
  return;
@@ -410,3 +415,7 @@ function mdLoader(content) {
410
415
  delete deferrer[cacheKey];
411
416
  }).catch(cb);
412
417
  }
418
+ // Annotate the CommonJS export names for ESM import in node:
419
+ 0 && (module.exports = {
420
+ getMdLoaderCacheSync
421
+ });
@@ -48,13 +48,7 @@ var isElement;
48
48
  var DEMO_NODE_CONTAINER = "$demo-container";
49
49
  var DEMO_PROP_VALUE_KEY = "$demo-prop-value-key";
50
50
  var DEMO_LOADER_PLACEHOLDER = "__DUMI_DEMO_LOADER__";
51
- var DEMO_LOADER_PLACEHOLDER_RE = new RegExp(
52
- `"${DEMO_LOADER_PLACEHOLDER}:([^"]+)"`,
53
- "g"
54
- );
55
- var getDemoLoaderPlaceholder = (id) => `${DEMO_LOADER_PLACEHOLDER}:${encodeURIComponent(
56
- id
57
- )}`;
51
+ var DEMO_LOADER_PLACEHOLDER_VALUE = DEMO_LOADER_PLACEHOLDER;
58
52
  var DUMI_DEMO_TAG = "DumiDemo";
59
53
  var DUMI_DEMO_GRID_TAG = "DumiDemoGrid";
60
54
  var SKIP_DEMO_PARSE = "pure";
@@ -258,97 +252,106 @@ function rehypeDemo(opts) {
258
252
  }
259
253
  const propDemo = { id: parseOpts.id };
260
254
  if (opts.useUtoopackDemoHMR) {
261
- propDemo.loader = getDemoLoaderPlaceholder(parseOpts.id);
255
+ propDemo.loader = DEMO_LOADER_PLACEHOLDER_VALUE;
262
256
  }
263
257
  demoIds.push(parseOpts.id);
264
258
  deferrers.push(
265
259
  (0, import_block.default)({
266
260
  ...parseOpts,
267
261
  cacheable: opts.useUtoopackDemoHMR
268
- }).then(async ({ asset, resolveMap, frontmatter }) => {
269
- var _a2, _b2, _c2;
270
- if (demoIds.indexOf(parseOpts.id) !== demoIds.lastIndexOf(parseOpts.id)) {
271
- const startLine = (_a2 = node.position) == null ? void 0 : _a2.start.line;
272
- const suffix = startLine ? `:${startLine}` : "";
273
- import_plugin_utils.logger.warn(
274
- `Duplicate demo id found due to filename conflicts, please consider adding a unique id to code tag to resolve this.
262
+ }).then(
263
+ async ({ asset, resolveMap, frontmatter }) => {
264
+ var _a2, _b2, _c2;
265
+ if (demoIds.indexOf(parseOpts.id) !== demoIds.lastIndexOf(parseOpts.id)) {
266
+ const startLine = (_a2 = node.position) == null ? void 0 : _a2.start.line;
267
+ const suffix = startLine ? `:${startLine}` : "";
268
+ import_plugin_utils.logger.warn(
269
+ `Duplicate demo id found due to filename conflicts, please consider adding a unique id to code tag to resolve this.
275
270
  at ${opts.fileAbsPath}${suffix}`
271
+ );
272
+ }
273
+ const { src, className, ...restAttrs } = codeNode.properties || {};
274
+ const validAssetAttrs = [
275
+ "title",
276
+ "snapshot",
277
+ "keywords"
278
+ ];
279
+ const techStackOpts = {
280
+ type: codeType,
281
+ mdAbsPath: opts.fileAbsPath,
282
+ fileAbsPath: codeType === "external" ? parseOpts.fileAbsPath : void 0,
283
+ entryPointCode: parseOpts.entryPointCode
284
+ };
285
+ Object.keys(restAttrs).forEach((key) => {
286
+ if (restAttrs[key] === "")
287
+ restAttrs[key] = true;
288
+ });
289
+ const originalProps = Object.assign(
290
+ {},
291
+ frontmatter,
292
+ restAttrs
276
293
  );
277
- }
278
- const { src, className, ...restAttrs } = codeNode.properties || {};
279
- const validAssetAttrs = [
280
- "title",
281
- "snapshot",
282
- "keywords"
283
- ];
284
- const techStackOpts = {
285
- type: codeType,
286
- mdAbsPath: opts.fileAbsPath,
287
- fileAbsPath: codeType === "external" ? parseOpts.fileAbsPath : void 0,
288
- entryPointCode: parseOpts.entryPointCode
289
- };
290
- Object.keys(restAttrs).forEach((key) => {
291
- if (restAttrs[key] === "")
292
- restAttrs[key] = true;
293
- });
294
- const originalProps = Object.assign({}, frontmatter, restAttrs);
295
- validAssetAttrs.forEach((key) => {
296
- if (originalProps[key])
297
- asset[key] = originalProps[key];
298
- });
299
- if (opts.useUtoopackDemoHMR) {
300
- propDemo.version = (0, import_utils.getContentHash)(
301
- JSON.stringify(asset.dependencies)
294
+ validAssetAttrs.forEach((key) => {
295
+ if (originalProps[key])
296
+ asset[key] = originalProps[key];
297
+ });
298
+ if (opts.useUtoopackDemoHMR) {
299
+ propDemo.version = (0, import_utils.getContentHash)(
300
+ JSON.stringify(asset.dependencies)
301
+ );
302
+ }
303
+ if (/ inline/.test(String((_b2 = codeNode.data) == null ? void 0 : _b2.meta)) || originalProps.inline) {
304
+ propDemo.inline = true;
305
+ return {
306
+ // TODO: special id for inline demo
307
+ id: asset.id,
308
+ component,
309
+ renderOpts: {
310
+ rendererPath: runtimeOpts == null ? void 0 : runtimeOpts.rendererPath,
311
+ preflightPath: runtimeOpts == null ? void 0 : runtimeOpts.preflightPath
312
+ }
313
+ };
314
+ }
315
+ Object.assign(
316
+ previewerProps,
317
+ await ((_c2 = techStack.generatePreviewerProps) == null ? void 0 : _c2.call(
318
+ techStack,
319
+ originalProps,
320
+ techStackOpts
321
+ )) || originalProps
302
322
  );
303
- }
304
- if (/ inline/.test(String((_b2 = codeNode.data) == null ? void 0 : _b2.meta)) || originalProps.inline) {
305
- propDemo.inline = true;
323
+ if (previewerProps.description) {
324
+ const { unified } = await import("unified");
325
+ const { default: remarkParse } = await import("remark-parse");
326
+ const { default: remarkGfm } = await import("remark-gfm");
327
+ const { default: remarkRehype } = await import("remark-rehype");
328
+ const { default: rehypeStringify } = await import("rehype-stringify");
329
+ const { convert } = require("html-to-text");
330
+ const result = await unified().use(remarkParse).use(remarkGfm).use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).process(previewerProps.description);
331
+ previewerProps.description = String(result.value);
332
+ asset.description = convert(result.value, {
333
+ wordwrap: false
334
+ });
335
+ }
306
336
  return {
307
- // TODO: special id for inline demo
308
337
  id: asset.id,
309
338
  component,
339
+ asset: techStack.generateMetadata ? await techStack.generateMetadata(asset, techStackOpts) : asset,
340
+ /**
341
+ * keep `generateSources` rather than `generateResolveMap` for compatibility
342
+ */
343
+ resolveMap: techStack.generateSources ? await techStack.generateSources(
344
+ resolveMap,
345
+ techStackOpts
346
+ ) : resolveMap,
310
347
  renderOpts: {
311
348
  rendererPath: runtimeOpts == null ? void 0 : runtimeOpts.rendererPath,
349
+ compilePath: runtimeOpts == null ? void 0 : runtimeOpts.compilePath,
312
350
  preflightPath: runtimeOpts == null ? void 0 : runtimeOpts.preflightPath
313
351
  }
314
352
  };
315
353
  }
316
- Object.assign(
317
- previewerProps,
318
- await ((_c2 = techStack.generatePreviewerProps) == null ? void 0 : _c2.call(
319
- techStack,
320
- originalProps,
321
- techStackOpts
322
- )) || originalProps
323
- );
324
- if (previewerProps.description) {
325
- const { unified } = await import("unified");
326
- const { default: remarkParse } = await import("remark-parse");
327
- const { default: remarkGfm } = await import("remark-gfm");
328
- const { default: remarkRehype } = await import("remark-rehype");
329
- const { default: rehypeStringify } = await import("rehype-stringify");
330
- const { convert } = require("html-to-text");
331
- const result = await unified().use(remarkParse).use(remarkGfm).use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).process(previewerProps.description);
332
- previewerProps.description = String(result.value);
333
- asset.description = convert(result.value, {
334
- wordwrap: false
335
- });
336
- }
337
- return {
338
- id: asset.id,
339
- component,
340
- asset: techStack.generateMetadata ? await techStack.generateMetadata(asset, techStackOpts) : asset,
341
- /**
342
- * keep `generateSources` rather than `generateResolveMap` for compatibility
343
- */
344
- resolveMap: techStack.generateSources ? await techStack.generateSources(resolveMap, techStackOpts) : resolveMap,
345
- renderOpts: {
346
- rendererPath: runtimeOpts == null ? void 0 : runtimeOpts.rendererPath,
347
- compilePath: runtimeOpts == null ? void 0 : runtimeOpts.compilePath,
348
- preflightPath: runtimeOpts == null ? void 0 : runtimeOpts.preflightPath
349
- }
350
- };
351
- })
354
+ )
352
355
  );
353
356
  demosPropData.push({
354
357
  demo: propDemo,
@@ -378,13 +381,15 @@ function rehypeDemo(opts) {
378
381
  await Promise.all(deferrers).then((demos) => {
379
382
  vFile.data.demos = demos;
380
383
  replaceNodes.forEach((node) => {
384
+ const demoLoader = `() => import('${(0, import_plugin_utils.winPath)(
385
+ opts.fileAbsPath
386
+ )}?type=demo')`;
381
387
  let value = JSON.stringify(node.data[DEMO_PROP_VALUE_KEY]);
382
388
  if (opts.useUtoopackDemoHMR) {
383
- value = value.replace(DEMO_LOADER_PLACEHOLDER_RE, (_, demoId) => {
384
- return `() => import('${(0, import_plugin_utils.winPath)(
385
- opts.fileAbsPath
386
- )}?type=demo&demoId=${demoId}')`;
387
- });
389
+ value = value.replace(
390
+ new RegExp(`"${DEMO_LOADER_PLACEHOLDER}"`, "g"),
391
+ demoLoader
392
+ );
388
393
  }
389
394
  if (node.JSXAttributes[0].type === "JSXAttribute") {
390
395
  node.JSXAttributes[0].value = value;
@@ -201,18 +201,14 @@ export function useDemo(
201
201
  /**
202
202
  * get all demos
203
203
  */
204
- export async function getFullDemos(opts: { loadLazy?: boolean } = {}) {
205
- const loadLazy = opts.loadLazy ?? process.env.NODE_ENV === 'production';
206
- const lazyDemoIndexes = loadLazy
207
- ? await loadDemoIndexMap().then((demoIndexMap) =>
208
- Promise.all(
209
- Object.entries(demoIndexMap).map(async ([id, demoIndexGetter]) => ({
210
- id,
211
- demoIndex: await demoIndexGetter?.().catch(() => undefined),
212
- })),
213
- ),
214
- )
215
- : [];
204
+ export async function getFullDemos() {
205
+ const demoIndexMap = await loadDemoIndexMap();
206
+ const lazyDemoIndexes = await Promise.all(
207
+ Object.entries(demoIndexMap).map(async ([id, demoIndexGetter]) => ({
208
+ id,
209
+ demoIndex: await demoIndexGetter?.().catch(() => undefined),
210
+ })),
211
+ );
216
212
  const allDemoIndexes = [
217
213
  ...demoIndexes,
218
214
  ...lazyDemoIndexes,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dumi",
3
- "version": "2.4.38-beta.0",
3
+ "version": "2.4.38-beta.1",
4
4
  "description": "📖 Documentation Generator of React Component",
5
5
  "keywords": [
6
6
  "generator",
package/theme-api.d.ts CHANGED
@@ -309,9 +309,7 @@ export declare const useTabMeta: () =>
309
309
  export declare const openCodeSandbox: (data: IPreviewerProps) => void;
310
310
  export declare const openStackBlitz: (data: IPreviewerProps) => void;
311
311
  export declare function useDemo(id: string): IDemoData | undefined;
312
- export declare function getFullDemos(opts?: {
313
- loadLazy?: boolean;
314
- }): Promise<Record<string, IDemoData>>;
312
+ export declare function getFullDemos(): Promise<Record<string, IDemoData>>;
315
313
  export declare function getRouteMetaById<T extends { syncOnly?: boolean }>(
316
314
  id: string,
317
315
  opts?: T,