@takazudo/zudo-sg 0.3.5 → 0.4.0

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +3 -3
  3. package/dist/catalog/catalog-thumb.d.ts +19 -0
  4. package/dist/catalog/catalog-thumb.js +11 -0
  5. package/dist/catalog/descriptor-thumb.d.ts +20 -0
  6. package/dist/catalog/descriptor-thumb.js +31 -0
  7. package/dist/catalog/index.d.ts +4 -0
  8. package/dist/catalog/index.js +5 -0
  9. package/dist/code-panel/code-panel.d.ts +8 -1
  10. package/dist/code-panel/code-panel.js +76 -24
  11. package/dist/code-panel/editor-setup.d.ts +2 -0
  12. package/dist/code-panel/editor-setup.js +3 -0
  13. package/dist/code-panel/source-editor.d.ts +3 -1
  14. package/dist/code-panel/source-editor.js +10 -1
  15. package/dist/config/index.d.ts +54 -5
  16. package/dist/config/index.js +72 -12
  17. package/dist/host-paths.d.ts +2 -0
  18. package/dist/host-paths.js +5 -0
  19. package/dist/plugins/routes.d.ts +60 -11
  20. package/dist/plugins/routes.js +135 -23
  21. package/dist/preview/detail-workbench.d.ts +63 -1
  22. package/dist/preview/detail-workbench.js +112 -22
  23. package/dist/preview/index.d.ts +3 -3
  24. package/dist/preview/index.js +7 -1
  25. package/dist/preview/messages.d.ts +34 -5
  26. package/dist/preview/messages.js +34 -6
  27. package/dist/preview/preview-app.js +22 -10
  28. package/dist/preview/variant-frame.d.ts +50 -2
  29. package/dist/preview/variant-frame.js +64 -23
  30. package/dist/registry/catalog.d.ts +64 -0
  31. package/dist/registry/catalog.js +79 -0
  32. package/dist/registry/descriptors.d.ts +46 -0
  33. package/dist/registry/descriptors.js +148 -0
  34. package/dist/registry/index.d.ts +5 -1
  35. package/dist/registry/index.js +7 -1
  36. package/dist/registry/nav-nodes.d.ts +4 -1
  37. package/dist/registry/nav-nodes.js +4 -1
  38. package/dist/registry/registry.d.ts +15 -0
  39. package/dist/registry/registry.js +18 -9
  40. package/dist/safelist.css +1 -1
  41. package/dist/sg-context.d.ts +29 -0
  42. package/dist/sg-routes.d.ts +49 -1
  43. package/dist/sg-routes.js +15 -1
  44. package/dist/shared/tablist-keyboard.d.ts +14 -0
  45. package/dist/shared/tablist-keyboard.js +19 -0
  46. package/package.json +10 -5
  47. package/routes-src/_preview-app.tsx +2 -2
  48. package/routes-src/_registry.ts +31 -6
  49. package/routes-src/components-index.tsx +15 -8
  50. package/routes-src/components-preview.tsx +5 -0
  51. package/routes-src/components-slug.tsx +63 -31
  52. package/routes-src/tokens.tsx +9 -4
  53. package/styles.css +10 -0
  54. package/virtual-modules.d.ts +6 -0
@@ -4,7 +4,7 @@ import {
4
4
  componentDocsRoots
5
5
  } from "../registry/component-docs.js";
6
6
  import { DEFAULT_PREVIEW_CSS_URL } from "../sg-context.js";
7
- import { resolveSgRoutes } from "../sg-routes.js";
7
+ import { isPreviewTokenPanelWired, isTokensRouteEnabled, resolveSgRoutes } from "../sg-routes.js";
8
8
  import { PREVIEW_TOKEN_PANEL_CAPTURE_SCRIPT } from "../token-tweak/preview-token-panel-capture.js";
9
9
  const ROUTES_PLUGIN_NAME = "@takazudo/zudo-sg/plugins/routes";
10
10
  const PREVIEW_CSS_PLUGIN_NAME = "@takazudo/zudo-sg/plugins/preview-css";
