@deot/docs-playground 1.1.4 → 1.1.6

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,17 +1,35 @@
1
- import { s as isIgnoredFilename } from "./files-BqucFldk.js";
2
- import { c as NEW_SFC_CODE, i as normalizeCdnURL, n as createBuiltinImports, o as DEFAULT_CDN_URL, r as createBuiltinStyles, s as DEFAULT_ENTRY } from "./cdn-DQoETju_.js";
3
- 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-BOyC8F2y.js";
4
- import { i as whenSassReady } from "./scss-DIh6971q.js";
5
- 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, nextTick, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, ref, renderList, shallowRef, toDisplayString, unref, vModelText, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
4
+ import * as Vc from "@deot/vc";
6
5
  import { Clipboard, Dropdown, DropdownItem, DropdownMenu, Message, Popconfirm, Portal, Scroller, TransitionFade } from "@deot/vc";
7
6
  import { provideLocale, useLocale } from "@deot/docs-locale";
8
7
  import hljs from "highlight.js";
9
- import { Sandbox } from "@vue/repl";
8
+ import { File, Sandbox, useStore } from "@vue/repl";
10
9
  import { EditorView, basicSetup } from "codemirror";
11
10
  import { css } from "@codemirror/lang-css";
12
11
  import { javascript } from "@codemirror/lang-javascript";
13
12
  import { vue } from "@codemirror/lang-vue";
14
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
15
33
  //#region packages/playground/src/highlight.ts
16
34
  var vueHighlight = (api) => ({
17
35
  subLanguage: "xml",
@@ -119,7 +137,7 @@ var PLAYGROUND_ICONS = {
119
137
  };
120
138
  //#endregion
121
139
  //#region packages/playground/src/icon/icon.vue?vue&type=script&setup=true&lang.ts
122
- var _hoisted_1$7 = ["fill", "stroke"];
140
+ var _hoisted_1$8 = ["fill", "stroke"];
123
141
  var _hoisted_2$7 = ["d"];
124
142
  //#endregion
125
143
  //#region packages/playground/src/icon/icon.vue
@@ -151,16 +169,16 @@ var icon_default = /* @__PURE__ */ defineComponent({
151
169
  "stroke-linecap": "round",
152
170
  "stroke-linejoin": "round",
153
171
  "aria-hidden": "true"
154
- }, [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);
155
173
  };
156
174
  }
157
175
  });
158
176
  //#endregion
159
177
  //#region packages/playground/src/core/code-preview/github.css?inline
160
- 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}";
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}@media screen{[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}}";
161
179
  //#endregion
162
180
  //#region packages/playground/src/core/code-preview/code-preview.scss?inline
163
- 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-border-color,#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-lightest,#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}";
164
182
  //#endregion
165
183
  //#region packages/playground/src/core/code-preview/style.ts
166
184
  var CODE_PREVIEW_STYLE_ID = "docs-code-preview-style";
@@ -177,7 +195,7 @@ var ensureCodePreviewStyle = () => {
177
195
  };
178
196
  //#endregion
179
197
  //#region packages/playground/src/core/code-preview/code-preview.vue?vue&type=script&setup=true&lang.ts
180
- var _hoisted_1$6 = { class: "docs-code-preview" };
198
+ var _hoisted_1$7 = { class: "docs-code-preview" };
181
199
  var _hoisted_2$6 = ["title"];
182
200
  var _hoisted_3$6 = { class: "docs-code-preview__code" };
183
201
  var _hoisted_4$6 = ["innerHTML"];
