@takazudo/zudo-sg 0.1.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 (138) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +99 -0
  4. package/bin/zudo-sg.js +6 -0
  5. package/dist/catalog/component-thumb.d.ts +78 -0
  6. package/dist/catalog/component-thumb.js +110 -0
  7. package/dist/catalog/index.d.ts +4 -0
  8. package/dist/catalog/index.js +40 -0
  9. package/dist/catalog/tile-size.d.ts +28 -0
  10. package/dist/catalog/tile-size.js +42 -0
  11. package/dist/chrome/_styleguide-layout.d.ts +59 -0
  12. package/dist/chrome/_styleguide-layout.js +69 -0
  13. package/dist/chrome/index.d.ts +4 -0
  14. package/dist/chrome/index.js +39 -0
  15. package/dist/chrome/panel-contract.d.ts +15 -0
  16. package/dist/chrome/panel-contract.js +65 -0
  17. package/dist/chrome/panel-scripts-source.d.ts +2 -0
  18. package/dist/chrome/panel-scripts-source.js +121 -0
  19. package/dist/chrome/panel-scripts.d.ts +5 -0
  20. package/dist/chrome/panel-scripts.js +12 -0
  21. package/dist/cli/bin.d.ts +1 -0
  22. package/dist/cli/bin.js +74 -0
  23. package/dist/cli/config.d.ts +54 -0
  24. package/dist/cli/config.js +14 -0
  25. package/dist/cli/registry/build-registry-source.d.ts +27 -0
  26. package/dist/cli/registry/build-registry-source.js +77 -0
  27. package/dist/cli/registry/discover-stories.d.ts +36 -0
  28. package/dist/cli/registry/discover-stories.js +61 -0
  29. package/dist/cli/registry/gen-registry.d.ts +23 -0
  30. package/dist/cli/registry/gen-registry.js +74 -0
  31. package/dist/cli/scaffold/component-scaffold.d.ts +64 -0
  32. package/dist/cli/scaffold/component-scaffold.js +233 -0
  33. package/dist/cli/scaffold/new-component.d.ts +17 -0
  34. package/dist/cli/scaffold/new-component.js +119 -0
  35. package/dist/cli/token-manifest/css-var-parser.d.ts +9 -0
  36. package/dist/cli/token-manifest/css-var-parser.js +23 -0
  37. package/dist/cli/token-manifest/gen-token-manifest.d.ts +16 -0
  38. package/dist/cli/token-manifest/gen-token-manifest.js +49 -0
  39. package/dist/cli/token-manifest/ui-token-manifest.d.ts +78 -0
  40. package/dist/cli/token-manifest/ui-token-manifest.js +340 -0
  41. package/dist/code-panel/code-panel.d.ts +18 -0
  42. package/dist/code-panel/code-panel.js +76 -0
  43. package/dist/code-panel/copy-button.d.ts +15 -0
  44. package/dist/code-panel/copy-button.js +92 -0
  45. package/dist/code-panel/css-injection.d.ts +6 -0
  46. package/dist/code-panel/css-injection.js +37 -0
  47. package/dist/code-panel/editor-setup.d.ts +10 -0
  48. package/dist/code-panel/editor-setup.js +33 -0
  49. package/dist/code-panel/index.d.ts +6 -0
  50. package/dist/code-panel/index.js +10 -0
  51. package/dist/code-panel/source-editor.d.ts +8 -0
  52. package/dist/code-panel/source-editor.js +39 -0
  53. package/dist/config/index.d.ts +73 -0
  54. package/dist/config/index.js +68 -0
  55. package/dist/host-paths.d.ts +19 -0
  56. package/dist/host-paths.js +41 -0
  57. package/dist/index.d.ts +6 -0
  58. package/dist/index.js +18 -0
  59. package/dist/islands.d.ts +2 -0
  60. package/dist/islands.js +6 -0
  61. package/dist/plugins/preview-css.d.ts +53 -0
  62. package/dist/plugins/preview-css.js +183 -0
  63. package/dist/plugins/routes.d.ts +84 -0
  64. package/dist/plugins/routes.js +237 -0
  65. package/dist/plugins/zdtp-apply-proxy.d.ts +58 -0
  66. package/dist/plugins/zdtp-apply-proxy.js +171 -0
  67. package/dist/preview/detail-workbench.d.ts +22 -0
  68. package/dist/preview/detail-workbench.js +179 -0
  69. package/dist/preview/index.d.ts +8 -0
  70. package/dist/preview/index.js +21 -0
  71. package/dist/preview/messages.d.ts +34 -0
  72. package/dist/preview/messages.js +32 -0
  73. package/dist/preview/preview-app.d.ts +11 -0
  74. package/dist/preview/preview-app.js +87 -0
  75. package/dist/preview/route.d.ts +1 -0
  76. package/dist/preview/route.js +5 -0
  77. package/dist/preview/variant-frame.d.ts +42 -0
  78. package/dist/preview/variant-frame.js +289 -0
  79. package/dist/preview-css/compile.d.ts +40 -0
  80. package/dist/preview-css/compile.js +42 -0
  81. package/dist/preview-css/index.d.ts +2 -0
  82. package/dist/preview-css/index.js +10 -0
  83. package/dist/registry/component-docs.d.ts +38 -0
  84. package/dist/registry/component-docs.js +34 -0
  85. package/dist/registry/index.d.ts +6 -0
  86. package/dist/registry/index.js +28 -0
  87. package/dist/registry/nav-nodes.d.ts +22 -0
  88. package/dist/registry/nav-nodes.js +36 -0
  89. package/dist/registry/registry.d.ts +68 -0
  90. package/dist/registry/registry.js +91 -0
  91. package/dist/safelist.css +2 -0
  92. package/dist/search/catalog-filter.d.ts +12 -0
  93. package/dist/search/catalog-filter.js +175 -0
  94. package/dist/search/index.d.ts +2 -0
  95. package/dist/search/index.js +4 -0
  96. package/dist/sg-context.d.ts +24 -0
  97. package/dist/sg-context.js +6 -0
  98. package/dist/sg-routes.d.ts +12 -0
  99. package/dist/sg-routes.js +17 -0
  100. package/dist/stories/index.d.ts +2 -0
  101. package/dist/stories/index.js +4 -0
  102. package/dist/stories/types.d.ts +164 -0
  103. package/dist/stories/types.js +6 -0
  104. package/dist/token-dashboard/create-token-dashboards.d.ts +24 -0
  105. package/dist/token-dashboard/create-token-dashboards.js +57 -0
  106. package/dist/token-dashboard/dashboard-inventory.d.ts +11 -0
  107. package/dist/token-dashboard/dashboard-inventory.js +13 -0
  108. package/dist/token-dashboard/index.d.ts +5 -0
  109. package/dist/token-dashboard/index.js +20 -0
  110. package/dist/token-dashboard/ui-token-tabs.d.ts +53 -0
  111. package/dist/token-dashboard/ui-token-tabs.js +159 -0
  112. package/dist/token-tweak/bootstrap-preview-token-panel.d.ts +12 -0
  113. package/dist/token-tweak/bootstrap-preview-token-panel.js +18 -0
  114. package/dist/token-tweak/iframe-css-vars-bridge.d.ts +35 -0
  115. package/dist/token-tweak/iframe-css-vars-bridge.js +73 -0
  116. package/dist/token-tweak/index.d.ts +6 -0
  117. package/dist/token-tweak/index.js +36 -0
  118. package/dist/token-tweak/preview-iframe-registry.d.ts +16 -0
  119. package/dist/token-tweak/preview-iframe-registry.js +48 -0
  120. package/dist/token-tweak/preview-token-panel-bootstrap.d.ts +6 -0
  121. package/dist/token-tweak/preview-token-panel-bootstrap.js +17 -0
  122. package/dist/token-tweak/preview-token-panel-config.d.ts +42 -0
  123. package/dist/token-tweak/preview-token-panel-config.js +37 -0
  124. package/dist/token-tweak/preview-tokens-button.d.ts +5 -0
  125. package/dist/token-tweak/preview-tokens-button.js +17 -0
  126. package/dist/token-tweak/token-panel-native-bootstrap.d.ts +17 -0
  127. package/dist/token-tweak/token-panel-native-bootstrap.js +49 -0
  128. package/package.json +172 -0
  129. package/routes-src/_chrome.tsx +83 -0
  130. package/routes-src/_context.ts +15 -0
  131. package/routes-src/_preview-app.tsx +32 -0
  132. package/routes-src/_registry.ts +12 -0
  133. package/routes-src/components-index.tsx +95 -0
  134. package/routes-src/components-preview.tsx +55 -0
  135. package/routes-src/components-slug.tsx +145 -0
  136. package/routes-src/tokens.tsx +76 -0
  137. package/styles.css +612 -0
  138. package/virtual-modules.d.ts +25 -0
