@deot/docs-playground 1.1.3 → 1.1.5

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/index.js CHANGED
@@ -1,16 +1,35 @@
1
- import { a as DEFAULT_CDN_URL, i as normalizeCdnURL, n as createBuiltinImports, o as DEFAULT_ENTRY, r as createBuiltinStyles, s as NEW_SFC_CODE } from "./cdn-DEvdGJu2.js";
2
- import { A as PREVIEW_SCROLLER_USE_CODE, C as toErrorText, D as resolveSandboxMessageSource, E as resolveSandboxContainer, M as PREVIEW_SCROLL_HTML_CLASS, N as PREVIEW_SCROLL_RESET_CODE, O as useSandboxAutoHeight, S as formatSandboxRuntimeError, T as isSandboxMessage, _ as removePlaygroundStyleOverride, a as createRuntimeStore, b as setPlaygroundSiteStyles, c as applyPlaygroundImportMapOverride, d as getPlaygroundImportMapOverrides, f as getPlaygroundSiteModules, g as removePlaygroundImportMapOverride, h as isSafePlaygroundHref, i as createRuntimePreviewOptions, j as PREVIEW_SCROLL_CONTENT_CLASS, k as PREVIEW_SCROLLER_IMPORT_CODE, l as applyPlaygroundStyleOverride, m as getPlaygroundStyleOverrides, n as createReplFile, o as toReplFilename, p as getPlaygroundSiteStyles, s as PlaygroundService, t as PLAYGROUND_RUNTIME_CANVAS_BACKGROUND, u as clearPlaygroundMaps, v as setPlaygroundImportMapOverrides, w as useSandboxRuntimeErrorGuard, x as setPlaygroundStyleOverrides, y as setPlaygroundSiteModules } from "./store-D8vwi-HV.js";
3
- import { r as whenSassReady } from "./scss-Co2it4vB.js";
4
- import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineAsyncComponent, defineComponent, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, ref, renderList, toDisplayString, unref, vModelText, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
1
+ import { C as normalizeCdnURL, D as NEW_SFC_CODE, E as DEFAULT_ENTRY, S as createBuiltinStyles, T as DEFAULT_CDN_URL, _ as bindPlaygroundScss, a as transformScript, b as whenSassReady, c as createFileIndex, d as isIgnoredFilename, f as isInsideRoot, g as resolveModulePath, i as rewriteImportMeta, l as getCommonRoot, m as normalizeVirtualPath, n as injectStyle, o as collectBareSpecifiers, p as isRelativeSpecifier, r as removeStyle, s as collectReachableFilenames, w as resolveNpmImport, x as createBuiltinImports } from "./css-DleINdoA.js";
2
+ import * as Vue from "vue";
3
+ import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineAsyncComponent, defineComponent, h, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onErrorCaptured, onMounted, openBlock, provide, ref, renderList, shallowRef, toDisplayString, unref, vModelText, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
4
+ import * as Vc from "@deot/vc";
5
5
  import { Clipboard, Dropdown, DropdownItem, DropdownMenu, Message, Popconfirm, Portal, Scroller, TransitionFade } from "@deot/vc";
6
6
  import { provideLocale, useLocale } from "@deot/docs-locale";
7
7
  import hljs from "highlight.js";
8
- import { Sandbox } from "@vue/repl";
8
+ import { File, Sandbox, useStore } from "@vue/repl";
9
9
  import { EditorView, basicSetup } from "codemirror";
10
10
  import { css } from "@codemirror/lang-css";
11
11
  import { javascript } from "@codemirror/lang-javascript";
12
12
  import { vue } from "@codemirror/lang-vue";
13
13
  import { highlightActiveLine } from "@codemirror/view";
14
+ import { init, parse } from "es-module-lexer";
15
+ import { transform } from "sucrase";
16
+ import * as VueCompiler from "@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js";
17
+ import * as VueRouter from "vue-router";
18
+ import * as Pinia from "pinia";
19
+ import * as VcComponents from "@deot/vc-components";
20
+ import * as VcHooks from "@deot/vc-hooks";
21
+ //#region \0rolldown/runtime.js
22
+ var __defProp = Object.defineProperty;
23
+ var __exportAll = (all, no_symbols) => {
24
+ let target = {};
25
+ for (var name in all) __defProp(target, name, {
26
+ get: all[name],
27
+ enumerable: true
28
+ });
29
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
30
+ return target;
31
+ };
32
+ //#endregion
14
33
  //#region packages/playground/src/highlight.ts
15
34
  var vueHighlight = (api) => ({
16
35
  subLanguage: "xml",
@@ -118,7 +137,7 @@ var PLAYGROUND_ICONS = {
118
137
  };
119
138
  //#endregion
120
139
  //#region packages/playground/src/icon/icon.vue?vue&type=script&setup=true&lang.ts
121
- var _hoisted_1$7 = ["fill", "stroke"];
140
+ var _hoisted_1$8 = ["fill", "stroke"];
122
141
  var _hoisted_2$7 = ["d"];
123
142
  //#endregion
124
143
  //#region packages/playground/src/icon/icon.vue
@@ -150,7 +169,7 @@ var icon_default = /* @__PURE__ */ defineComponent({
150
169
  "stroke-linecap": "round",
151
170
  "stroke-linejoin": "round",
152
171
  "aria-hidden": "true"
153
- }, [createElementVNode("path", { d: icon.value.path }, null, 8, _hoisted_2$7)], 12, _hoisted_1$7);
172
+ }, [createElementVNode("path", { d: icon.value.path }, null, 8, _hoisted_2$7)], 12, _hoisted_1$8);
154
173
  };
155
174
  }
156
175
  });