@@ -211,7 +229,7 @@ var code_preview_default = /* @__PURE__ */ defineComponent({
211
229
  const highlightLanguage = computed(() => props.language || resolveHighlightLanguage(props.filename));
212
230
  const highlightedCode = computed(() => highlightCodeByLanguage(props.code, highlightLanguage.value));
213
231
  return (_ctx, _cache) => {
214
- return openBlock(), createElementBlock("div", _hoisted_1$6, [
232
+ return openBlock(), createElementBlock("div", _hoisted_1$7, [
215
233
  languageLabel.value ? (openBlock(), createElementBlock("span", {
216
234
  key: 0,
217
235
  class: "docs-code-preview__language",
@@ -251,7 +269,7 @@ var code_preview_default = /* @__PURE__ */ defineComponent({
251
269
  });
252
270
  //#endregion
253
271
  //#region packages/playground/src/core/files-preview/files-preview.vue?vue&type=script&setup=true&lang.ts
254
- var _hoisted_1$5 = { class: "docs-playground-files" };
272
+ var _hoisted_1$6 = { class: "docs-playground-files" };
255
273
  var _hoisted_2$5 = { class: "docs-playground-files__tabs-row" };
256
274
  var _hoisted_3$5 = ["data-filename", "onClick"];
257
275
  var _hoisted_4$5 = {
@@ -280,7 +298,7 @@ var files_preview_default = /* @__PURE__ */ defineComponent({
280
298
  if (filename !== props.activeFilename) emit("active-change", filename);
281
299
  };
282
300
  return (_ctx, _cache) => {
283
- 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), {
284
302
  class: "docs-playground-files__scroller",
285
303
  "auto-resize": true,
286
304
  native: false,
@@ -425,7 +443,7 @@ var Drag = class {
425
443
  };
426
444
  //#endregion
427
445
  //#region packages/playground/src/editor/editor.vue?vue&type=script&setup=true&lang.ts
428
- var _hoisted_1$4 = { class: "docs-playground-editor" };
446
+ var _hoisted_1$5 = { class: "docs-playground-editor" };
429
447
  var _hoisted_2$4 = ["title"];
430
448
  var _hoisted_3$4 = { class: "docs-playground-editor__files" };
431
449
  var _hoisted_4$4 = [
@@ -675,7 +693,7 @@ var Editor = new Portal(/* @__PURE__ */ defineComponent({
675
693
  editor.value?.destroy();
676
694
  });
677
695
  return (_ctx, _cache) => {
678
- 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 }, {
679
697
  default: withCtx(() => [withDirectives(createElementVNode("div", {
680
698
  ref_key: "wrapper",
681
699
  ref: wrapper,
@@ -831,6 +849,316 @@ var resolvePlaygroundTitleId = (title, explicitId = "", isOccupied) => {
831
849
  while (isOccupied(`${base}-${index}`)) index += 1;
832
850
  return `${base}-${index}`;
833
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
+ };
834
1162
  var resolvePreviewBoxHeight = (contentHeight, verticalInset = 0, borderWidth = 1) => {
835
1163
  const content = Number.isFinite(contentHeight) ? Math.max(0, contentHeight) : 0;
836
1164
  const inset = Number.isFinite(verticalInset) ? Math.max(0, verticalInset) : 0;
@@ -909,6 +1237,68 @@ var scrollPlaygroundToViewportStart = (el) => {
909
1237
  });
910
1238
  };
911
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
912
1302
  //#region packages/playground/src/core/runtime/viewport.ts
913
1303
  var DEFAULT_VIEWPORT_OPTIONS = ["auto", 375];
914
1304
  var isValidViewport = (viewport) => {
@@ -1159,7 +1549,7 @@ function usePreviewHeightBridge(sandbox, maxHeight = () => Infinity) {
1159
1549
  }
1160
1550
  //#endregion
1161
1551
  //#region packages/playground/src/core/runtime/toolbar.vue?vue&type=script&setup=true&lang.ts
1162
- var _hoisted_1$3 = { class: "docs-playground__tools" };
1552
+ var _hoisted_1$4 = { class: "docs-playground__tools" };
1163
1553
  var _hoisted_2$3 = {
1164
1554
  key: 0,
1165
1555
  class: "docs-playground__tool-group"
@@ -1249,7 +1639,7 @@ var toolbar_default = /* @__PURE__ */ defineComponent({
1249
1639
  if (!enabled) viewportMenuVisible.value = false;
1250
1640
  });
1251
1641
  return (_ctx, _cache) => {
1252
- return openBlock(), createElementBlock("div", _hoisted_1$3, [
1642
+ return openBlock(), createElementBlock("div", _hoisted_1$4, [
1253
1643
  __props.showRuntimeActions ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
1254
1644
  __props.viewportOptions.length > 1 ? (openBlock(), createElementBlock("div", _hoisted_2$3, [createVNode(unref(Dropdown), {
1255
1645
  modelValue: viewportMenuVisible.value,
@@ -1374,8 +1764,554 @@ var toolbar_default = /* @__PURE__ */ defineComponent({
1374
1764
  }
1375
1765
  });
1376
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-lightest` 不同,否则会出现色带割裂。
2207
+ */
2208
+ var PLAYGROUND_RUNTIME_CANVAS_BACKGROUND = "var(--vc-background-color-lightest, 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 === "import-map.json" || 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
+ * 保留显式配置的模块,供 local 区分宿主默认与 URL 覆盖。
2245
+ * @param builtinImportMap 实例层 import map。
2246
+ * @returns 按优先级合并的显式模块地址。
2247
+ */
2248
+ var createRuntimeImportOverrides = (builtinImportMap) => ({
2249
+ ...getPlaygroundSiteModules(),
2250
+ ...getPlaygroundImportMapOverrides(),
2251
+ ...filterSafeHrefs(builtinImportMap?.imports)
2252
+ });
2253
+ /**
2254
+ * 默认 CDN → 站点 modules → 管理页覆盖 → 实例 builtinImportMap。
2255
+ * iframe import map 与直接渲染加载的是同一份地址表。
2256
+ * @param cdnURL
2257
+ * @param builtinImportMap
2258
+ */
2259
+ var createRuntimeImports = (cdnURL = DEFAULT_CDN_URL, builtinImportMap) => ({
2260
+ ...createBuiltinImports(cdnURL),
2261
+ ...createRuntimeImportOverrides(builtinImportMap)
2262
+ });
2263
+ var createRuntimeStore = (files, entry, options) => {
2264
+ const { cdnURL, builtinImportMap, ...storeOptions } = options;
2265
+ const replFiles = ref(Object.fromEntries(Object.entries(files).map(([filename, code]) => {
2266
+ const file = createReplFile(filename, code);
2267
+ return [file.filename, file];
2268
+ })));
2269
+ replFiles.value["import-map.json"] ??= new File("import-map.json", "{}");
2270
+ const mainFile = ref(toReplFilename(entry));
2271
+ const activeFilename = ref(toReplFilename(entry));
2272
+ const imports = createRuntimeImports(cdnURL, builtinImportMap);
2273
+ const store = useStore({
2274
+ ...storeOptions,
2275
+ files: replFiles,
2276
+ mainFile,
2277
+ activeFilename,
2278
+ builtinImportMap: ref({
2279
+ ...builtinImportMap,
2280
+ imports
2281
+ }),
2282
+ template: ref({
2283
+ welcomeSFC: files[entry],
2284
+ newSFC: NEW_SFC_CODE
2285
+ })
2286
+ });
2287
+ bindPlaygroundScss(store);
2288
+ const setFiles = store.setFiles.bind(store);
2289
+ store.setFiles = (nextFiles, nextEntry) => setFiles({
2290
+ "import-map.json": store.files["import-map.json"].code,
2291
+ ...nextFiles
2292
+ }, nextEntry);
2293
+ bindReplModules(store);
2294
+ whenSassReady(files, () => {
2295
+ const specifiers = collectBareSpecifiers(files, Object.keys(files));
2296
+ if (!specifiers.length) {
2297
+ store.init();
2298
+ return;
2299
+ }
2300
+ store.loading = true;
2301
+ resolveReplImports(imports, specifiers).then((resolved) => {
2302
+ if (Object.keys(resolved).length !== Object.keys(imports).length) store.setImportMap({ imports: resolved }, true);
2303
+ store.init();
2304
+ }).catch((error) => {
2305
+ store.errors.push(error);
2306
+ }).finally(() => {
2307
+ store.loading = false;
2308
+ });
2309
+ });
2310
+ return store;
2311
+ };
2312
+ //#endregion
1377
2313
  //#region packages/playground/src/core/runtime/alone/wrapper.vue?vue&type=script&setup=true&lang.ts
1378
- var _hoisted_1$2 = ["aria-label"];
2314
+ var _hoisted_1$3 = ["aria-label"];
1379
2315
  var _hoisted_2$2 = { class: "docs-playground-popup__frame" };
1380
2316
  var _hoisted_3$2 = { class: "docs-playground-popup__header" };
1381
2317
  var _hoisted_4$2 = ["title"];
@@ -1420,7 +2356,7 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1420
2356
  "portal-fulfilled"
1421
2357
  ],
1422
2358
  setup(__props, { emit: __emit }) {
1423
- const LocalSandbox = defineAsyncComponent(() => import("./local-sandbox-DvcgaBOa.js").then((n) => n.t));
2359
+ const LocalSandbox = defineAsyncComponent(() => Promise.resolve().then(() => local_sandbox_exports));
1424
2360
  const props = __props;
1425
2361
  const emit = __emit;
1426
2362
  const { t } = useLocale();
@@ -1589,7 +2525,7 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1589
2525
  ])) : createCommentVNode("v-if", true)], 4)]),
1590
2526
  _: 1
1591
2527
  })])
1592
- ])], 4)], 8, _hoisted_1$2);
2528
+ ])], 4)], 8, _hoisted_1$3);
1593
2529
  };
1594
2530
  }
1595
2531
  }), {
@@ -1598,6 +2534,935 @@ var Alone = new Portal(/* @__PURE__ */ defineComponent({
1598
2534
  multiple: false
1599
2535
  });
1600
2536
  //#endregion
2537
+ //#region packages/playground/src/core/runtime/local/playground.ts
2538
+ /**
2539
+ * 直接渲染与页面同文档,弹层不需要临时撑高。
2540
+ * `run` 仍返回可调用函数,但不会申请高度,也不会改动预览尺寸。
2541
+ * @param vue 当前预览的 Vue,只用其中的 `isRef`。
2542
+ * @returns 注入给预览的 `docs:playground`。
2543
+ */
2544
+ var createLocalPlayground = (vue) => {
2545
+ const run = (_height, optionsOrHandler, lastHandler) => {
2546
+ const visible = (typeof optionsOrHandler === "function" || optionsOrHandler == null ? {} : optionsOrHandler).visible;
2547
+ const handler = typeof optionsOrHandler === "function" ? optionsOrHandler : typeof lastHandler === "function" ? lastHandler : vue.isRef(visible) ? () => {
2548
+ visible.value = true;
2549
+ } : void 0;
2550
+ return (...args) => {
2551
+ if (typeof handler !== "function") return void 0;
2552
+ return handler(...args);
2553
+ };
2554
+ };
2555
+ return {
2556
+ enable: () => Promise.resolve(true),
2557
+ disable() {},
2558
+ dispose() {},
2559
+ run
2560
+ };
2561
+ };
2562
+ //#endregion
2563
+ //#region packages/playground/src/core/runtime/local/port.ts
2564
+ /** 只在桥接 iframe 内部转发,保证父页面收到的 source 是该 iframe。 */
2565
+ var LOCAL_BRIDGE_CHANNEL = "docs:local-out";
2566
+ var BRIDGE_INSTALLER = `
2567
+ if (!window.__docsLocalBridge) {
2568
+ window.__docsLocalBridge = true;
2569
+ window.addEventListener('message', function (event) {
2570
+ var data = event.data;
2571
+ if (!data || data.channel !== ${JSON.stringify(LOCAL_BRIDGE_CHANNEL)}) return;
2572
+ window.parent.postMessage(data.payload, '*');
2573
+ });
2574
+ }
2575
+ `;
2576
+ var LOCAL_BRIDGE_SRCDOC = `<!doctype html><html><head></head><body><script>${BRIDGE_INSTALLER}<\/script></body></html>`;
2577
+ /**
2578
+ * 在同源空白 iframe 里安装转发脚本。调用发生在 iframe realm,父页面看到的 source 才是它。
2579
+ * @param iframe 用作消息身份的空白 iframe。
2580
+ * @returns 脚本是否已经装上。
2581
+ */
2582
+ var installLocalBridge = (iframe) => {
2583
+ const win = iframe.contentWindow;
2584
+ if (!win || win.__docsLocalBridge) return Boolean(win?.__docsLocalBridge);
2585
+ win.eval(BRIDGE_INSTALLER);
2586
+ return Boolean(win.__docsLocalBridge);
2587
+ };
2588
+ /**
2589
+ * 满足 PlaygroundService 现有 Window 调用的预览窗口。
2590
+ * 出站消息经 iframe 转发,入站回复再交回服务,协议仍是 docs:height / docs:navigate。
2591
+ */
2592
+ var LocalPreviewPort = class {
2593
+ iframe;
2594
+ parent;
2595
+ listeners = /* @__PURE__ */ new Map();
2596
+ constructor(iframe) {
2597
+ this.iframe = iframe;
2598
+ this.parent = { postMessage: (data) => {
2599
+ this.iframe.contentWindow?.postMessage({
2600
+ channel: LOCAL_BRIDGE_CHANNEL,
2601
+ payload: data
2602
+ }, "*");
2603
+ } };
2604
+ }
2605
+ get contentWindow() {
2606
+ return this.iframe.contentWindow;
2607
+ }
2608
+ get innerHeight() {
2609
+ const fromWindow = this.iframe.contentWindow?.innerHeight ?? 0;
2610
+ if (fromWindow > 0) return fromWindow;
2611
+ return this.iframe.clientHeight || this.iframe.parentElement?.clientHeight || 0;
2612
+ }
2613
+ addEventListener(type, listener) {
2614
+ const win = this.iframe.contentWindow;
2615
+ if (!win) return;
2616
+ if (type !== "message") {
2617
+ win.addEventListener(type, listener);
2618
+ return;
2619
+ }
2620
+ const wrapped = (event) => {
2621
+ const message = event;
2622
+ const data = message.data;
2623
+ if (data && data.channel === "docs:local-out") return;
2624
+ listener({
2625
+ data: message.data,
2626
+ source: this.parent
2627
+ });
2628
+ };
2629
+ this.listeners.set(listener, wrapped);
2630
+ win.addEventListener("message", wrapped);
2631
+ }
2632
+ removeEventListener(type, listener) {
2633
+ const win = this.iframe.contentWindow;
2634
+ if (!win) return;
2635
+ const wrapped = this.listeners.get(listener);
2636
+ if (wrapped) {
2637
+ this.listeners.delete(listener);
2638
+ win.removeEventListener(type, wrapped);
2639
+ return;
2640
+ }
2641
+ win.removeEventListener(type, listener);
2642
+ }
2643
+ requestAnimationFrame(callback) {
2644
+ return window.requestAnimationFrame(callback);
2645
+ }
2646
+ cancelAnimationFrame(handle) {
2647
+ window.cancelAnimationFrame(handle);
2648
+ }
2649
+ setTimeout(handler, timeout, ...args) {
2650
+ return window.setTimeout(handler, timeout, ...args);
2651
+ }
2652
+ clearTimeout(handle) {
2653
+ window.clearTimeout(handle);
2654
+ }
2655
+ };
2656
+ //#endregion
2657
+ //#region packages/playground/src/core/runtime/local/format-error.ts
2658
+ /**
2659
+ * 空 reject(例如弹层取消)不要渲染成红条。
2660
+ * @param error 运行时抛出的值。
2661
+ * @returns 可展示的错误文本;空取消返回空字符串。
2662
+ */
2663
+ var formatPlaygroundRuntimeError = (error) => {
2664
+ if (error == null) return "";
2665
+ const raw = typeof error === "object" && "message" in error ? error.message : error;
2666
+ if (raw == null || raw === "") return "";
2667
+ const text = String(raw);
2668
+ if (text === "undefined" || text === "null") return "";
2669
+ return text;
2670
+ };
2671
+ //#endregion
2672
+ //#region packages/playground/src/core/runtime/local/builtins.ts
2673
+ var loaders = {
2674
+ "vue": () => import("vue"),
2675
+ "vue-router": () => import("vue-router"),
2676
+ "pinia": async () => Pinia,
2677
+ "@deot/helper": () => import("@deot/helper"),
2678
+ "@deot/helper-cache": () => import("@deot/helper-cache"),
2679
+ "@deot/helper-device": () => import("@deot/helper-device"),
2680
+ "@deot/helper-dom": () => import("@deot/helper-dom"),
2681
+ "@deot/helper-emitter": () => import("@deot/helper-emitter"),
2682
+ "@deot/helper-fp": () => import("@deot/helper-fp"),
2683
+ "@deot/helper-is": () => import("@deot/helper-is"),
2684
+ "@deot/helper-load": () => import("@deot/helper-load"),
2685
+ "@deot/helper-resize": () => import("@deot/helper-resize"),
2686
+ "@deot/helper-route": () => import("@deot/helper-route"),
2687
+ "@deot/helper-scheduler": () => import("@deot/helper-scheduler"),
2688
+ "@deot/helper-shared": () => import("@deot/helper-shared"),
2689
+ "@deot/helper-unicode": () => import("@deot/helper-unicode"),
2690
+ "@deot/helper-utils": () => import("@deot/helper-utils"),
2691
+ "@deot/helper-validator": () => import("@deot/helper-validator"),
2692
+ "@deot/helper-wheel": () => import("@deot/helper-wheel"),
2693
+ "@deot/http-client": () => import("@deot/http-client"),
2694
+ "@deot/http-core": () => import("@deot/http-core"),
2695
+ "@deot/http-hooks": () => import("@deot/http-hooks"),
2696
+ "@deot/http": () => import("@deot/http"),
2697
+ "@deot/vc": async () => Vc,
2698
+ "@deot/vc-components": async () => VcComponents,
2699
+ "@deot/vc-hooks": async () => VcHooks,
2700
+ "@deot/vc-locale": () => import("@deot/vc-locale"),
2701
+ "lodash-es": () => import("lodash-es"),
2702
+ "echarts": () => import("echarts"),
2703
+ "photoswipe": () => import("photoswipe"),
2704
+ "jszip": () => import("jszip"),
2705
+ "jspdf": () => import("jspdf"),
2706
+ "dayjs": async () => (await import("dayjs")).default
2707
+ };
2708
+ var cache = /* @__PURE__ */ new Map();
2709
+ /** 直接渲染可从宿主包注入的说明符;与 Vue 无关的大型依赖按需加载。 */
2710
+ var localBuiltinIds = new Set(Object.keys(loaders));
2711
+ var ensureLocalBuiltin = (id) => {
2712
+ const loader = loaders[id];
2713
+ if (!loader) return Promise.reject(/* @__PURE__ */ new Error(`[Playground] 没有本地模块 "${id}"`));
2714
+ let pending = cache.get(id);
2715
+ if (!pending) {
2716
+ pending = loader();
2717
+ cache.set(id, pending);
2718
+ }
2719
+ return pending;
2720
+ };
2721
+ //#endregion
2722
+ //#region packages/playground/src/core/runtime/local/modules.ts
2723
+ var SKIP_COPY_KEYS = /* @__PURE__ */ new Set([
2724
+ "prototype",
2725
+ "caller",
2726
+ "arguments"
2727
+ ]);
2728
+ var toHostModule = (ns) => {
2729
+ if (ns == null || typeof ns !== "object" && typeof ns !== "function") return {
2730
+ __esModule: true,
2731
+ default: ns
2732
+ };
2733
+ const source = ns;
2734
+ const mod = { __esModule: true };
2735
+ const assignKey = (key) => {
2736
+ if (SKIP_COPY_KEYS.has(key) || key === "__esModule") return;
2737
+ try {
2738
+ mod[key] = source[key];
2739
+ } catch {}
2740
+ };
2741
+ try {
2742
+ Object.keys(source).forEach(assignKey);
2743
+ } catch {}
2744
+ try {
2745
+ Object.getOwnPropertyNames(source).forEach(assignKey);
2746
+ } catch {}
2747
+ if (!("default" in mod) || mod.default === void 0) mod.default = source.default !== void 0 ? source.default : source;
2748
+ return mod;
2749
+ };
2750
+ var lookupHostModule = (id, modules) => {
2751
+ if (Object.prototype.hasOwnProperty.call(modules, id)) return toHostModule(modules[id]);
2752
+ return null;
2753
+ };
2754
+ var pickNestedExport = (rootMod, rest) => {
2755
+ if (!rest) return void 0;
2756
+ const parts = rest.split("/").filter(Boolean);
2757
+ let current = rootMod;
2758
+ for (const part of parts) {
2759
+ if (current == null || typeof current !== "object" && typeof current !== "function") return;
2760
+ const record = current;
2761
+ if (!(part in record)) return void 0;
2762
+ current = record[part];
2763
+ }
2764
+ return current;
2765
+ };
2766
+ /**
2767
+ * 先精确匹配,再从右往左剥路径,把剩余段当成导出属性。
2768
+ * 模块表只来自当前 Playground,不写入全局注册表。
2769
+ * @param id 裸模块说明符。
2770
+ * @param modules 当前 Playground 的模块表。
2771
+ * @returns 可被 `require` 使用的模块;找不到时返回 null。
2772
+ */
2773
+ var resolveHostModule = (id, modules) => {
2774
+ const exact = lookupHostModule(id, modules);
2775
+ if (exact) return exact;
2776
+ let cursor = id;
2777
+ while (true) {
2778
+ const slash = cursor.lastIndexOf("/");
2779
+ if (slash <= 0) break;
2780
+ const parent = cursor.slice(0, slash);
2781
+ const rest = id.slice(parent.length + 1);
2782
+ const rootMod = lookupHostModule(parent, modules);
2783
+ if (rootMod) {
2784
+ const nested = pickNestedExport(rootMod, rest);
2785
+ if (nested !== void 0) return toHostModule(nested);
2786
+ }
2787
+ cursor = parent;
2788
+ }
2789
+ return null;
2790
+ };
2791
+ var HOST_VUE_SPECIFIERS = /* @__PURE__ */ new Set(["vue", "vue/server-renderer"]);
2792
+ var VUE_DEPENDENT_BUILTINS = /* @__PURE__ */ new Set([
2793
+ "vue/server-renderer",
2794
+ "vue-router",
2795
+ "pinia",
2796
+ "@deot/vc",
2797
+ "@deot/vc-components",
2798
+ "@deot/vc-hooks",
2799
+ "@deot/vc-locale"
2800
+ ]);
2801
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
2802
+ /**
2803
+ * 找到 import map 里能覆盖该说明符的键。子路径没有独立 URL 时回退到父包。
2804
+ * @param id 裸模块说明符。
2805
+ * @param imports 合并后的 import map。
2806
+ * @returns 命中的 import map 键;没有地址时返回 null。
2807
+ */
2808
+ var resolveImportTarget = (id, imports) => {
2809
+ if (imports[id]) return id;
2810
+ let cursor = id;
2811
+ while (true) {
2812
+ const slash = cursor.lastIndexOf("/");
2813
+ if (slash <= 0) return null;
2814
+ const parent = cursor.slice(0, slash);
2815
+ if (imports[parent]) return parent;
2816
+ cursor = parent;
2817
+ }
2818
+ };
2819
+ var prefersLocalBuiltin = (id, imports, overrides = new Set(Object.keys(imports))) => {
2820
+ if (!localBuiltinIds.has(id) && !HOST_VUE_SPECIFIERS.has(id)) return false;
2821
+ if (overrides.has(id)) return false;
2822
+ return !VUE_DEPENDENT_BUILTINS.has(id) || !overrides.has("vue");
2823
+ };
2824
+ /**
2825
+ * 内置依赖默认注入宿主副本,显式 URL 按模块覆盖,包括与默认 CDN 相同的地址。
2826
+ * @param specifiers 本次预览用到的裸模块说明符。
2827
+ * @param imports 合并后的 import map。
2828
+ * @param builtins 宿主 Vue 与 vue-router。
2829
+ * @param builtins.vue 当前页面的 Vue 模块。
2830
+ * @param builtins.vueRouter 打包进来的 vue-router,可被 import map 覆盖。
2831
+ * @param loader 按 URL 加载远程模块。
2832
+ * @param overrides 显式配置的模块名,与自动补齐的默认地址区分。
2833
+ * @returns 模块表和加载错误。
2834
+ */
2835
+ var loadLocalModules = async (specifiers, imports, builtins, loader, overrides = new Set(Object.keys(imports))) => {
2836
+ const modules = {
2837
+ "vue": builtins.vue,
2838
+ "vue-router": builtins.vueRouter
2839
+ };
2840
+ const errors = [];
2841
+ const targets = /* @__PURE__ */ new Set();
2842
+ const localIds = /* @__PURE__ */ new Set();
2843
+ specifiers.forEach((specifier) => {
2844
+ let local = false;
2845
+ if (prefersLocalBuiltin(specifier, imports, overrides)) localIds.add(specifier);
2846
+ else {
2847
+ let cursor = specifier;
2848
+ while (true) {
2849
+ const slash = cursor.lastIndexOf("/");
2850
+ if (slash <= 0) break;
2851
+ const parent = cursor.slice(0, slash);
2852
+ if (prefersLocalBuiltin(parent, imports, overrides)) {
2853
+ localIds.add(parent);
2854
+ local = true;
2855
+ break;
2856
+ }
2857
+ cursor = parent;
2858
+ }
2859
+ }
2860
+ const target = resolveImportTarget(specifier, imports);
2861
+ if (target && prefersLocalBuiltin(target, imports, overrides)) localIds.add(target);
2862
+ else if (target) targets.add(target);
2863
+ else if (!local && !localIds.has(specifier)) {
2864
+ imports[specifier] = resolveNpmImport(specifier);
2865
+ targets.add(specifier);
2866
+ }
2867
+ });
2868
+ await Promise.all([...localIds].map(async (id) => {
2869
+ if (id === "vue" || id === "vue-router") return;
2870
+ if (id === "vue/server-renderer") {
2871
+ modules[id] = builtins.vue;
2872
+ return;
2873
+ }
2874
+ modules[id] = await ensureLocalBuiltin(id);
2875
+ }));
2876
+ for (const id of targets) {
2877
+ const url = imports[id];
2878
+ if (!url || prefersLocalBuiltin(id, imports, overrides)) continue;
2879
+ try {
2880
+ modules[id] = await loader(url);
2881
+ } catch (error) {
2882
+ errors.push(`[Playground] 无法加载模块 "${id}" (${url}): ${messageOf(error)}`);
2883
+ }
2884
+ }
2885
+ return {
2886
+ modules,
2887
+ errors
2888
+ };
2889
+ };
2890
+ //#endregion
2891
+ //#region packages/playground/src/core/runtime/local/vue-guard.ts
2892
+ /**
2893
+ * 给 files 注入选定的 Vue,但 `createApp().mount` 不会卸掉页面。
2894
+ * 防护按本次 link 创建,多个 Playground 互不覆盖。
2895
+ * @param capture 本次链接收集到的根组件、局部组件和 provide。
2896
+ * @param vue 当前预览选定的 Vue。
2897
+ * @returns 带防护的 Vue 模块。
2898
+ */
2899
+ var createGuardedVue = (capture, vue = Vue) => {
2900
+ const createApp = (rootComponent, rootProps) => {
2901
+ const fakeApp = {
2902
+ _component: rootComponent,
2903
+ _props: rootProps,
2904
+ config: {
2905
+ errorHandler: null,
2906
+ warnHandler: null,
2907
+ globalProperties: {}
2908
+ },
2909
+ _context: {
2910
+ provides: Object.create(null),
2911
+ components: Object.create(null),
2912
+ directives: Object.create(null),
2913
+ mixins: []
2914
+ },
2915
+ use() {
2916
+ return fakeApp;
2917
+ },
2918
+ mixin(mixin) {
2919
+ fakeApp._context.mixins.push(mixin);
2920
+ return fakeApp;
2921
+ },
2922
+ component(name, component) {
2923
+ if (component) {
2924
+ fakeApp._context.components[name] = component;
2925
+ return fakeApp;
2926
+ }
2927
+ return fakeApp._context.components[name];
2928
+ },
2929
+ directive() {
2930
+ return fakeApp;
2931
+ },
2932
+ provide(key, value) {
2933
+ fakeApp._context.provides[key] = value;
2934
+ return fakeApp;
2935
+ },
2936
+ mount() {
2937
+ capture.components = { ...fakeApp._context.components };
2938
+ capture.provides = { ...fakeApp._context.provides };
2939
+ capture.mountedComponent = vue.defineComponent({
2940
+ name: "PlaygroundCapturedApp",
2941
+ components: fakeApp._context.components,
2942
+ setup() {
2943
+ Reflect.ownKeys(fakeApp._context.provides).forEach((key) => {
2944
+ vue.provide(key, fakeApp._context.provides[key]);
2945
+ });
2946
+ return () => vue.h(rootComponent, rootProps || null);
2947
+ }
2948
+ });
2949
+ return capture.mountedComponent;
2950
+ },
2951
+ unmount() {},
2952
+ onUnmount() {
2953
+ return fakeApp;
2954
+ }
2955
+ };
2956
+ return fakeApp;
2957
+ };
2958
+ return new Proxy(vue, { get(target, prop, receiver) {
2959
+ if (prop === "createApp" || prop === "createSSRApp") return createApp;
2960
+ if (prop === "default") return receiver;
2961
+ return Reflect.get(target, prop, receiver);
2962
+ } });
2963
+ };
2964
+ //#endregion
2965
+ //#region packages/playground/src/core/runtime/local/linker.ts
2966
+ /**
2967
+ * 在当前页面链接编译结果,返回入口组件。
2968
+ * 给选定的 Vue 加上 mount 防护,避免字符串入口卸掉页面。
2969
+ * @param compiled 浏览器编译结果。
2970
+ * @param files 当前 Playground 文件表。
2971
+ * @param options 可选的宿主模块表。
2972
+ * @returns 入口组件、样式和链接错误。
2973
+ */
2974
+ var linkPlayground = (compiled, files, options = {}) => {
2975
+ const errors = [...compiled.errors || []];
2976
+ if (!compiled.entry || errors.length) return {
2977
+ component: null,
2978
+ css: compiled.css || [],
2979
+ errors
2980
+ };
2981
+ const capture = {
2982
+ mountedComponent: null,
2983
+ components: {},
2984
+ provides: {}
2985
+ };
2986
+ const modules = { ...options.modules || {} };
2987
+ modules.vue = createGuardedVue(capture, modules.vue || Vue);
2988
+ const fileIndex = createFileIndex(files);
2989
+ const root = getCommonRoot([...fileIndex.keys()]);
2990
+ const cache = /* @__PURE__ */ new Map();
2991
+ const visiting = /* @__PURE__ */ new Set();
2992
+ const requireFn = (fromFilename) => (id) => {
2993
+ if (isRelativeSpecifier(id)) {
2994
+ const resolved = resolveModulePath(fromFilename, id, fileIndex);
2995
+ if (!resolved) throw new Error(`[Playground] 无法解析相对模块 "${id}"(来自 ${fromFilename})`);
2996
+ /* istanbul ignore if -- 公共根已包含全部 files,正常解析不会逃出 */
2997
+ if (!isInsideRoot(resolved, root)) throw new Error(`[Playground] 模块逃出虚拟根: ${resolved}`);
2998
+ return loadModule(resolved);
2999
+ }
3000
+ const host = resolveHostModule(id, modules);
3001
+ if (host) return host;
3002
+ throw new Error(`[Playground] 未注册的模块 "${id}"。请在 import map 中提供可加载的地址。`);
3003
+ };
3004
+ const loadModule = (filename) => {
3005
+ const key = normalizeVirtualPath(filename);
3006
+ if (cache.has(key)) return cache.get(key);
3007
+ if (visiting.has(key)) return cache.get(key);
3008
+ const mod = compiled.modules[key];
3009
+ if (!mod) throw new Error(`[Playground] 缺少编译模块: ${key}`);
3010
+ const module = { exports: {} };
3011
+ cache.set(key, module.exports);
3012
+ visiting.add(key);
3013
+ try {
3014
+ new Function("require", "module", "exports", mod.js)(requireFn(key), module, module.exports);
3015
+ cache.set(key, module.exports);
3016
+ return module.exports;
3017
+ } catch (error) {
3018
+ const message = error instanceof Error ? error.message : String(error);
3019
+ errors.push(`[Playground] 执行失败 ${key}: ${message}`);
3020
+ throw error;
3021
+ } finally {
3022
+ visiting.delete(key);
3023
+ }
3024
+ };
3025
+ try {
3026
+ const entryExports = loadModule(compiled.entry);
3027
+ let component = entryExports?.default ?? entryExports;
3028
+ if (capture.mountedComponent) component = capture.mountedComponent;
3029
+ /* istanbul ignore if -- 空入口在编译阶段已经报错 */
3030
+ if (!component) {
3031
+ errors.push("[Playground] 入口必须 export default 组件,或调用 createApp(App).mount()");
3032
+ return {
3033
+ component: null,
3034
+ css: compiled.css || [],
3035
+ errors
3036
+ };
3037
+ }
3038
+ return {
3039
+ component,
3040
+ css: compiled.css || [],
3041
+ errors
3042
+ };
3043
+ } catch (error) {
3044
+ if (!errors.length) errors.push(error instanceof Error ? error.message : String(error));
3045
+ return {
3046
+ component: null,
3047
+ css: compiled.css || [],
3048
+ errors
3049
+ };
3050
+ }
3051
+ };
3052
+ //#endregion
3053
+ //#region packages/playground/src/core/runtime/local/remote.ts
3054
+ var HOST_VUE = /* @__PURE__ */ new Set(["vue", "vue/server-renderer"]);
3055
+ var moduleUrl = (url) => new URL(url, globalThis.location?.href).href;
3056
+ /**
3057
+ * 把 CDN 上的 ESM 先拉完整张依赖图,再在当前页面里执行。
3058
+ * 裸导入优先走 import map,缺失的 npm 依赖回退到 CDN ESM;import() 按需加载。
3059
+ * @param imports 合并后的 import map。
3060
+ * @param builtins 宿主 Vue 与 vue-router。
3061
+ * @param overrides 显式配置的模块名,与自动补齐的默认地址区分。
3062
+ * @param importModule 浏览器原生 ESM 加载器。
3063
+ * @returns 按 URL 加载并执行远程模块的加载器。
3064
+ */
3065
+ var createRemoteLoader = (imports, builtins, overrides = new Set(Object.keys(imports)), importModule = (url) => import(
3066
+ /* @vite-ignore */
3067
+ url
3068
+ )) => {
3069
+ const hostModules = {
3070
+ "vue": builtins.vue,
3071
+ "vue-router": builtins.vueRouter
3072
+ };
3073
+ const pendingBuiltins = /* @__PURE__ */ new Set();
3074
+ const texts = /* @__PURE__ */ new Map();
3075
+ const evaluated = /* @__PURE__ */ new Map();
3076
+ const crawled = /* @__PURE__ */ new Set();
3077
+ const nativeModules = /* @__PURE__ */ new Map();
3078
+ const loadNative = (url) => {
3079
+ let pending = nativeModules.get(url);
3080
+ if (!pending) {
3081
+ pending = importModule(url).then((module) => {
3082
+ const exports = toHostModule(module);
3083
+ evaluated.set(url, exports);
3084
+ return exports;
3085
+ });
3086
+ nativeModules.set(url, pending);
3087
+ }
3088
+ return pending;
3089
+ };
3090
+ const localBuiltinId = (id) => {
3091
+ if (imports[id] && !prefersLocalBuiltin(id, imports, overrides)) return null;
3092
+ if (prefersLocalBuiltin(id, imports, overrides)) return id;
3093
+ let cursor = id;
3094
+ while (true) {
3095
+ const slash = cursor.lastIndexOf("/");
3096
+ if (slash <= 0) return null;
3097
+ const parent = cursor.slice(0, slash);
3098
+ if (prefersLocalBuiltin(parent, imports, overrides)) return parent;
3099
+ cursor = parent;
3100
+ }
3101
+ };
3102
+ const dependencySpecifier = (from, specifier) => {
3103
+ if (isRelativeSpecifier(specifier) || /^https?:\/\//.test(specifier)) {
3104
+ const url = new URL(specifier, from);
3105
+ const match = url.origin === "https://cdn.jsdelivr.net" ? url.pathname.match(/^\/npm\/((?:@[^/]+\/)?[^/@]+)(?:@[^/]+)?\/\+esm$/) : null;
3106
+ if (match && (imports[match[1]] || localBuiltinIds.has(match[1]))) return match[1];
3107
+ return url.href;
3108
+ }
3109
+ return specifier;
3110
+ };
3111
+ const dependencyUrl = (from, id) => {
3112
+ const specifier = dependencySpecifier(from, id);
3113
+ if (/^https?:\/\//.test(specifier)) return specifier;
3114
+ if (imports[specifier] && !prefersLocalBuiltin(specifier, imports, overrides)) return moduleUrl(imports[specifier]);
3115
+ if (HOST_VUE.has(specifier) && prefersLocalBuiltin(specifier, imports, overrides)) return null;
3116
+ let cursor = specifier;
3117
+ while (cursor) {
3118
+ if (localBuiltinIds.has(cursor) && prefersLocalBuiltin(cursor, imports, overrides)) {
3119
+ pendingBuiltins.add(cursor);
3120
+ return null;
3121
+ }
3122
+ const slash = cursor.lastIndexOf("/");
3123
+ if (slash <= 0) break;
3124
+ cursor = cursor.slice(0, slash);
3125
+ }
3126
+ const target = imports[specifier] ? specifier : resolveImportTarget(specifier, imports);
3127
+ if (!target) {
3128
+ imports[specifier] = resolveNpmImport(specifier);
3129
+ return imports[specifier];
3130
+ }
3131
+ return moduleUrl(imports[target]);
3132
+ };
3133
+ const crawl = async (url) => {
3134
+ if (!overrides.size && /\/\+esm(?:[?#]|$)/.test(url)) {
3135
+ await loadNative(url);
3136
+ return;
3137
+ }
3138
+ if (crawled.has(url)) return;
3139
+ crawled.add(url);
3140
+ const response = await fetch(url);
3141
+ if (!response.ok) throw new Error(`${response.status} ${url}`);
3142
+ const text = await response.text();
3143
+ await init();
3144
+ const [specifiers] = parse(text);
3145
+ let source = text;
3146
+ for (const item of [...specifiers].reverse()) if (item.type === "dynamic") source = source.slice(0, item.importStart) + "__import" + source.slice(item.importStart + 6);
3147
+ texts.set(url, source);
3148
+ await Promise.all(specifiers.map(async (item) => {
3149
+ if (item.type !== "static" && item.type !== "reexport-star") return;
3150
+ const next = dependencyUrl(url, item.specifier);
3151
+ if (next) await crawl(next);
3152
+ }));
3153
+ };
3154
+ const requireFrom = (from) => (specifier) => {
3155
+ const id = dependencySpecifier(from, specifier);
3156
+ if (HOST_VUE.has(id) && prefersLocalBuiltin(id, imports, overrides)) return toHostModule(builtins.vue);
3157
+ const builtinId = localBuiltinId(id);
3158
+ if (builtinId) return toHostModule(hostModules[builtinId]);
3159
+ if (isRelativeSpecifier(id) || /^https?:\/\//.test(id)) return evaluate(dependencyUrl(from, id));
3160
+ const target = imports[id] ? id : resolveImportTarget(id, imports);
3161
+ if (!target || !imports[target]) throw new Error(`[Playground] 未注册的模块 "${id}"`);
3162
+ const loaded = evaluate(moduleUrl(imports[target]));
3163
+ if (target === id) return loaded;
3164
+ if (!resolveHostModule(id, { [target]: loaded }))
3165
+ /* istanbul ignore next -- 父包没有对应导出时才拒绝 */
3166
+ throw new Error(`[Playground] 未注册的模块 "${id}"`);
3167
+ return loaded;
3168
+ };
3169
+ const evaluate = (url) => {
3170
+ if (evaluated.has(url)) return evaluated.get(url);
3171
+ const text = texts.get(url);
3172
+ if (text == null) throw new Error(`[Playground] 远程模块尚未下载: ${url}`);
3173
+ const cjs = transform(rewriteImportMeta(text, url), {
3174
+ transforms: ["imports"],
3175
+ disableESTransforms: true,
3176
+ production: true,
3177
+ filePath: url
3178
+ }).code;
3179
+ const module = { exports: {} };
3180
+ evaluated.set(url, module.exports);
3181
+ new Function("require", "module", "exports", "__import", cjs)(requireFrom(url), module, module.exports, async (id) => {
3182
+ const next = dependencyUrl(url, id);
3183
+ if (next) await load(next);
3184
+ else {
3185
+ const builtinId = localBuiltinId(dependencySpecifier(url, id));
3186
+ if (builtinId && !(builtinId in hostModules)) hostModules[builtinId] = await ensureLocalBuiltin(builtinId);
3187
+ }
3188
+ return requireFrom(url)(id);
3189
+ });
3190
+ evaluated.set(url, module.exports);
3191
+ return module.exports;
3192
+ };
3193
+ const loading = /* @__PURE__ */ new Map();
3194
+ const load = (sourceUrl) => {
3195
+ const url = moduleUrl(sourceUrl);
3196
+ const pending = loading.get(url);
3197
+ if (pending) return pending;
3198
+ const task = (async () => {
3199
+ await crawl(url);
3200
+ await Promise.all([...pendingBuiltins].map(async (id) => {
3201
+ if (id === "vue" || id === "vue-router") return;
3202
+ hostModules[id] = await ensureLocalBuiltin(id);
3203
+ }));
3204
+ return evaluate(url);
3205
+ })();
3206
+ loading.set(url, task);
3207
+ return task;
3208
+ };
3209
+ return { load };
3210
+ };
3211
+ //#endregion
3212
+ //#region packages/playground/src/core/runtime/local/local-sandbox.vue?vue&type=script&setup=true&lang.ts
3213
+ var _hoisted_1$2 = ["srcdoc"];
3214
+ var local_sandbox_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
3215
+ __name: "local-sandbox",
3216
+ props: {
3217
+ files: {},
3218
+ entry: {},
3219
+ options: {},
3220
+ previewScroller: {
3221
+ type: Boolean,
3222
+ default: false
3223
+ },
3224
+ clearConsole: {
3225
+ type: Boolean,
3226
+ default: false
3227
+ },
3228
+ autoHeight: {
3229
+ type: Boolean,
3230
+ default: false
3231
+ }
3232
+ },
3233
+ emits: ["error"],
3234
+ setup(__props, { expose: __expose, emit: __emit }) {
3235
+ const props = __props;
3236
+ const emit = __emit;
3237
+ const bridgeSrcdoc = LOCAL_BRIDGE_SRCDOC;
3238
+ const containerEl = ref(null);
3239
+ const bridgeEl = ref(null);
3240
+ const mountEl = ref(null);
3241
+ const compileError = ref("");
3242
+ const runtimeError = ref("");
3243
+ const messageSource = shallowRef(null);
3244
+ let port = null;
3245
+ let previewApp = null;
3246
+ let version = 0;
3247
+ let pendingMount = null;
3248
+ const styleId = `docs-local-${Math.random().toString(36).slice(2, 10)}`;
3249
+ const publishError = () => {
3250
+ emit("error", {
3251
+ compile: compileError.value,
3252
+ runtime: runtimeError.value
3253
+ });
3254
+ };
3255
+ watch([compileError, runtimeError], publishError);
3256
+ const createDocsLink = (preview, vue) => vue.defineComponent({
3257
+ name: "DocsLink",
3258
+ props: { to: {
3259
+ type: String,
3260
+ default: ""
3261
+ } },
3262
+ setup(linkProps, { slots }) {
3263
+ return () => vue.h("a", {
3264
+ href: linkProps.to,
3265
+ style: {
3266
+ color: "inherit",
3267
+ textDecoration: "none"
3268
+ },
3269
+ onClick(event) {
3270
+ event.preventDefault();
3271
+ preview.parent.postMessage({
3272
+ action: "docs:navigate",
3273
+ to: linkProps.to
3274
+ });
3275
+ }
3276
+ }, slots.default?.());
3277
+ }
3278
+ });
3279
+ const destroyPreview = () => {
3280
+ previewApp?.unmount();
3281
+ previewApp = null;
3282
+ removeStyle(styleId);
3283
+ };
3284
+ const mountPreview = (job, preview) => {
3285
+ if (!mountEl.value) return;
3286
+ const { component, vue, scroller, css } = job;
3287
+ destroyPreview();
3288
+ injectStyle(styleId, css);
3289
+ if (props.clearConsole) console.clear();
3290
+ const app = vue.createApp({
3291
+ name: "LocalSandboxRoot",
3292
+ setup() {
3293
+ const service = createLocalPlayground(vue);
3294
+ vue.provide("docs:playground", service);
3295
+ vue.onErrorCaptured((error) => {
3296
+ const message = formatPlaygroundRuntimeError(error);
3297
+ if (message) runtimeError.value = message;
3298
+ return false;
3299
+ });
3300
+ vue.onBeforeUnmount(() => service.dispose());
3301
+ return () => {
3302
+ const content = vue.h(component);
3303
+ if (!scroller) return content;
3304
+ return vue.h(scroller, {
3305
+ height: "100%",
3306
+ native: false,
3307
+ autoResize: true,
3308
+ showBar: true,
3309
+ contentClass: PREVIEW_SCROLL_CONTENT_CLASS
3310
+ }, { default: () => content });
3311
+ };
3312
+ }
3313
+ });
3314
+ app.component("DocsLink", createDocsLink(preview, vue));
3315
+ app.config.errorHandler = (error) => {
3316
+ const message = formatPlaygroundRuntimeError(error);
3317
+ if (message) runtimeError.value = message;
3318
+ };
3319
+ app.mount(mountEl.value);
3320
+ previewApp = app;
3321
+ };
3322
+ const ensurePort = () => {
3323
+ const iframe = bridgeEl.value;
3324
+ if (!iframe?.contentWindow) return null;
3325
+ try {
3326
+ if (!installLocalBridge(iframe)) return null;
3327
+ } catch {
3328
+ return null;
3329
+ }
3330
+ port ??= new LocalPreviewPort(iframe);
3331
+ messageSource.value = iframe.contentWindow;
3332
+ return port;
3333
+ };
3334
+ const tryMount = async () => {
3335
+ const job = pendingMount;
3336
+ /* istanbul ignore if -- 桥接 iframe 尚未就绪或编译已被取代 */
3337
+ if (!job || job.version !== version) return;
3338
+ const preview = ensurePort();
3339
+ /* istanbul ignore if -- 挂载点在编译完成时已经存在 */
3340
+ if (!preview || !mountEl.value) return;
3341
+ await nextTick();
3342
+ /* istanbul ignore if -- 桥接 iframe 尚未就绪或编译已被取代 */
3343
+ if (pendingMount !== job || !mountEl.value) return;
3344
+ pendingMount = null;
3345
+ mountPreview(job, preview);
3346
+ };
3347
+ const run = async () => {
3348
+ const current = ++version;
3349
+ pendingMount = null;
3350
+ compileError.value = "";
3351
+ runtimeError.value = "";
3352
+ publishError();
3353
+ destroyPreview();
3354
+ try {
3355
+ const { compilePlayground } = await import("./compile-CM_OyqYN.js");
3356
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3357
+ if (current !== version) return;
3358
+ const compiled = await compilePlayground(props.files, { entry: props.entry });
3359
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3360
+ if (current !== version) return;
3361
+ if (compiled.errors.length || !compiled.entry) {
3362
+ compileError.value = compiled.errors.join("\n") || "[Playground] 未能确定入口";
3363
+ publishError();
3364
+ return;
3365
+ }
3366
+ const imports = createRuntimeImports(props.options.cdnURL, props.options.builtinImportMap);
3367
+ const overrides = new Set(Object.keys(createRuntimeImportOverrides(props.options.builtinImportMap)));
3368
+ const specifiers = collectBareSpecifiers(props.files, collectReachableFilenames(props.files, compiled.entry));
3369
+ specifiers.push("vue");
3370
+ if (props.previewScroller === true) specifiers.push("@deot/vc");
3371
+ const remote = createRemoteLoader(imports, {
3372
+ vue: Vue,
3373
+ vueRouter: VueRouter
3374
+ }, overrides);
3375
+ const loaded = await loadLocalModules(specifiers, imports, {
3376
+ vue: Vue,
3377
+ vueRouter: VueRouter
3378
+ }, (url) => remote.load(url), overrides);
3379
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3380
+ if (current !== version) return;
3381
+ if (loaded.errors.length) {
3382
+ compileError.value = loaded.errors.join("\n");
3383
+ publishError();
3384
+ return;
3385
+ }
3386
+ const linked = linkPlayground(compiled, props.files, { modules: loaded.modules });
3387
+ /* istanbul ignore if -- 并发编译时只保留最后一次 */
3388
+ if (current !== version) return;
3389
+ if (linked.errors.length || !linked.component) {
3390
+ compileError.value = (linked.errors.length ? linked.errors : ["[Playground] 未能解析入口组件"]).join("\n");
3391
+ publishError();
3392
+ return;
3393
+ }
3394
+ pendingMount = {
3395
+ component: linked.component,
3396
+ vue: loaded.modules.vue,
3397
+ scroller: props.previewScroller === true ? loaded.modules["@deot/vc"].Scroller : void 0,
3398
+ css: linked.css,
3399
+ version: current
3400
+ };
3401
+ await tryMount();
3402
+ } catch (error) {
3403
+ /* istanbul ignore next -- 编译器自身异常才进入,普通错误走结果里的 errors */
3404
+ if (current !== version) return;
3405
+ /* istanbul ignore next -- 同上,只兜底编译器抛错 */
3406
+ compileError.value = error instanceof Error ? error.message : String(error);
3407
+ /* istanbul ignore next -- 同上,只兜底编译器抛错 */
3408
+ publishError();
3409
+ }
3410
+ };
3411
+ const handleBridgeLoad = () => {
3412
+ tryMount();
3413
+ };
3414
+ onMounted(() => {
3415
+ run();
3416
+ });
3417
+ watch(() => [
3418
+ props.files,
3419
+ props.entry,
3420
+ props.options,
3421
+ props.previewScroller
3422
+ ], () => {
3423
+ if (!containerEl.value) return;
3424
+ run();
3425
+ }, { deep: true });
3426
+ onBeforeUnmount(() => {
3427
+ version += 1;
3428
+ pendingMount = null;
3429
+ destroyPreview();
3430
+ });
3431
+ __expose({
3432
+ container: containerEl,
3433
+ messageSource,
3434
+ local: true,
3435
+ refresh: () => {
3436
+ run();
3437
+ }
3438
+ });
3439
+ return (_ctx, _cache) => {
3440
+ return openBlock(), createElementBlock("div", {
3441
+ ref_key: "containerEl",
3442
+ ref: containerEl,
3443
+ class: "docs-playground-local"
3444
+ }, [createElementVNode("iframe", {
3445
+ ref_key: "bridgeEl",
3446
+ ref: bridgeEl,
3447
+ class: "docs-playground-local__bridge",
3448
+ tabindex: "-1",
3449
+ "aria-hidden": "true",
3450
+ title: "",
3451
+ srcdoc: unref(bridgeSrcdoc),
3452
+ onLoad: handleBridgeLoad
3453
+ }, null, 40, _hoisted_1$2), createElementVNode("div", {
3454
+ ref_key: "mountEl",
3455
+ ref: mountEl,
3456
+ class: normalizeClass(["docs-playground-local__mount", { "docs-playground-local__mount--auto": __props.autoHeight }])
3457
+ }, null, 2)], 512);
3458
+ };
3459
+ }
3460
+ });
3461
+ //#endregion
3462
+ //#region packages/playground/src/core/runtime/local/local-sandbox.vue
3463
+ var local_sandbox_exports = /* @__PURE__ */ __exportAll({ default: () => local_sandbox_default });
3464
+ var local_sandbox_default = local_sandbox_vue_vue_type_script_setup_true_lang_default;
3465
+ //#endregion
1601
3466
  //#region packages/playground/src/core/runtime/runtime.vue?vue&type=script&setup=true&lang.ts
1602
3467
  var _hoisted_1$1 = {
1603
3468
  key: 0,
@@ -1663,7 +3528,6 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1663
3528
  "navigate"
1664
3529
  ],
1665
3530
  setup(__props, { expose: __expose, emit: __emit }) {
1666
- const LocalSandbox = defineAsyncComponent(() => import("./local-sandbox-DvcgaBOa.js").then((n) => n.t));
1667
3531
  const props = __props;
1668
3532
  const { locale, t } = useLocale();
1669
3533
  const displayTitle = computed(() => props.title.trim());
@@ -1938,7 +3802,7 @@ var runtime_default = /* @__PURE__ */ defineComponent({
1938
3802
  }, [errorText.value ? (openBlock(), createElementBlock("pre", _hoisted_1$1, toDisplayString(errorText.value), 1)) : createCommentVNode("v-if", true), createElementVNode("div", {
1939
3803
  class: "docs-playground-runtime__viewport",
1940
3804
  style: normalizeStyle(viewportStyle.value)
1941
- }, [__props.local ? (openBlock(), createBlock(unref(LocalSandbox), {
3805
+ }, [__props.local ? (openBlock(), createBlock(local_sandbox_default, {
1942
3806
  key: 0,
1943
3807
  ref_key: "sandboxRef",
1944
3808
  ref: sandboxRef,
@@ -2000,7 +3864,7 @@ var runtime_default = /* @__PURE__ */ defineComponent({
2000
3864
  }, [createElementVNode("div", _hoisted_7, [createElementVNode("div", {
2001
3865
  class: "docs-playground-runtime__viewport",
2002
3866
  style: normalizeStyle(viewportStyle.value)
2003
- }, [__props.local ? (openBlock(), createBlock(unref(LocalSandbox), {
3867
+ }, [__props.local ? (openBlock(), createBlock(local_sandbox_default, {
2004
3868
  key: sandboxKey.value,
2005
3869
  ref_key: "sandboxRef",
2006
3870
  ref: sandboxRef,