@@ -0,0 +1,237 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join } from "node:path";
4
+ import { resolveHostModule, toForwardSlash } from "../host-paths.js";
5
+ import {
6
+ DEFAULT_CATALOG_TITLE,
7
+ DEFAULT_PREVIEW_CSS_URL
8
+ } from "../sg-context.js";
9
+ import { DEFAULT_SG_ROUTES } from "../sg-routes.js";
10
+ const PLUGIN_NAME = "@takazudo/zudo-sg/plugins/routes";
11
+ const ZUDO_DOC_ROUTES_PLUGIN_NAME = "@takazudo/zudo-doc/plugins/routes";
12
+ const CONTEXT_MODULE_ID = "virtual:zudo-sg-context";
13
+ const REGISTRY_MODULE_ID = "virtual:zudo-sg-registry";
14
+ const TOKENS_MODULE_ID = "virtual:zudo-sg-tokens";
15
+ const TOKENS_MANIFEST_EXPORTS = Object.freeze({
16
+ paletteColors: "UI_PALETTE_COLORS",
17
+ colorTokens: "UI_COLOR_TOKENS",
18
+ spacingTokens: "UI_SPACING_TOKENS",
19
+ fontTokens: "UI_FONT_TOKENS",
20
+ sizeTokens: "UI_SIZE_TOKENS"
21
+ });
22
+ const ROUTE_ENTRYPOINTS = Object.freeze({
23
+ componentsIndex: "components-index.tsx",
24
+ componentsSlug: "components-slug.tsx",
25
+ componentsPreview: "components-preview.tsx",
26
+ tokens: "tokens.tsx"
27
+ });
28
+ const OPTION_KEYS = /* @__PURE__ */ new Set([
29
+ "registryModule",
30
+ "routes",
31
+ "categoryOrder",
32
+ "uiPackageName",
33
+ "previewCssUrl",
34
+ "catalog",
35
+ "tokensManifestModule",
36
+ "componentDocs"
37
+ ]);
38
+ const ROUTE_KEYS = Object.keys(DEFAULT_SG_ROUTES);
39
+ const CATALOG_KEYS = /* @__PURE__ */ new Set(["title", "intro"]);
40
+ function fail(message) {
41
+ throw new Error(`[zudo-sg] ${message}`);
42
+ }
43
+ function isPlainObject(value) {
44
+ return typeof value === "object" && value !== null && !Array.isArray(value);
45
+ }
46
+ function optionalString(name, value) {
47
+ if (value === void 0 || value === null) return void 0;
48
+ if (typeof value !== "string" || value === "") fail(`option "${name}" must be a non-empty string`);
49
+ return value;
50
+ }
51
+ function urlPath(name, value) {
52
+ if (!value.startsWith("/")) fail(`option "${name}" = "${value}" must be a root-absolute path starting with "/"`);
53
+ return value;
54
+ }
55
+ function normalizeRoutes(value) {
56
+ if (value === void 0 || value === null) return { ...DEFAULT_SG_ROUTES };
57
+ if (!isPlainObject(value)) fail(`option "routes" must be an object`);
58
+ for (const key of Object.keys(value)) {
59
+ if (!ROUTE_KEYS.includes(key)) {
60
+ fail(`option "routes.${key}" is not a known route (expected one of ${ROUTE_KEYS.join(", ")})`);
61
+ }
62
+ }
63
+ const routes = { ...DEFAULT_SG_ROUTES };
64
+ for (const key of ROUTE_KEYS) {
65
+ const pattern = optionalString(`routes.${key}`, value[key]);
66
+ if (pattern !== void 0) routes[key] = urlPath(`routes.${key}`, pattern);
67
+ }
68
+ if (!routes.componentsSlug.includes("[slug]")) {
69
+ fail(`option "routes.componentsSlug" = "${routes.componentsSlug}" must contain the "[slug]" segment`);
70
+ }
71
+ const seen = /* @__PURE__ */ new Map();
72
+ for (const key of ROUTE_KEYS) {
73
+ const other = seen.get(routes[key]);
74
+ if (other) fail(`options "routes.${other}" and "routes.${key}" both resolve to "${routes[key]}"`);
75
+ seen.set(routes[key], key);
76
+ }
77
+ return routes;
78
+ }
79
+ function normalizeCategoryOrder(value) {
80
+ if (value === void 0 || value === null) return [];
81
+ if (!Array.isArray(value) || value.some((c) => typeof c !== "string")) {
82
+ fail(`option "categoryOrder" must be an array of strings`);
83
+ }
84
+ return [...value];
85
+ }
86
+ function normalizeCatalog(value) {
87
+ if (value === void 0 || value === null) return { title: DEFAULT_CATALOG_TITLE, intro: null };
88
+ if (!isPlainObject(value)) fail(`option "catalog" must be an object ({ title?, intro? })`);
89
+ for (const key of Object.keys(value)) {
90
+ if (!CATALOG_KEYS.has(key)) fail(`option "catalog.${key}" is not supported (expected title, intro)`);
91
+ }
92
+ return {
93
+ title: optionalString("catalog.title", value.title) ?? DEFAULT_CATALOG_TITLE,
94
+ intro: optionalString("catalog.intro", value.intro) ?? null
95
+ };
96
+ }
97
+ function normalizeComponentDocs(value) {
98
+ if (value === void 0 || value === null) return [];
99
+ if (!Array.isArray(value)) fail(`option "componentDocs" must be an array of { keyPrefix, collection }`);
100
+ return value.map((item, i) => {
101
+ if (!isPlainObject(item)) fail(`option "componentDocs[${i}]" must be an object ({ keyPrefix, collection })`);
102
+ for (const key of Object.keys(item)) {
103
+ if (key !== "keyPrefix" && key !== "collection") {
104
+ fail(`option "componentDocs[${i}].${key}" is not supported (expected keyPrefix, collection)`);
105
+ }
106
+ }
107
+ const keyPrefix = optionalString(`componentDocs[${i}].keyPrefix`, item.keyPrefix);
108
+ const collection = optionalString(`componentDocs[${i}].collection`, item.collection);
109
+ if (keyPrefix === void 0 || collection === void 0) {
110
+ fail(`option "componentDocs[${i}]" requires non-empty "keyPrefix" and "collection" strings`);
111
+ }
112
+ return { keyPrefix, collection };
113
+ });
114
+ }
115
+ function resolveRoutesPluginOptions(projectRoot, options) {
116
+ for (const key of Object.keys(options)) {
117
+ if (!OPTION_KEYS.has(key)) {
118
+ fail(`unknown option "${key}" for ${PLUGIN_NAME} (expected one of ${[...OPTION_KEYS].join(", ")})`);
119
+ }
120
+ }
121
+ const registryValue = options.registryModule;
122
+ if (registryValue !== void 0 && registryValue !== null && typeof registryValue !== "string") {
123
+ fail(`option "registryModule" must be a string (project-root-relative path)`);
124
+ }
125
+ const registryModule = resolveHostModule(projectRoot, "registryModule", registryValue, {
126
+ required: true,
127
+ example: "./src/styleguide/sg-registry.ts"
128
+ });
129
+ const previewCssUrl = optionalString("previewCssUrl", options.previewCssUrl);
130
+ const tokensValue = options.tokensManifestModule;
131
+ if (tokensValue !== void 0 && tokensValue !== null && typeof tokensValue !== "string") {
132
+ fail(`option "tokensManifestModule" must be a string (project-root-relative path)`);
133
+ }
134
+ const tokensManifestModule = resolveHostModule(projectRoot, "tokensManifestModule", tokensValue, {
135
+ example: "./src/config/ui-design-tokens-manifest.ts"
136
+ });
137
+ return {
138
+ registryModule,
139
+ routes: normalizeRoutes(options.routes),
140
+ categoryOrder: normalizeCategoryOrder(options.categoryOrder),
141
+ uiPackageName: optionalString("uiPackageName", options.uiPackageName) ?? null,
142
+ previewCssUrl: previewCssUrl === void 0 ? DEFAULT_PREVIEW_CSS_URL : urlPath("previewCssUrl", previewCssUrl),
143
+ catalog: normalizeCatalog(options.catalog),
144
+ tokensManifestModule: tokensManifestModule ?? null,
145
+ componentDocs: normalizeComponentDocs(options.componentDocs)
146
+ };
147
+ }
148
+ function assertZudoDocRoutesPlugin(config) {
149
+ const plugins = Array.isArray(config.plugins) ? config.plugins : [];
150
+ if (plugins.some((plugin) => plugin?.name === ZUDO_DOC_ROUTES_PLUGIN_NAME)) return;
151
+ fail(
152
+ `${PLUGIN_NAME} requires the "${ZUDO_DOC_ROUTES_PLUGIN_NAME}" plugin in the zfb config \u2014 the engine routes import virtual:zudo-doc-route-context and virtual:zudo-doc-chrome-bindings, which only that plugin registers. Set packageOwnedRoutes: true in the zudo-doc settings and list the zudo-doc preset's plugins before the zudo-sg plugins.`
153
+ );
154
+ }
155
+ function buildSgContext(base, resolved) {
156
+ return {
157
+ base: base === void 0 || base === "" ? "/" : base,
158
+ routes: resolved.routes,
159
+ categoryOrder: resolved.categoryOrder,
160
+ uiPackageName: resolved.uiPackageName,
161
+ previewCssUrl: resolved.previewCssUrl,
162
+ catalog: resolved.catalog,
163
+ componentDocs: resolved.componentDocs
164
+ };
165
+ }
166
+ function buildContextModuleSource(context) {
167
+ return `export const sgContext = ${JSON.stringify(context)};
168
+ `;
169
+ }
170
+ function buildRegistryModuleSource(registryModule) {
171
+ return `export { storyModules, storyExportOrder } from ${JSON.stringify(toForwardSlash(registryModule))};
172
+ `;
173
+ }
174
+ function buildTokensModuleSource(tokensManifestModule) {
175
+ if (tokensManifestModule === null) return "export const tokensManifest = null;\n";
176
+ const names = Object.values(TOKENS_MANIFEST_EXPORTS);
177
+ const fields = Object.entries(TOKENS_MANIFEST_EXPORTS).map(([field, name]) => `${field}: ${name}`);
178
+ return `import { ${names.join(", ")} } from ${JSON.stringify(toForwardSlash(tokensManifestModule))};
179
+ export const tokensManifest = { ${fields.join(", ")} };
180
+ `;
181
+ }
182
+ function resolvePackageRoot() {
183
+ const require2 = createRequire(import.meta.url);
184
+ return toForwardSlash(dirname(realpathSync(require2.resolve("@takazudo/zudo-sg/package.json"))));
185
+ }
186
+ function deriveRouteInjections(routes, packageRoot) {
187
+ const routesSrc = toForwardSlash(join(packageRoot, "routes-src"));
188
+ return ROUTE_KEYS.map((key) => ({
189
+ key,
190
+ pattern: routes[key],
191
+ entrypoint: `${routesSrc}/${ROUTE_ENTRYPOINTS[key]}`
192
+ }));
193
+ }
194
+ function createRoutesPlugin({ packageRoot = resolvePackageRoot } = {}) {
195
+ return {
196
+ name: PLUGIN_NAME,
197
+ setup(ctx) {
198
+ const resolved = resolveRoutesPluginOptions(ctx.projectRoot, ctx.options);
199
+ assertZudoDocRoutesPlugin(ctx.config);
200
+ const injections = deriveRouteInjections(resolved.routes, packageRoot());
201
+ for (const { entrypoint } of injections) {
202
+ if (!existsSync(entrypoint)) {
203
+ fail(
204
+ `route entrypoint ${entrypoint} is missing \u2014 build @takazudo/zudo-sg (routes-src/ is generated by scripts/copy-routes-src.mjs)`
205
+ );
206
+ }
207
+ }
208
+ const context = buildSgContext(ctx.config.base, resolved);
209
+ ctx.addVirtualModule(CONTEXT_MODULE_ID, () => buildContextModuleSource(context));
210
+ ctx.addVirtualModule(REGISTRY_MODULE_ID, () => buildRegistryModuleSource(resolved.registryModule));
211
+ ctx.addVirtualModule(TOKENS_MODULE_ID, () => buildTokensModuleSource(resolved.tokensManifestModule));
212
+ for (const { pattern, entrypoint } of injections) {
213
+ ctx.injectRoute(pattern, entrypoint);
214
+ }
215
+ }
216
+ };
217
+ }
218
+ var routes_default = createRoutesPlugin();
219
+ export {
220
+ CONTEXT_MODULE_ID,
221
+ PLUGIN_NAME,
222
+ REGISTRY_MODULE_ID,
223
+ ROUTE_ENTRYPOINTS,
224
+ TOKENS_MANIFEST_EXPORTS,
225
+ TOKENS_MODULE_ID,
226
+ ZUDO_DOC_ROUTES_PLUGIN_NAME,
227
+ assertZudoDocRoutesPlugin,
228
+ buildContextModuleSource,
229
+ buildRegistryModuleSource,
230
+ buildSgContext,
231
+ buildTokensModuleSource,
232
+ createRoutesPlugin,
233
+ routes_default as default,
234
+ deriveRouteInjections,
235
+ resolvePackageRoot,
236
+ resolveRoutesPluginOptions
237
+ };
@@ -0,0 +1,58 @@
1
+ import type { ZfbDevMiddlewareRequest, ZfbDevMiddlewareResponse, ZfbPlugin, ZfbPluginLogger, ZfbSetupContext } from "@takazudo/zfb/plugins";
2
+ import type { ApplyRoutingMap } from "@takazudo/zdtp/server";
3
+ type ZdtpServerModule = typeof import("@takazudo/zdtp/server");
4
+ type ZdtpServerImporter = () => Promise<ZdtpServerModule>;
5
+ export declare const PLUGIN_NAME = "@takazudo/zudo-sg/plugins/zdtp-apply-proxy";
6
+ /** Virtual module read by the preview token panel island. */
7
+ export declare const VIRTUAL_MODULE_ID = "virtual:zudo-sg-preview-token-panel";
8
+ /** Same-origin path the preview panel POSTs its apply diff to. */
9
+ export declare const APPLY_PATH = "/__zdtp/apply";
10
+ export interface ZdtpApplyProxyOptions {
11
+ /** Project-root-relative routing JSON (e.g. `./zdtp-panel-routing.json`). */
12
+ routingFile: string;
13
+ /** Project-root-relative write sandbox directory (e.g. `./packages/demo-ui/styles`). */
14
+ writeRoot: string;
15
+ /** Project-root-relative module exporting `tabs` (the manifest-derived zdtp tab set). */
16
+ tabsModule?: string;
17
+ }
18
+ export type ResolvedZdtpApplyProxyOptions = {
19
+ enabled: true;
20
+ routingFile: string;
21
+ writeRoot: string;
22
+ tabsModule: string | undefined;
23
+ }
24
+ /** Neither `routingFile` nor `writeRoot` given (`zudoSg()` without `zdtpApplyProxy`): no Apply endpoint. */
25
+ | {
26
+ enabled: false;
27
+ tabsModule: string | undefined;
28
+ };
29
+ /** Resolves the plugin options through the shared host-path contract; throws on invalid input. */
30
+ export declare function resolveZdtpApplyProxyOptions(projectRoot: string, options: Record<string, unknown>): ResolvedZdtpApplyProxyOptions;
31
+ /** Loads the zdtp server entry; resolves `null` (warning once) if its import fails. */
32
+ export declare function loadZdtpServer(logger?: Pick<ZfbPluginLogger, "warn">, importer?: ZdtpServerImporter): Promise<ZdtpServerModule | null>;
33
+ /** Test seam: re-arms the one-shot missing-peer warning. */
34
+ export declare function __resetZdtpWarningForTests(): void;
35
+ /**
36
+ * Convert a zfb devMiddleware request into a standard Fetch API `Request`.
37
+ * zdtp's handler only calls `req.json()`, so any absolute URL works.
38
+ */
39
+ export declare function toFetchRequest(zfbReq: ZfbDevMiddlewareRequest): Request;
40
+ /** Convert a standard Fetch API `Response` into a zfb devMiddleware response. */
41
+ export declare function fromFetchResponse(res: Response): Promise<ZfbDevMiddlewareResponse>;
42
+ export interface DevMiddlewareHandlerOptions {
43
+ rootDir: string;
44
+ writeRoot: string;
45
+ routing: ApplyRoutingMap;
46
+ importer?: ZdtpServerImporter;
47
+ logger?: Pick<ZfbPluginLogger, "warn">;
48
+ }
49
+ /**
50
+ * Build the devMiddleware handler for the apply endpoint. zdtp is loaded on the
51
+ * first real POST; a failed import disables this endpoint without rejecting.
52
+ */
53
+ export declare function createDevMiddlewareHandler({ rootDir, writeRoot, routing, importer, logger, }: DevMiddlewareHandlerOptions): (zfbReq: ZfbDevMiddlewareRequest) => Promise<ZfbDevMiddlewareResponse>;
54
+ /** Builds the `virtual:zudo-sg-preview-token-panel` source. */
55
+ export declare function buildVirtualModuleSource(command: ZfbSetupContext["command"], resolved: ResolvedZdtpApplyProxyOptions, logger?: Pick<ZfbPluginLogger, "warn">, importer?: ZdtpServerImporter): Promise<string>;
56
+ export declare function createZdtpApplyProxyPlugin(importer?: ZdtpServerImporter): ZfbPlugin;
57
+ declare const _default: ZfbPlugin;
58
+ export default _default;
@@ -0,0 +1,171 @@
1
+ import { statSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { resolveHostModule, toForwardSlash } from "../host-paths.js";
4
+ const PLUGIN_NAME = "@takazudo/zudo-sg/plugins/zdtp-apply-proxy";
5
+ const VIRTUAL_MODULE_ID = "virtual:zudo-sg-preview-token-panel";
6
+ const APPLY_PATH = "/__zdtp/apply";
7
+ function isDirectory(absPath) {
8
+ try {
9
+ return statSync(absPath).isDirectory();
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+ function resolveZdtpApplyProxyOptions(projectRoot, options) {
15
+ const str = (name) => {
16
+ const value = options[name];
17
+ if (value === void 0 || value === null) return void 0;
18
+ if (typeof value !== "string") {
19
+ throw new Error(`[zudo-sg] option "${name}" must be a string (project-root-relative path)`);
20
+ }
21
+ return value;
22
+ };
23
+ const tabsModule = resolveHostModule(projectRoot, "tabsModule", str("tabsModule"), {
24
+ example: "./src/config/preview-token-panel-tabs.ts"
25
+ });
26
+ const writeRootValue = str("writeRoot");
27
+ if (str("routingFile") === void 0 && writeRootValue === void 0) {
28
+ return { enabled: false, tabsModule };
29
+ }
30
+ const routingFile = resolveHostModule(projectRoot, "routingFile", str("routingFile"), {
31
+ required: true,
32
+ example: "./zdtp-panel-routing.json"
33
+ });
34
+ if (writeRootValue === void 0) {
35
+ throw new Error(
36
+ `[zudo-sg] option "writeRoot" is required (project-root-relative path, e.g. "./packages/demo-ui/styles")`
37
+ );
38
+ }
39
+ const writeRoot = toForwardSlash(
40
+ isAbsolute(writeRootValue) ? resolve(writeRootValue) : resolve(projectRoot, writeRootValue)
41
+ );
42
+ if (writeRootValue === "" || !isDirectory(writeRoot)) {
43
+ throw new Error(
44
+ `[zudo-sg] option "writeRoot" = "${writeRootValue}" resolved to ${writeRoot} (relative to projectRoot ${toForwardSlash(resolve(projectRoot))}), which is not a directory`
45
+ );
46
+ }
47
+ return { enabled: true, routingFile, writeRoot, tabsModule };
48
+ }
49
+ let warnedMissingZdtp = false;
50
+ async function loadZdtpServer(logger, importer = () => import("@takazudo/zdtp/server")) {
51
+ try {
52
+ return await importer();
53
+ } catch (error) {
54
+ if (!warnedMissingZdtp) {
55
+ warnedMissingZdtp = true;
56
+ const message = `[zudo-sg] @takazudo/zdtp is not installed; the preview token panel Apply endpoint is disabled (${String(error)})`;
57
+ if (logger) logger.warn(message);
58
+ else console.warn(message);
59
+ }
60
+ return null;
61
+ }
62
+ }
63
+ function __resetZdtpWarningForTests() {
64
+ warnedMissingZdtp = false;
65
+ }
66
+ function toFetchRequest(zfbReq) {
67
+ const hasBody = zfbReq.method !== "GET" && zfbReq.method !== "HEAD";
68
+ return new Request(new URL(zfbReq.url, "http://127.0.0.1"), {
69
+ method: zfbReq.method,
70
+ headers: zfbReq.headers,
71
+ body: hasBody ? zfbReq.body : void 0
72
+ });
73
+ }
74
+ async function fromFetchResponse(res) {
75
+ const headers = {};
76
+ res.headers.forEach((value, key) => {
77
+ headers[key] = value;
78
+ });
79
+ return { status: res.status, headers, body: await res.text(), bodyEncoding: "utf8" };
80
+ }
81
+ const ALLOWED_METHODS = "POST, OPTIONS";
82
+ function createDevMiddlewareHandler({
83
+ rootDir,
84
+ writeRoot,
85
+ routing,
86
+ importer,
87
+ logger
88
+ }) {
89
+ let applyHandler;
90
+ return async function handleApplyRequest(zfbReq) {
91
+ if (zfbReq.method === "OPTIONS") {
92
+ return { status: 204, headers: { allow: ALLOWED_METHODS } };
93
+ }
94
+ if (zfbReq.method !== "POST") {
95
+ return { status: 405, headers: { allow: ALLOWED_METHODS }, body: "Method Not Allowed" };
96
+ }
97
+ applyHandler ??= loadZdtpServer(logger, importer).then(
98
+ (server) => server ? server.createApplyHandler({ rootDir, writeRoot, routing }) : null
99
+ );
100
+ const handler = await applyHandler;
101
+ if (!handler) {
102
+ return {
103
+ status: 503,
104
+ headers: { "content-type": "application/json" },
105
+ body: JSON.stringify({ ok: false, error: "@takazudo/zdtp is not installed" }),
106
+ bodyEncoding: "utf8"
107
+ };
108
+ }
109
+ return fromFetchResponse(await handler(toFetchRequest(zfbReq)));
110
+ };
111
+ }
112
+ async function buildVirtualModuleSource(command, resolved, logger, importer) {
113
+ const lines = [
114
+ resolved.tabsModule ? `export { tabs } from ${JSON.stringify(resolved.tabsModule)};` : "export const tabs = undefined;"
115
+ ];
116
+ const server = command === "dev" && resolved.enabled ? await loadZdtpServer(logger, importer) : null;
117
+ if (server && resolved.enabled) {
118
+ const routing = server.loadRoutingFromFile(resolved.routingFile);
119
+ lines.push(
120
+ `export const applyEndpoint = ${JSON.stringify(APPLY_PATH)};`,
121
+ `export const applyRouting = ${JSON.stringify(routing)};`
122
+ );
123
+ } else {
124
+ lines.push("export const applyEndpoint = undefined;", "export const applyRouting = undefined;");
125
+ }
126
+ return `${lines.join("\n")}
127
+ `;
128
+ }
129
+ function createZdtpApplyProxyPlugin(importer) {
130
+ return {
131
+ name: PLUGIN_NAME,
132
+ setup(ctx) {
133
+ const resolved = resolveZdtpApplyProxyOptions(ctx.projectRoot, ctx.options);
134
+ ctx.addVirtualModule(
135
+ VIRTUAL_MODULE_ID,
136
+ () => buildVirtualModuleSource(ctx.command, resolved, ctx.logger, importer),
137
+ ctx.command === "dev" && resolved.enabled ? { watchFiles: [resolved.routingFile] } : void 0
138
+ );
139
+ },
140
+ async devMiddleware(ctx) {
141
+ const resolved = resolveZdtpApplyProxyOptions(ctx.projectRoot, ctx.options);
142
+ if (!resolved.enabled) return;
143
+ const server = await loadZdtpServer(ctx.logger, importer);
144
+ ctx.register(
145
+ APPLY_PATH,
146
+ createDevMiddlewareHandler({
147
+ rootDir: ctx.projectRoot,
148
+ writeRoot: resolved.writeRoot,
149
+ routing: server ? server.loadRoutingFromFile(resolved.routingFile) : {},
150
+ importer,
151
+ logger: ctx.logger
152
+ })
153
+ );
154
+ }
155
+ };
156
+ }
157
+ var zdtp_apply_proxy_default = createZdtpApplyProxyPlugin();
158
+ export {
159
+ APPLY_PATH,
160
+ PLUGIN_NAME,
161
+ VIRTUAL_MODULE_ID,
162
+ __resetZdtpWarningForTests,
163
+ buildVirtualModuleSource,
164
+ createDevMiddlewareHandler,
165
+ createZdtpApplyProxyPlugin,
166
+ zdtp_apply_proxy_default as default,
167
+ fromFetchResponse,
168
+ loadZdtpServer,
169
+ resolveZdtpApplyProxyOptions,
170
+ toFetchRequest
171
+ };
@@ -0,0 +1,22 @@
1
+ import type { JSX } from "preact";
2
+ import type { StoryControl } from "../stories/index.js";
3
+ /** One variant, flattened to the JSON-serializable shape an island can take. */
4
+ export interface WorkbenchVariant {
5
+ /** Story export name (e.g. "Variants"). */
6
+ exportName: string;
7
+ /** Human label shown above the preview. */
8
+ name: string;
9
+ /** Declarative control descriptors (metadata only). */
10
+ controls?: StoryControl[];
11
+ }
12
+ export interface DetailWorkbenchProps {
13
+ slug: string;
14
+ variants: WorkbenchVariant[];
15
+ /** Base-prefixed preview route URL, forwarded to every stage (see VariantFrame). */
16
+ previewUrl?: string;
17
+ }
18
+ declare function DetailWorkbench({ slug, variants, previewUrl, }: DetailWorkbenchProps): JSX.Element;
19
+ declare namespace DetailWorkbench {
20
+ var displayName: string;
21
+ }
22
+ export default DetailWorkbench;
@@ -0,0 +1,179 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "preact/jsx-runtime";
3
+ import { useEffect, useState } from "preact/hooks";
4
+ import VariantFrame, {
5
+ DEFAULT_THEME_MODE,
6
+ DEFAULT_VIEWPORT_ID,
7
+ THEME_OPTIONS,
8
+ VIEWPORTS
9
+ } from "./variant-frame.js";
10
+ import {
11
+ ATTR_CODE_PANEL_HIDDEN,
12
+ isCodePanelHidden,
13
+ toggleCodePanel
14
+ } from "../chrome/panel-contract.js";
15
+ const LAYOUT_OPTIONS = [
16
+ { id: "stacked", label: "Stacked" },
17
+ { id: "grid", label: "Grid" }
18
+ ];
19
+ const TRACK_CLASS = "flex flex-wrap items-center gap-hsp-2xs rounded-md border border-border bg-surface-2 p-hsp-2xs";
20
+ const SEGMENT_BASE_CLASS = "rounded-sm border px-hsp-sm py-vsp-3xs text-caption leading-normal transition-colors cursor-pointer ";
21
+ const SEGMENT_ON_CLASS = "border-border-strong bg-surface text-fg";
22
+ const SEGMENT_OFF_CLASS = "border-transparent text-muted hover:text-fg";
23
+ const PILL_BASE_CLASS = "inline-flex items-center gap-hsp-2xs rounded-md border px-hsp-sm py-vsp-3xs text-caption leading-normal transition-colors cursor-pointer ";
24
+ const PILL_ON_CLASS = "border-border-strong bg-surface-2 text-fg";
25
+ const PILL_OFF_CLASS = "border-border bg-surface text-muted hover:text-fg";
26
+ const STACKED_GRID_CLASS = "grid items-start gap-x-hsp-xl gap-y-vsp-xl grid-cols-1";
27
+ const COLUMNS_GRID_CLASS = "grid items-start gap-x-hsp-xl gap-y-vsp-xl grid-cols-[repeat(auto-fit,minmax(min(18rem,100%),1fr))]";
28
+ function segmentClass(selected) {
29
+ return SEGMENT_BASE_CLASS + (selected ? SEGMENT_ON_CLASS : SEGMENT_OFF_CLASS);
30
+ }
31
+ function DetailWorkbench({
32
+ slug,
33
+ variants,
34
+ previewUrl
35
+ }) {
36
+ const [themeMode, setThemeMode] = useState(DEFAULT_THEME_MODE);
37
+ const [viewportId, setViewportId] = useState(DEFAULT_VIEWPORT_ID);
38
+ const [layout, setLayout] = useState("stacked");
39
+ const [codePanelShown, setCodePanelShown] = useState(true);
40
+ useEffect(() => {
41
+ const sync = () => setCodePanelShown(!isCodePanelHidden());
42
+ sync();
43
+ const observer = new MutationObserver(sync);
44
+ observer.observe(document.documentElement, {
45
+ attributes: true,
46
+ attributeFilter: [ATTR_CODE_PANEL_HIDDEN]
47
+ });
48
+ return () => observer.disconnect();
49
+ }, []);
50
+ function openPreviewTokenPanel() {
51
+ window.dispatchEvent(new CustomEvent("toggle-preview-token-panel"));
52
+ }
53
+ return /* @__PURE__ */ jsxs("div", { children: [
54
+ /* @__PURE__ */ jsxs("div", { class: "sg-workbench-toolbar", children: [
55
+ /* @__PURE__ */ jsx("div", { role: "group", "aria-label": "Preview theme", class: TRACK_CLASS, children: THEME_OPTIONS.map((option) => /* @__PURE__ */ jsx(
56
+ "button",
57
+ {
58
+ type: "button",
59
+ onClick: () => setThemeMode(option.id),
60
+ "aria-pressed": themeMode === option.id,
61
+ class: segmentClass(themeMode === option.id),
62
+ children: option.label
63
+ },
64
+ option.id
65
+ )) }),
66
+ /* @__PURE__ */ jsx("div", { role: "group", "aria-label": "Preview viewport", class: TRACK_CLASS, children: VIEWPORTS.map((preset) => /* @__PURE__ */ jsx(
67
+ "button",
68
+ {
69
+ type: "button",
70
+ onClick: () => setViewportId(preset.id),
71
+ "aria-pressed": viewportId === preset.id,
72
+ class: segmentClass(viewportId === preset.id),
73
+ children: preset.label
74
+ },
75
+ preset.id
76
+ )) }),
77
+ /* @__PURE__ */ jsx("div", { role: "group", "aria-label": "Preview layout", class: TRACK_CLASS, children: LAYOUT_OPTIONS.map((option) => /* @__PURE__ */ jsx(
78
+ "button",
79
+ {
80
+ type: "button",
81
+ onClick: () => setLayout(option.id),
82
+ "aria-pressed": layout === option.id,
83
+ class: segmentClass(layout === option.id),
84
+ children: option.label
85
+ },
86
+ option.id
87
+ )) }),
88
+ /* @__PURE__ */ jsxs("div", { class: "ms-auto flex flex-wrap items-center gap-hsp-sm", children: [
89
+ /* @__PURE__ */ jsxs(
90
+ "button",
91
+ {
92
+ type: "button",
93
+ onClick: () => toggleCodePanel(),
94
+ "aria-pressed": codePanelShown,
95
+ title: "Toggle code panel",
96
+ class: PILL_BASE_CLASS + (codePanelShown ? PILL_ON_CLASS : PILL_OFF_CLASS),
97
+ children: [
98
+ /* @__PURE__ */ jsxs(
99
+ "svg",
100
+ {
101
+ xmlns: "http://www.w3.org/2000/svg",
102
+ width: "20",
103
+ height: "20",
104
+ viewBox: "0 0 24 24",
105
+ fill: "none",
106
+ stroke: "currentColor",
107
+ "stroke-width": "2",
108
+ "stroke-linecap": "round",
109
+ "stroke-linejoin": "round",
110
+ "aria-hidden": "true",
111
+ children: [
112
+ /* @__PURE__ */ jsx("polyline", { points: "16 18 22 12 16 6" }),
113
+ /* @__PURE__ */ jsx("polyline", { points: "8 6 2 12 8 18" })
114
+ ]
115
+ }
116
+ ),
117
+ "Code panel"
118
+ ]
119
+ }
120
+ ),
121
+ /* @__PURE__ */ jsxs(
122
+ "button",
123
+ {
124
+ type: "button",
125
+ onClick: openPreviewTokenPanel,
126
+ title: "Edit the design tokens used inside the preview iframes",
127
+ class: PILL_BASE_CLASS + PILL_OFF_CLASS,
128
+ children: [
129
+ /* @__PURE__ */ jsxs(
130
+ "svg",
131
+ {
132
+ xmlns: "http://www.w3.org/2000/svg",
133
+ width: "20",
134
+ height: "20",
135
+ viewBox: "0 0 24 24",
136
+ fill: "none",
137
+ stroke: "currentColor",
138
+ "stroke-width": "2",
139
+ "stroke-linecap": "round",
140
+ "stroke-linejoin": "round",
141
+ "aria-hidden": "true",
142
+ children: [
143
+ /* @__PURE__ */ jsx("rect", { x: "3", y: "3", width: "13", height: "13", rx: "1.5" }),
144
+ /* @__PURE__ */ jsx("path", { d: "M8 8h12.5A1.5 1.5 0 0 1 22 9.5V20a1.5 1.5 0 0 1-1.5 1.5H10A1.5 1.5 0 0 1 8.5 20" })
145
+ ]
146
+ }
147
+ ),
148
+ "Preview tokens"
149
+ ]
150
+ }
151
+ )
152
+ ] })
153
+ ] }),
154
+ /* @__PURE__ */ jsx(
155
+ "div",
156
+ {
157
+ "data-sg-stage-grid": layout,
158
+ class: layout === "grid" ? COLUMNS_GRID_CLASS : STACKED_GRID_CLASS,
159
+ children: variants.map((variant) => /* @__PURE__ */ jsx(
160
+ VariantFrame,
161
+ {
162
+ slug,
163
+ exportName: variant.exportName,
164
+ name: variant.name,
165
+ controls: variant.controls,
166
+ themeMode,
167
+ viewportId,
168
+ previewUrl
169
+ },
170
+ variant.exportName
171
+ ))
172
+ }
173
+ )
174
+ ] });
175
+ }
176
+ DetailWorkbench.displayName = "DetailWorkbench";
177
+ export {
178
+ DetailWorkbench as default
179
+ };
@@ -0,0 +1,8 @@
1
+ export { default as PreviewApp } from "./preview-app.js";
2
+ export type { PreviewAppProps } from "./preview-app.js";
3
+ export { default as DetailWorkbench } from "./detail-workbench.js";
4
+ export type { DetailWorkbenchProps, WorkbenchVariant } from "./detail-workbench.js";
5
+ export { default as VariantFrame, DEFAULT_THEME_MODE, DEFAULT_VIEWPORT_ID, THEME_OPTIONS, VIEWPORTS, } from "./variant-frame.js";
6
+ export type { ThemeMode, ThemeOption, VariantFrameProps, Viewport, ViewportId, } from "./variant-frame.js";
7
+ export * from "./messages.js";
8
+ export { PREVIEW_ROUTE_PATH } from "./route.js";