@@ -159,7 +178,7 @@ var icon_default = /* @__PURE__ */ defineComponent({
159
178
  var github_default = "pre code.hljs{display:block;padding:1em}code.hljs{padding:3px 5px}.hljs{color:#24292e;background:#fff}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#d73a49}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#6f42c1}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id,.hljs-variable{color:#005cc5}.hljs-meta .hljs-string,.hljs-regexp,.hljs-string{color:#032f62}.hljs-built_in,.hljs-symbol{color:#e36209}.hljs-code,.hljs-comment,.hljs-formula{color:#6a737d}.hljs-name,.hljs-quote,.hljs-selector-pseudo,.hljs-selector-tag{color:#22863a}.hljs-subst{color:#24292e}.hljs-section{font-weight:700;color:#005cc5}.hljs-bullet{color:#735c0f}.hljs-emphasis{font-style:italic;color:#24292e}.hljs-strong{font-weight:700;color:#24292e}.hljs-addition{color:#22863a;background-color:#f0fff4}.hljs-deletion{color:#b31d28;background-color:#ffeef0}[data-doc-theme=dark] .hljs,[data-vc-theme=dark] .hljs{color:#c9d1d9;background:#0d1117}[data-doc-theme=dark] .hljs-doctag,[data-doc-theme=dark] .hljs-keyword,[data-doc-theme=dark] .hljs-meta .hljs-keyword,[data-doc-theme=dark] .hljs-template-tag,[data-doc-theme=dark] .hljs-template-variable,[data-doc-theme=dark] .hljs-type,[data-doc-theme=dark] .hljs-variable.language_,[data-vc-theme=dark] .hljs-doctag,[data-vc-theme=dark] .hljs-keyword,[data-vc-theme=dark] .hljs-meta .hljs-keyword,[data-vc-theme=dark] .hljs-template-tag,[data-vc-theme=dark] .hljs-template-variable,[data-vc-theme=dark] .hljs-type,[data-vc-theme=dark] .hljs-variable.language_{color:#ff7b72}[data-doc-theme=dark] .hljs-title,[data-doc-theme=dark] .hljs-title.class_,[data-doc-theme=dark] .hljs-title.function_,[data-vc-theme=dark] .hljs-title,[data-vc-theme=dark] .hljs-title.class_,[data-vc-theme=dark] .hljs-title.function_{color:#d2a8ff}[data-doc-theme=dark] .hljs-attr,[data-doc-theme=dark] .hljs-literal,[data-doc-theme=dark] .hljs-number,[data-doc-theme=dark] .hljs-variable,[data-vc-theme=dark] .hljs-attr,[data-vc-theme=dark] .hljs-literal,[data-vc-theme=dark] .hljs-number,[data-vc-theme=dark] .hljs-variable{color:#79c0ff}[data-doc-theme=dark] .hljs-regexp,[data-doc-theme=dark] .hljs-string,[data-vc-theme=dark] .hljs-regexp,[data-vc-theme=dark] .hljs-string{color:#a5d6ff}[data-doc-theme=dark] .hljs-code,[data-doc-theme=dark] .hljs-comment,[data-vc-theme=dark] .hljs-code,[data-vc-theme=dark] .hljs-comment{color:#8b949e}[data-doc-theme=dark] .hljs-name,[data-doc-theme=dark] .hljs-selector-tag,[data-vc-theme=dark] .hljs-name,[data-vc-theme=dark] .hljs-selector-tag{color:#7ee787}";
160
179
  //#endregion
161
180
  //#region packages/playground/src/core/code-preview/code-preview.scss?inline
162
- var code_preview_default$1 = ".docs-code-preview{position:relative;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;min-height:0;overflow:hidden;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa));border-radius:8px}.docs-code-preview__language{z-index:1;min-width:28px;padding:0 8px;font-size:12px;line-height:18px;white-space:nowrap;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-transition:opacity .15s ease;transition:opacity .15s ease}.docs-code-preview__copy,.docs-code-preview__language{position:absolute;top:6px;right:12px;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;height:28px;color:var(--docs-foreground-color-mute,var(--vc-color-dark-extralight,#71717a));-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center}.docs-code-preview__copy{z-index:2;width:28px;padding:0;pointer-events:none;cursor:pointer;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa));border:1px solid var(--docs-border-color,var(--vc-color-light-deeper,#d4d4d8));border-radius:8px;opacity:0;-webkit-transition:opacity .15s ease,background-color .15s ease;transition:opacity .15s ease,background-color .15s ease}.docs-code-preview__copy:hover{background:var(--docs-background-color,var(--vc-background-color-light,#fff))}.docs-code-preview__copy:focus-visible{pointer-events:auto;opacity:1}.docs-code-preview:has(.docs-code-preview__copy:focus-visible) .docs-code-preview__language,.docs-code-preview:hover .docs-code-preview__language{opacity:0}.docs-code-preview:has(.docs-code-preview__copy:focus-visible) .docs-code-preview__copy,.docs-code-preview:hover .docs-code-preview__copy{pointer-events:auto;opacity:1}.docs-code-preview__scroller{width:100%;height:100%;min-width:0;min-height:0;-webkit-box-flex:1;-webkit-flex:1 1 auto;-ms-flex:1 1 auto;flex:1 1 auto}.docs-code-preview__code{width:-webkit-max-content;width:-moz-max-content;width:max-content;margin:0}.docs-code-preview__code,.docs-code-preview__code code.hljs{min-width:100%;min-height:100%;overflow:visible;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa))}.docs-code-preview__code code.hljs{display:block;padding:12px 96px 12px 24px;-webkit-box-sizing:border-box;box-sizing:border-box}";
181
+ var code_preview_default$1 = ".docs-code-preview{position:relative;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;min-height:0;overflow:hidden;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa));border-radius:8px}.docs-code-preview__language{z-index:1;min-width:28px;padding:0 8px;font-size:12px;line-height:18px;white-space:nowrap;-webkit-box-sizing:border-box;box-sizing:border-box;-webkit-transition:opacity .15s;transition:opacity .15s}.docs-code-preview__copy,.docs-code-preview__language{position:absolute;top:6px;right:12px;display:-webkit-inline-box;display:-webkit-inline-flex;display:-ms-inline-flexbox;display:inline-flex;height:28px;color:var(--docs-foreground-color-mute,var(--vc-color-dark-extralight,#71717a));-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center}.docs-code-preview__copy{z-index:2;width:28px;padding:0;pointer-events:none;cursor:pointer;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa));border:1px solid var(--docs-border-color,var(--vc-color-light-deeper,#d4d4d8));border-radius:8px;opacity:0;-webkit-transition:opacity .15s,background-color .15s;transition:opacity .15s,background-color .15s}.docs-code-preview__copy:hover{background:var(--docs-background-color,var(--vc-background-color-light,#fff))}.docs-code-preview__copy:focus-visible{pointer-events:auto;opacity:1}.docs-code-preview:has(.docs-code-preview__copy:focus-visible) .docs-code-preview__language,.docs-code-preview:hover .docs-code-preview__language{opacity:0}.docs-code-preview:has(.docs-code-preview__copy:focus-visible) .docs-code-preview__copy,.docs-code-preview:hover .docs-code-preview__copy{pointer-events:auto;opacity:1}.docs-code-preview__scroller{width:100%;height:100%;min-width:0;min-height:0;-webkit-box-flex:1;-webkit-flex:1 1 auto;-ms-flex:1 1 auto;flex:1 1 auto}.docs-code-preview__code{width:-webkit-max-content;width:-moz-max-content;width:max-content;margin:0}.docs-code-preview__code,.docs-code-preview__code code.hljs{min-width:100%;min-height:100%;overflow:visible;background:var(--docs-background-color-soft,var(--vc-background-color,#f7f8fa))}.docs-code-preview__code code.hljs{display:block;padding:12px 96px 12px 24px;-webkit-box-sizing:border-box;box-sizing:border-box}";
163
182
  //#endregion
164
183
  //#region packages/playground/src/core/code-preview/style.ts
165
184
  var CODE_PREVIEW_STYLE_ID = "docs-code-preview-style";
@@ -176,7 +195,7 @@ var ensureCodePreviewStyle = () => {
176
195
  };
177
196
  //#endregion
178
197
  //#region packages/playground/src/core/code-preview/code-preview.vue?vue&type=script&setup=true&lang.ts
179
- var _hoisted_1$6 = { class: "docs-code-preview" };
198
+ var _hoisted_1$7 = { class: "docs-code-preview" };
180
199
  var _hoisted_2$6 = ["title"];
181
200
  var _hoisted_3$6 = { class: "docs-code-preview__code" };
182
201
  var _hoisted_4$6 = ["innerHTML"];
@@ -210,7 +229,7 @@ var code_preview_default = /* @__PURE__ */ defineComponent({
210
229
  const highlightLanguage = computed(() => props.language || resolveHighlightLanguage(props.filename));
211
230
  const highlightedCode = computed(() => highlightCodeByLanguage(props.code, highlightLanguage.value));
212
231
  return (_ctx, _cache) => {
213
- return openBlock(), createElementBlock("div", _hoisted_1$6, [
232
+ return openBlock(), createElementBlock("div", _hoisted_1$7, [
214
233
  languageLabel.value ? (openBlock(), createElementBlock("span", {
215
234
  key: 0,
216
235
  class: "docs-code-preview__language",
@@ -250,7 +269,7 @@ var code_preview_default = /* @__PURE__ */ defineComponent({
250
269
  });
251
270
  //#endregion
252
271
  //#region packages/playground/src/core/files-preview/files-preview.vue?vue&type=script&setup=true&lang.ts
253
- var _hoisted_1$5 = { class: "docs-playground-files" };
272
+ var _hoisted_1$6 = { class: "docs-playground-files" };
254
273
  var _hoisted_2$5 = { class: "docs-playground-files__tabs-row" };
255
274
  var _hoisted_3$5 = ["data-filename", "onClick"];
256
275
  var _hoisted_4$5 = {
@@ -279,7 +298,7 @@ var files_preview_default = /* @__PURE__ */ defineComponent({
279
298
  if (filename !== props.activeFilename) emit("active-change", filename);
280
299
  };
281
300
  return (_ctx, _cache) => {
282
- return openBlock(), createElementBlock("div", _hoisted_1$5, [createElementVNode("div", _hoisted_2$5, [createVNode(unref(Scroller), {
301
+ return openBlock(), createElementBlock("div", _hoisted_1$6, [createElementVNode("div", _hoisted_2$5, [createVNode(unref(Scroller), {
283
302
  class: "docs-playground-files__scroller",
284
303
  "auto-resize": true,
285
304
  native: false,
@@ -424,7 +443,7 @@ var Drag = class {
424
443
  };
425
444
  //#endregion
426
445
  //#region packages/playground/src/editor/editor.vue?vue&type=script&setup=true&lang.ts
427
- var _hoisted_1$4 = { class: "docs-playground-editor" };
446
+ var _hoisted_1$5 = { class: "docs-playground-editor" };
428
447
  var _hoisted_2$4 = ["title"];
429
448
  var _hoisted_3$4 = { class: "docs-playground-editor__files" };
430
449
  var _hoisted_4$4 = [
@@ -436,7 +455,7 @@ var _hoisted_5$4 = ["onKeydown"];
436
455
  var _hoisted_6$3 = ["title"];
437
456
  var _hoisted_7$3 = ["title", "aria-label"];
438
457
  var _hoisted_8$2 = ["title", "aria-label"];
439
- var _hoisted_9$2 = { class: "docs-playground-editor__actions" };
458
+ var _hoisted_9$1 = { class: "docs-playground-editor__actions" };
440
459
  var _hoisted_10$1 = ["title"];
441
460
  var _hoisted_11$1 = ["title", "disabled"];
442
461
  var _hoisted_12$1 = {
@@ -674,7 +693,7 @@ var Editor = new Portal(/* @__PURE__ */ defineComponent({
674
693
  editor.value?.destroy();
675
694
  });
676
695
  return (_ctx, _cache) => {
677
- return openBlock(), createElementBlock("div", _hoisted_1$4, [createVNode(unref(TransitionFade), { onAfterLeave: handleHide }, {
696
+ return openBlock(), createElementBlock("div", _hoisted_1$5, [createVNode(unref(TransitionFade), { onAfterLeave: handleHide }, {
678
697
  default: withCtx(() => [withDirectives(createElementVNode("div", {
679
698
  ref_key: "wrapper",
680
699
  ref: wrapper,
@@ -752,7 +771,7 @@ var Editor = new Portal(/* @__PURE__ */ defineComponent({
752
771
  ], 64))], 42, _hoisted_4$4);
753
772
  }), 128))]),
754
773
  _: 1
755
- }, 512), createElementVNode("div", _hoisted_9$2, [createElementVNode("button", {
774
+ }, 512), createElementVNode("div", _hoisted_9$1, [createElementVNode("button", {
756
775
  type: "button",
757
776
  title: unref(t)("playground.editor.createFile"),
758
777
  onClick: handleCreate
@@ -830,6 +849,316 @@ var resolvePlaygroundTitleId = (title, explicitId = "", isOccupied) => {
830
849
  while (isOccupied(`${base}-${index}`)) index += 1;
831
850
  return `${base}-${index}`;
832
851
  };
852
+ //#endregion
853
+ //#region packages/playground/src/core/preview-scroll.ts
854
+ /** iframe 包装成功后挂在 `html` 上,供样式与 auto-height 识别。 */
855
+ var PREVIEW_SCROLL_HTML_CLASS = "docs-playground-preview-scroll";
856
+ /** Scroller 内容节点 class,auto-height 优先测量该节点。 */
857
+ var PREVIEW_SCROLL_CONTENT_CLASS = "docs-playground-preview-scroll__content";
858
+ /** 重评时先清掉 html class,避免 `await import` 期间仍套用 `height:100%`。 */
859
+ var PREVIEW_SCROLL_RESET_CODE = `document.documentElement.classList.remove("${PREVIEW_SCROLL_HTML_CLASS}");`;
860
+ /** 动态探测 `@deot/vc`;失败时为空对象,不阻断 DocsLink / 预览挂载。 */
861
+ var PREVIEW_SCROLLER_IMPORT_CODE = "const __docsVc=await import(\"@deot/vc\").catch(()=>({}))";
862
+ /**
863
+ * Vue 的 `mount` 闭包的是 `createApp(root)` 时的根组件,改 `app._component` 不会生效。
864
+ * 因此劫持 `app.mount`:等全部 useCode 注册完后,再 `createApp` 包一层 Scroller。
865
+ * 前导分号避免接在 `app.component(...)` 后被 ASI 解析成调用返回值。
866
+ */
867
+ var PREVIEW_SCROLLER_USE_CODE = [
868
+ ";(()=>{",
869
+ PREVIEW_SCROLL_RESET_CODE,
870
+ "const __DocsScroller=__docsVc&&__docsVc.Scroller;",
871
+ "if(!__DocsScroller)return;",
872
+ "const UserApp=app._component;",
873
+ "app.mount=(container,...rest)=>{",
874
+ "const next=_createApp({",
875
+ "name:\"DocsPreviewRoot\",",
876
+ "setup(){return()=>__docsH(__DocsScroller,{",
877
+ "height:\"100%\",",
878
+ "native:false,",
879
+ "autoResize:true,",
880
+ "showBar:true,",
881
+ `contentClass:"${PREVIEW_SCROLL_CONTENT_CLASS}"`,
882
+ "},{default:()=>__docsH(UserApp)})}",
883
+ "});",
884
+ "next.config.errorHandler=app.config.errorHandler;",
885
+ "if(app._context&&next._context){",
886
+ "if(app._context.components)Object.assign(next._context.components,app._context.components);",
887
+ "if(app._context.directives)Object.assign(next._context.directives,app._context.directives);",
888
+ "Object.assign(next._context.provides,app._context.provides);",
889
+ "next._context.mixins.push(...app._context.mixins);",
890
+ "}",
891
+ "window.__app__=next;",
892
+ `document.documentElement.classList.add("${PREVIEW_SCROLL_HTML_CLASS}");`,
893
+ "return next.mount(container,...rest)",
894
+ "}",
895
+ "})()"
896
+ ].join("");
897
+ var PREVIEW_SCROLLER_STYLE = [
898
+ `html.${PREVIEW_SCROLL_HTML_CLASS},`,
899
+ `html.${PREVIEW_SCROLL_HTML_CLASS} body,`,
900
+ `html.${PREVIEW_SCROLL_HTML_CLASS} #app{`,
901
+ "height:100%;min-height:100%;margin:0;overflow:hidden",
902
+ "}",
903
+ `html.${PREVIEW_SCROLL_HTML_CLASS} #app>.vc-scroller{`,
904
+ "height:100%;max-height:100%;box-sizing:border-box",
905
+ "}"
906
+ ].join("");
907
+ var resolveSandboxContainer = (sandbox) => sandbox?.container ? unref(sandbox.container) : null;
908
+ var resolveSandboxMessageSource = (sandbox) => {
909
+ const exposed = sandbox?.messageSource ? unref(sandbox.messageSource) : null;
910
+ if (exposed && typeof exposed.postMessage === "function") return exposed;
911
+ return (resolveSandboxContainer(sandbox)?.querySelector("iframe"))?.contentWindow ?? null;
912
+ };
913
+ /**
914
+ * iframe 的 contentWindow 在 jsdom 里可能是 null,仍要和旧的元素校验一致。
915
+ * 直接渲染会暴露真实的 messageSource。
916
+ * @param sandbox
917
+ * @param event
918
+ */
919
+ var isSandboxMessage = (sandbox, event) => {
920
+ const explicit = sandbox?.messageSource ? unref(sandbox.messageSource) : null;
921
+ if (explicit && typeof explicit.postMessage === "function") return event.source === explicit;
922
+ const iframe = resolveSandboxContainer(sandbox)?.querySelector("iframe");
923
+ return !!iframe && event.source === iframe.contentWindow;
924
+ };
925
+ var resolveScrollContent = (iframeDocument) => {
926
+ if (!iframeDocument.documentElement.classList.contains("docs-playground-preview-scroll")) return null;
927
+ return iframeDocument.querySelector(`.${PREVIEW_SCROLL_CONTENT_CLASS}`);
928
+ };
929
+ var useSandboxAutoHeight = (sandboxRef) => {
930
+ const height = ref(24);
931
+ let container = null;
932
+ let iframe = null;
933
+ let containerObserver = null;
934
+ let contentObserver = null;
935
+ let scrollMountObserver = null;
936
+ let observedScrollNode = null;
937
+ let frameId = 0;
938
+ const cancelMeasure = () => {
939
+ if (!frameId) return;
940
+ cancelAnimationFrame(frameId);
941
+ frameId = 0;
942
+ };
943
+ const measureDocumentContent = (iframeWindow, iframeDocument) => {
944
+ const { body, documentElement } = iframeDocument;
945
+ const bodyStyle = iframeWindow.getComputedStyle(body);
946
+ const bodyMargins = (Number.parseFloat(bodyStyle.marginTop) || 0) + (Number.parseFloat(bodyStyle.marginBottom) || 0);
947
+ const rootTop = documentElement.getBoundingClientRect().top;
948
+ const bodyRect = body.getBoundingClientRect();
949
+ const collapsedTop = Math.max(0, bodyRect.top - rootTop);
950
+ let childrenBottom = 0;
951
+ for (const child of body.children) {
952
+ if (iframeWindow.getComputedStyle(child).position === "fixed") continue;
953
+ const rect = child.getBoundingClientRect();
954
+ const marginBottom = Number.parseFloat(iframeWindow.getComputedStyle(child).marginBottom) || 0;
955
+ childrenBottom = Math.max(childrenBottom, rect.bottom + marginBottom - rootTop);
956
+ }
957
+ const scrollHeight = Math.max(body.scrollHeight, documentElement.scrollHeight);
958
+ const overflowingHeight = scrollHeight > (iframe?.clientHeight || 0) + 1 ? scrollHeight : 0;
959
+ return Math.ceil(Math.max(body.offsetHeight + bodyMargins + collapsedTop, bodyRect.height + bodyMargins + collapsedTop, childrenBottom, overflowingHeight));
960
+ };
961
+ const measureScrollContent = (scrollContent) => {
962
+ const contentStyle = scrollContent.ownerDocument.defaultView?.getComputedStyle(scrollContent);
963
+ const margins = contentStyle ? (Number.parseFloat(contentStyle.marginTop) || 0) + (Number.parseFloat(contentStyle.marginBottom) || 0) : 0;
964
+ let childrenBottom = 0;
965
+ const rootTop = scrollContent.getBoundingClientRect().top;
966
+ for (const child of scrollContent.children) {
967
+ const rect = child.getBoundingClientRect();
968
+ const marginBottom = Number.parseFloat(scrollContent.ownerDocument.defaultView?.getComputedStyle(child).marginBottom || "0") || 0;
969
+ childrenBottom = Math.max(childrenBottom, rect.bottom + marginBottom - rootTop);
970
+ }
971
+ return Math.ceil(Math.max(scrollContent.scrollHeight + margins, scrollContent.offsetHeight + margins, childrenBottom + margins));
972
+ };
973
+ const isPendingPreviewApp = (iframeDocument) => {
974
+ const app = iframeDocument.getElementById("app");
975
+ return app ? app.childElementCount === 0 : !!iframe?.srcdoc;
976
+ };
977
+ const releaseBootstrapHeight = (target) => {
978
+ nextTick(() => {
979
+ if (iframe === target) target.style.height = "100%";
980
+ });
981
+ };
982
+ const measureElementChildren = (root) => {
983
+ const view = root.ownerDocument.defaultView || window;
984
+ const rootTop = root.getBoundingClientRect().top;
985
+ let childrenBottom = 0;
986
+ for (const child of root.children) {
987
+ if (view.getComputedStyle(child).position === "fixed") continue;
988
+ const rect = child.getBoundingClientRect();
989
+ const marginBottom = Number.parseFloat(view.getComputedStyle(child).marginBottom) || 0;
990
+ childrenBottom = Math.max(childrenBottom, rect.bottom + marginBottom - rootTop);
991
+ }
992
+ const overflowingHeight = root.scrollHeight > root.clientHeight + 1 ? root.scrollHeight : 0;
993
+ const naturalHeight = root.classList.contains("docs-playground-local__mount--auto") ? root.offsetHeight : 0;
994
+ return Math.ceil(Math.max(childrenBottom, overflowingHeight, naturalHeight));
995
+ };
996
+ const measureLocalContainer = () => {
997
+ if (!container) return;
998
+ const scrollContent = container.querySelector(`.${PREVIEW_SCROLL_CONTENT_CLASS}`);
999
+ const mount = container.querySelector(".docs-playground-local__mount");
1000
+ const target = scrollContent || mount;
1001
+ if (!target || !scrollContent && target.childElementCount === 0) return;
1002
+ const contentHeight = scrollContent ? measureScrollContent(scrollContent) : measureElementChildren(target);
1003
+ const nextHeight = Math.max(contentHeight, 24);
1004
+ if (height.value !== nextHeight) height.value = nextHeight;
1005
+ };
1006
+ const isLocalContainer = (element) => element?.classList.contains("docs-playground-local") === true;
1007
+ const measure = () => {
1008
+ frameId = 0;
1009
+ if (isLocalContainer(container)) {
1010
+ measureLocalContainer();
1011
+ return;
1012
+ }
1013
+ if (!iframe) return;
1014
+ try {
1015
+ const iframeWindow = iframe.contentWindow;
1016
+ const iframeDocument = iframe.contentDocument;
1017
+ if (!iframeWindow || !iframeDocument?.body) return;
1018
+ const scrollContent = resolveScrollContent(iframeDocument);
1019
+ if (!scrollContent && isPendingPreviewApp(iframeDocument)) return;
1020
+ const contentHeight = scrollContent ? measureScrollContent(scrollContent) : measureDocumentContent(iframeWindow, iframeDocument);
1021
+ const nextHeight = Math.max(contentHeight, 24);
1022
+ if (height.value !== nextHeight) height.value = nextHeight;
1023
+ releaseBootstrapHeight(iframe);
1024
+ } catch {
1025
+ if (height.value !== 24) height.value = 24;
1026
+ }
1027
+ };
1028
+ const scheduleMeasure = () => {
1029
+ if (frameId) return;
1030
+ frameId = requestAnimationFrame(measure);
1031
+ };
1032
+ const disconnectContent = () => {
1033
+ contentObserver?.disconnect();
1034
+ contentObserver = null;
1035
+ scrollMountObserver?.disconnect();
1036
+ scrollMountObserver = null;
1037
+ observedScrollNode = null;
1038
+ cancelMeasure();
1039
+ };
1040
+ const observeContent = () => {
1041
+ disconnectContent();
1042
+ if (!iframe) return;
1043
+ try {
1044
+ const iframeWindow = iframe.contentWindow;
1045
+ const iframeDocument = iframe.contentDocument;
1046
+ const Observer = iframeWindow?.ResizeObserver;
1047
+ if (!iframeWindow || !iframeDocument?.body || !Observer) {
1048
+ scheduleMeasure();
1049
+ return;
1050
+ }
1051
+ const observer = new Observer(scheduleMeasure);
1052
+ observer.observe(iframeDocument.documentElement);
1053
+ observer.observe(iframeDocument.body);
1054
+ contentObserver = observer;
1055
+ const attachScrollContent = (node) => {
1056
+ if (!node || !contentObserver) return false;
1057
+ if (observedScrollNode === node) return true;
1058
+ if (observedScrollNode) contentObserver.unobserve(observedScrollNode);
1059
+ observedScrollNode = node;
1060
+ contentObserver.observe(node);
1061
+ return true;
1062
+ };
1063
+ const syncScrollContent = () => {
1064
+ attachScrollContent(resolveScrollContent(iframeDocument));
1065
+ scheduleMeasure();
1066
+ };
1067
+ scrollMountObserver = new MutationObserver(syncScrollContent);
1068
+ scrollMountObserver.observe(iframeDocument.documentElement, {
1069
+ attributes: true,
1070
+ attributeFilter: ["class"]
1071
+ });
1072
+ scrollMountObserver.observe(iframeDocument.body, {
1073
+ childList: true,
1074
+ subtree: true
1075
+ });
1076
+ syncScrollContent();
1077
+ } catch {
1078
+ if (height.value !== 24) height.value = 24;
1079
+ }
1080
+ };
1081
+ const handleIframeLoad = () => observeContent();
1082
+ const setIframe = (nextIframe) => {
1083
+ if (iframe === nextIframe) return;
1084
+ iframe?.removeEventListener("load", handleIframeLoad);
1085
+ disconnectContent();
1086
+ iframe = nextIframe;
1087
+ if (!iframe) {
1088
+ height.value = 24;
1089
+ return;
1090
+ }
1091
+ iframe.addEventListener("load", handleIframeLoad);
1092
+ iframe.style.height = `${Math.max(window.innerHeight, 24)}px`;
1093
+ observeContent();
1094
+ };
1095
+ const observeLocal = () => {
1096
+ disconnectContent();
1097
+ if (!container || typeof ResizeObserver === "undefined") {
1098
+ scheduleMeasure();
1099
+ return;
1100
+ }
1101
+ const observer = new ResizeObserver(scheduleMeasure);
1102
+ observer.observe(container);
1103
+ const mount = container.querySelector(".docs-playground-local__mount");
1104
+ if (mount) observer.observe(mount);
1105
+ contentObserver = observer;
1106
+ scrollMountObserver = new MutationObserver(() => {
1107
+ const nextMount = container?.querySelector(".docs-playground-local__mount");
1108
+ if (nextMount && contentObserver) {
1109
+ contentObserver.observe(nextMount);
1110
+ for (const child of nextMount.children) contentObserver.observe(child);
1111
+ }
1112
+ scheduleMeasure();
1113
+ });
1114
+ scrollMountObserver.observe(container, {
1115
+ childList: true,
1116
+ subtree: true
1117
+ });
1118
+ scheduleMeasure();
1119
+ };
1120
+ const syncIframe = () => {
1121
+ if (isLocalContainer(container)) {
1122
+ iframe?.removeEventListener("load", handleIframeLoad);
1123
+ iframe = null;
1124
+ observeLocal();
1125
+ return;
1126
+ }
1127
+ setIframe(container?.querySelector("iframe") || null);
1128
+ };
1129
+ const setContainer = (nextContainer) => {
1130
+ if (container === nextContainer) return;
1131
+ containerObserver?.disconnect();
1132
+ containerObserver = null;
1133
+ disconnectContent();
1134
+ iframe?.removeEventListener("load", handleIframeLoad);
1135
+ iframe = null;
1136
+ container = nextContainer;
1137
+ if (!container) {
1138
+ height.value = 24;
1139
+ return;
1140
+ }
1141
+ if (isLocalContainer(container)) {
1142
+ observeLocal();
1143
+ return;
1144
+ }
1145
+ containerObserver = new MutationObserver(syncIframe);
1146
+ containerObserver.observe(container, {
1147
+ childList: true,
1148
+ subtree: true
1149
+ });
1150
+ syncIframe();
1151
+ };
1152
+ watch(() => resolveSandboxContainer(sandboxRef.value), setContainer, {
1153
+ flush: "post",
1154
+ immediate: true
1155
+ });
1156
+ onBeforeUnmount(() => {
1157
+ setContainer(null);
1158
+ cancelMeasure();
1159
+ });
1160
+ return height;
1161
+ };
833
1162
  var resolvePreviewBoxHeight = (contentHeight, verticalInset = 0, borderWidth = 1) => {
834
1163
  const content = Number.isFinite(contentHeight) ? Math.max(0, contentHeight) : 0;
835
1164
  const inset = Number.isFinite(verticalInset) ? Math.max(0, verticalInset) : 0;
@@ -908,6 +1237,68 @@ var scrollPlaygroundToViewportStart = (el) => {
908
1237
  });
909
1238
  };
910
1239
  //#endregion
1240
+ //#region packages/playground/src/core/runtime/error-guard.ts
1241
+ var UNKNOWN_RUNTIME_ERROR = "运行时发生未知错误";
1242
+ var MODULE_SPECIFIER_RE = /Failed to resolve module specifier|Error resolving module specifier/u;
1243
+ var forwardSandboxRuntimeError = (event) => {
1244
+ if (!(event instanceof ErrorEvent) || event.error != null || !event.message) return;
1245
+ event.stopImmediatePropagation();
1246
+ if (event.message === "ResizeObserver loop limit exceeded" || event.message === "ResizeObserver loop completed with undelivered notifications.") return;
1247
+ window.parent.postMessage({
1248
+ action: "error",
1249
+ value: event.message
1250
+ }, "*");
1251
+ };
1252
+ var SANDBOX_RUNTIME_ERROR_CAPTURE_HTML = [
1253
+ "<script>",
1254
+ `window.addEventListener('error', ${forwardSandboxRuntimeError.toString()}, true);`,
1255
+ "<\/script>"
1256
+ ].join("\n");
1257
+ var toRuntimeErrorMessage = (value, message) => {
1258
+ if (typeof value === "string" && value) return value;
1259
+ if (value instanceof Error && value.message) return value.message;
1260
+ if (value && typeof value === "object" && "message" in value) {
1261
+ const valueMessage = value.message;
1262
+ if (typeof valueMessage === "string" && valueMessage) return valueMessage;
1263
+ }
1264
+ if (typeof message === "string" && message) return message;
1265
+ if (value !== null && value !== void 0) try {
1266
+ return String(value);
1267
+ } catch {
1268
+ return UNKNOWN_RUNTIME_ERROR;
1269
+ }
1270
+ return UNKNOWN_RUNTIME_ERROR;
1271
+ };
1272
+ var normalizeRuntimeErrorMessage = (data) => {
1273
+ if (!data || typeof data !== "object") return false;
1274
+ const message = data;
1275
+ if (message.action !== "error") return false;
1276
+ message.value = toRuntimeErrorMessage(message.value, message.message);
1277
+ return true;
1278
+ };
1279
+ var toErrorText = (value) => {
1280
+ if (typeof value === "string" && value) return value;
1281
+ if (value instanceof Error && value.message) return value.message;
1282
+ return "";
1283
+ };
1284
+ var formatSandboxRuntimeError = (message, importMapTip) => {
1285
+ if (!MODULE_SPECIFIER_RE.test(message)) return message;
1286
+ return `${message.replace(/\. Relative references must.*$/u, "").replace(/\.$/u, "")}.\n${importMapTip}`;
1287
+ };
1288
+ var useSandboxRuntimeErrorGuard = (sandboxRef) => {
1289
+ const error = ref("");
1290
+ if (typeof window === "undefined") return error;
1291
+ const handleMessage = (event) => {
1292
+ const source = resolveSandboxMessageSource(sandboxRef.value);
1293
+ if (!source || event.source !== source) return;
1294
+ if (!normalizeRuntimeErrorMessage(event.data)) return;
1295
+ error.value = event.data.value;
1296
+ };
1297
+ window.addEventListener("message", handleMessage, true);
1298
+ onBeforeUnmount(() => window.removeEventListener("message", handleMessage, true));
1299
+ return error;
1300
+ };
1301
+ //#endregion
911
1302
  //#region packages/playground/src/core/runtime/viewport.ts
912
1303
  var DEFAULT_VIEWPORT_OPTIONS = ["auto", 375];
913
1304
  var isValidViewport = (viewport) => {
@@ -1158,7 +1549,7 @@ function usePreviewHeightBridge(sandbox, maxHeight = () => Infinity) {
1158
1549
  }
1159
1550
  //#endregion
1160
1551
  //#region packages/playground/src/core/runtime/toolbar.vue?vue&type=script&setup=true&lang.ts
1161
- var _hoisted_1$3 = { class: "docs-playground__tools" };
1552
+ var _hoisted_1$4 = { class: "docs-playground__tools" };
1162
1553
  var _hoisted_2$3 = {
1163
1554
  key: 0,
1164
1555
  class: "docs-playground__tool-group"
@@ -1181,7 +1572,7 @@ var _hoisted_8$1 = {
1181
1572
  class: "docs-playground__tool-divider",
1182
1573
  "aria-hidden": "true"
1183
1574
  };
1184
- var _hoisted_9$1 = ["aria-label"];
1575
+ var _hoisted_9 = ["aria-label"];
1185
1576
  var _hoisted_10 = [
1186
1577
  "title",
1187
1578
  "aria-label",
@@ -1248,7 +1639,7 @@ var toolbar_default = /* @__PURE__ */ defineComponent({
1248
1639
  if (!enabled) viewportMenuVisible.value = false;
1249
1640
  });
1250
1641
  return (_ctx, _cache) => {
1251
- return openBlock(), createElementBlock("div", _hoisted_1$3, [
1642
+ return openBlock(), createElementBlock("div", _hoisted_1$4, [
1252
1643
  __props.showRuntimeActions ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
1253
1644
  __props.viewportOptions.length > 1 ? (openBlock(), createElementBlock("div", _hoisted_2$3, [createVNode(unref(Dropdown), {
1254
1645
  modelValue: viewportMenuVisible.value,
@@ -1354,7 +1745,7 @@ var toolbar_default = /* @__PURE__ */ defineComponent({
1354
1745
  "aria-pressed": item === __props.activeView,
1355
1746
  onClick: ($event) => emit("view-change", item)
1356
1747
  }, toDisplayString(getViewLabel(item)), 11, _hoisted_10);
1357
- }), 128))], 8, _hoisted_9$1)) : createCommentVNode("v-if", true),
1748
+ }), 128))], 8, _hoisted_9)) : createCommentVNode("v-if", true),
1358
1749
  __props.showClose && (__props.showRuntimeActions || showViews.value) ? (openBlock(), createElementBlock("span", _hoisted_11)) : createCommentVNode("v-if", true),
1359
1750
  __props.showClose ? (openBlock(), createElementBlock("button", {
1360
1751
  key: 3,
@@ -1373,8 +1764,540 @@ var toolbar_default = /* @__PURE__ */ defineComponent({
1373
1764
  }
1374
1765
  });
1375
1766
  //#endregion
1767
+ //#region packages/playground/src/import-map.ts
1768
+ /**
1769
+ * 站点级同步内存:`$docs.modules` / `$docs.styles` 与管理页 import、CSS 覆盖。
1770
+ */
1771
+ var normalize = (value) => value.trim();
1772
+ var isSafePlaygroundHref = (href) => {
1773
+ const next = href.trim();
1774
+ if (!next) return false;
1775
+ if (/^https?:\/\//iu.test(next)) return true;
1776
+ return next.startsWith("/") && !next.startsWith("//");
1777
+ };
1778
+ var filterSafeHrefs = (value = {}) => Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string" && isSafePlaygroundHref(entry[1])));
1779
+ var sanitizeMap = (value = {}) => filterSafeHrefs(Object.fromEntries(Object.entries(value).map(([alias, url]) => [normalize(alias), normalize(url)]).filter(([alias]) => Boolean(alias))));
1780
+ var createMapStore = () => {
1781
+ let data = {};
1782
+ const snapshot = () => ({ ...data });
1783
+ const drop = (alias) => {
1784
+ if (data[alias] === void 0) return snapshot();
1785
+ const next = { ...data };
1786
+ delete next[alias];
1787
+ data = next;
1788
+ return snapshot();
1789
+ };
1790
+ return {
1791
+ get: snapshot,
1792
+ set: (value = {}) => {
1793
+ data = sanitizeMap(value);
1794
+ },
1795
+ apply: (alias, url) => {
1796
+ const nextAlias = normalize(alias);
1797
+ const nextUrl = normalize(url);
1798
+ if (!nextAlias) return snapshot();
1799
+ if (!isSafePlaygroundHref(nextUrl)) return drop(nextAlias);
1800
+ data = {
1801
+ ...data,
1802
+ [nextAlias]: nextUrl
1803
+ };
1804
+ return snapshot();
1805
+ },
1806
+ remove: (alias) => {
1807
+ const nextAlias = normalize(alias);
1808
+ return nextAlias ? drop(nextAlias) : snapshot();
1809
+ }
1810
+ };
1811
+ };
1812
+ var siteModules = createMapStore();
1813
+ var siteStyles = createMapStore();
1814
+ var importOverrides = createMapStore();
1815
+ var styleOverrides = createMapStore();
1816
+ /**
1817
+ * 站点默认 import。合并时夹在内置 CDN 与实例 `builtinImportMap` 之间。
1818
+ */
1819
+ var getPlaygroundSiteModules = siteModules.get;
1820
+ var setPlaygroundSiteModules = siteModules.set;
1821
+ /**
1822
+ * 站点默认预览 CSS。合并时夹在内置样式表与管理页覆盖之间。
1823
+ */
1824
+ var getPlaygroundSiteStyles = siteStyles.get;
1825
+ var setPlaygroundSiteStyles = siteStyles.set;
1826
+ var getPlaygroundImportMapOverrides = importOverrides.get;
1827
+ var setPlaygroundImportMapOverrides = importOverrides.set;
1828
+ var applyPlaygroundImportMapOverride = importOverrides.apply;
1829
+ var removePlaygroundImportMapOverride = importOverrides.remove;
1830
+ var getPlaygroundStyleOverrides = styleOverrides.get;
1831
+ var setPlaygroundStyleOverrides = styleOverrides.set;
1832
+ var applyPlaygroundStyleOverride = styleOverrides.apply;
1833
+ var removePlaygroundStyleOverride = styleOverrides.remove;
1834
+ var clearPlaygroundMaps = () => {
1835
+ [
1836
+ siteModules,
1837
+ siteStyles,
1838
+ importOverrides,
1839
+ styleOverrides
1840
+ ].forEach((store) => store.set());
1841
+ };
1842
+ //#endregion
1843
+ //#region packages/playground/src/preview-service.ts
1844
+ /** Preview iframe 内的高度服务;class 会被序列化到 iframe 执行。 */
1845
+ var PlaygroundService = class {
1846
+ target;
1847
+ vue;
1848
+ session;
1849
+ /* istanbul ignore next -- class 会被序列化到没有覆盖率运行时的 iframe。 */
1850
+ sequence = 0;
1851
+ /* istanbul ignore next -- class 会被序列化到没有覆盖率运行时的 iframe。 */
1852
+ disposed = false;
1853
+ manual;
1854
+ /* istanbul ignore next -- class 会被序列化到没有覆盖率运行时的 iframe。 */
1855
+ requests = /* @__PURE__ */ new Set();
1856
+ /* istanbul ignore next -- class 会被序列化到没有覆盖率运行时的 iframe。 */
1857
+ owners = /* @__PURE__ */ new Set();
1858
+ /**
1859
+ * @param target 当前预览窗口。
1860
+ * @param vue 与预览应用共用的 Vue 实例。
1861
+ */
1862
+ /* istanbul ignore next -- class 会被序列化到没有覆盖率运行时的 iframe。 */
1863
+ constructor(target, vue) {
1864
+ this.target = target;
1865
+ this.vue = vue;
1866
+ this.session = `${Date.now()}-${Math.random()}`;
1867
+ this.dispose = this.dispose.bind(this);
1868
+ this.post("start");
1869
+ this.target.addEventListener("pagehide", this.dispose);
1870
+ }
1871
+ /**
1872
+ * 申请手动临时高度;新请求会替换上一个手动请求。
1873
+ * @param height iframe 最小高度。
1874
+ * @returns iframe 是否在超时前应用目标高度。
1875
+ */
1876
+ enable(height) {
1877
+ this.validateHeight(height);
1878
+ this.manual?.release();
1879
+ this.manual = this.createRequest(height);
1880
+ return this.manual.ready;
1881
+ }
1882
+ /** 释放手动临时高度,不影响 `run` 创建的请求。 */
1883
+ disable() {
1884
+ this.manual?.release();
1885
+ this.manual = void 0;
1886
+ }
1887
+ /**
1888
+ * 创建等待高度后执行的事件处理函数。
1889
+ * @param height iframe 最小高度。
1890
+ * @param optionsOrHandler 可见状态配置,或最后一个 handler。
1891
+ * @param lastHandler 使用配置时的最后一个 handler。
1892
+ * @returns 保留 handler 参数和结果的异步事件处理函数。
1893
+ */
1894
+ run(height, optionsOrHandler, lastHandler) {
1895
+ this.validateHeight(height);
1896
+ if (optionsOrHandler === void 0) return (visible) => {
1897
+ if (visible) return this.enable(height);
1898
+ this.disable();
1899
+ return Promise.resolve(void 0);
1900
+ };
1901
+ const visible = (typeof optionsOrHandler === "function" ? {} : optionsOrHandler).visible;
1902
+ if (visible !== void 0 && !this.vue.isRef(visible) && typeof visible !== "function") throw new TypeError("Playground visible must be a ref or getter");
1903
+ const handler = typeof optionsOrHandler === "function" ? optionsOrHandler : lastHandler ?? (this.vue.isRef(visible) ? () => {
1904
+ visible.value = true;
1905
+ } : void 0);
1906
+ if (typeof handler !== "function") throw new TypeError("Playground run requires a handler");
1907
+ let ownerDisposed = false;
1908
+ let current;
1909
+ let pending;
1910
+ const disposeOwner = () => {
1911
+ ownerDisposed = true;
1912
+ current?.release();
1913
+ this.owners.delete(disposeOwner);
1914
+ };
1915
+ this.owners.add(disposeOwner);
1916
+ if (this.vue.getCurrentScope()) this.vue.onScopeDispose(disposeOwner);
1917
+ return (...args) => {
1918
+ if (this.disposed || ownerDisposed) return Promise.resolve(void 0);
1919
+ if (pending) return pending;
1920
+ const request = current = this.createRequest(height);
1921
+ let executionFinished = false;
1922
+ const unlock = () => {
1923
+ if (executionFinished && request.released && current === request) {
1924
+ pending = void 0;
1925
+ current = void 0;
1926
+ }
1927
+ };
1928
+ request.closed.then(unlock);
1929
+ const execution = (async () => {
1930
+ try {
1931
+ if (!await request.ready || ownerDisposed || this.disposed) return void 0;
1932
+ if (visible) request.watch(visible);
1933
+ const result = await handler(...args);
1934
+ if (!visible || !this.vue.toValue(visible)) request.release();
1935
+ return result;
1936
+ } catch (error) {
1937
+ request.release();
1938
+ throw error;
1939
+ } finally {
1940
+ executionFinished = true;
1941
+ unlock();
1942
+ }
1943
+ })();
1944
+ pending = execution;
1945
+ return execution;
1946
+ };
1947
+ }
1948
+ /** 释放当前预览应用持有的全部高度和监听。 */
1949
+ /* istanbul ignore next -- 注入测试会从序列化后的 iframe class 调用该方法。 */
1950
+ dispose() {
1951
+ if (this.disposed) return;
1952
+ this.disposed = true;
1953
+ for (const disposeOwner of this.owners) disposeOwner();
1954
+ for (const request of this.requests) request.release();
1955
+ this.post("stop");
1956
+ this.target.removeEventListener("pagehide", this.dispose);
1957
+ if (this.target.$docsPlayground === this) delete this.target.$docsPlayground;
1958
+ }
1959
+ /** @param height iframe 最小高度。 */
1960
+ validateHeight(height) {
1961
+ if (!Number.isFinite(height) || height <= 0) throw new TypeError("Playground height must be a positive finite number");
1962
+ }
1963
+ /**
1964
+ * @param operation 请求操作。
1965
+ * @param id 请求标识。
1966
+ * @param height iframe 最小高度。
1967
+ */
1968
+ /* istanbul ignore next -- 构造和销毁时会从序列化后的 iframe class 调用该方法。 */
1969
+ post(operation, id = 0, height = 0) {
1970
+ this.target.parent.postMessage({
1971
+ action: "docs:height",
1972
+ session: this.session,
1973
+ operation,
1974
+ id,
1975
+ height
1976
+ }, "*");
1977
+ }
1978
+ /**
1979
+ * @param height iframe 最小高度。
1980
+ * @returns 内部等待与释放句柄。
1981
+ */
1982
+ createRequest(height) {
1983
+ this.validateHeight(height);
1984
+ const id = ++this.sequence;
1985
+ let released = false;
1986
+ let settled = false;
1987
+ let frame = 0;
1988
+ let timer = 0;
1989
+ let stopWatch;
1990
+ let resolveReady;
1991
+ let resolveClosed;
1992
+ const ready = new Promise((resolve) => {
1993
+ resolveReady = resolve;
1994
+ });
1995
+ const closed = new Promise((resolve) => {
1996
+ resolveClosed = resolve;
1997
+ });
1998
+ const stopWaiting = () => {
1999
+ this.target.cancelAnimationFrame(frame);
2000
+ if (timer) {
2001
+ this.target.clearTimeout(timer);
2002
+ timer = 0;
2003
+ }
2004
+ this.target.removeEventListener("message", onMessage);
2005
+ };
2006
+ const release = () => {
2007
+ if (released) return;
2008
+ released = true;
2009
+ stopWaiting();
2010
+ stopWatch?.();
2011
+ resolveReady(false);
2012
+ resolveClosed();
2013
+ this.requests.delete(request);
2014
+ this.post("release", id);
2015
+ };
2016
+ const check = () => {
2017
+ if (released) return;
2018
+ if (this.target.innerHeight >= height) {
2019
+ settled = true;
2020
+ stopWaiting();
2021
+ resolveReady(true);
2022
+ } else frame = this.target.requestAnimationFrame(check);
2023
+ };
2024
+ const onMessage = (event) => {
2025
+ const data = event.data;
2026
+ if (event.source !== this.target.parent || data?.action !== "docs:height:applied" || data.session !== this.session || data.id !== id || settled) return;
2027
+ if (!data.accepted) release();
2028
+ else check();
2029
+ };
2030
+ const request = {
2031
+ ready,
2032
+ closed,
2033
+ get released() {
2034
+ return released;
2035
+ },
2036
+ release,
2037
+ watch: (visible) => {
2038
+ stopWatch = this.vue.watch(() => this.vue.toValue(visible), (value) => {
2039
+ if (!value) release();
2040
+ }, { flush: "sync" });
2041
+ }
2042
+ };
2043
+ this.requests.add(request);
2044
+ if (this.disposed) release();
2045
+ else {
2046
+ this.target.addEventListener("message", onMessage);
2047
+ timer = this.target.setTimeout(() => {
2048
+ timer = 0;
2049
+ release();
2050
+ }, 2e3);
2051
+ this.post("enable", id, height);
2052
+ }
2053
+ return request;
2054
+ }
2055
+ };
2056
+ var PREVIEW_SERVICE_IMPORT_CODE = "import * as __docsPreviewVue from \"vue\"";
2057
+ var PREVIEW_SERVICE_USE_CODE = [
2058
+ `;const __docsPlayground=new (${PlaygroundService.toString()})(window,__docsPreviewVue);`,
2059
+ "app.provide(\"docs:playground\",__docsPlayground);",
2060
+ "window.$docsPlayground=__docsPlayground;",
2061
+ "app.mixin({beforeUnmount(){if(this===this.$root)__docsPlayground.dispose()}});"
2062
+ ].join("");
2063
+ //#endregion
2064
+ //#region packages/playground/src/core/repl-modules.ts
2065
+ var { babelParse, MagicString, walkIdentifiers } = VueCompiler;
2066
+ var moduleSpecifier = (item) => item.type === "import-meta" || !item.specifier || item.type === "dynamic" && item.glob ? void 0 : item.specifier;
2067
+ /**
2068
+ * 发现自定义 ESM 的传递引用;缺失的 npm 包映射到 CDN,动态依赖只登记地址。
2069
+ * @param imports 当前预览的模块覆盖。
2070
+ * @param specifiers 源文件实际引用的模块。
2071
+ * @returns 补齐后的 import map。
2072
+ */
2073
+ var resolveReplImports = async (imports, specifiers) => {
2074
+ const resolved = { ...imports };
2075
+ const visited = /* @__PURE__ */ new Set();
2076
+ const visit = async (specifier, importer) => {
2077
+ const url = isRelativeSpecifier(specifier) || /^https?:\/\//.test(specifier) ? new URL(specifier, importer || location.href).href : resolved[specifier] ||= resolveNpmImport(specifier);
2078
+ if (visited.has(url) || /\/\+esm(?:[?#]|$)/.test(url)) return;
2079
+ visited.add(url);
2080
+ const response = await fetch(url);
2081
+ if (!response.ok) throw new Error(`${response.status} ${url}`);
2082
+ const modules = parse(await response.text())[0];
2083
+ await Promise.all(modules.flatMap((item) => {
2084
+ const dependency = moduleSpecifier(item);
2085
+ return dependency ? [visit(dependency, url)] : [];
2086
+ }));
2087
+ };
2088
+ await Promise.all(specifiers.map((specifier) => visit(specifier)));
2089
+ return resolved;
2090
+ };
2091
+ var rewriteImportedExports = (code) => {
2092
+ const statements = babelParse(code, { sourceType: "module" }).program.body;
2093
+ const bindings = /* @__PURE__ */ new Map();
2094
+ const source = new MagicString(code);
2095
+ for (const statement of statements) {
2096
+ if (statement.type !== "ImportDeclaration") continue;
2097
+ for (const spec of statement.specifiers) {
2098
+ if (spec.type === "ImportNamespaceSpecifier") continue;
2099
+ const imported = spec.type === "ImportDefaultSpecifier" ? "default" : spec.imported.type === "Identifier" ? spec.imported.name : JSON.stringify(spec.imported.value);
2100
+ bindings.set(spec.local.name, {
2101
+ imported,
2102
+ source: statement.source.value,
2103
+ rename: (name) => source.overwrite(spec.local.start, spec.local.end, spec.type === "ImportSpecifier" && spec.imported.start === spec.local.start ? `${imported} as ${name}` : name)
2104
+ });
2105
+ }
2106
+ }
2107
+ const aliases = /* @__PURE__ */ new Map();
2108
+ const rewritten = /* @__PURE__ */ new Set();
2109
+ for (const statement of statements) {
2110
+ if (statement.type !== "ExportNamedDeclaration" || statement.source || statement.declaration) continue;
2111
+ const exports = statement.specifiers.map((spec) => {
2112
+ if (spec.type !== "ExportSpecifier") return "";
2113
+ const local = spec.local.name;
2114
+ const exported = spec.exported.type === "Identifier" ? spec.exported.name : JSON.stringify(spec.exported.value);
2115
+ const binding = bindings.get(local);
2116
+ if (!binding) return `export { ${local} as ${exported} };`;
2117
+ if (!aliases.has(local)) {
2118
+ const alias = `__docs_reexport_${aliases.size}__`;
2119
+ aliases.set(local, alias);
2120
+ binding.rename(alias);
2121
+ }
2122
+ return `export { ${binding.imported} as ${exported} } from ${JSON.stringify(binding.source)};`;
2123
+ });
2124
+ if (statement.specifiers.some((spec) => spec.type === "ExportSpecifier" && bindings.has(spec.local.name))) {
2125
+ source.overwrite(statement.start, statement.end, exports.join("\n"));
2126
+ rewritten.add(statement);
2127
+ }
2128
+ }
2129
+ for (const statement of statements) {
2130
+ if (statement.type === "ImportDeclaration" || rewritten.has(statement)) continue;
2131
+ walkIdentifiers(statement, (id, parent) => {
2132
+ const alias = aliases.get(id.name);
2133
+ if (!alias) return;
2134
+ if (parent?.type === "ObjectProperty" && parent.shorthand) source.appendLeft(id.end, `: ${alias}`);
2135
+ else source.overwrite(id.start, id.end, alias);
2136
+ });
2137
+ }
2138
+ return source.toString();
2139
+ };
2140
+ /**
2141
+ * REPL 将 ./ 引用按 src 根目录解析,编译结果需要先转成文件表中的完整路径。
2142
+ * @param store iframe 预览的文件和编译结果。
2143
+ */
2144
+ var bindReplModules = (store) => {
2145
+ watch(() => Object.values(store.files).map((file) => [
2146
+ file.filename,
2147
+ file.code,
2148
+ file.compiled.js,
2149
+ file.compiled.ssr
2150
+ ]), () => {
2151
+ const files = createFileIndex(Object.fromEntries(Object.entries(store.files).map(([name, file]) => [name, file.code])));
2152
+ const importMap = store.getImportMap();
2153
+ const imports = { ...importMap.imports };
2154
+ let importsChanged = false;
2155
+ for (const file of Object.values(store.files)) for (const output of ["js", "ssr"]) {
2156
+ if (!file.compiled[output]) continue;
2157
+ try {
2158
+ let code = /\.[jt]sx?$/.test(file.filename) ? transformScript(file.code, file.filename, {
2159
+ esm: true,
2160
+ jsx: /\.[jt]sx$/.test(file.filename)
2161
+ }) : rewriteImportMeta(file.compiled[output], file.filename);
2162
+ code = rewriteImportedExports(code);
2163
+ for (const item of [...parse(code)[0]].reverse()) {
2164
+ const specifier = moduleSpecifier(item);
2165
+ if (!specifier) continue;
2166
+ if (isRelativeSpecifier(specifier)) {
2167
+ const resolved = resolveModulePath(file.filename, specifier, files);
2168
+ if (!resolved) continue;
2169
+ const target = `./${resolved.replace(/^\/?src\//, "")}`;
2170
+ const text = item.type === "dynamic" ? JSON.stringify(target) : target;
2171
+ code = code.slice(0, item.start) + text + code.slice(item.end);
2172
+ } else if (!/^https?:\/\//.test(specifier) && !imports[specifier]) {
2173
+ imports[specifier] = resolveNpmImport(specifier);
2174
+ importsChanged = true;
2175
+ }
2176
+ }
2177
+ if (file.compiled[output] !== code) file.compiled[output] = code;
2178
+ } catch (error) {
2179
+ store.errors.push(error instanceof Error ? error : String(error));
2180
+ }
2181
+ }
2182
+ if (importsChanged) store.setImportMap({
2183
+ ...importMap,
2184
+ imports
2185
+ });
2186
+ }, { immediate: true });
2187
+ };
2188
+ //#endregion
2189
+ //#region packages/playground/src/core/store.ts
2190
+ var DOCS_LINK_IMPORT_CODE = "import { h as __docsH } from \"vue\"";
2191
+ var DOCS_LINK_USE_CODE = [
2192
+ PREVIEW_SCROLL_RESET_CODE,
2193
+ "app.component(\"DocsLink\",{",
2194
+ "props:{to:{type:String,default:\"\"}},",
2195
+ "setup(props,{slots}){return()=>__docsH(\"a\",{",
2196
+ "href:props.to,",
2197
+ "style:{color:\"inherit\",textDecoration:\"none\"},",
2198
+ "onClick(event){event.preventDefault();window.parent.postMessage({action:\"docs:navigate\",to:props.to},\"*\")}",
2199
+ "},slots.default?.())}",
2200
+ "})"
2201
+ ].join("");
2202
+ var escapeHtmlAttr = (value) => value.replace(/&/gu, "&amp;").replace(/"/gu, "&quot;").replace(/'/gu, "&#39;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
2203
+ /**
2204
+ * runtime 画布色。`previewInset` 露出的 padding、iframe chrome 和 sandbox
2205
+ * `html`/`body` 必须共用这一变量,暗色下 `--docs-background-color` 与
2206
+ * `--vc-background-color-light` 不同,否则会出现色带割裂。
2207
+ */
2208
+ var PLAYGROUND_RUNTIME_CANVAS_BACKGROUND = "var(--vc-background-color-light, var(--docs-background-color, #fff))";
2209
+ var createRuntimePreviewOptions = (cdnURL = DEFAULT_CDN_URL, options = {}) => {
2210
+ const previewScroller = options.previewScroller === true;
2211
+ const hrefs = Object.values({
2212
+ ...createBuiltinStyles(cdnURL),
2213
+ ...getPlaygroundSiteStyles(),
2214
+ ...getPlaygroundStyleOverrides()
2215
+ });
2216
+ const styleBlocks = [
2217
+ `html,body{height:auto;min-height:0;background:${PLAYGROUND_RUNTIME_CANVAS_BACKGROUND}}`,
2218
+ "body{color:var(--vc-foreground-color,#080f20)}",
2219
+ ...previewScroller ? [PREVIEW_SCROLLER_STYLE] : []
2220
+ ];
2221
+ return {
2222
+ showRuntimeError: false,
2223
+ showRuntimeWarning: false,
2224
+ headHTML: [
2225
+ SANDBOX_RUNTIME_ERROR_CAPTURE_HTML,
2226
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
2227
+ ...hrefs.map((href) => `<link rel="stylesheet" href="${escapeHtmlAttr(href)}">`),
2228
+ "<style>",
2229
+ ...styleBlocks,
2230
+ "</style>"
2231
+ ].join("\n"),
2232
+ customCode: {
2233
+ importCode: `${DOCS_LINK_IMPORT_CODE}\n${PREVIEW_SERVICE_IMPORT_CODE}`,
2234
+ useCode: `${DOCS_LINK_USE_CODE}\n${PREVIEW_SERVICE_USE_CODE}`
2235
+ }
2236
+ };
2237
+ };
2238
+ var toReplFilename = (filename) => filename.startsWith("src/") ? filename : `src/${filename}`;
2239
+ var createReplFile = (filename, code) => {
2240
+ const replFilename = toReplFilename(filename);
2241
+ return new File(replFilename, code);
2242
+ };
2243
+ /**
2244
+ * 默认 CDN → 站点 modules → 实例 builtinImportMap → 管理页覆盖。
2245
+ * iframe import map 与直接渲染加载的是同一份地址表。
2246
+ * @param cdnURL
2247
+ * @param builtinImportMap
2248
+ */
2249
+ var createRuntimeImports = (cdnURL = DEFAULT_CDN_URL, builtinImportMap) => ({
2250
+ ...createBuiltinImports(cdnURL),
2251
+ ...getPlaygroundSiteModules(),
2252
+ ...filterSafeHrefs(builtinImportMap?.imports),
2253
+ ...getPlaygroundImportMapOverrides()
2254
+ });
2255
+ var createRuntimeStore = (files, entry, options) => {
2256
+ const { cdnURL, builtinImportMap, ...storeOptions } = options;
2257
+ const replFiles = ref(Object.fromEntries(Object.entries(files).map(([filename, code]) => {
2258
+ const file = createReplFile(filename, code);
2259
+ return [file.filename, file];
2260
+ })));
2261
+ const mainFile = ref(toReplFilename(entry));
2262
+ const activeFilename = ref(toReplFilename(entry));
2263
+ const imports = createRuntimeImports(cdnURL, builtinImportMap);
2264
+ const store = useStore({
2265
+ ...storeOptions,
2266
+ files: replFiles,
2267
+ mainFile,
2268
+ activeFilename,
2269
+ builtinImportMap: ref({
2270
+ ...builtinImportMap,
2271
+ imports
2272
+ }),
2273
+ template: ref({
2274
+ welcomeSFC: files[entry],
2275
+ newSFC: NEW_SFC_CODE
2276
+ })
2277
+ });
2278
+ bindPlaygroundScss(store);
2279
+ bindReplModules(store);
2280
+ whenSassReady(files, () => {
2281
+ const specifiers = collectBareSpecifiers(files, Object.keys(files));
2282
+ if (!specifiers.length) {
2283
+ store.init();
2284
+ return;
2285
+ }
2286
+ store.loading = true;
2287
+ resolveReplImports(imports, specifiers).then((resolved) => {
2288
+ if (Object.keys(resolved).length !== Object.keys(imports).length) store.setImportMap({ imports: resolved }, true);
2289
+ store.init();
2290
+ }).catch((error) => {
2291
+ store.errors.push(error);
2292
+ }).finally(() => {
2293
+ store.loading = false;
2294
+ });
2295
+ });
2296
+ return store;
2297
+ };
2298
+ //#endregion
1376
2299
  //#region packages/playground/src/core/runtime/alone/wrapper.vue?vue&type=script&setup=true&lang.ts
1377
- var _hoisted_1$2 = ["aria-label"];
2300
+ var _hoisted_1$3 = ["aria-label"];
1378
2301
  var _hoisted_2$2 = { class: "docs-playground-popup__frame" };
1379
2302
  var _hoisted_3$2 = { class: "docs-playground-popup__header" };
1380
2303
  var _hoisted_4$2 = ["title"];
@@ -1419,7 +2342,7 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1419
2342
  "portal-fulfilled"
1420
2343
  ],
1421
2344
  setup(__props, { emit: __emit }) {
1422
- const LocalSandbox = defineAsyncComponent(() => import("./local-sandbox-B8IJ5jWb.js").then((n) => n.t));
2345
+ const LocalSandbox = defineAsyncComponent(() => Promise.resolve().then(() => local_sandbox_exports));
1423
2346
  const props = __props;
1424
2347
  const emit = __emit;
1425
2348
  const { t } = useLocale();
@@ -1588,7 +2511,7 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1588
2511
  ])) : createCommentVNode("v-if", true)], 4)]),
1589
2512
  _: 1
1590
2513
  })])
1591
- ])], 4)], 8, _hoisted_1$2);
2514
+ ])], 4)], 8, _hoisted_1$3);
1592
2515
  };
1593
2516
  }
1594
2517
  }), {
@@ -1597,27 +2520,932 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1597
2520
  multiple: false
1598
2521
  });
1599
2522
  //#endregion
2523
+ //#region packages/playground/src/core/runtime/local/playground.ts
2524
+ /**
2525
+ * 直接渲染与页面同文档,弹层不需要临时撑高。
2526
+ * `run` 仍返回可调用函数,但不会申请高度,也不会改动预览尺寸。
2527
+ * @param vue 宿主 Vue,只用其中的 `isRef`。
2528
+ * @returns 注入给预览的 `docs:playground`。
2529
+ */
2530
+ var createLocalPlayground = (vue) => {
2531
+ const run = (_height, optionsOrHandler, lastHandler) => {
2532
+ const visible = (typeof optionsOrHandler === "function" || optionsOrHandler == null ? {} : optionsOrHandler).visible;
2533
+ const handler = typeof optionsOrHandler === "function" ? optionsOrHandler : typeof lastHandler === "function" ? lastHandler : vue.isRef(visible) ? () => {
2534
+ visible.value = true;
2535
+ } : void 0;
2536
+ return (...args) => {
2537
+ if (typeof handler !== "function") return void 0;
2538
+ return handler(...args);
2539
+ };
2540
+ };
2541
+ return {
2542
+ enable: () => Promise.resolve(true),
2543
+ disable() {},
2544
+ dispose() {},
2545
+ run
2546
+ };
2547
+ };
2548
+ //#endregion
2549
+ //#region packages/playground/src/core/runtime/local/port.ts
2550
+ /** 只在桥接 iframe 内部转发,保证父页面收到的 source 是该 iframe。 */
2551
+ var LOCAL_BRIDGE_CHANNEL = "docs:local-out";
2552
+ var BRIDGE_INSTALLER = `
2553
+ if (!window.__docsLocalBridge) {
2554
+ window.__docsLocalBridge = true;
2555
+ window.addEventListener('message', function (event) {
2556
+ var data = event.data;
2557
+ if (!data || data.channel !== ${JSON.stringify(LOCAL_BRIDGE_CHANNEL)}) return;
2558
+ window.parent.postMessage(data.payload, '*');
2559
+ });
2560
+ }
2561
+ `;
2562
+ var LOCAL_BRIDGE_SRCDOC = `<!doctype html><html><head></head><body><script>${BRIDGE_INSTALLER}<\/script></body></html>`;
2563
+ /**
2564
+ * 在同源空白 iframe 里安装转发脚本。调用发生在 iframe realm,父页面看到的 source 才是它。
2565
+ * @param iframe 用作消息身份的空白 iframe。
2566
+ * @returns 脚本是否已经装上。
2567
+ */
2568
+ var installLocalBridge = (iframe) => {
2569
+ const win = iframe.contentWindow;
2570
+ if (!win || win.__docsLocalBridge) return Boolean(win?.__docsLocalBridge);
2571
+ win.eval(BRIDGE_INSTALLER);
2572
+ return Boolean(win.__docsLocalBridge);
2573
+ };
2574
+ /**
2575
+ * 满足 PlaygroundService 现有 Window 调用的预览窗口。
2576
+ * 出站消息经 iframe 转发,入站回复再交回服务,协议仍是 docs:height / docs:navigate。
2577
+ */
2578
+ var LocalPreviewPort = class {
2579
+ iframe;
2580
+ parent;
2581
+ listeners = /* @__PURE__ */ new Map();
2582
+ constructor(iframe) {
2583
+ this.iframe = iframe;
2584
+ this.parent = { postMessage: (data) => {
2585
+ this.iframe.contentWindow?.postMessage({
2586
+ channel: LOCAL_BRIDGE_CHANNEL,
2587
+ payload: data
2588
+ }, "*");
2589
+ } };
2590
+ }
2591
+ get contentWindow() {
2592
+ return this.iframe.contentWindow;
2593
+ }
2594
+ get innerHeight() {
2595
+ const fromWindow = this.iframe.contentWindow?.innerHeight ?? 0;
2596
+ if (fromWindow > 0) return fromWindow;
2597
+ return this.iframe.clientHeight || this.iframe.parentElement?.clientHeight || 0;
2598
+ }
2599
+ addEventListener(type, listener) {
2600
+ const win = this.iframe.contentWindow;
2601
+ if (!win) return;
2602
+ if (type !== "message") {
2603
+ win.addEventListener(type, listener);
2604
+ return;
2605
+ }
2606
+ const wrapped = (event) => {
2607
+ const message = event;
2608
+ const data = message.data;
2609
+ if (data && data.channel === "docs:local-out") return;
2610
+ listener({
2611
+ data: message.data,
2612
+ source: this.parent
2613
+ });
2614
+ };
2615
+ this.listeners.set(listener, wrapped);
2616
+ win.addEventListener("message", wrapped);
2617
+ }
2618
+ removeEventListener(type, listener) {
2619
+ const win = this.iframe.contentWindow;
2620
+ if (!win) return;
2621
+ const wrapped = this.listeners.get(listener);
2622
+ if (wrapped) {
2623
+ this.listeners.delete(listener);
2624
+ win.removeEventListener(type, wrapped);
2625
+ return;
2626
+ }
2627
+ win.removeEventListener(type, listener);
2628
+ }
2629
+ requestAnimationFrame(callback) {
2630
+ return window.requestAnimationFrame(callback);
2631
+ }
2632
+ cancelAnimationFrame(handle) {
2633
+ window.cancelAnimationFrame(handle);
2634
+ }
2635
+ setTimeout(handler, timeout, ...args) {
2636
+ return window.setTimeout(handler, timeout, ...args);
2637
+ }
2638
+ clearTimeout(handle) {
2639
+ window.clearTimeout(handle);
2640
+ }
2641
+ };
2642
+ //#endregion
2643
+ //#region packages/playground/src/core/runtime/local/format-error.ts
2644
+ /**
2645
+ * 空 reject(例如弹层取消)不要渲染成红条。
2646
+ * @param error 运行时抛出的值。
2647
+ * @returns 可展示的错误文本;空取消返回空字符串。
2648
+ */
2649
+ var formatPlaygroundRuntimeError = (error) => {
2650
+ if (error == null) return "";
2651
+ const raw = typeof error === "object" && "message" in error ? error.message : error;
2652
+ if (raw == null || raw === "") return "";
2653
+ const text = String(raw);
2654
+ if (text === "undefined" || text === "null") return "";
2655
+ return text;
2656
+ };
2657
+ //#endregion
2658
+ //#region packages/playground/src/core/runtime/local/builtins.ts
2659
+ var loaders = {
2660
+ "vue": () => import("vue"),
2661
+ "vue-router": () => import("vue-router"),
2662
+ "pinia": async () => Pinia,
2663
+ "@deot/helper": () => import("@deot/helper"),
2664
+ "@deot/helper-cache": () => import("@deot/helper-cache"),
2665
+ "@deot/helper-device": () => import("@deot/helper-device"),
2666
+ "@deot/helper-dom": () => import("@deot/helper-dom"),
2667
+ "@deot/helper-emitter": () => import("@deot/helper-emitter"),
2668
+ "@deot/helper-fp": () => import("@deot/helper-fp"),
2669
+ "@deot/helper-is": () => import("@deot/helper-is"),
2670
+ "@deot/helper-load": () => import("@deot/helper-load"),
2671
+ "@deot/helper-resize": () => import("@deot/helper-resize"),
2672
+ "@deot/helper-route": () => import("@deot/helper-route"),
2673
+ "@deot/helper-scheduler": () => import("@deot/helper-scheduler"),
2674
+ "@deot/helper-shared": () => import("@deot/helper-shared"),
2675
+ "@deot/helper-unicode": () => import("@deot/helper-unicode"),
2676
+ "@deot/helper-utils": () => import("@deot/helper-utils"),
2677
+ "@deot/helper-validator": () => import("@deot/helper-validator"),
2678
+ "@deot/helper-wheel": () => import("@deot/helper-wheel"),
2679
+ "@deot/http-client": () => import("@deot/http-client"),
2680
+ "@deot/http-core": () => import("@deot/http-core"),
2681
+ "@deot/http-hooks": () => import("@deot/http-hooks"),
2682
+ "@deot/http": () => import("@deot/http"),
2683
+ "@deot/vc": async () => Vc,
2684
+ "@deot/vc-components": async () => VcComponents,
2685
+ "@deot/vc-hooks": async () => VcHooks,
2686
+ "@deot/vc-locale": () => import("@deot/vc-locale"),
2687
+ "lodash-es": () => import("lodash-es"),
2688
+ "echarts": () => import("echarts"),
2689
+ "photoswipe": () => import("photoswipe"),
2690
+ "jszip": () => import("jszip"),
2691
+ "jspdf": () => import("jspdf"),
2692
+ "dayjs": async () => (await import("dayjs")).default
2693
+ };
2694
+ var cache = /* @__PURE__ */ new Map();
2695
+ /** 直接渲染可从宿主包注入的说明符;与 Vue 无关的大型依赖按需加载。 */
2696
+ var localBuiltinIds = new Set(Object.keys(loaders));
2697
+ var ensureLocalBuiltin = (id) => {
2698
+ const loader = loaders[id];
2699
+ if (!loader) return Promise.reject(/* @__PURE__ */ new Error(`[Playground] 没有本地模块 "${id}"`));
2700
+ let pending = cache.get(id);
2701
+ if (!pending) {
2702
+ pending = loader();
2703
+ cache.set(id, pending);
2704
+ }
2705
+ return pending;
2706
+ };
2707
+ //#endregion
2708
+ //#region packages/playground/src/core/runtime/local/modules.ts
2709
+ var SKIP_COPY_KEYS = /* @__PURE__ */ new Set([
2710
+ "prototype",
2711
+ "caller",
2712
+ "arguments"
2713
+ ]);
2714
+ var toHostModule = (ns) => {
2715
+ if (ns == null || typeof ns !== "object" && typeof ns !== "function") return {
2716
+ __esModule: true,
2717
+ default: ns
2718
+ };
2719
+ const source = ns;
2720
+ const mod = { __esModule: true };
2721
+ const assignKey = (key) => {
2722
+ if (SKIP_COPY_KEYS.has(key) || key === "__esModule") return;
2723
+ try {
2724
+ mod[key] = source[key];
2725
+ } catch {}
2726
+ };
2727
+ try {
2728
+ Object.keys(source).forEach(assignKey);
2729
+ } catch {}
2730
+ try {
2731
+ Object.getOwnPropertyNames(source).forEach(assignKey);
2732
+ } catch {}
2733
+ if (!("default" in mod) || mod.default === void 0) mod.default = source.default !== void 0 ? source.default : source;
2734
+ return mod;
2735
+ };
2736
+ var lookupHostModule = (id, modules) => {
2737
+ if (Object.prototype.hasOwnProperty.call(modules, id)) return toHostModule(modules[id]);
2738
+ return null;
2739
+ };
2740
+ var pickNestedExport = (rootMod, rest) => {
2741
+ if (!rest) return void 0;
2742
+ const parts = rest.split("/").filter(Boolean);
2743
+ let current = rootMod;
2744
+ for (const part of parts) {
2745
+ if (current == null || typeof current !== "object" && typeof current !== "function") return;
2746
+ const record = current;
2747
+ if (!(part in record)) return void 0;
2748
+ current = record[part];
2749
+ }
2750
+ return current;
2751
+ };
2752
+ /**
2753
+ * 先精确匹配,再从右往左剥路径,把剩余段当成导出属性。
2754
+ * 模块表只来自当前 Playground,不写入全局注册表。
2755
+ * @param id 裸模块说明符。
2756
+ * @param modules 当前 Playground 的模块表。
2757
+ * @returns 可被 `require` 使用的模块;找不到时返回 null。
2758
+ */
2759
+ var resolveHostModule = (id, modules) => {
2760
+ const exact = lookupHostModule(id, modules);
2761
+ if (exact) return exact;
2762
+ let cursor = id;
2763
+ while (true) {
2764
+ const slash = cursor.lastIndexOf("/");
2765
+ if (slash <= 0) break;
2766
+ const parent = cursor.slice(0, slash);
2767
+ const rest = id.slice(parent.length + 1);
2768
+ const rootMod = lookupHostModule(parent, modules);
2769
+ if (rootMod) {
2770
+ const nested = pickNestedExport(rootMod, rest);
2771
+ if (nested !== void 0) return toHostModule(nested);
2772
+ }
2773
+ cursor = parent;
2774
+ }
2775
+ return null;
2776
+ };
2777
+ var HOST_VUE_SPECIFIERS = /* @__PURE__ */ new Set(["vue", "vue/server-renderer"]);
2778
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
2779
+ /**
2780
+ * 找到 import map 里能覆盖该说明符的键。子路径没有独立 URL 时回退到父包。
2781
+ * @param id 裸模块说明符。
2782
+ * @param imports 合并后的 import map。
2783
+ * @returns 命中的 import map 键;没有地址时返回 null。
2784
+ */
2785
+ var resolveImportTarget = (id, imports) => {
2786
+ if (imports[id]) return id;
2787
+ let cursor = id;
2788
+ while (true) {
2789
+ const slash = cursor.lastIndexOf("/");
2790
+ if (slash <= 0) return null;
2791
+ const parent = cursor.slice(0, slash);
2792
+ if (imports[parent]) return parent;
2793
+ cursor = parent;
2794
+ }
2795
+ };
2796
+ var prefersLocalBuiltin = (id, imports, cdnURL) => {
2797
+ if (!localBuiltinIds.has(id) && !HOST_VUE_SPECIFIERS.has(id)) return false;
2798
+ const url = imports[id];
2799
+ if (!url) return true;
2800
+ return url === createBuiltinImports(cdnURL)[id];
2801
+ };
2802
+ /**
2803
+ * 内置依赖先注入宿主副本。import map 里与默认 CDN 不同的地址会覆盖,包括 `vue`。
2804
+ * @param specifiers 本次预览用到的裸模块说明符。
2805
+ * @param imports 合并后的 import map。
2806
+ * @param builtins 宿主 Vue 与 vue-router。
2807
+ * @param builtins.vue 当前页面的 Vue 模块。
2808
+ * @param builtins.vueRouter 打包进来的 vue-router,可被 import map 覆盖。
2809
+ * @param loader 按 URL 加载远程模块。
2810
+ * @param cdnURL 当前 CDN 根,用来识别默认地址。
2811
+ * @returns 模块表和加载错误。
2812
+ */
2813
+ var loadLocalModules = async (specifiers, imports, builtins, loader, cdnURL) => {
2814
+ const modules = {
2815
+ "vue": builtins.vue,
2816
+ "vue-router": builtins.vueRouter
2817
+ };
2818
+ const errors = [];
2819
+ const targets = /* @__PURE__ */ new Set();
2820
+ const localIds = /* @__PURE__ */ new Set();
2821
+ specifiers.forEach((specifier) => {
2822
+ let local = false;
2823
+ if (prefersLocalBuiltin(specifier, imports, cdnURL)) localIds.add(specifier);
2824
+ else {
2825
+ let cursor = specifier;
2826
+ while (true) {
2827
+ const slash = cursor.lastIndexOf("/");
2828
+ if (slash <= 0) break;
2829
+ const parent = cursor.slice(0, slash);
2830
+ if (prefersLocalBuiltin(parent, imports, cdnURL)) {
2831
+ localIds.add(parent);
2832
+ local = true;
2833
+ break;
2834
+ }
2835
+ cursor = parent;
2836
+ }
2837
+ }
2838
+ if (specifier === "vue-router") {
2839
+ if (imports["vue-router"]) targets.add("vue-router");
2840
+ return;
2841
+ }
2842
+ const target = resolveImportTarget(specifier, imports);
2843
+ if (target && prefersLocalBuiltin(target, imports, cdnURL)) localIds.add(target);
2844
+ else if (target) targets.add(target);
2845
+ else if (!local && !localIds.has(specifier)) {
2846
+ imports[specifier] = resolveNpmImport(specifier);
2847
+ targets.add(specifier);
2848
+ }
2849
+ });
2850
+ await Promise.all([...localIds].map(async (id) => {
2851
+ if (id === "vue" || id === "vue-router") return;
2852
+ if (id === "vue/server-renderer") {
2853
+ modules[id] = builtins.vue;
2854
+ return;
2855
+ }
2856
+ modules[id] = await ensureLocalBuiltin(id);
2857
+ }));
2858
+ for (const id of targets) {
2859
+ const url = imports[id];
2860
+ if (!url || prefersLocalBuiltin(id, imports, cdnURL)) continue;
2861
+ try {
2862
+ modules[id] = await loader(url);
2863
+ } catch (error) {
2864
+ errors.push(`[Playground] 无法加载模块 "${id}" (${url}): ${messageOf(error)}`);
2865
+ }
2866
+ }
2867
+ return {
2868
+ modules,
2869
+ errors
2870
+ };
2871
+ };
2872
+ //#endregion
2873
+ //#region packages/playground/src/core/runtime/local/vue-guard.ts
2874
+ /**
2875
+ * 给 files 注入的 vue:同一份宿主 Vue,但 `createApp().mount` 不会卸掉页面。
2876
+ * 防护按本次 link 创建,多个 Playground 互不覆盖。
2877
+ * @param capture 本次链接收集到的根组件、局部组件和 provide。
2878
+ * @returns 带防护的 Vue 模块。
2879
+ */
2880
+ var createGuardedVue = (capture) => {
2881
+ const createApp = (rootComponent, rootProps) => {
2882
+ const fakeApp = {
2883
+ _component: rootComponent,
2884
+ _props: rootProps,
2885
+ config: {
2886
+ errorHandler: null,
2887
+ warnHandler: null,
2888
+ globalProperties: {}
2889
+ },
2890
+ _context: {
2891
+ provides: Object.create(null),
2892
+ components: Object.create(null),
2893
+ directives: Object.create(null),
2894
+ mixins: []
2895
+ },
2896
+ use() {
2897
+ return fakeApp;
2898
+ },
2899
+ mixin(mixin) {
2900
+ fakeApp._context.mixins.push(mixin);
2901
+ return fakeApp;
2902
+ },
2903
+ component(name, component) {
2904
+ if (component) {
2905
+ fakeApp._context.components[name] = component;
2906
+ return fakeApp;
2907
+ }
2908
+ return fakeApp._context.components[name];
2909
+ },
2910
+ directive() {
2911
+ return fakeApp;
2912
+ },
2913
+ provide(key, value) {
2914
+ fakeApp._context.provides[key] = value;
2915
+ return fakeApp;
2916
+ },
2917
+ mount() {
2918
+ capture.components = { ...fakeApp._context.components };
2919
+ capture.provides = { ...fakeApp._context.provides };
2920
+ capture.mountedComponent = defineComponent({
2921
+ name: "PlaygroundCapturedApp",
2922
+ components: fakeApp._context.components,
2923
+ setup() {
2924
+ Reflect.ownKeys(fakeApp._context.provides).forEach((key) => {
2925
+ provide(key, fakeApp._context.provides[key]);
2926
+ });
2927
+ return () => h(rootComponent, rootProps || null);
2928
+ }
2929
+ });
2930
+ return capture.mountedComponent;
2931
+ },
2932
+ unmount() {},
2933
+ onUnmount() {
2934
+ return fakeApp;
2935
+ }
2936
+ };
2937
+ return fakeApp;
2938
+ };
2939
+ return new Proxy(Vue, { get(target, prop, receiver) {
2940
+ if (prop === "createApp" || prop === "createSSRApp") return createApp;
2941
+ if (prop === "default") return receiver;
2942
+ return Reflect.get(target, prop, receiver);
2943
+ } });
2944
+ };
2945
+ //#endregion
2946
+ //#region packages/playground/src/core/runtime/local/linker.ts
2947
+ /**
2948
+ * 在当前页面链接编译结果,返回入口组件。
2949
+ * 未覆盖 `vue` 时换成带防护的宿主实例,避免 `mount` 卸掉页面。
2950
+ * @param compiled 浏览器编译结果。
2951
+ * @param files 当前 Playground 文件表。
2952
+ * @param options 可选的宿主模块表。
2953
+ * @returns 入口组件、样式和链接错误。
2954
+ */
2955
+ var linkPlayground = (compiled, files, options = {}) => {
2956
+ const errors = [...compiled.errors || []];
2957
+ if (!compiled.entry || errors.length) return {
2958
+ component: null,
2959
+ css: compiled.css || [],
2960
+ errors
2961
+ };
2962
+ const capture = {
2963
+ mountedComponent: null,
2964
+ components: {},
2965
+ provides: {}
2966
+ };
2967
+ const modules = { ...options.modules || {} };
2968
+ if (modules.vue == null || modules.vue === Vue) modules.vue = createGuardedVue(capture);
2969
+ const fileIndex = createFileIndex(files);
2970
+ const root = getCommonRoot([...fileIndex.keys()]);
2971
+ const cache = /* @__PURE__ */ new Map();
2972
+ const visiting = /* @__PURE__ */ new Set();
2973
+ const requireFn = (fromFilename) => (id) => {
2974
+ if (isRelativeSpecifier(id)) {
2975
+ const resolved = resolveModulePath(fromFilename, id, fileIndex);
2976
+ if (!resolved) throw new Error(`[Playground] 无法解析相对模块 "${id}"(来自 ${fromFilename})`);
2977
+ /* istanbul ignore if -- 公共根已包含全部 files,正常解析不会逃出 */
2978
+ if (!isInsideRoot(resolved, root)) throw new Error(`[Playground] 模块逃出虚拟根: ${resolved}`);
2979
+ return loadModule(resolved);
2980
+ }
2981
+ const host = resolveHostModule(id, modules);
2982
+ if (host) return host;
2983
+ throw new Error(`[Playground] 未注册的模块 "${id}"。请在 import map 中提供可加载的地址。`);
2984
+ };
2985
+ const loadModule = (filename) => {
2986
+ const key = normalizeVirtualPath(filename);
2987
+ if (cache.has(key)) return cache.get(key);
2988
+ if (visiting.has(key)) return cache.get(key);
2989
+ const mod = compiled.modules[key];
2990
+ if (!mod) throw new Error(`[Playground] 缺少编译模块: ${key}`);
2991
+ const module = { exports: {} };
2992
+ cache.set(key, module.exports);
2993
+ visiting.add(key);
2994
+ try {
2995
+ new Function("require", "module", "exports", mod.js)(requireFn(key), module, module.exports);
2996
+ cache.set(key, module.exports);
2997
+ return module.exports;
2998
+ } catch (error) {
2999
+ const message = error instanceof Error ? error.message : String(error);
3000
+ errors.push(`[Playground] 执行失败 ${key}: ${message}`);
3001
+ throw error;
3002
+ } finally {
3003
+ visiting.delete(key);
3004
+ }
3005
+ };
3006
+ try {
3007
+ const entryExports = loadModule(compiled.entry);
3008
+ let component = entryExports?.default ?? entryExports;
3009
+ if (capture.mountedComponent) component = capture.mountedComponent;
3010
+ /* istanbul ignore if -- 空入口在编译阶段已经报错 */
3011
+ if (!component) {
3012
+ errors.push("[Playground] 入口必须 export default 组件,或调用 createApp(App).mount()");
3013
+ return {
3014
+ component: null,
3015
+ css: compiled.css || [],
3016
+ errors
3017
+ };
3018
+ }
3019
+ return {
3020
+ component,
3021
+ css: compiled.css || [],
3022
+ errors
3023
+ };
3024
+ } catch (error) {
3025
+ if (!errors.length) errors.push(error instanceof Error ? error.message : String(error));
3026
+ return {
3027
+ component: null,
3028
+ css: compiled.css || [],
3029
+ errors
3030
+ };
3031
+ }
3032
+ };
3033
+ //#endregion
3034
+ //#region packages/playground/src/core/runtime/local/remote.ts
3035
+ var HOST_VUE = /* @__PURE__ */ new Set(["vue", "vue/server-renderer"]);
3036
+ /**
3037
+ * 把 CDN 上的 ESM 先拉完整张依赖图,再在当前页面里执行。
3038
+ * 裸导入优先走 import map,缺失的 npm 依赖回退到 CDN ESM;import() 按需加载。
3039
+ * @param imports 合并后的 import map。
3040
+ * @param builtins 宿主 Vue 与 vue-router。
3041
+ * @param cdnURL 当前 CDN 根,用来识别默认地址。
3042
+ * @param importModule 浏览器原生 ESM 加载器。
3043
+ * @returns 按 URL 加载并执行远程模块的加载器。
3044
+ */
3045
+ var createRemoteLoader = (imports, builtins, cdnURL, importModule = (url) => import(
3046
+ /* @vite-ignore */
3047
+ url
3048
+ )) => {
3049
+ const hostModules = {
3050
+ "vue": builtins.vue,
3051
+ "vue-router": builtins.vueRouter
3052
+ };
3053
+ const pendingBuiltins = /* @__PURE__ */ new Set();
3054
+ const texts = /* @__PURE__ */ new Map();
3055
+ const evaluated = /* @__PURE__ */ new Map();
3056
+ const crawled = /* @__PURE__ */ new Set();
3057
+ const nativeModules = /* @__PURE__ */ new Map();
3058
+ const loadNative = (url) => {
3059
+ let pending = nativeModules.get(url);
3060
+ if (!pending) {
3061
+ pending = importModule(url).then((module) => {
3062
+ const exports = toHostModule(module);
3063
+ evaluated.set(url, exports);
3064
+ return exports;
3065
+ });
3066
+ nativeModules.set(url, pending);
3067
+ }
3068
+ return pending;
3069
+ };
3070
+ const localBuiltinId = (id) => {
3071
+ if (imports[id] && !prefersLocalBuiltin(id, imports, cdnURL)) return null;
3072
+ if (prefersLocalBuiltin(id, imports, cdnURL)) return id;
3073
+ let cursor = id;
3074
+ while (true) {
3075
+ const slash = cursor.lastIndexOf("/");
3076
+ if (slash <= 0) return null;
3077
+ const parent = cursor.slice(0, slash);
3078
+ if (prefersLocalBuiltin(parent, imports, cdnURL)) return parent;
3079
+ cursor = parent;
3080
+ }
3081
+ };
3082
+ const dependencyUrl = (from, specifier) => {
3083
+ if (isRelativeSpecifier(specifier) || /^https?:\/\//.test(specifier)) return new URL(specifier, from).href;
3084
+ if (imports[specifier] && !prefersLocalBuiltin(specifier, imports, cdnURL)) return imports[specifier];
3085
+ if (HOST_VUE.has(specifier) && prefersLocalBuiltin(specifier, imports, cdnURL)) return null;
3086
+ let cursor = specifier;
3087
+ while (cursor) {
3088
+ if (localBuiltinIds.has(cursor) && prefersLocalBuiltin(cursor, imports, cdnURL)) {
3089
+ pendingBuiltins.add(cursor);
3090
+ return null;
3091
+ }
3092
+ const slash = cursor.lastIndexOf("/");
3093
+ if (slash <= 0) break;
3094
+ cursor = cursor.slice(0, slash);
3095
+ }
3096
+ const target = imports[specifier] ? specifier : resolveImportTarget(specifier, imports);
3097
+ if (!target) {
3098
+ imports[specifier] = resolveNpmImport(specifier);
3099
+ return imports[specifier];
3100
+ }
3101
+ return imports[target];
3102
+ };
3103
+ const crawl = async (url) => {
3104
+ if (/\/\+esm(?:[?#]|$)/.test(url)) {
3105
+ await loadNative(url);
3106
+ return;
3107
+ }
3108
+ if (crawled.has(url)) return;
3109
+ crawled.add(url);
3110
+ const response = await fetch(url);
3111
+ if (!response.ok) throw new Error(`${response.status} ${url}`);
3112
+ const text = await response.text();
3113
+ await init();
3114
+ const [specifiers] = parse(text);
3115
+ let source = text;
3116
+ for (const item of [...specifiers].reverse()) if (item.type === "dynamic") source = source.slice(0, item.importStart) + "__import" + source.slice(item.importStart + 6);
3117
+ texts.set(url, source);
3118
+ await Promise.all(specifiers.map(async (item) => {
3119
+ if (item.type !== "static" && item.type !== "reexport-star") return;
3120
+ const next = dependencyUrl(url, item.specifier);
3121
+ if (next) await crawl(next);
3122
+ }));
3123
+ };
3124
+ const requireFrom = (from) => (id) => {
3125
+ if (HOST_VUE.has(id) && prefersLocalBuiltin(id, imports, cdnURL)) return toHostModule(builtins.vue);
3126
+ const builtinId = localBuiltinId(id);
3127
+ if (builtinId) return toHostModule(hostModules[builtinId]);
3128
+ if (isRelativeSpecifier(id) || /^https?:\/\//.test(id)) return evaluate(new URL(id, from).href);
3129
+ const target = imports[id] ? id : resolveImportTarget(id, imports);
3130
+ if (!target || !imports[target]) throw new Error(`[Playground] 未注册的模块 "${id}"`);
3131
+ const loaded = evaluate(imports[target]);
3132
+ if (target === id) return loaded;
3133
+ if (!resolveHostModule(id, { [target]: loaded }))
3134
+ /* istanbul ignore next -- 父包没有对应导出时才拒绝 */
3135
+ throw new Error(`[Playground] 未注册的模块 "${id}"`);
3136
+ return loaded;
3137
+ };
3138
+ const evaluate = (url) => {
3139
+ if (evaluated.has(url)) return evaluated.get(url);
3140
+ const text = texts.get(url);
3141
+ if (text == null) throw new Error(`[Playground] 远程模块尚未下载: ${url}`);
3142
+ const cjs = transform(rewriteImportMeta(text, url), {
3143
+ transforms: ["imports"],
3144
+ disableESTransforms: true,
3145
+ production: true,
3146
+ filePath: url
3147
+ }).code;
3148
+ const module = { exports: {} };
3149
+ evaluated.set(url, module.exports);
3150
+ new Function("require", "module", "exports", "__import", cjs)(requireFrom(url), module, module.exports, async (id) => {
3151
+ const next = dependencyUrl(url, id);
3152
+ if (next) await load(next);
3153
+ else {
3154
+ const builtinId = localBuiltinId(id);
3155
+ if (builtinId && !(builtinId in hostModules)) hostModules[builtinId] = await ensureLocalBuiltin(builtinId);
3156
+ }
3157
+ return requireFrom(url)(id);
3158
+ });
3159
+ evaluated.set(url, module.exports);
3160
+ return module.exports;
3161
+ };
3162
+ const loading = /* @__PURE__ */ new Map();
3163
+ const load = (url) => {
3164
+ const pending = loading.get(url);
3165
+ if (pending) return pending;
3166
+ const task = (async () => {
3167
+ await crawl(url);
3168
+ await Promise.all([...pendingBuiltins].map(async (id) => {
3169
+ if (id === "vue" || id === "vue-router") return;
3170
+ hostModules[id] = await ensureLocalBuiltin(id);
3171
+ }));
3172
+ return evaluate(url);
3173
+ })();
3174
+ loading.set(url, task);
3175
+ return task;
3176
+ };
3177
+ return { load };
3178
+ };
3179
+ //#endregion
3180
+ //#region packages/playground/src/core/runtime/local/local-sandbox.vue?vue&type=script&setup=true&lang.ts
3181
+ var _hoisted_1$2 = ["srcdoc"];
3182
+ var local_sandbox_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
3183
+ __name: "local-sandbox",
3184
+ props: {
3185
+ files: {},
3186
+ entry: {},
3187
+ options: {},
3188
+ previewScroller: {
3189
+ type: Boolean,
3190
+ default: false
3191
+ },
3192
+ clearConsole: {
3193
+ type: Boolean,
3194
+ default: false
3195
+ },
3196
+ autoHeight: {
3197
+ type: Boolean,
3198
+ default: false
3199
+ }
3200
+ },
3201
+ emits: ["error"],
3202
+ setup(__props, { expose: __expose, emit: __emit }) {
3203
+ const props = __props;
3204
+ const emit = __emit;
3205
+ const bridgeSrcdoc = LOCAL_BRIDGE_SRCDOC;
3206
+ const containerEl = ref(null);
3207
+ const bridgeEl = ref(null);
3208
+ const mountEl = ref(null);
3209
+ const compileError = ref("");
3210
+ const runtimeError = ref("");
3211
+ const messageSource = shallowRef(null);
3212
+ let port = null;
3213
+ let previewApp = null;
3214
+ let version = 0;
3215
+ let pendingMount = null;
3216
+ const styleId = `docs-local-${Math.random().toString(36).slice(2, 10)}`;
3217
+ const publishError = () => {
3218
+ emit("error", {
3219
+ compile: compileError.value,
3220
+ runtime: runtimeError.value
3221
+ });
3222
+ };
3223
+ watch([compileError, runtimeError], publishError);
3224
+ const createDocsLink = (preview) => defineComponent({
3225
+ name: "DocsLink",
3226
+ props: { to: {
3227
+ type: String,
3228
+ default: ""
3229
+ } },
3230
+ setup(linkProps, { slots }) {
3231
+ return () => h("a", {
3232
+ href: linkProps.to,
3233
+ style: {
3234
+ color: "inherit",
3235
+ textDecoration: "none"
3236
+ },
3237
+ onClick(event) {
3238
+ event.preventDefault();
3239
+ preview.parent.postMessage({
3240
+ action: "docs:navigate",
3241
+ to: linkProps.to
3242
+ });
3243
+ }
3244
+ }, slots.default?.());
3245
+ }
3246
+ });
3247
+ const destroyPreview = () => {
3248
+ previewApp?.unmount();
3249
+ previewApp = null;
3250
+ removeStyle(styleId);
3251
+ };
3252
+ const mountPreview = (component, preview, css) => {
3253
+ if (!mountEl.value) return;
3254
+ destroyPreview();
3255
+ injectStyle(styleId, css);
3256
+ if (props.clearConsole) console.clear();
3257
+ const useScroller = props.previewScroller === true;
3258
+ const app = Vue.createApp({
3259
+ name: "LocalSandboxRoot",
3260
+ setup() {
3261
+ const service = createLocalPlayground(Vue);
3262
+ provide("docs:playground", service);
3263
+ onErrorCaptured((error) => {
3264
+ const message = formatPlaygroundRuntimeError(error);
3265
+ if (message) runtimeError.value = message;
3266
+ return false;
3267
+ });
3268
+ onBeforeUnmount(() => service.dispose());
3269
+ return () => {
3270
+ const content = h(component);
3271
+ if (!useScroller) return content;
3272
+ return h(Scroller, {
3273
+ height: "100%",
3274
+ native: false,
3275
+ autoResize: true,
3276
+ showBar: true,
3277
+ contentClass: PREVIEW_SCROLL_CONTENT_CLASS
3278
+ }, { default: () => content });
3279
+ };
3280
+ }
3281
+ });
3282
+ app.component("DocsLink", createDocsLink(preview));
3283
+ app.config.errorHandler = (error) => {
3284
+ const message = formatPlaygroundRuntimeError(error);
3285
+ if (message) runtimeError.value = message;
3286
+ };
3287
+ app.mount(mountEl.value);
3288
+ previewApp = app;
3289
+ };
3290
+ const ensurePort = () => {
3291
+ const iframe = bridgeEl.value;
3292
+ if (!iframe?.contentWindow) return null;
3293
+ try {
3294
+ if (!installLocalBridge(iframe)) return null;
3295
+ } catch {
3296
+ return null;
3297
+ }
3298
+ port ??= new LocalPreviewPort(iframe);
3299
+ messageSource.value = iframe.contentWindow;
3300
+ return port;
3301
+ };
3302
+ const tryMount = async () => {
3303
+ const job = pendingMount;
3304
+ /* istanbul ignore if -- 桥接 iframe 尚未就绪或编译已被取代 */
3305
+ if (!job || job.version !== version) return;
3306
+ const preview = ensurePort();
3307
+ /* istanbul ignore if -- 挂载点在编译完成时已经存在 */
3308
+ if (!preview || !mountEl.value) return;
3309
+ await nextTick();
3310
+ /* istanbul ignore if -- 桥接 iframe 尚未就绪或编译已被取代 */
3311
+ if (pendingMount !== job || !mountEl.value) return;
3312
+ pendingMount = null;
3313
+ mountPreview(job.component, preview, job.css);
3314
+ };
3315
+ const run = async () => {
3316
+ const current = ++version;
3317
+ pendingMount = null;
3318
+ compileError.value = "";
3319
+ runtimeError.value = "";
3320
+ publishError();
3321
+ destroyPreview();
3322
+ try {
3323
+ const { compilePlayground } = await import("./compile-CM_OyqYN.js");
3324
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3325
+ if (current !== version) return;
3326
+ const compiled = await compilePlayground(props.files, { entry: props.entry });
3327
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3328
+ if (current !== version) return;
3329
+ if (compiled.errors.length || !compiled.entry) {
3330
+ compileError.value = compiled.errors.join("\n") || "[Playground] 未能确定入口";
3331
+ publishError();
3332
+ return;
3333
+ }
3334
+ const imports = createRuntimeImports(props.options.cdnURL, props.options.builtinImportMap);
3335
+ const specifiers = collectBareSpecifiers(props.files, collectReachableFilenames(props.files, compiled.entry));
3336
+ const remote = createRemoteLoader(imports, {
3337
+ vue: Vue,
3338
+ vueRouter: VueRouter
3339
+ }, props.options.cdnURL);
3340
+ const loaded = await loadLocalModules(specifiers, imports, {
3341
+ vue: Vue,
3342
+ vueRouter: VueRouter
3343
+ }, (url) => remote.load(url), props.options.cdnURL);
3344
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3345
+ if (current !== version) return;
3346
+ if (loaded.errors.length) {
3347
+ compileError.value = loaded.errors.join("\n");
3348
+ publishError();
3349
+ return;
3350
+ }
3351
+ const linked = linkPlayground(compiled, props.files, { modules: loaded.modules });
3352
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3353
+ if (current !== version) return;
3354
+ if (linked.errors.length || !linked.component) {
3355
+ compileError.value = (linked.errors.length ? linked.errors : ["[Playground] 未能解析入口组件"]).join("\n");
3356
+ publishError();
3357
+ return;
3358
+ }
3359
+ pendingMount = {
3360
+ component: linked.component,
3361
+ css: linked.css,
3362
+ version: current
3363
+ };
3364
+ await tryMount();
3365
+ } catch (error) {
3366
+ /* istanbul ignore next -- 编译器自身异常才进入,普通错误走结果里的 errors */
3367
+ if (current !== version) return;
3368
+ /* istanbul ignore next -- 同上,只兜底编译器抛错 */
3369
+ compileError.value = error instanceof Error ? error.message : String(error);
3370
+ /* istanbul ignore next -- 同上,只兜底编译器抛错 */
3371
+ publishError();
3372
+ }
3373
+ };
3374
+ const handleBridgeLoad = () => {
3375
+ tryMount();
3376
+ };
3377
+ onMounted(() => {
3378
+ run();
3379
+ });
3380
+ watch(() => [
3381
+ props.files,
3382
+ props.entry,
3383
+ props.options,
3384
+ props.previewScroller
3385
+ ], () => {
3386
+ if (!containerEl.value) return;
3387
+ run();
3388
+ }, { deep: true });
3389
+ onBeforeUnmount(() => {
3390
+ version += 1;
3391
+ pendingMount = null;
3392
+ destroyPreview();
3393
+ });
3394
+ __expose({
3395
+ container: containerEl,
3396
+ messageSource,
3397
+ local: true,
3398
+ refresh: () => {
3399
+ run();
3400
+ }
3401
+ });
3402
+ return (_ctx, _cache) => {
3403
+ return openBlock(), createElementBlock("div", {
3404
+ ref_key: "containerEl",
3405
+ ref: containerEl,
3406
+ class: "docs-playground-local"
3407
+ }, [createElementVNode("iframe", {
3408
+ ref_key: "bridgeEl",
3409
+ ref: bridgeEl,
3410
+ class: "docs-playground-local__bridge",
3411
+ tabindex: "-1",
3412
+ "aria-hidden": "true",
3413
+ title: "",
3414
+ srcdoc: unref(bridgeSrcdoc),
3415
+ onLoad: handleBridgeLoad
3416
+ }, null, 40, _hoisted_1$2), createElementVNode("div", {
3417
+ ref_key: "mountEl",
3418
+ ref: mountEl,
3419
+ class: normalizeClass(["docs-playground-local__mount", { "docs-playground-local__mount--auto": __props.autoHeight }])
3420
+ }, null, 2)], 512);
3421
+ };
3422
+ }
3423
+ });
3424
+ //#endregion
3425
+ //#region packages/playground/src/core/runtime/local/local-sandbox.vue
3426
+ var local_sandbox_exports = /* @__PURE__ */ __exportAll({ default: () => local_sandbox_default });
3427
+ var local_sandbox_default = local_sandbox_vue_vue_type_script_setup_true_lang_default;
3428
+ //#endregion
1600
3429
  //#region packages/playground/src/core/runtime/runtime.vue?vue&type=script&setup=true&lang.ts
1601
- var _hoisted_1$1 = { class: "docs-playground-runtime-host" };
1602
- var _hoisted_2$1 = {
3430
+ var _hoisted_1$1 = {
1603
3431
  key: 0,
1604
3432
  class: "docs-playground__runtime-error",
1605
3433
  role: "alert"
1606
3434
  };
1607
- var _hoisted_3$1 = {
3435
+ var _hoisted_2$1 = {
1608
3436
  key: 0,
1609
3437
  class: "docs-playground__header"
1610
3438
  };
1611
- var _hoisted_4$1 = ["id", "title"];
1612
- var _hoisted_5$1 = ["href"];
1613
- var _hoisted_6 = { class: "docs-playground__title-text" };
1614
- var _hoisted_7 = {
3439
+ var _hoisted_3$1 = ["id", "title"];
3440
+ var _hoisted_4$1 = ["href"];
3441
+ var _hoisted_5$1 = { class: "docs-playground__title-text" };
3442
+ var _hoisted_6 = {
1615
3443
  key: 1,
1616
3444
  class: "docs-playground__runtime-error",
1617
3445
  role: "alert"
1618
3446
  };
1619
- var _hoisted_8 = { class: "docs-playground-runtime__viewport-stage" };
1620
- var _hoisted_9 = [
3447
+ var _hoisted_7 = { class: "docs-playground-runtime__viewport-stage" };
3448
+ var _hoisted_8 = [
1621
3449
  "aria-expanded",
1622
3450
  "title",
1623
3451
  "aria-label"
@@ -1663,7 +3491,6 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1663
3491
  "navigate"
1664
3492
  ],
1665
3493
  setup(__props, { expose: __expose, emit: __emit }) {
1666
- const LocalSandbox = defineAsyncComponent(() => import("./local-sandbox-B8IJ5jWb.js").then((n) => n.t));
1667
3494
  const props = __props;
1668
3495
  const { locale, t } = useLocale();
1669
3496
  const displayTitle = computed(() => props.title.trim());
@@ -1702,6 +3529,7 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1702
3529
  }.MODE !== "development";
1703
3530
  const copyValue = computed(() => props.files[props.entry] || "");
1704
3531
  const store = props.local ? null : createRuntimeStore(props.files, props.entry, props.options);
3532
+ const storeReady = computed(() => store && !store.loading && Object.values(store.files).every((file) => isIgnoredFilename(file.filename) || !/\.(?:vue|[jt]sx?|json|s[ac]ss)$/.test(file.filename) || !file.code.trim() || !!file.compiled.js));
1705
3533
  const sandboxRef = ref(null);
1706
3534
  const localError = ref({
1707
3535
  compile: "",
@@ -1928,16 +3756,16 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1928
3756
  openPopup: handleOpenPopup
1929
3757
  });
1930
3758
  return (_ctx, _cache) => {
1931
- return openBlock(), createElementBlock("div", _hoisted_1$1, [__props.styleless ? (openBlock(), createElementBlock("div", {
3759
+ return openBlock(), createElementBlock("div", { class: normalizeClass(["docs-playground-runtime-host", { "docs-playground-runtime-host--direct": __props.local && __props.styleless }]) }, [__props.styleless ? (openBlock(), createElementBlock("div", {
1932
3760
  key: 0,
1933
3761
  ref_key: "runtimeRoot",
1934
3762
  ref: runtimeRoot,
1935
3763
  class: "docs-playground-runtime--styleless",
1936
3764
  style: normalizeStyle(stylelessStyle.value)
1937
- }, [errorText.value ? (openBlock(), createElementBlock("pre", _hoisted_2$1, toDisplayString(errorText.value), 1)) : createCommentVNode("v-if", true), createElementVNode("div", {
3765
+ }, [errorText.value ? (openBlock(), createElementBlock("pre", _hoisted_1$1, toDisplayString(errorText.value), 1)) : createCommentVNode("v-if", true), createElementVNode("div", {
1938
3766
  class: "docs-playground-runtime__viewport",
1939
3767
  style: normalizeStyle(viewportStyle.value)
1940
- }, [__props.local ? (openBlock(), createBlock(unref(LocalSandbox), {
3768
+ }, [__props.local ? (openBlock(), createBlock(local_sandbox_default, {
1941
3769
  key: 0,
1942
3770
  ref_key: "sandboxRef",
1943
3771
  ref: sandboxRef,
@@ -1946,13 +3774,15 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1946
3774
  options: __props.options,
1947
3775
  "preview-scroller": __props.previewScroller,
1948
3776
  "clear-console": clearConsole,
3777
+ "auto-height": !unref(getViewportHeight)(__props.viewport),
1949
3778
  onError: handleLocalError
1950
3779
  }, null, 8, [
1951
3780
  "files",
1952
3781
  "entry",
1953
3782
  "options",
1954
- "preview-scroller"
1955
- ])) : unref(store) ? (openBlock(), createBlock(unref(Sandbox), {
3783
+ "preview-scroller",
3784
+ "auto-height"
3785
+ ])) : unref(store) && storeReady.value ? (openBlock(), createBlock(unref(Sandbox), {
1956
3786
  key: 1,
1957
3787
  ref_key: "sandboxRef",
1958
3788
  ref: sandboxRef,
@@ -1965,7 +3795,7 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1965
3795
  ref: runtimeRoot,
1966
3796
  class: "docs-playground-runtime"
1967
3797
  }, [
1968
- !__props.hideChrome ? (openBlock(), createElementBlock("div", _hoisted_3$1, [displayTitle.value ? (openBlock(), createElementBlock("span", {
3798
+ !__props.hideChrome ? (openBlock(), createElementBlock("div", _hoisted_2$1, [displayTitle.value ? (openBlock(), createElementBlock("span", {
1969
3799
  key: 0,
1970
3800
  ref_key: "titleEl",
1971
3801
  ref: titleEl,
@@ -1976,7 +3806,7 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1976
3806
  }, [createElementVNode("a", {
1977
3807
  class: "docs-playground__title-anchor",
1978
3808
  href: `#${titleId.value}`
1979
- }, "#", 8, _hoisted_5$1), createElementVNode("span", _hoisted_6, toDisplayString(displayTitle.value), 1)], 8, _hoisted_4$1)) : createCommentVNode("v-if", true), createVNode(toolbar_default, {
3809
+ }, "#", 8, _hoisted_4$1), createElementVNode("span", _hoisted_5$1, toDisplayString(displayTitle.value), 1)], 8, _hoisted_3$1)) : createCommentVNode("v-if", true), createVNode(toolbar_default, {
1980
3810
  "copy-value": copyValue.value,
1981
3811
  viewport: __props.viewport,
1982
3812
  "viewport-options": __props.viewportOptions,
@@ -1990,14 +3820,14 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1990
3820
  "viewport",
1991
3821
  "viewport-options"
1992
3822
  ])])) : createCommentVNode("v-if", true),
1993
- errorText.value ? (openBlock(), createElementBlock("pre", _hoisted_7, toDisplayString(errorText.value), 1)) : createCommentVNode("v-if", true),
3823
+ errorText.value ? (openBlock(), createElementBlock("pre", _hoisted_6, toDisplayString(errorText.value), 1)) : createCommentVNode("v-if", true),
1994
3824
  createElementVNode("section", {
1995
3825
  class: normalizeClass(["docs-playground__preview", { "is-expanded": previewExpanded.value }]),
1996
3826
  style: normalizeStyle(previewStyle.value)
1997
- }, [createElementVNode("div", _hoisted_8, [createElementVNode("div", {
3827
+ }, [createElementVNode("div", _hoisted_7, [createElementVNode("div", {
1998
3828
  class: "docs-playground-runtime__viewport",
1999
3829
  style: normalizeStyle(viewportStyle.value)
2000
- }, [__props.local ? (openBlock(), createBlock(unref(LocalSandbox), {
3830
+ }, [__props.local ? (openBlock(), createBlock(local_sandbox_default, {
2001
3831
  key: sandboxKey.value,
2002
3832
  ref_key: "sandboxRef",
2003
3833
  ref: sandboxRef,
@@ -2006,13 +3836,15 @@ var runtime_default = /* @__PURE__ */ defineComponent({
2006
3836
  options: __props.options,
2007
3837
  "preview-scroller": __props.previewScroller,
2008
3838
  "clear-console": clearConsole,
3839
+ "auto-height": !unref(getViewportHeight)(__props.viewport),
2009
3840
  onError: handleLocalError
2010
3841
  }, null, 8, [
2011
3842
  "files",
2012
3843
  "entry",
2013
3844
  "options",
2014
- "preview-scroller"
2015
- ])) : unref(store) ? (openBlock(), createBlock(unref(Sandbox), {
3845
+ "preview-scroller",
3846
+ "auto-height"
3847
+ ])) : unref(store) && storeReady.value ? (openBlock(), createBlock(unref(Sandbox), {
2016
3848
  key: sandboxKey.value,
2017
3849
  ref_key: "sandboxRef",
2018
3850
  ref: sandboxRef,
@@ -2029,8 +3861,8 @@ var runtime_default = /* @__PURE__ */ defineComponent({
2029
3861
  title: expandLabel.value,
2030
3862
  "aria-label": expandLabel.value,
2031
3863
  onClick: handleTogglePreviewExpand
2032
- }, [createVNode(unref(icon_default), { name: "expand" })], 10, _hoisted_9)) : createCommentVNode("v-if", true)], 6)
2033
- ], 512))]);
3864
+ }, [createVNode(unref(icon_default), { name: "expand" })], 10, _hoisted_8)) : createCommentVNode("v-if", true)], 6)
3865
+ ], 512))], 2);
2034
3866
  };
2035
3867
  }
2036
3868
  });