@@ -18,7 +18,7 @@ function definedOnly(record) {
18
18
  function isRecord(value) {
19
19
  return typeof value === "object" && value !== null && !Array.isArray(value);
20
20
  }
21
- function withStyleguideChromeDefaults(plugin, routes) {
21
+ function withStyleguideChromeDefaults(plugin, routes, tokensEnabled) {
22
22
  if (!isRecord(plugin) || plugin.name !== ZUDO_DOC_ROUTES_PLUGIN_NAME) return plugin;
23
23
  const options = isRecord(plugin.options) ? plugin.options : {};
24
24
  const settings = isRecord(options.settings) ? options.settings : {};
@@ -28,20 +28,21 @@ function withStyleguideChromeDefaults(plugin, routes) {
28
28
  const hasSearch = headerRightItems.some(
29
29
  (item) => isRecord(item) && item.type === "component" && item.component === "search"
30
30
  );
31
+ const navGlobalPaths = tokensEnabled ? [routes.componentsIndex, routes.tokens] : [routes.componentsIndex];
31
32
  return {
32
33
  ...plugin,
33
34
  options: {
34
35
  ...options,
35
36
  settings: {
36
37
  ...settings,
37
- headerNav: [
38
+ headerNav: tokensEnabled ? [
38
39
  { label: "Components", path: routes.componentsIndex, categoryMatch: "components", versioned: false },
39
40
  { label: "Design Tokens", path: routes.tokens, versioned: false }
40
- ],
41
+ ] : [{ label: "Components", path: routes.componentsIndex, categoryMatch: "components", versioned: false }],
41
42
  // Engine navigation targets global routes, including from translated docs.
42
43
  defaultLocaleOnlyPrefixes: [.../* @__PURE__ */ new Set([
43
44
  ...Array.isArray(settings.defaultLocaleOnlyPrefixes) ? settings.defaultLocaleOnlyPrefixes : [],
44
- ...[routes.componentsIndex, routes.tokens].map((path) => `${path.replace(/\/+$/, "")}/`)
45
+ ...navGlobalPaths.map((path) => `${path.replace(/\/+$/, "")}/`)
45
46
  ])],
46
47
  headerRightItems: hasSearch ? headerRightItems : [...headerRightItems, { type: "component", component: "search" }]
47
48
  }
@@ -78,26 +79,70 @@ function withHeaderTokenTrigger(plugin) {
78
79
  }
79
80
  };
80
81
  }
82
+ let warnedUnwiredHeaderTrigger = false;
83
+ function __resetHeaderTokenTriggerWarningForTests() {
84
+ warnedUnwiredHeaderTrigger = false;
85
+ }
86
+ function descriptorModuleOf(registry) {
87
+ if (registry === void 0) return null;
88
+ if (!isRecord(registry)) {
89
+ throw new Error('[zudo-sg] option "registry" must be { mode: "module" } or { mode: "descriptor", module }');
90
+ }
91
+ for (const key of Object.keys(registry)) {
92
+ if (key !== "mode" && key !== "module") {
93
+ throw new Error(`[zudo-sg] option "registry.${key}" is not supported (expected mode, module)`);
94
+ }
95
+ }
96
+ if (registry.mode === "module") {
97
+ if (registry.module !== void 0) {
98
+ throw new Error('[zudo-sg] option "registry.module" is only valid with registry.mode "descriptor"');
99
+ }
100
+ return null;
101
+ }
102
+ if (registry.mode === "descriptor") {
103
+ if (typeof registry.module !== "string" || registry.module === "") {
104
+ throw new Error(
105
+ '[zudo-sg] option "registry.module" is required with registry.mode "descriptor" (project-root-relative path, e.g. "./src/styleguide/story-descriptors.ts")'
106
+ );
107
+ }
108
+ return registry.module;
109
+ }
110
+ throw new Error(`[zudo-sg] option "registry.mode" must be "module" or "descriptor" (got ${JSON.stringify(registry.mode)})`);
111
+ }
112
+ function stringRoutesOnly(routes) {
113
+ const out = {};
114
+ if (!routes) return out;
115
+ for (const [key, value] of Object.entries(routes)) {
116
+ if (typeof value === "string") out[key] = value;
117
+ }
118
+ return out;
119
+ }
81
120
  function zudoSg(options) {
82
121
  if (!options || typeof options !== "object") {
83
122
  throw new Error("[zudo-sg] zudoSg(options) requires an options object (the zudo-sg.config.mjs shape)");
84
123
  }
85
- const roots = Array.isArray(options.componentsRoots) ? options.componentsRoots : [];
124
+ const descriptorModule = descriptorModuleOf(options.registry);
125
+ const roots = descriptorModule === null && Array.isArray(options.componentsRoots) ? options.componentsRoots : [];
86
126
  const previewCssUrl = options.previewCssUrl ?? DEFAULT_PREVIEW_CSS_URL;
127
+ const registrySource = descriptorModule === null ? {
128
+ registryModule: options.registryOut,
129
+ // Pairs each root's registry key prefix with its collection below, so the
130
+ // detail route resolves a story's doc from the root its key belongs to.
131
+ componentDocs: componentDocsRoots(roots)
132
+ } : { registryMode: "descriptor", descriptorModule };
87
133
  const plugins = [
88
134
  {
89
135
  name: ROUTES_PLUGIN_NAME,
90
136
  options: definedOnly({
91
- registryModule: options.registryOut,
137
+ ...registrySource,
92
138
  routes: options.routes,
139
+ externalPreview: options.externalPreview,
93
140
  categoryOrder: options.categoryOrder,
94
141
  uiPackageName: options.uiPackageName,
95
142
  previewCssUrl,
96
143
  catalog: options.catalog,
97
144
  tokensManifestModule: options.tokens?.manifestOut,
98
- // Pairs each root's registry key prefix with its collection below, so the
99
- // detail route resolves a story's doc from the root its key belongs to.
100
- componentDocs: componentDocsRoots(roots)
145
+ previewTokenPanel: isPreviewTokenPanelWired(options.zdtpApplyProxy)
101
146
  })
102
147
  },
103
148
  {
@@ -119,8 +164,22 @@ function zudoSg(options) {
119
164
  function withZudoSg(presetFragment, options) {
120
165
  const sg = zudoSg(options);
121
166
  const presetPlugins = [...presetFragment.plugins ?? []];
122
- const pluginsWithChrome = options.chromeDefaults === false ? presetPlugins : presetPlugins.map((plugin) => withStyleguideChromeDefaults(plugin, resolveSgRoutes(options.routes)));
123
- const pluginsWithTrigger = options.headerTokenTrigger === false ? pluginsWithChrome : pluginsWithChrome.map(withHeaderTokenTrigger);
167
+ const registryMode = descriptorModuleOf(options.registry) === null ? "module" : "descriptor";
168
+ const tokensEnabled = isTokensRouteEnabled({
169
+ registryMode,
170
+ tokensRouteOption: options.routes?.tokens,
171
+ hasTokensManifest: Boolean(options.tokens?.manifestOut)
172
+ });
173
+ const pluginsWithChrome = options.chromeDefaults === false ? presetPlugins : presetPlugins.map((plugin) => withStyleguideChromeDefaults(plugin, resolveSgRoutes(stringRoutesOnly(options.routes)), tokensEnabled));
174
+ const previewTokenPanelWired = isPreviewTokenPanelWired(options.zdtpApplyProxy);
175
+ const triggerEnabled = options.headerTokenTrigger ?? previewTokenPanelWired;
176
+ if (options.headerTokenTrigger === true && !previewTokenPanelWired && !warnedUnwiredHeaderTrigger) {
177
+ warnedUnwiredHeaderTrigger = true;
178
+ console.warn(
179
+ '[zudo-sg] headerTokenTrigger is explicitly enabled but "zdtpApplyProxy.tabsModule" is not configured \u2014 the header trigger will render as a dead control until tabsModule is set (issue #872)'
180
+ );
181
+ }
182
+ const pluginsWithTrigger = triggerEnabled ? pluginsWithChrome.map(withHeaderTokenTrigger) : pluginsWithChrome;
124
183
  return {
125
184
  ...presetFragment,
126
185
  plugins: [...pluginsWithTrigger, ...sg.plugins],
@@ -133,6 +192,7 @@ export {
133
192
  PREVIEW_CSS_PLUGIN_NAME,
134
193
  ROUTES_PLUGIN_NAME,
135
194
  ZDTP_APPLY_PROXY_PLUGIN_NAME,
195
+ __resetHeaderTokenTriggerWarningForTests,
136
196
  componentDocsCollectionName,
137
197
  withZudoSg,
138
198
  zudoSg
@@ -3,6 +3,8 @@ export interface ResolveHostModuleOptions {
3
3
  required?: boolean;
4
4
  /** Example value quoted in the "is required" error, e.g. `./src/styleguide/sg-registry.ts`. */
5
5
  example?: string;
6
+ /** Reject a path that resolves outside `projectRoot`. */
7
+ insideRoot?: boolean;
6
8
  }
7
9
  /** Converts a native path to forward slashes (`C:\a\b` → `C:/a/b`). */
8
10
  export declare function toForwardSlash(path: string): string;
@@ -20,6 +20,11 @@ function resolveHostModule(projectRoot, optionName, value, options = {}) {
20
20
  }
21
21
  const root = toForwardSlash(resolve(projectRoot));
22
22
  const abs = toForwardSlash(isAbsolute(value) ? resolve(value) : resolve(projectRoot, value));
23
+ if (options.insideRoot && value !== "" && !abs.startsWith(`${root.replace(/\/+$/, "")}/`)) {
24
+ throw new Error(
25
+ `[zudo-sg] option "${optionName}" = "${value}" resolved to ${abs}, which is outside projectRoot ${root}`
26
+ );
27
+ }
23
28
  if (value === "" || !isFile(abs)) {
24
29
  throw new Error(
25
30
  `[zudo-sg] option "${optionName}" = "${value}" resolved to ${abs} (relative to projectRoot ${root}), which is not a file`
@@ -1,7 +1,7 @@
1
1
  import type { ZfbPlugin, ZfbSetupContext } from "@takazudo/zfb/plugins";
2
2
  import type { ComponentDocsRoot } from "../registry/component-docs.js";
3
- import { type SgCatalogText, type SgContext } from "../sg-context.js";
4
- import { type SgRoutes } from "../sg-routes.js";
3
+ import { type SgCatalogText, type SgContext, type SgRegistryMode } from "../sg-context.js";
4
+ import { type SgRoutes, type SgRoutesOption } from "../sg-routes.js";
5
5
  export declare const PLUGIN_NAME = "@takazudo/zudo-sg/plugins/routes";
6
6
  /** The zudo-doc plugin whose virtual modules the engine routes import. */
7
7
  export declare const ZUDO_DOC_ROUTES_PLUGIN_NAME = "@takazudo/zudo-doc/plugins/routes";
@@ -17,9 +17,29 @@ export declare const TOKENS_MANIFEST_EXPORTS: Readonly<Record<string, string>>;
17
17
  /** Route key → `routes-src/` entrypoint file (ADR decision 6). */
18
18
  export declare const ROUTE_ENTRYPOINTS: Readonly<Record<keyof SgRoutes, string>>;
19
19
  export interface RoutesPluginOptions {
20
- /** Project-root-relative path to the generated host registry (`zudo-sg.config.mjs` `registryOut`). */
21
- registryModule: string;
22
- routes?: Partial<SgRoutes>;
20
+ /** Default `"module"`. `"descriptor"` reads plain-data story descriptors from `descriptorModule` instead. */
21
+ registryMode?: SgRegistryMode;
22
+ /** Module mode (required there): project-root-relative path to the generated host registry (`registryOut`). */
23
+ registryModule?: string;
24
+ /**
25
+ * Descriptor mode (required there): project-root-relative module exporting
26
+ * `StoryDescriptor[]` as the named export `storyDescriptors`, or — when that
27
+ * export is absent — as its default export. Must sit inside the project root.
28
+ */
29
+ descriptorModule?: string;
30
+ routes?: SgRoutesOption;
31
+ /**
32
+ * A host-served preview document that replaces the in-engine
33
+ * `componentsPreview` route (which is then implied disabled). `url` must be
34
+ * root-absolute (a single leading `/`, no scheme, no `//`); `trailingSlash`
35
+ * normalizes it (`"never"` strips a trailing `/`, `"always"` adds one).
36
+ * Required in descriptor mode: descriptors carry no render functions, so
37
+ * the engine has nothing to render at an in-engine preview route.
38
+ */
39
+ externalPreview?: {
40
+ url: string;
41
+ trailingSlash?: "never" | "always";
42
+ };
23
43
  categoryOrder?: string[];
24
44
  uiPackageName?: string;
25
45
  previewCssUrl?: string;
@@ -40,11 +60,29 @@ export interface RoutesPluginOptions {
40
60
  * `componentsRoots`; omitted → detail pages render no component docs.
41
61
  */
42
62
  componentDocs?: ComponentDocsRoot[];
63
+ /**
64
+ * `sgContext.previewTokenPanel` (issue #872): computed by `config/index.ts`'s
65
+ * `zudoSg()`/`withZudoSg()` from `isPreviewTokenPanelWired(zdtpApplyProxy)`
66
+ * and forwarded here verbatim — this plugin has no `zdtpApplyProxy` option of
67
+ * its own to derive it from. Default `false` (unwired) when omitted.
68
+ */
69
+ previewTokenPanel?: boolean;
43
70
  }
44
- export interface ResolvedRoutesPluginOptions {
45
- /** Forward-slash absolute path of the host registry file. */
71
+ /** The resolved story source; both paths are forward-slash absolute. */
72
+ export type ResolvedRegistrySource = {
73
+ mode: "module";
46
74
  registryModule: string;
75
+ } | {
76
+ mode: "descriptor";
77
+ descriptorModule: string;
78
+ };
79
+ export interface ResolvedRoutesPluginOptions {
80
+ registry: ResolvedRegistrySource;
47
81
  routes: SgRoutes;
82
+ /** Route keys with no `injectRoute()` call — explicit `false` or implied (see `SgContext.disabledRoutes`). */
83
+ disabledRoutes: Array<keyof SgRoutes>;
84
+ /** Root-absolute URL of the host preview document, or `null` — see `RoutesPluginOptions.externalPreview`. */
85
+ externalPreviewUrl: string | null;
48
86
  categoryOrder: string[];
49
87
  uiPackageName: string | null;
50
88
  previewCssUrl: string;
@@ -52,6 +90,8 @@ export interface ResolvedRoutesPluginOptions {
52
90
  /** Forward-slash absolute path of the host token manifest, or `null`. */
53
91
  tokensManifestModule: string | null;
54
92
  componentDocs: ComponentDocsRoot[];
93
+ /** See `RoutesPluginOptions.previewTokenPanel`. */
94
+ previewTokenPanel: boolean;
55
95
  }
56
96
  export interface RouteInjection {
57
97
  key: keyof SgRoutes;
@@ -59,22 +99,31 @@ export interface RouteInjection {
59
99
  /** Forward-slash absolute path of the `routes-src/*.tsx` entrypoint. */
60
100
  entrypoint: string;
61
101
  }
62
- /** Validates the options block and resolves `registryModule`; throws `[zudo-sg] …` on invalid input. */
102
+ /** Validates the options block and resolves the registry source; throws `[zudo-sg] …` on invalid input. */
63
103
  export declare function resolveRoutesPluginOptions(projectRoot: string, options: Record<string, unknown>): ResolvedRoutesPluginOptions;
64
104
  /** Throws unless the zfb config lists the zudo-doc routes plugin descriptor. */
65
105
  export declare function assertZudoDocRoutesPlugin(config: ZfbSetupContext["config"]): void;
66
106
  /** Builds the JSON-only `sgContext` payload. */
67
107
  export declare function buildSgContext(base: string | undefined, resolved: ResolvedRoutesPluginOptions): SgContext;
68
108
  export declare function buildContextModuleSource(context: SgContext): string;
69
- export declare function buildRegistryModuleSource(registryModule: string): string;
109
+ /**
110
+ * `virtual:zudo-sg-registry` exports the same three names in every mode, because
111
+ * the one fixed `routes-src/` tree (and the preview island) imports all of them.
112
+ * Descriptor mode imports no StoryModule: only the host descriptor module.
113
+ */
114
+ export declare function buildRegistryModuleSource(source: ResolvedRegistrySource): string;
70
115
  export declare function buildTokensModuleSource(tokensManifestModule: string | null): string;
71
116
  /**
72
117
  * This package's own root realpath — the workspace dir or
73
118
  * `node_modules/.pnpm/…/@takazudo/zudo-sg`, whichever the plugin loaded from.
74
119
  */
75
120
  export declare function resolvePackageRoot(): string;
76
- /** Pairs every route pattern with its `routes-src/` entrypoint under `packageRoot`. */
77
- export declare function deriveRouteInjections(routes: SgRoutes, packageRoot: string): RouteInjection[];
121
+ /**
122
+ * Pairs every ENABLED route pattern with its `routes-src/` entrypoint under
123
+ * `packageRoot`. `disabledRoutes` keys get no entry — no `injectRoute()` call,
124
+ * and their entrypoint file is not required to exist.
125
+ */
126
+ export declare function deriveRouteInjections(routes: SgRoutes, packageRoot: string, disabledRoutes?: ReadonlyArray<keyof SgRoutes>): RouteInjection[];
78
127
  export interface CreateRoutesPluginOptions {
79
128
  /** Test seam: overrides the package realpath lookup. */
80
129
  packageRoot?: () => string;
@@ -6,7 +6,12 @@ import {
6
6
  DEFAULT_CATALOG_TITLE,
7
7
  DEFAULT_PREVIEW_CSS_URL
8
8
  } from "../sg-context.js";
9
- import { DEFAULT_SG_ROUTES, previewCollisionSlug } from "../sg-routes.js";
9
+ import {
10
+ DEFAULT_SG_ROUTES,
11
+ DISABLEABLE_ROUTE_KEYS,
12
+ isTokensRouteEnabled,
13
+ previewCollisionSlug
14
+ } from "../sg-routes.js";
10
15
  const PLUGIN_NAME = "@takazudo/zudo-sg/plugins/routes";
11
16
  const ZUDO_DOC_ROUTES_PLUGIN_NAME = "@takazudo/zudo-doc/plugins/routes";
12
17
  const CONTEXT_MODULE_ID = "virtual:zudo-sg-context";
@@ -26,14 +31,18 @@ const ROUTE_ENTRYPOINTS = Object.freeze({
26
31
  tokens: "tokens.tsx"
27
32
  });
28
33
  const OPTION_KEYS = /* @__PURE__ */ new Set([
34
+ "registryMode",
29
35
  "registryModule",
36
+ "descriptorModule",
30
37
  "routes",
38
+ "externalPreview",
31
39
  "categoryOrder",
32
40
  "uiPackageName",
33
41
  "previewCssUrl",
34
42
  "catalog",
35
43
  "tokensManifestModule",
36
- "componentDocs"
44
+ "componentDocs",
45
+ "previewTokenPanel"
37
46
  ]);
38
47
  const ROUTE_KEYS = Object.keys(DEFAULT_SG_ROUTES);
39
48
  const CATALOG_KEYS = /* @__PURE__ */ new Set(["title", "intro"]);
@@ -53,7 +62,7 @@ function urlPath(name, value) {
53
62
  return value;
54
63
  }
55
64
  function normalizeRoutes(value) {
56
- if (value === void 0 || value === null) return { ...DEFAULT_SG_ROUTES };
65
+ if (value === void 0 || value === null) return { routes: { ...DEFAULT_SG_ROUTES }, disabledRoutes: [] };
57
66
  if (!isPlainObject(value)) fail(`option "routes" must be an object`);
58
67
  for (const key of Object.keys(value)) {
59
68
  if (!ROUTE_KEYS.includes(key)) {
@@ -61,8 +70,17 @@ function normalizeRoutes(value) {
61
70
  }
62
71
  }
63
72
  const routes = { ...DEFAULT_SG_ROUTES };
73
+ const disabledRoutes = [];
64
74
  for (const key of ROUTE_KEYS) {
65
- const pattern = optionalString(`routes.${key}`, value[key]);
75
+ const raw = value[key];
76
+ if (raw === false) {
77
+ if (!DISABLEABLE_ROUTE_KEYS.has(key)) {
78
+ fail(`option "routes.${key}" cannot be disabled \u2014 it is the engine's point (expected a string, or "false" for one of ${[...DISABLEABLE_ROUTE_KEYS].join(", ")})`);
79
+ }
80
+ disabledRoutes.push(key);
81
+ continue;
82
+ }
83
+ const pattern = optionalString(`routes.${key}`, raw);
66
84
  if (pattern !== void 0) routes[key] = urlPath(`routes.${key}`, pattern);
67
85
  }
68
86
  if (!routes.componentsSlug.includes("[slug]")) {
@@ -71,11 +89,37 @@ function normalizeRoutes(value) {
71
89
  previewCollisionSlug(routes);
72
90
  const seen = /* @__PURE__ */ new Map();
73
91
  for (const key of ROUTE_KEYS) {
92
+ if (disabledRoutes.includes(key)) continue;
74
93
  const other = seen.get(routes[key]);
75
94
  if (other) fail(`options "routes.${other}" and "routes.${key}" both resolve to "${routes[key]}"`);
76
95
  seen.set(routes[key], key);
77
96
  }
78
- return routes;
97
+ return { routes, disabledRoutes };
98
+ }
99
+ function isRootAbsoluteUrl(value) {
100
+ return /^\/(?!\/)/.test(value);
101
+ }
102
+ function normalizeExternalPreview(value) {
103
+ if (value === void 0 || value === null) return null;
104
+ if (!isPlainObject(value)) fail(`option "externalPreview" must be an object ({ url, trailingSlash? })`);
105
+ for (const key of Object.keys(value)) {
106
+ if (key !== "url" && key !== "trailingSlash") {
107
+ fail(`option "externalPreview.${key}" is not supported (expected url, trailingSlash)`);
108
+ }
109
+ }
110
+ const rawUrl = value.url;
111
+ if (typeof rawUrl !== "string" || rawUrl === "") fail(`option "externalPreview.url" must be a non-empty string`);
112
+ if (!isRootAbsoluteUrl(rawUrl)) {
113
+ fail(`option "externalPreview.url" = "${rawUrl}" must be a root-absolute path starting with a single "/" (no scheme, no "//")`);
114
+ }
115
+ const trailingSlash = value.trailingSlash;
116
+ if (trailingSlash !== void 0 && trailingSlash !== "never" && trailingSlash !== "always") {
117
+ fail(`option "externalPreview.trailingSlash" must be "never" or "always"`);
118
+ }
119
+ let url = rawUrl;
120
+ if (trailingSlash === "never") url = url.length > 1 ? url.replace(/\/+$/, "") : url;
121
+ if (trailingSlash === "always" && !url.endsWith("/")) url = `${url}/`;
122
+ return { url };
79
123
  }
80
124
  function normalizeCategoryOrder(value) {
81
125
  if (value === void 0 || value === null) return [];
@@ -113,20 +157,53 @@ function normalizeComponentDocs(value) {
113
157
  return { keyPrefix, collection };
114
158
  });
115
159
  }
160
+ function optionalBoolean(name, value) {
161
+ if (value === void 0 || value === null) return false;
162
+ if (typeof value !== "boolean") fail(`option "${name}" must be a boolean`);
163
+ return value;
164
+ }
165
+ function isPresent(value) {
166
+ return value !== void 0 && value !== null;
167
+ }
168
+ function hostPathValue(name, value) {
169
+ if (isPresent(value) && typeof value !== "string") fail(`option "${name}" must be a string (project-root-relative path)`);
170
+ return value;
171
+ }
172
+ function resolveRegistrySource(projectRoot, options) {
173
+ const mode = options.registryMode ?? "module";
174
+ if (mode !== "module" && mode !== "descriptor") {
175
+ fail(`option "registryMode" must be "module" or "descriptor" (got ${JSON.stringify(mode)})`);
176
+ }
177
+ if (mode === "module") {
178
+ if (isPresent(options.descriptorModule)) {
179
+ fail(`option "descriptorModule" is only valid with registryMode: "descriptor" (registryMode is "module")`);
180
+ }
181
+ const registryModule = resolveHostModule(projectRoot, "registryModule", hostPathValue("registryModule", options.registryModule), {
182
+ required: true,
183
+ example: "./src/styleguide/sg-registry.ts"
184
+ });
185
+ return { mode, registryModule };
186
+ }
187
+ if (isPresent(options.registryModule)) {
188
+ fail(`option "registryModule" is only valid with registryMode: "module" (registryMode is "descriptor")`);
189
+ }
190
+ if (Array.isArray(options.componentDocs) && options.componentDocs.length > 0) {
191
+ fail(`option "componentDocs" is only valid with registryMode: "module" (descriptor stories have no registry key to match)`);
192
+ }
193
+ const descriptorModule = resolveHostModule(projectRoot, "descriptorModule", hostPathValue("descriptorModule", options.descriptorModule), {
194
+ required: true,
195
+ example: "./src/styleguide/story-descriptors.ts",
196
+ insideRoot: true
197
+ });
198
+ return { mode, descriptorModule };
199
+ }
116
200
  function resolveRoutesPluginOptions(projectRoot, options) {
117
201
  for (const key of Object.keys(options)) {
118
202
  if (!OPTION_KEYS.has(key)) {
119
203
  fail(`unknown option "${key}" for ${PLUGIN_NAME} (expected one of ${[...OPTION_KEYS].join(", ")})`);
120
204
  }
121
205
  }
122
- const registryValue = options.registryModule;
123
- if (registryValue !== void 0 && registryValue !== null && typeof registryValue !== "string") {
124
- fail(`option "registryModule" must be a string (project-root-relative path)`);
125
- }
126
- const registryModule = resolveHostModule(projectRoot, "registryModule", registryValue, {
127
- required: true,
128
- example: "./src/styleguide/sg-registry.ts"
129
- });
206
+ const registry = resolveRegistrySource(projectRoot, options);
130
207
  const previewCssUrl = optionalString("previewCssUrl", options.previewCssUrl);
131
208
  const tokensValue = options.tokensManifestModule;
132
209
  if (tokensValue !== void 0 && tokensValue !== null && typeof tokensValue !== "string") {
@@ -135,15 +212,37 @@ function resolveRoutesPluginOptions(projectRoot, options) {
135
212
  const tokensManifestModule = resolveHostModule(projectRoot, "tokensManifestModule", tokensValue, {
136
213
  example: "./src/config/ui-design-tokens-manifest.ts"
137
214
  });
215
+ const rawRoutes = isPlainObject(options.routes) ? options.routes : {};
216
+ const { routes, disabledRoutes: explicitlyDisabledRoutes } = normalizeRoutes(options.routes);
217
+ const disabledRoutes = new Set(explicitlyDisabledRoutes);
218
+ const externalPreview = normalizeExternalPreview(options.externalPreview);
219
+ if (externalPreview) {
220
+ if (typeof rawRoutes.componentsPreview === "string") {
221
+ fail(
222
+ `option "routes.componentsPreview" cannot be set together with "externalPreview" \u2014 externalPreview replaces the in-engine preview route`
223
+ );
224
+ }
225
+ disabledRoutes.add("componentsPreview");
226
+ }
227
+ if (registry.mode === "descriptor" && !externalPreview) {
228
+ fail(`descriptor mode has no in-engine preview; set externalPreview`);
229
+ }
230
+ const tokensRouteOption = rawRoutes.tokens === false ? false : typeof rawRoutes.tokens === "string" ? rawRoutes.tokens : void 0;
231
+ if (!isTokensRouteEnabled({ registryMode: registry.mode, tokensRouteOption, hasTokensManifest: Boolean(tokensManifestModule) })) {
232
+ disabledRoutes.add("tokens");
233
+ }
138
234
  return {
139
- registryModule,
140
- routes: normalizeRoutes(options.routes),
235
+ registry,
236
+ routes,
237
+ disabledRoutes: [...disabledRoutes],
238
+ externalPreviewUrl: externalPreview?.url ?? null,
141
239
  categoryOrder: normalizeCategoryOrder(options.categoryOrder),
142
240
  uiPackageName: optionalString("uiPackageName", options.uiPackageName) ?? null,
143
241
  previewCssUrl: previewCssUrl === void 0 ? DEFAULT_PREVIEW_CSS_URL : urlPath("previewCssUrl", previewCssUrl),
144
242
  catalog: normalizeCatalog(options.catalog),
145
243
  tokensManifestModule: tokensManifestModule ?? null,
146
- componentDocs: normalizeComponentDocs(options.componentDocs)
244
+ componentDocs: normalizeComponentDocs(options.componentDocs),
245
+ previewTokenPanel: optionalBoolean("previewTokenPanel", options.previewTokenPanel)
147
246
  };
148
247
  }
149
248
  function assertZudoDocRoutesPlugin(config) {
@@ -157,19 +256,31 @@ function buildSgContext(base, resolved) {
157
256
  return {
158
257
  base: base === void 0 || base === "" ? "/" : base,
159
258
  routes: resolved.routes,
259
+ registryMode: resolved.registry.mode,
160
260
  categoryOrder: resolved.categoryOrder,
161
261
  uiPackageName: resolved.uiPackageName,
162
262
  previewCssUrl: resolved.previewCssUrl,
163
263
  catalog: resolved.catalog,
164
- componentDocs: resolved.componentDocs
264
+ componentDocs: resolved.componentDocs,
265
+ disabledRoutes: resolved.disabledRoutes,
266
+ externalPreviewUrl: resolved.externalPreviewUrl,
267
+ previewTokenPanel: resolved.previewTokenPanel
165
268
  };
166
269
  }
167
270
  function buildContextModuleSource(context) {
168
271
  return `export const sgContext = ${JSON.stringify(context)};
169
272
  `;
170
273
  }
171
- function buildRegistryModuleSource(registryModule) {
172
- return `export { storyModules, storyExportOrder } from ${JSON.stringify(toForwardSlash(registryModule))};
274
+ function buildRegistryModuleSource(source) {
275
+ if (source.mode === "module") {
276
+ return `export { storyModules, storyExportOrder } from ${JSON.stringify(toForwardSlash(source.registryModule))};
277
+ export const storyDescriptors = [];
278
+ `;
279
+ }
280
+ return `import * as descriptorModule from ${JSON.stringify(toForwardSlash(source.descriptorModule))};
281
+ export const storyModules = {};
282
+ export const storyExportOrder = {};
283
+ export const storyDescriptors = "storyDescriptors" in descriptorModule ? descriptorModule.storyDescriptors : descriptorModule.default;
173
284
  `;
174
285
  }
175
286
  function buildTokensModuleSource(tokensManifestModule) {
@@ -183,9 +294,10 @@ function resolvePackageRoot() {
183
294
  const require2 = createRequire(import.meta.url);
184
295
  return toForwardSlash(dirname(realpathSync(require2.resolve("@takazudo/zudo-sg/package.json"))));
185
296
  }
186
- function deriveRouteInjections(routes, packageRoot) {
297
+ function deriveRouteInjections(routes, packageRoot, disabledRoutes = []) {
187
298
  const routesSrc = toForwardSlash(join(packageRoot, "routes-src"));
188
- return ROUTE_KEYS.map((key) => ({
299
+ const disabled = new Set(disabledRoutes);
300
+ return ROUTE_KEYS.filter((key) => !disabled.has(key)).map((key) => ({
189
301
  key,
190
302
  pattern: routes[key],
191
303
  entrypoint: `${routesSrc}/${ROUTE_ENTRYPOINTS[key]}`
@@ -197,7 +309,7 @@ function createRoutesPlugin({ packageRoot = resolvePackageRoot } = {}) {
197
309
  setup(ctx) {
198
310
  const resolved = resolveRoutesPluginOptions(ctx.projectRoot, ctx.options);
199
311
  assertZudoDocRoutesPlugin(ctx.config);
200
- const injections = deriveRouteInjections(resolved.routes, packageRoot());
312
+ const injections = deriveRouteInjections(resolved.routes, packageRoot(), resolved.disabledRoutes);
201
313
  for (const { entrypoint } of injections) {
202
314
  if (!existsSync(entrypoint)) {
203
315
  fail(
@@ -207,7 +319,7 @@ function createRoutesPlugin({ packageRoot = resolvePackageRoot } = {}) {
207
319
  }
208
320
  const context = buildSgContext(ctx.config.base, resolved);
209
321
  ctx.addVirtualModule(CONTEXT_MODULE_ID, () => buildContextModuleSource(context));
210
- ctx.addVirtualModule(REGISTRY_MODULE_ID, () => buildRegistryModuleSource(resolved.registryModule));
322
+ ctx.addVirtualModule(REGISTRY_MODULE_ID, () => buildRegistryModuleSource(resolved.registry));
211
323
  ctx.addVirtualModule(TOKENS_MODULE_ID, () => buildTokensModuleSource(resolved.tokensManifestModule));
212
324
  for (const { pattern, entrypoint } of injections) {
213
325
  ctx.injectRoute(pattern, entrypoint);
@@ -9,13 +9,75 @@ export interface WorkbenchVariant {
9
9
  /** Declarative control descriptors (metadata only). */
10
10
  controls?: StoryControl[];
11
11
  }
12
+ /**
13
+ * `all` (default) renders one stage per variant. `single` renders variant tabs
14
+ * and exactly one live stage, switched by props (no remount). `active` makes
15
+ * the selection controlled; without it the first variant starts selected.
16
+ */
17
+ export type WorkbenchSelection = {
18
+ mode: "all";
19
+ } | {
20
+ mode: "single";
21
+ active?: string;
22
+ onChange?: (exportName: string) => void;
23
+ };
24
+ /**
25
+ * `toolbar` (default) renders the Follow/Light/Dark group and posts
26
+ * `sg:setTheme`. `host` renders no theme group and never posts `sg:setTheme`.
27
+ */
28
+ export type WorkbenchTheme = {
29
+ mode: "toolbar";
30
+ } | {
31
+ mode: "host";
32
+ };
33
+ /**
34
+ * `auto` (default) sizes each frame from its `sg:height` reports. `fixed`
35
+ * pins every frame to `height` px and ignores `sg:height`.
36
+ */
37
+ export type WorkbenchSizing = {
38
+ mode: "auto";
39
+ } | {
40
+ mode: "fixed";
41
+ height: number;
42
+ };
43
+ /**
44
+ * Per-group toolbar flags. A false group does not render at all; with every
45
+ * group hidden no toolbar box renders.
46
+ */
47
+ export interface WorkbenchToolbar {
48
+ /** Viewport preset group. Default `true`. */
49
+ viewport?: boolean;
50
+ /** Stacked/Grid layout group. Default `true`. */
51
+ layout?: boolean;
52
+ /** Code-panel toggle. Default `false` — only a page with a code panel should enable it. */
53
+ codePanel?: boolean;
54
+ /** Preview-tokens trigger. Default `false` — only a page mounting the preview token panel should enable it. */
55
+ tokenPanel?: boolean;
56
+ }
12
57
  export interface DetailWorkbenchProps {
13
58
  slug: string;
14
59
  variants: WorkbenchVariant[];
15
60
  /** Base-prefixed preview route URL, forwarded to every stage (see VariantFrame). */
16
61
  previewUrl?: string;
62
+ /** Iframe `sandbox` tokens, forwarded to every stage (see VariantFrame). */
63
+ frameSandbox?: readonly string[];
64
+ /** Iframe `allow` directives, forwarded to every stage (see VariantFrame). */
65
+ frameAllow?: readonly string[];
66
+ /** Variant presentation. Default `{ mode: "all" }`. */
67
+ selection?: WorkbenchSelection;
68
+ /** Who owns the preview theme. Default `{ mode: "toolbar" }`. */
69
+ theme?: WorkbenchTheme;
70
+ /**
71
+ * Extra query params appended, URL-encoded, to every frame URL after
72
+ * `slug`/`variant`. The reserved keys `slug` and `variant` are ignored.
73
+ */
74
+ previewParams?: Readonly<Record<string, string>>;
75
+ /** Frame height policy. Default `{ mode: "auto" }`. */
76
+ sizing?: WorkbenchSizing;
77
+ /** Which toolbar groups render. */
78
+ toolbar?: WorkbenchToolbar;
17
79
  }
18
- declare function DetailWorkbench({ slug, variants, previewUrl, }: DetailWorkbenchProps): JSX.Element;
80
+ declare function DetailWorkbench({ slug, variants, previewUrl, frameSandbox, frameAllow, selection, theme, previewParams, sizing, toolbar, }: DetailWorkbenchProps): JSX.Element;
19
81
  declare namespace DetailWorkbench {
20
82
  var displayName: string;
21
83
  }