@storybook-astro/framework 1.1.1 → 1.2.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.
- package/dist/{chunk-5EF25G5S.js → chunk-KXAAX3GN.js} +1 -1
- package/dist/chunk-KXAAX3GN.js.map +1 -0
- package/dist/{chunk-V76WSNSP.js → chunk-OUEDTRBO.js} +51 -1
- package/dist/chunk-OUEDTRBO.js.map +1 -0
- package/dist/{chunk-4HECE7IW.js → chunk-PBISP7PA.js} +77 -16
- package/dist/chunk-PBISP7PA.js.map +1 -0
- package/dist/index.d.ts +16 -6
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/middleware.js +3 -31
- package/dist/middleware.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/{portable-stories-BvdaQigq.d.ts → portable-stories-DXT_GOf6.d.ts} +3 -3
- package/dist/preset.d.ts +1 -1
- package/dist/preset.js +2 -2
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/{types-Cvor6Tyi.d.ts → types-C-jan6Px.d.ts} +9 -0
- package/dist/vitest/index.d.ts +19 -1
- package/dist/vitest/index.js +1 -0
- package/package.json +4 -4
- package/src/index.ts +12 -2
- package/src/lib/passthrough-image-service.ts +76 -0
- package/src/middleware.ts +4 -45
- package/src/portable-stories.test.ts +28 -0
- package/src/portable-stories.ts +12 -12
- package/src/types.ts +9 -0
- package/src/vitePluginAstroBuildPrerender.ts +141 -14
- package/src/vitest/index.ts +1 -0
- package/dist/chunk-4HECE7IW.js.map +0 -1
- package/dist/chunk-5EF25G5S.js.map +0 -1
- package/dist/chunk-V76WSNSP.js.map +0 -1
|
@@ -2,10 +2,11 @@ import { createRequire } from 'node:module';
|
|
|
2
2
|
import type { Dirent } from 'node:fs';
|
|
3
3
|
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { resolve } from 'node:path';
|
|
5
|
-
import { experimental_AstroContainer as AstroContainer } from 'astro/container';
|
|
5
|
+
import type { experimental_AstroContainer as AstroContainer } from 'astro/container';
|
|
6
6
|
import { createServer, mergeConfig, type Plugin, type Rollup } from 'vite';
|
|
7
7
|
import { importAstroConfig } from './importAstroConfig.ts';
|
|
8
8
|
import type { Integration } from './integrations/index.ts';
|
|
9
|
+
import { installPassthroughImageService } from './lib/passthrough-image-service.ts';
|
|
9
10
|
import { ssrLoadModuleWithFsFallback } from './lib/ssr-load-module-with-fs-fallback.ts';
|
|
10
11
|
import { resolveSanitizationOptions, sanitizeRenderPayload } from './lib/sanitization.ts';
|
|
11
12
|
import { resolveStoryModuleMock, withStoryModuleMocks } from './module-mocks.ts';
|
|
@@ -97,7 +98,9 @@ export function vitePluginAstroBuildPrerender(options: FrameworkOptions): Plugin
|
|
|
97
98
|
}
|
|
98
99
|
|
|
99
100
|
if (id.startsWith('\0virtual:astro-component-module/')) {
|
|
100
|
-
const
|
|
101
|
+
const withoutPrefix = id.replace('\0virtual:astro-component-module/', '');
|
|
102
|
+
// Strip the ?component-wrapper query appended by toComponentVirtualId
|
|
103
|
+
const encodedSpecifier = withoutPrefix.replace(/\?.*$/, '');
|
|
101
104
|
const specifier = decodeURIComponent(encodedSpecifier);
|
|
102
105
|
|
|
103
106
|
return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\n');
|
|
@@ -122,20 +125,34 @@ export function vitePluginAstroBuildPrerender(options: FrameworkOptions): Plugin
|
|
|
122
125
|
staticEntrypointRefs.set(specifier, fileReferenceId);
|
|
123
126
|
});
|
|
124
127
|
|
|
125
|
-
const
|
|
126
|
-
|
|
128
|
+
const componentRootPaths = [
|
|
129
|
+
resolve(resolveFrom, 'src/components'),
|
|
130
|
+
...(options.renderMode === 'static' && options.componentRoots
|
|
131
|
+
? options.componentRoots.map((root) => resolve(resolveFrom, root))
|
|
132
|
+
: [])
|
|
133
|
+
];
|
|
134
|
+
const specifierArrays = await Promise.all(
|
|
135
|
+
componentRootPaths.map((root) => collectHydratableSourceModules(root))
|
|
136
|
+
);
|
|
137
|
+
const specifiers = specifierArrays.flat();
|
|
127
138
|
|
|
128
139
|
specifiers.forEach((specifier) => {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
140
|
+
// .svelte and .vue files must be emitted as direct chunks so their
|
|
141
|
+
// native Vite compile plugins process them correctly. The virtual
|
|
142
|
+
// module wrapper exposes a JS re-export stub; vite-plugin-svelte and
|
|
143
|
+
// @vitejs/plugin-vue strip the query string before checking the
|
|
144
|
+
// extension, so they still try to compile the stub as framework source.
|
|
145
|
+
const chunkId = /\.(svelte|vue)$/.test(specifier)
|
|
146
|
+
? specifier
|
|
147
|
+
: toComponentVirtualId(specifier);
|
|
148
|
+
|
|
149
|
+
const fileReferenceId = this.emitFile({ type: 'chunk', id: chunkId });
|
|
133
150
|
|
|
134
151
|
componentEntrypointRefs.set(specifier, fileReferenceId);
|
|
135
152
|
});
|
|
136
153
|
},
|
|
137
154
|
|
|
138
|
-
async writeBundle(this: Rollup.PluginContext) {
|
|
155
|
+
async writeBundle(this: Rollup.PluginContext, _outputOptions: Rollup.NormalizedOutputOptions, bundle: Rollup.OutputBundle) {
|
|
139
156
|
const staticModuleMap = buildStaticModuleMap(
|
|
140
157
|
this,
|
|
141
158
|
staticEntrypointRefs,
|
|
@@ -157,7 +174,8 @@ export function vitePluginAstroBuildPrerender(options: FrameworkOptions): Plugin
|
|
|
157
174
|
storyRulesConfigFilePath,
|
|
158
175
|
staticModuleMap,
|
|
159
176
|
trackedSpecifiers,
|
|
160
|
-
resolveFrom
|
|
177
|
+
resolveFrom,
|
|
178
|
+
bundle
|
|
161
179
|
});
|
|
162
180
|
|
|
163
181
|
await writePrerenderedStoriesFile(outDir, prerenderedStories);
|
|
@@ -178,6 +196,7 @@ async function prerenderStories(options: {
|
|
|
178
196
|
staticModuleMap: Record<string, string>;
|
|
179
197
|
trackedSpecifiers: Set<string>;
|
|
180
198
|
resolveFrom: string;
|
|
199
|
+
bundle: Rollup.OutputBundle;
|
|
181
200
|
}) {
|
|
182
201
|
const sanitizationOptions = resolveSanitizationOptions(options.sanitization ?? undefined);
|
|
183
202
|
const resolveClientModule = createClientModuleResolver(
|
|
@@ -190,9 +209,29 @@ async function prerenderStories(options: {
|
|
|
190
209
|
options.resolveFrom
|
|
191
210
|
);
|
|
192
211
|
const rulesConfigModule = await loadRulesConfigModule(viteServer, options.storyRulesConfigFilePath);
|
|
212
|
+
const assetPathMap = buildAssetPathMap(options.bundle);
|
|
213
|
+
|
|
214
|
+
// Inject a passthrough image service before the container renders any
|
|
215
|
+
// components. The `image: { service: passthroughImageService() }` config
|
|
216
|
+
// passed to Astro above is not sufficient on Astro 6: at render time
|
|
217
|
+
// `getConfiguredImageService()` still dynamically imports
|
|
218
|
+
// "virtual:image-service", which fails in Vite 7's module runner with
|
|
219
|
+
// `InvalidImageService`. Pre-populating globalThis.astroAsset.imageService
|
|
220
|
+
// short-circuits that dynamic import. See `lib/passthrough-image-service.ts`.
|
|
221
|
+
installPassthroughImageService();
|
|
193
222
|
|
|
194
223
|
try {
|
|
195
|
-
|
|
224
|
+
// Load AstroContainer through the SSR module graph so that internal
|
|
225
|
+
// classes (SlotString, HTMLString) share the same module instance as the
|
|
226
|
+
// Astro components loaded via ssrLoadModule below. Cross-module instanceof
|
|
227
|
+
// checks fail when AstroContainer is imported statically (Node.js context)
|
|
228
|
+
// and components are loaded via Vite SSR (separate module graph), which
|
|
229
|
+
// causes slot HTML to be escaped character-by-character instead of being
|
|
230
|
+
// passed through as raw HTML.
|
|
231
|
+
const containerModule = await viteServer.ssrLoadModule('astro/container');
|
|
232
|
+
const AstroContainerRuntime = containerModule.experimental_AstroContainer as typeof AstroContainer;
|
|
233
|
+
|
|
234
|
+
const container = await AstroContainerRuntime.create({
|
|
196
235
|
resolve: async (specifier) => {
|
|
197
236
|
const mockedModule = resolveStoryModuleMock(specifier);
|
|
198
237
|
|
|
@@ -270,7 +309,7 @@ async function prerenderStories(options: {
|
|
|
270
309
|
});
|
|
271
310
|
|
|
272
311
|
if (html !== undefined) {
|
|
273
|
-
output[story.id] = html;
|
|
312
|
+
output[story.id] = rewriteAssetPaths(html, assetPathMap);
|
|
274
313
|
}
|
|
275
314
|
}
|
|
276
315
|
|
|
@@ -308,6 +347,15 @@ async function createStorySsrServer(
|
|
|
308
347
|
server: {
|
|
309
348
|
middlewareMode: true
|
|
310
349
|
},
|
|
350
|
+
ssr: {
|
|
351
|
+
// Force Astro runtime modules to be loaded through Vite's SSR transform
|
|
352
|
+
// pipeline rather than being externalized via Node.js native import().
|
|
353
|
+
// Without this, the AstroContainer (loaded via ssrLoadModule) and the
|
|
354
|
+
// component rendering pipeline may resolve internal classes like
|
|
355
|
+
// SlotString/HTMLString from separate module instances, causing
|
|
356
|
+
// instanceof checks to fail and slot HTML to be escaped.
|
|
357
|
+
noExternal: /^astro(\/.+)?$/
|
|
358
|
+
},
|
|
311
359
|
plugins: [
|
|
312
360
|
createProjectAstroResolutionPlugin(resolveFrom),
|
|
313
361
|
vitePluginAstroFontsFallback(),
|
|
@@ -538,7 +586,9 @@ function toStaticVirtualId(specifier: string) {
|
|
|
538
586
|
}
|
|
539
587
|
|
|
540
588
|
function toComponentVirtualId(specifier: string) {
|
|
541
|
-
|
|
589
|
+
// Append a non-extension suffix so framework compile plugins (e.g. vite-plugin-svelte)
|
|
590
|
+
// don't match the virtual module ID by extension and try to compile the JS re-export stub.
|
|
591
|
+
return `virtual:astro-component-module/${encodeURIComponent(specifier)}?component-wrapper`;
|
|
542
592
|
}
|
|
543
593
|
|
|
544
594
|
function isClientEntrypoint(specifier: string) {
|
|
@@ -549,6 +599,80 @@ function toPublicPath(fileName: string) {
|
|
|
549
599
|
return `./${fileName}`;
|
|
550
600
|
}
|
|
551
601
|
|
|
602
|
+
function buildAssetPathMap(bundle: Rollup.OutputBundle): Map<string, string> {
|
|
603
|
+
const exactMap = new Map<string, string>();
|
|
604
|
+
const stemMap = new Map<string, string>();
|
|
605
|
+
|
|
606
|
+
for (const chunk of Object.values(bundle)) {
|
|
607
|
+
if (chunk.type !== 'asset') {
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const asset = chunk as Rollup.OutputAsset;
|
|
612
|
+
|
|
613
|
+
if (asset.originalFileNames && asset.originalFileNames.length > 0) {
|
|
614
|
+
for (const originalPath of asset.originalFileNames) {
|
|
615
|
+
exactMap.set(originalPath, `/${asset.fileName}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
// Vite does not populate originalFileNames for image assets processed
|
|
620
|
+
// through its asset pipeline. Build a secondary lookup by the filename
|
|
621
|
+
// stem so /@fs/ URLs in prerendered HTML can still be mapped to their
|
|
622
|
+
// content-hashed output paths. e.g. "storybook-astro-CfMmZdup.png" ⟶
|
|
623
|
+
// stem key "storybook-astro.png" ⟶ "/_astro/storybook-astro-CfMmZdup.png".
|
|
624
|
+
const baseName = asset.fileName.split('/').pop() ?? '';
|
|
625
|
+
const stemMatch = baseName.match(/^(.+)-[A-Za-z0-9]{6,12}\.(png|jpe?g|gif|webp|svg|avif|ico)$/);
|
|
626
|
+
|
|
627
|
+
if (stemMatch) {
|
|
628
|
+
stemMap.set(`${stemMatch[1]}.${stemMatch[2]}`, `/${asset.fileName}`);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
return { exactMap, stemMap } as unknown as Map<string, string>;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function rewriteAssetPaths(html: string, assetPathMap: ReturnType<typeof buildAssetPathMap>): string {
|
|
636
|
+
const { exactMap, stemMap } = assetPathMap as unknown as {
|
|
637
|
+
exactMap: Map<string, string>;
|
|
638
|
+
stemMap: Map<string, string>;
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
if (exactMap.size === 0 && stemMap.size === 0) {
|
|
642
|
+
return html;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Match /@fs/ URLs in HTML attribute values, stripping any query string.
|
|
646
|
+
// Vite dev server uses /@fs//absolute/path for filesystem assets; in static
|
|
647
|
+
// builds these are emitted as /_astro/name.hash.ext output assets.
|
|
648
|
+
// The character class deliberately excludes only quotes (the attribute
|
|
649
|
+
// delimiters) so that paths containing spaces are captured in full.
|
|
650
|
+
return html.replace(/\/@fs\/[^"']+/g, (match) => {
|
|
651
|
+
const pathOnly = match.replace(/\?.*$/, '');
|
|
652
|
+
const fsPath = pathOnly.slice('/@fs'.length);
|
|
653
|
+
// Handle /@fs//abs/path (double leading slash on Unix)
|
|
654
|
+
const absolutePath = fsPath.startsWith('//') ? fsPath.slice(1) : fsPath;
|
|
655
|
+
|
|
656
|
+
// Try exact match by originalFileNames first
|
|
657
|
+
const exact = exactMap.get(absolutePath);
|
|
658
|
+
|
|
659
|
+
if (exact) {
|
|
660
|
+
return exact;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// Fall back to stem-based matching for image assets whose
|
|
664
|
+
// originalFileNames are empty (standard Vite asset pipeline behaviour).
|
|
665
|
+
const baseName = absolutePath.split('/').pop() ?? '';
|
|
666
|
+
const stemHit = stemMap.get(baseName);
|
|
667
|
+
|
|
668
|
+
if (stemHit) {
|
|
669
|
+
return stemHit;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
return match;
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
|
|
552
676
|
async function collectHydratableSourceModules(srcRoot: string): Promise<string[]> {
|
|
553
677
|
const modules: string[] = [];
|
|
554
678
|
|
|
@@ -596,7 +720,10 @@ async function collectHydratableSourceModules(srcRoot: string): Promise<string[]
|
|
|
596
720
|
}
|
|
597
721
|
|
|
598
722
|
function isHydratableSourceFile(input: string) {
|
|
599
|
-
|
|
723
|
+
// Only framework component extensions — plain .js/.ts are utilities/data
|
|
724
|
+
// files that are not hydratable client components and must not be emitted
|
|
725
|
+
// as entry chunks (they may lack a default export, causing a build error).
|
|
726
|
+
return /\.(jsx|tsx|vue|svelte)$/.test(input);
|
|
600
727
|
}
|
|
601
728
|
|
|
602
729
|
function isNonHydratableSourceFile(input: string) {
|
package/src/vitest/index.ts
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/viteStorybookRendererFallbackPlugin.ts","../src/viteStorybookAstroRendererPlugin.ts","../src/vitePluginAstroBuildPrerender.ts","../src/vitePluginAstroBuildServer.ts","../src/vitePluginAstro.ts","../src/vite/astroFilesVirtualModulePlugin.ts","../src/vite/storybookAstroRulesConfigVirtualModulePlugin.ts","../src/vite/storybookAstroSanitizationConfigVirtualModulePlugin.ts","../src/vite/storybookAstroServerAuthConfigVirtualModulePlugin.ts","../src/vitePluginAstroToolbarFallback.ts","../src/preset.ts"],"sourcesContent":["import type { Integration } from './integrations/index.ts';\nimport { createVirtualModulePlugin } from './vite/createVirtualModulePlugin.ts';\n\nexport function viteStorybookRendererFallbackPlugin(integrations: Integration[]) {\n const safeIntegrations = integrations ?? [];\n\n return createVirtualModulePlugin({\n pluginName: 'storybook-renderer-fallback',\n virtualModuleId: 'virtual:storybook-renderer-fallback',\n load() {\n return safeIntegrations\n .filter((integration) => integration.storybookEntryPreview)\n .map(\n (integration) =>\n `export * as ${integration.name} from '${integration.storybookEntryPreview}';`\n )\n .join('\\n');\n }\n });\n}\n","import type { RenderMode, ServerBuildOptions } from './types.ts';\nimport { createVirtualModulePlugin } from './vite/createVirtualModulePlugin.ts';\n\nconst packageName = '@storybook-astro/framework';\n\nexport function viteStorybookAstroRendererPlugin(options: {\n mode: 'development' | 'production';\n renderMode?: RenderMode;\n server?: ServerBuildOptions;\n}) {\n const pluginName = 'storybook-astro:renderer-module';\n const virtualModuleId = 'virtual:storybook-astro-renderer';\n const isProduction = options.mode === 'production';\n const isStaticMode = options.renderMode === 'static';\n\n return createVirtualModulePlugin({\n pluginName,\n virtualModuleId,\n load() {\n if (!isProduction) {\n return `export * from '${packageName}/renderer/renderer-dev.ts';`;\n }\n\n if (isStaticMode) {\n return `export * from '${packageName}/renderer/renderer-static.ts';`;\n }\n\n return [\n `import { createServerRenderer } from '${packageName}/renderer/renderer-server.ts';`,\n `const renderer = createServerRenderer(${JSON.stringify(\n {\n serverUrl: options.server?.serverUrl,\n authToken: options.server?.authToken,\n authHeader: options.server?.authHeader\n },\n null,\n 2\n )});`,\n 'export const render = renderer.render;',\n 'export const init = renderer.init;',\n 'export const applyStyles = renderer.applyStyles;'\n ].join('\\n');\n }\n });\n}\n","import { createRequire } from 'node:module';\nimport type { Dirent } from 'node:fs';\nimport { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { experimental_AstroContainer as AstroContainer } from 'astro/container';\nimport { createServer, mergeConfig, type Plugin, type Rollup } from 'vite';\nimport { importAstroConfig } from './importAstroConfig.ts';\nimport type { Integration } from './integrations/index.ts';\nimport { ssrLoadModuleWithFsFallback } from './lib/ssr-load-module-with-fs-fallback.ts';\nimport { resolveSanitizationOptions, sanitizeRenderPayload } from './lib/sanitization.ts';\nimport { resolveStoryModuleMock, withStoryModuleMocks } from './module-mocks.ts';\nimport { resolveRulesConfigFilePath } from './rules-options.ts';\nimport { selectStoryRules, withStoryRuleCleanups } from './rules.ts';\nimport type { FrameworkOptions } from './types.ts';\nimport { vitePluginAstroFontsFallback } from './vitePluginAstroFontsFallback.ts';\nimport { vitePluginAstroIntegrationOptsFallback } from './vitePluginAstroIntegrationOptsFallback.ts';\nimport { vitePluginAstroRoutesFallback } from './vitePluginAstroRoutesFallback.ts';\nimport { vitePluginAstroVueFallback } from './vitePluginAstroVueFallback.ts';\n\nconst PRERENDERED_STORIES_FILE = 'astro-prerendered-stories.json';\n\ntype StoryIndex = {\n entries?: Record<\n string,\n {\n type?: string;\n id?: string;\n importPath?: string;\n exportName?: string;\n componentPath?: string;\n title?: string;\n name?: string;\n }\n >;\n};\n\ntype StoryEntry = {\n id: string;\n importPath: string;\n exportName: string;\n title?: string;\n name?: string;\n};\n\ntype AstroCreateResult = {\n createAstro?: (...args: unknown[]) => unknown;\n};\n\ntype AstroComponentFactory = ((\n result: AstroCreateResult,\n props: unknown,\n slots: unknown\n) => unknown) & {\n isAstroComponentFactory?: boolean;\n moduleId?: string;\n propagation?: unknown;\n};\n\nexport function vitePluginAstroBuildPrerender(options: FrameworkOptions): Plugin {\n const integrations = options.integrations ?? [];\n const resolveFrom = options.resolveFrom ?? process.cwd();\n const storyRulesConfigFilePath = resolveRulesConfigFilePath(options.storyRules, resolveFrom);\n const trackedSpecifiers = collectTrackedSpecifiers(integrations);\n const staticEntrypointRefs = new Map<string, string>();\n const componentEntrypointRefs = new Map<string, string>();\n let outDir = resolve(resolveFrom, 'storybook-static');\n\n return {\n name: 'storybook-astro:build-prerender',\n apply: 'build',\n enforce: 'post',\n\n configResolved(config) {\n outDir = resolve(resolveFrom, config.build.outDir ?? 'storybook-static');\n },\n\n resolveId(id: string) {\n if (id.startsWith('virtual:astro-static-module/')) {\n return `\\0${id}`;\n }\n\n if (id.startsWith('virtual:astro-component-module/')) {\n return `\\0${id}`;\n }\n },\n\n load(id: string) {\n if (id.startsWith('\\0virtual:astro-static-module/')) {\n const encodedSpecifier = id.replace('\\0virtual:astro-static-module/', '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n if (isClientEntrypoint(specifier)) {\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\\n');\n }\n\n return [`import '${specifier}';`, 'export default undefined;'].join('\\n');\n }\n\n if (id.startsWith('\\0virtual:astro-component-module/')) {\n const encodedSpecifier = id.replace('\\0virtual:astro-component-module/', '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\\n');\n }\n },\n\n async buildStart(this: Rollup.PluginContext) {\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n this.addWatchFile(entrypoint);\n }\n });\n\n trackedSpecifiers.forEach((specifier) => {\n const fileReferenceId = this.emitFile({\n type: 'chunk',\n id: toStaticVirtualId(specifier)\n });\n\n staticEntrypointRefs.set(specifier, fileReferenceId);\n });\n\n const srcRoot = resolve(resolveFrom, 'src/components');\n const specifiers = await collectHydratableSourceModules(srcRoot);\n\n specifiers.forEach((specifier) => {\n const fileReferenceId = this.emitFile({\n type: 'chunk',\n id: toComponentVirtualId(specifier)\n });\n\n componentEntrypointRefs.set(specifier, fileReferenceId);\n });\n },\n\n async writeBundle(this: Rollup.PluginContext) {\n const staticModuleMap = buildStaticModuleMap(\n this,\n staticEntrypointRefs,\n componentEntrypointRefs\n );\n\n const stories = await collectAstroStories(outDir);\n\n if (stories.length === 0) {\n await writePrerenderedStoriesFile(outDir, {});\n\n return;\n }\n\n const prerenderedStories = await prerenderStories({\n stories,\n integrations,\n sanitization: options.sanitization,\n storyRulesConfigFilePath,\n staticModuleMap,\n trackedSpecifiers,\n resolveFrom\n });\n\n await writePrerenderedStoriesFile(outDir, prerenderedStories);\n }\n };\n}\n\nasync function writePrerenderedStoriesFile(outDir: string, payload: Record<string, string>) {\n await mkdir(outDir, { recursive: true });\n await writeFile(resolve(outDir, PRERENDERED_STORIES_FILE), JSON.stringify(payload), 'utf-8');\n}\n\nasync function prerenderStories(options: {\n stories: StoryEntry[];\n integrations: Integration[];\n sanitization?: FrameworkOptions['sanitization'];\n storyRulesConfigFilePath?: string;\n staticModuleMap: Record<string, string>;\n trackedSpecifiers: Set<string>;\n resolveFrom: string;\n}) {\n const sanitizationOptions = resolveSanitizationOptions(options.sanitization ?? undefined);\n const resolveClientModule = createClientModuleResolver(\n options.integrations,\n options.staticModuleMap\n );\n const viteServer = await createStorySsrServer(\n options.integrations,\n options.trackedSpecifiers,\n options.resolveFrom\n );\n const rulesConfigModule = await loadRulesConfigModule(viteServer, options.storyRulesConfigFilePath);\n\n try {\n const container = await AstroContainer.create({\n resolve: async (specifier) => {\n const mockedModule = resolveStoryModuleMock(specifier);\n\n if (mockedModule) {\n return mockedModule;\n }\n\n const resolution = resolveClientModule(specifier);\n\n if (resolution) {\n return resolution;\n }\n\n return specifier;\n }\n });\n\n await addContainerRenderers(container, options.integrations, resolveClientModule, viteServer);\n\n const output: Record<string, string> = {};\n\n for (const story of options.stories) {\n const selectedRules = await selectStoryRules({\n configModule: rulesConfigModule,\n configFilePath: options.storyRulesConfigFilePath,\n story: {\n id: story.id,\n title: story.title,\n name: story.name\n }\n });\n\n if (selectedRules.moduleMocks.size > 0) {\n viteServer.moduleGraph.invalidateAll();\n }\n\n const html = await withStoryRuleCleanups(selectedRules.cleanups, async () => {\n return withStoryModuleMocks(selectedRules.moduleMocks, async () => {\n const modulePath = resolveImportPath(story.importPath, options.resolveFrom);\n const storyModule = await viteServer.ssrLoadModule(modulePath);\n const meta = isRecord(storyModule.default) ? storyModule.default : {};\n const storyExport = isRecord(storyModule[story.exportName])\n ? storyModule[story.exportName]\n : {};\n\n if (typeof meta.component !== 'function') {\n throw new Error(\n `Unable to prerender story \"${story.id}\". Missing default export component in ${story.importPath}.`\n );\n }\n\n if (storyExport.component && storyExport.component !== meta.component) {\n return undefined;\n }\n\n const mergedArgs = mergeStoryArgs(toRecord(meta.args), toRecord(storyExport.args));\n const { args, slots } = separateSlots(mergedArgs);\n const processedArgs = await processImageMetadata(args);\n const sanitizedPayload = sanitizeRenderPayload(\n {\n args: processedArgs,\n slots\n },\n sanitizationOptions\n );\n\n return container.renderToString(\n patchCreateAstroCompat(meta.component) as Parameters<typeof container.renderToString>[0],\n {\n props: sanitizedPayload.args,\n slots: sanitizedPayload.slots\n }\n );\n });\n });\n\n if (html !== undefined) {\n output[story.id] = html;\n }\n }\n\n return output;\n } finally {\n await viteServer.close();\n }\n}\n\nasync function createStorySsrServer(\n integrations: Integration[],\n trackedSpecifiers: Set<string>,\n resolveFrom: string\n) {\n const { getViteConfig, passthroughImageService } = await importAstroConfig(resolveFrom);\n const astroConfig = await getViteConfig(\n { root: resolveFrom },\n {\n configFile: false,\n integrations: await Promise.all(\n integrations.map((integration) => integration.loadIntegration(resolveFrom))\n ),\n // Use the passthrough image service so nested components that use <Image>\n // from astro:assets render as plain <img> tags without triggering image\n // optimization (which fails in the Storybook SSR context).\n image: { service: passthroughImageService() }\n }\n )({\n mode: 'production',\n command: 'serve'\n });\n\n const config = mergeConfig(astroConfig, {\n appType: 'custom',\n server: {\n middlewareMode: true\n },\n plugins: [\n createProjectAstroResolutionPlugin(resolveFrom),\n vitePluginAstroFontsFallback(),\n vitePluginAstroIntegrationOptsFallback(),\n vitePluginAstroVueFallback(),\n vitePluginAstroRoutesFallback(),\n {\n name: 'storybook-astro:static-prerender-ssr-stubs',\n resolveId(id: string) {\n if (trackedSpecifiers.has(id)) {\n return `\\0storybook-astro-static-prerender-stub:${encodeURIComponent(id)}`;\n }\n },\n load(id: string) {\n if (id.startsWith('\\0storybook-astro-static-prerender-stub:')) {\n return 'export default undefined;';\n }\n }\n }\n ]\n });\n\n return createServer(config);\n}\n\nasync function loadRulesConfigModule(\n viteServer: Awaited<ReturnType<typeof createStorySsrServer>>,\n configFilePath?: string\n) {\n if (!configFilePath) {\n return undefined;\n }\n\n try {\n return await ssrLoadModuleWithFsFallback(viteServer, configFilePath, {\n fixStacktrace: true\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n throw new Error(\n `Unable to load framework.options.storyRules config module at ${configFilePath}: ${reason}`\n );\n }\n}\n\nasync function addContainerRenderers(\n container: Awaited<ReturnType<typeof AstroContainer.create>>,\n integrations: Integration[],\n resolveClientModule: (specifier: string) => string | undefined,\n viteServer: Awaited<ReturnType<typeof createStorySsrServer>>\n) {\n for (const integration of integrations) {\n const serverRenderer = integration.renderer.server;\n\n if (serverRenderer) {\n const serverRendererModule = await viteServer.ssrLoadModule(serverRenderer.entrypoint);\n const renderer = serverRendererModule.default ?? serverRendererModule;\n\n if (integration.name === 'solid' && isRecord(renderer)) {\n container.addServerRenderer({\n name: serverRenderer.name,\n renderer: {\n ...renderer,\n name: serverRenderer.name\n } as Parameters<typeof container.addServerRenderer>[0]['renderer']\n });\n } else {\n container.addServerRenderer({\n name: serverRenderer.name,\n renderer\n });\n }\n }\n\n const clientRenderer = integration.renderer.client;\n\n if (clientRenderer) {\n const resolvedEntrypoint =\n resolveClientModule(clientRenderer.entrypoint) ?? clientRenderer.entrypoint;\n\n container.addClientRenderer({\n name: clientRenderer.name,\n entrypoint: resolvedEntrypoint\n });\n }\n }\n}\n\nfunction createClientModuleResolver(\n integrations: Integration[],\n staticModuleMap: Record<string, string>\n) {\n return function resolveClientModule(specifier: string) {\n if (Object.hasOwn(staticModuleMap, specifier)) {\n return staticModuleMap[specifier];\n }\n\n const normalizedSpecifier = specifier.replace(/\\\\/g, '/').replace(/\\?.*$/, '');\n\n if (Object.hasOwn(staticModuleMap, normalizedSpecifier)) {\n return staticModuleMap[normalizedSpecifier];\n }\n\n for (const integration of integrations) {\n const resolution = integration.resolveClient(specifier);\n\n if (resolution) {\n return resolution;\n }\n }\n };\n}\n\nasync function collectAstroStories(outDir: string): Promise<StoryEntry[]> {\n const indexFile = resolve(outDir, 'index.json');\n const indexRaw = await readFile(indexFile, 'utf-8');\n const indexJson = JSON.parse(indexRaw) as StoryIndex;\n\n return Object.values(indexJson.entries ?? {})\n .filter((entry) => entry.type === 'story' && entry.componentPath?.endsWith('.astro'))\n .map((entry) => {\n if (!entry.id || !entry.importPath || !entry.exportName) {\n throw new Error(`Encountered an invalid Storybook index entry in ${indexFile}.`);\n }\n\n return {\n id: entry.id,\n importPath: entry.importPath,\n exportName: entry.exportName,\n title: entry.title,\n name: entry.name\n };\n });\n}\n\nfunction mergeStoryArgs(\n metaArgs: Record<string, unknown> | undefined,\n storyArgs: Record<string, unknown> | undefined\n) {\n return {\n ...(metaArgs ?? {}),\n ...(storyArgs ?? {})\n };\n}\n\nfunction separateSlots(inputArgs: Record<string, unknown>) {\n const args = { ...inputArgs };\n const slotsCandidate = args.slots;\n\n delete args.slots;\n\n if (!isRecord(slotsCandidate)) {\n return {\n args,\n slots: {}\n };\n }\n\n return {\n args,\n slots: slotsCandidate as Record<string, string>\n };\n}\n\nfunction resolveImportPath(importPath: string, resolveFrom: string) {\n if (importPath.startsWith('./')) {\n return resolve(resolveFrom, importPath.slice(2));\n }\n\n return resolve(resolveFrom, importPath);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n return value;\n}\n\nfunction collectTrackedSpecifiers(integrations: Integration[]) {\n const specifiers = new Set<string>(['astro:scripts/page.js', 'astro:scripts/before-hydration.js']);\n\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n specifiers.add(entrypoint);\n }\n });\n\n return specifiers;\n}\n\nfunction buildStaticModuleMap(\n pluginContext: Rollup.PluginContext,\n staticEntrypointRefs: Map<string, string>,\n componentEntrypointRefs: Map<string, string>\n) {\n const map: Record<string, string> = {};\n\n staticEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n componentEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n return map;\n}\n\nfunction toStaticVirtualId(specifier: string) {\n return `virtual:astro-static-module/${encodeURIComponent(specifier)}`;\n}\n\nfunction toComponentVirtualId(specifier: string) {\n return `virtual:astro-component-module/${encodeURIComponent(specifier)}`;\n}\n\nfunction isClientEntrypoint(specifier: string) {\n return specifier.startsWith('@astrojs/') && specifier.endsWith('/client.js');\n}\n\nfunction toPublicPath(fileName: string) {\n return `./${fileName}`;\n}\n\nasync function collectHydratableSourceModules(srcRoot: string): Promise<string[]> {\n const modules: string[] = [];\n\n async function walk(directory: string) {\n let entries: Dirent[];\n\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch {\n return;\n }\n\n await Promise.all(\n entries.map(async (entry) => {\n const absolutePath = resolve(directory, entry.name);\n\n if (entry.isDirectory()) {\n await walk(absolutePath);\n\n return;\n }\n\n if (!entry.isFile()) {\n return;\n }\n\n const normalizedPath = absolutePath.replace(/\\\\/g, '/');\n\n if (!isHydratableSourceFile(normalizedPath)) {\n return;\n }\n\n if (isNonHydratableSourceFile(normalizedPath)) {\n return;\n }\n\n modules.push(normalizedPath);\n })\n );\n }\n\n await walk(srcRoot);\n\n return modules;\n}\n\nfunction isHydratableSourceFile(input: string) {\n return /\\.(jsx|tsx|vue|svelte|js|ts)$/.test(input);\n}\n\nfunction isNonHydratableSourceFile(input: string) {\n return /\\.stories\\.[jt]sx?$|\\.stories\\.vue$|\\.stories\\.svelte$|\\.(spec|test)\\.[jt]sx?$/.test(\n input\n );\n}\n\nfunction patchCreateAstroCompat(component: unknown): AstroComponentFactory {\n if (typeof component !== 'function') {\n throw new Error('Expected Astro component factory to be a function.');\n }\n\n const originalComponent = component as AstroComponentFactory;\n const wrapped = ((result: AstroCreateResult, props: unknown, slots: unknown) => {\n if (result && typeof result.createAstro === 'function') {\n const originalCreateAstro = result.createAstro;\n const runtimeExpectsAstroGlobal = originalCreateAstro.length >= 3;\n\n result.createAstro = (...args: unknown[]) => {\n if (args.length === 3 && !runtimeExpectsAstroGlobal) {\n return originalCreateAstro(args[1], args[2]);\n }\n\n return originalCreateAstro(...args);\n };\n }\n\n return originalComponent(result, props, slots);\n }) as AstroComponentFactory;\n\n wrapped.isAstroComponentFactory = originalComponent.isAstroComponentFactory;\n wrapped.moduleId = originalComponent.moduleId;\n wrapped.propagation = originalComponent.propagation;\n\n return wrapped;\n}\n\nasync function processImageMetadata(\n args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n const processed: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(args)) {\n if (isImageMetadata(value)) {\n // Keep ImageMetadata as a plain object — Astro's image service checks\n // isESMImportedImage (typeof src === 'object') and skips the /@fs/ string\n // validation that throws LocalImageUsedWrongly. Converting to a URL string\n // causes that error when the string starts with /@fs/.\n processed[key] = value;\n\n continue;\n }\n\n if (Array.isArray(value)) {\n processed[key] = await Promise.all(\n value.map(async (item) => {\n if (isImageMetadata(item)) {\n return item;\n }\n\n if (isRecord(item)) {\n return processImageMetadata(item);\n }\n\n return item;\n })\n );\n\n continue;\n }\n\n if (isRecord(value)) {\n processed[key] = await processImageMetadata(value);\n\n continue;\n }\n\n processed[key] = value;\n }\n\n return processed;\n}\n\nfunction isImageMetadata(value: unknown): value is Record<string, unknown> {\n return (\n isRecord(value) &&\n typeof value.src === 'string' &&\n ('width' in value || 'height' in value || 'format' in value)\n );\n}\n\n\nfunction createProjectAstroResolutionPlugin(resolveFrom: string): Plugin {\n const require = createRequire(import.meta.url);\n\n return {\n name: 'storybook-astro:resolve-project-astro-prerender',\n enforce: 'pre',\n resolveId(id: string) {\n if (id !== 'astro' && !id.startsWith('astro/')) {\n return null;\n }\n\n try {\n return require.resolve(id, {\n paths: [resolveFrom]\n });\n } catch {\n return null;\n }\n }\n };\n}\n","import type { Dirent } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { build, type Rollup } from 'vite';\nimport type { FrameworkOptions } from './types.ts';\nimport { mergeWithAstroConfig } from './vitePluginAstro.ts';\nimport { viteAstroContainerRenderersPlugin } from './viteAstroContainerRenderersPlugin.ts';\nimport { astroFilesVirtualModulePlugin } from './vite/astroFilesVirtualModulePlugin.ts';\nimport { storybookAstroStoryRulesConfigVirtualModulePlugin } from './vite/storybookAstroRulesConfigVirtualModulePlugin.ts';\nimport { storybookAstroSanitizationConfigVirtualModulePlugin } from './vite/storybookAstroSanitizationConfigVirtualModulePlugin.ts';\nimport { storybookAstroServerAuthConfigVirtualModulePlugin } from './vite/storybookAstroServerAuthConfigVirtualModulePlugin.ts';\n\nconst moduleRoot = resolve(dirname(fileURLToPath(import.meta.url)), '.');\n// packageRoot works regardless of whether this file is running from src/ or dist/\nconst packageRoot = resolve(moduleRoot, '..');\n\nexport function vitePluginAstroBuildServer(options: FrameworkOptions) {\n const integrations = options.integrations ?? [];\n const resolveFrom = options.resolveFrom ?? process.cwd();\n const storiesMap = new Map<string, Set<string>>();\n const trackedSpecifiers = collectTrackedSpecifiers(integrations);\n const staticEntrypointRefs = new Map<string, string>();\n const componentEntrypointRefs = new Map<string, string>();\n let storybookStaticOutDir = resolve(resolveFrom, 'storybook-static');\n\n return {\n name: 'storybook-astro:build-server',\n apply: 'build',\n enforce: 'post',\n\n configResolved(config: { build: { outDir?: string } }) {\n storybookStaticOutDir = resolve(resolveFrom, config.build.outDir ?? 'storybook-static');\n },\n\n resolveId(id: string, importer?: string) {\n if (id.endsWith('.astro') && importer) {\n const absoluteAstroPath = resolve(dirname(importer), id);\n\n if (!storiesMap.has(absoluteAstroPath)) {\n storiesMap.set(absoluteAstroPath, new Set());\n }\n\n storiesMap.get(absoluteAstroPath)?.add(importer);\n }\n\n if (id.startsWith('virtual:astro-static-module/')) {\n return `\\0${id}`;\n }\n\n if (id.startsWith('virtual:astro-component-module/')) {\n return `\\0${id}`;\n }\n },\n\n load(id: string) {\n if (id.startsWith('\\0virtual:astro-static-module/')) {\n const encodedSpecifier = id.replace('\\0virtual:astro-static-module/', '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n if (isClientEntrypoint(specifier)) {\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\\n');\n }\n\n return [`import '${specifier}';`, 'export default undefined;'].join('\\n');\n }\n\n if (id.startsWith('\\0virtual:astro-component-module/')) {\n const encodedSpecifier = id.replace('\\0virtual:astro-component-module/', '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\\n');\n }\n },\n\n async buildStart(this: Rollup.PluginContext) {\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n this.addWatchFile(entrypoint);\n }\n });\n\n trackedSpecifiers.forEach((specifier) => {\n const fileReferenceId = this.emitFile({\n type: 'chunk',\n id: toStaticVirtualId(specifier)\n });\n\n staticEntrypointRefs.set(specifier, fileReferenceId);\n });\n\n const srcRoot = resolve(resolveFrom, 'src/components');\n const specifiers = await collectHydratableSourceModules(srcRoot);\n\n specifiers.forEach((specifier) => {\n const fileReferenceId = this.emitFile({\n type: 'chunk',\n id: toComponentVirtualId(specifier)\n });\n\n componentEntrypointRefs.set(specifier, fileReferenceId);\n });\n },\n\n async writeBundle(this: Rollup.PluginContext) {\n const astroComponents = Array.from(storiesMap.keys());\n const staticModuleMap = buildStaticModuleMap(\n this,\n staticEntrypointRefs,\n componentEntrypointRefs\n );\n const serverOutDir = resolve(dirname(storybookStaticOutDir), 'storybook-server');\n\n await buildAstroServer({\n astroComponents,\n integrations,\n sanitization: options.sanitization,\n storyRules: options.storyRules,\n server: options.server,\n outDir: serverOutDir,\n staticModuleMap,\n resolveFrom\n });\n }\n };\n}\n\nasync function buildAstroServer(options: {\n astroComponents: string[];\n integrations: FrameworkOptions['integrations'];\n sanitization?: FrameworkOptions['sanitization'];\n storyRules?: FrameworkOptions['storyRules'];\n server?: FrameworkOptions['server'];\n outDir: string;\n staticModuleMap: Record<string, string>;\n resolveFrom: string;\n}) {\n const buildConfig = {\n root: resolve(packageRoot, 'src/server'),\n ssr: {\n noExternal: /(@astrojs\\/.+|react|react-dom)/\n },\n build: {\n ssr: true,\n outDir: options.outDir,\n emptyOutDir: true,\n sourcemap: true,\n manifest: false,\n rollupOptions: {\n input: resolve(packageRoot, 'src/server/index.ts'),\n treeshake: true\n }\n },\n plugins: [\n astroFilesVirtualModulePlugin(options.astroComponents),\n storybookAstroSanitizationConfigVirtualModulePlugin(options.sanitization),\n storybookAstroStoryRulesConfigVirtualModulePlugin(options.storyRules, options.resolveFrom),\n storybookAstroServerAuthConfigVirtualModulePlugin(options.server),\n viteAstroContainerRenderersPlugin(options.integrations, {\n mode: 'production',\n staticModuleMap: options.staticModuleMap\n })\n ]\n };\n\n const finalConfig = await mergeWithAstroConfig(\n buildConfig,\n options.integrations,\n options.resolveFrom,\n 'production',\n 'build'\n );\n\n await build(finalConfig);\n}\n\nfunction collectTrackedSpecifiers(integrations: FrameworkOptions['integrations']) {\n const specifiers = new Set<string>(['astro:scripts/page.js', 'astro:scripts/before-hydration.js']);\n\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n specifiers.add(entrypoint);\n }\n });\n\n return specifiers;\n}\n\nfunction buildStaticModuleMap(\n pluginContext: Rollup.PluginContext,\n staticEntrypointRefs: Map<string, string>,\n componentEntrypointRefs: Map<string, string>\n) {\n const map: Record<string, string> = {};\n\n staticEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n componentEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n return map;\n}\n\nfunction toStaticVirtualId(specifier: string) {\n return `virtual:astro-static-module/${encodeURIComponent(specifier)}`;\n}\n\nfunction toComponentVirtualId(specifier: string) {\n return `virtual:astro-component-module/${encodeURIComponent(specifier)}`;\n}\n\nfunction isClientEntrypoint(specifier: string) {\n return specifier.startsWith('@astrojs/') && specifier.endsWith('/client.js');\n}\n\nfunction toPublicPath(fileName: string) {\n return `./${fileName}`;\n}\n\nasync function collectHydratableSourceModules(srcRoot: string): Promise<string[]> {\n const modules: string[] = [];\n\n async function walk(directory: string) {\n let entries: Dirent[];\n\n try {\n entries = await readdir(directory, { withFileTypes: true });\n } catch {\n return;\n }\n\n await Promise.all(\n entries.map(async (entry) => {\n const absolutePath = resolve(directory, entry.name);\n\n if (entry.isDirectory()) {\n await walk(absolutePath);\n\n return;\n }\n\n if (!entry.isFile()) {\n return;\n }\n\n const normalizedPath = absolutePath.replace(/\\\\/g, '/');\n\n if (!isHydratableSourceFile(normalizedPath)) {\n return;\n }\n\n if (isNonHydratableSourceFile(normalizedPath)) {\n return;\n }\n\n modules.push(normalizedPath);\n })\n );\n }\n\n await walk(srcRoot);\n\n return modules;\n}\n\nfunction isHydratableSourceFile(input: string) {\n return /\\.(jsx|tsx|vue|svelte|js|ts)$/.test(input);\n}\n\nfunction isNonHydratableSourceFile(input: string) {\n return /\\.stories\\.[jt]sx?$|\\.stories\\.vue$|\\.stories\\.svelte$|\\.(spec|test)\\.[jt]sx?$/.test(\n input\n );\n}\n","import { mergeConfig, type InlineConfig } from 'vite';\nimport type { Integration } from './integrations/index.ts';\nimport { importAstroConfig } from './importAstroConfig.ts';\n\nconst ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK = [\n '@astro/plugin-actions',\n '@astrojs/vite-plugin-astro-ssr-manifest',\n 'astro-content-virtual-mod-plugin',\n 'astro:actions',\n 'astro:build:normal',\n 'astro:container',\n 'astro:content-asset-propagation',\n 'astro:content-imports',\n 'astro:content-listen',\n 'astro:dev-toolbar',\n 'astro:head-metadata',\n 'astro:html',\n 'astro:i18n',\n 'astro:integration-container',\n 'astro:jsx',\n 'astro:markdown',\n 'astro:postprocess',\n 'astro:prefetch',\n 'astro:scanner',\n 'astro:scripts:page-ssr',\n 'astro:server',\n 'astro:vite-plugin-env',\n 'astro:vite-plugin-file-url'\n];\n\nexport async function mergeWithAstroConfig(\n config: InlineConfig,\n integrations: Integration[] = [],\n resolveFrom = process.cwd(),\n mode = 'development',\n command: 'build' | 'serve' = 'serve'\n) {\n const { getViteConfig } = await importAstroConfig(resolveFrom);\n const safeIntegrations = integrations ?? [];\n\n const astroConfig = await getViteConfig(\n {},\n {\n configFile: false,\n integrations: await Promise.all(\n safeIntegrations.map((integration) => integration.loadIntegration(resolveFrom))\n )\n }\n )({\n mode,\n command\n });\n\n const filteredPlugins = astroConfig\n .plugins!.flat()\n .filter(\n (plugin) =>\n plugin &&\n 'name' in plugin &&\n !ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK.includes(plugin.name)\n );\n\n return mergeConfig(config, {\n ...astroConfig,\n plugins: filteredPlugins\n });\n}\n","import type { Plugin } from 'vite';\nimport { createVirtualModulePlugin } from './createVirtualModulePlugin.ts';\n\ntype ImportRecord = {\n id: string;\n file: string;\n importStatement: string;\n};\n\nexport function astroFilesVirtualModulePlugin(astroComponents: string[]): Plugin {\n return createVirtualModulePlugin({\n pluginName: 'storybook-astro:virtual-astro-files',\n virtualModuleId: 'virtual:astro-files',\n load() {\n const imports = astroComponents.reduce<ImportRecord[]>((records, file, index) => {\n const moduleId = `_astroFile${index}`;\n\n return [\n ...records,\n {\n id: moduleId,\n file,\n importStatement: `import ${moduleId} from '${file}';`\n }\n ];\n }, []);\n\n return [\n imports.map(({ importStatement }) => importStatement).join('\\n'),\n 'export default {',\n imports.map(({ file, id }) => `'${file}': ${id}`).join(',\\n'),\n '};'\n ].join('\\n');\n }\n });\n}\n","import type { Plugin } from 'vite';\nimport type { StoryRulesOptions } from '../rules-options.ts';\nimport { resolveRulesConfigFilePath } from '../rules-options.ts';\nimport { createVirtualModulePlugin } from './createVirtualModulePlugin.ts';\n\nexport const STORYBOOK_ASTRO_STORY_RULES_CONFIG_VIRTUAL_MODULE_ID =\n 'virtual:storybook-astro-story-rules-config';\n\nexport function storybookAstroStoryRulesConfigVirtualModulePlugin(\n options?: StoryRulesOptions,\n resolveFrom = process.cwd()\n): Plugin {\n return createVirtualModulePlugin({\n pluginName: 'storybook-astro:virtual-story-rules-config',\n virtualModuleId: STORYBOOK_ASTRO_STORY_RULES_CONFIG_VIRTUAL_MODULE_ID,\n load() {\n const configFilePath = resolveRulesConfigFilePath(options, resolveFrom);\n\n if (!configFilePath) {\n return [\n 'const storybookAstroStoryRulesConfig = { rules: [] };',\n 'export default storybookAstroStoryRulesConfig;',\n 'export const storybookAstroStoryRulesConfigFilePath = undefined;'\n ].join('\\n');\n }\n\n const importPath = JSON.stringify(configFilePath.replace(/\\\\/g, '/'));\n const configPath = JSON.stringify(configFilePath.replace(/\\\\/g, '/'));\n\n return [\n `import * as storybookAstroStoryRulesConfigModule from ${importPath};`,\n 'export default storybookAstroStoryRulesConfigModule;',\n `export const storybookAstroStoryRulesConfigFilePath = ${configPath};`\n ].join('\\n');\n }\n });\n}\n","import type { Plugin } from 'vite';\nimport type { SanitizationOptions } from '../lib/sanitization.ts';\nimport { serializeSanitizationOptions } from '../lib/sanitization.ts';\nimport { createVirtualModulePlugin } from './createVirtualModulePlugin.ts';\n\nexport const STORYBOOK_ASTRO_SANITIZATION_CONFIG_VIRTUAL_MODULE_ID =\n 'virtual:storybook-astro-sanitization-config';\n\nexport function storybookAstroSanitizationConfigVirtualModulePlugin(\n options?: SanitizationOptions\n): Plugin {\n return createVirtualModulePlugin({\n pluginName: 'storybook-astro:virtual-sanitization-config',\n virtualModuleId: STORYBOOK_ASTRO_SANITIZATION_CONFIG_VIRTUAL_MODULE_ID,\n load() {\n const serializedConfig = serializeSanitizationOptions(options);\n\n return `export default ${serializedConfig};`;\n }\n });\n}\n","import type { Plugin } from 'vite';\nimport type { ServerBuildOptions } from '../types.ts';\nimport { createVirtualModulePlugin } from './createVirtualModulePlugin.ts';\n\nexport const STORYBOOK_ASTRO_SERVER_AUTH_CONFIG_VIRTUAL_MODULE_ID =\n 'virtual:storybook-astro-server-auth-config';\n\nexport function storybookAstroServerAuthConfigVirtualModulePlugin(\n options?: ServerBuildOptions\n): Plugin {\n const authToken = normalizeOptionalString(options?.authToken);\n const authHeader = normalizeAuthHeader(options?.authHeader);\n\n return createVirtualModulePlugin({\n pluginName: 'storybook-astro:virtual-server-auth-config',\n virtualModuleId: STORYBOOK_ASTRO_SERVER_AUTH_CONFIG_VIRTUAL_MODULE_ID,\n load() {\n return [\n `export const storybookAstroServerAuthToken = ${\n authToken ? JSON.stringify(authToken) : 'undefined'\n };`,\n `export const storybookAstroServerAuthHeader = ${JSON.stringify(authHeader)};`\n ].join('\\n');\n }\n });\n}\n\nfunction normalizeOptionalString(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalizedValue = value.trim();\n\n return normalizedValue || undefined;\n}\n\nfunction normalizeAuthHeader(value: string | undefined) {\n const normalizedValue = normalizeOptionalString(value);\n\n return (normalizedValue ?? 'authorization').toLowerCase();\n}\n","import type { Plugin } from 'vite';\n\nconst TOOLBAR_INTERNAL_STUB = `\nexport const loadDevToolbarApps = async () => [];\n`;\n\n/**\n * Provides a fallback stub for Astro's dev toolbar virtual module.\n *\n * Astro's `astro/dist/runtime/client/dev-toolbar/entrypoint.js` imports\n * from `astro:toolbar:internal`, a virtual module normally provided by\n * Astro's own `vite-plugin-dev-toolbar` Vite plugin. In the Storybook\n * context that plugin is not active, causing esbuild to fail during\n * dependency optimisation when it encounters the unresolvable import.\n *\n * Storybook doesn't use Astro's dev toolbar, so a no-op stub is safe.\n */\nexport function vitePluginAstroToolbarFallback(): Plugin {\n const VIRTUAL_ID = 'astro:toolbar:internal';\n const RESOLVED_ID = '\\0' + VIRTUAL_ID;\n\n return {\n name: 'storybook-astro-toolbar-fallback',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ID) {\n return RESOLVED_ID;\n }\n },\n\n load(id) {\n if (id === RESOLVED_ID) {\n return { code: TOOLBAR_INTERNAL_STUB };\n }\n }\n };\n}\n","import type { StorybookConfigVite, FrameworkOptions } from './types.ts';\nimport { vitePluginStorybookAstroMiddleware } from './viteStorybookAstroMiddlewarePlugin.ts';\nimport { viteStorybookRendererFallbackPlugin } from './viteStorybookRendererFallbackPlugin.ts';\nimport { viteStorybookAstroRendererPlugin } from './viteStorybookAstroRendererPlugin.ts';\nimport { vitePluginAstroComponentMarker } from './vitePluginAstroComponentMarker.ts';\nimport { vitePluginAstroBuildPrerender } from './vitePluginAstroBuildPrerender.ts';\nimport { vitePluginAstroBuildServer } from './vitePluginAstroBuildServer.ts';\nimport { vitePluginAstroIntegrationOptsFallback } from './vitePluginAstroIntegrationOptsFallback.ts';\nimport { vitePluginAstroVueFallback } from './vitePluginAstroVueFallback.ts';\nimport { vitePluginAstroToolbarFallback } from './vitePluginAstroToolbarFallback.ts';\nimport { resolveSanitizationOptions } from './lib/sanitization.ts';\nimport { mergeWithAstroConfig } from './vitePluginAstro.ts';\n\nexport const core = {\n builder: '@storybook/builder-vite',\n // Use import.meta.resolve so Storybook receives an absolute file:// URL\n // to the renderer preset rather than a bare package specifier. When\n // package managers like pnpm use strict node_modules isolation, bare\n // specifiers are resolved from the *project root*, where the renderer\n // (a dep of this framework, not the user's project) is not hoisted.\n // The absolute URL is resolved from *this* file's location where the\n // renderer is always accessible as a direct dependency.\n renderer: import.meta.resolve('@storybook-astro/renderer')\n};\n\nexport const viteFinal: StorybookConfigVite['viteFinal'] = async (config, { configType, presets }) => {\n const options = await presets.apply<FrameworkOptions>('frameworkOptions');\n\n if (!config.plugins) {\n config.plugins = [];\n }\n\n const integrations = options.integrations ?? [];\n const resolveFrom = options.resolveFrom ?? process.cwd();\n const renderMode = options.renderMode ?? 'server';\n const mode = configType === 'DEVELOPMENT' ? 'development' : 'production';\n const command = configType === 'DEVELOPMENT' ? 'serve' : 'build';\n\n resolveSanitizationOptions(options.sanitization);\n\n config.envPrefix = mergeEnvPrefixes(config.envPrefix, 'STORYBOOK_');\n\n const { vitePlugin: storybookAstroMiddlewarePlugin, viteConfig } =\n await vitePluginStorybookAstroMiddleware(options);\n\n config.plugins.push(\n viteStorybookRendererFallbackPlugin(integrations),\n viteStorybookAstroRendererPlugin({\n mode,\n renderMode,\n server: options.server\n }),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n vitePluginAstroComponentMarker() as any,\n vitePluginAstroIntegrationOptsFallback(),\n vitePluginAstroToolbarFallback(),\n vitePluginAstroVueFallback(),\n );\n\n if (configType === 'DEVELOPMENT') {\n config.plugins.push(storybookAstroMiddlewarePlugin, ...viteConfig.plugins);\n } else if (renderMode === 'static') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config.plugins.push(vitePluginAstroBuildPrerender(options) as any);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config.plugins.push(vitePluginAstroBuildServer(options) as any);\n }\n\n if (configType !== 'DEVELOPMENT') {\n config.build = {\n ...(config.build ?? {}),\n manifest: true\n };\n\n config.build.rollupOptions = {\n ...(config.build.rollupOptions ?? {}),\n preserveEntrySignatures: 'strict'\n };\n }\n\n // Add React/ReactDOM aliases for storybook-solidjs compatibility\n if (!config.resolve) {\n config.resolve = {};\n }\n if (!config.resolve.alias) {\n config.resolve.alias = {};\n }\n \n // Ensure React is available for storybook-solidjs\n const aliases = config.resolve.alias as Record<string, string>;\n\n if (!aliases['react']) {\n aliases['react'] = 'react';\n }\n if (!aliases['react-dom']) {\n aliases['react-dom'] = 'react-dom';\n }\n\n const finalConfig = await mergeWithAstroConfig(config, integrations, resolveFrom, mode, command);\n\n // Exclude Astro integration packages from dependency optimization because\n // they import virtual modules that esbuild cannot resolve.\n if (!finalConfig.optimizeDeps) {\n finalConfig.optimizeDeps = {};\n }\n if (!finalConfig.optimizeDeps.exclude) {\n finalConfig.optimizeDeps.exclude = [];\n }\n for (const pkg of ['@astrojs/vue', '@astrojs/react', '@astrojs/preact']) {\n if (!finalConfig.optimizeDeps.exclude.includes(pkg)) {\n finalConfig.optimizeDeps.exclude.push(pkg);\n }\n }\n // Exclude the renderer from Vite's esbuild pre-bundler so that\n // import.meta.hot is preserved in the preview iframe. When installed\n // via npm (not workspace:*), Vite would otherwise pre-bundle the\n // renderer with esbuild, which strips import.meta.hot and causes the\n // renderer to fall back to fetching astro-prerendered-stories.json\n // (a 404 in dev mode) rather than using the Vite HMR channel.\n if (!finalConfig.optimizeDeps.exclude.includes('@storybook-astro/renderer')) {\n finalConfig.optimizeDeps.exclude.push('@storybook-astro/renderer');\n }\n // Mark integration virtual modules as external so the dep bundler doesn't\n // try to resolve them (they are Vite virtual modules with no real package).\n // Set both esbuildOptions (Vite ≤7) and rolldownOptions (Vite 8+, Rolldown)\n // so the correct key is populated regardless of Vite version.\n const integrationVirtualModules = [\n 'virtual:@astrojs/vue/app',\n 'virtual:astro:vue-app',\n 'astro:react:opts',\n 'astro:preact:opts',\n 'astro:toolbar:internal'\n ];\n\n // Vite ≤7 (esbuild-based optimizer)\n if (!finalConfig.optimizeDeps.esbuildOptions) {\n finalConfig.optimizeDeps.esbuildOptions = {};\n }\n if (!finalConfig.optimizeDeps.esbuildOptions.external) {\n finalConfig.optimizeDeps.esbuildOptions.external = [];\n }\n for (const mod of integrationVirtualModules) {\n if (!finalConfig.optimizeDeps.esbuildOptions.external.includes(mod)) {\n finalConfig.optimizeDeps.esbuildOptions.external.push(mod);\n }\n }\n\n // Vite 8+ (Rolldown-based optimizer) — same semantics, different key\n // Use a loose cast because rolldownOptions is absent from Vite <8 types.\n const optimizeDepsMut = finalConfig.optimizeDeps as Record<string, unknown>;\n const rolldownOpts = (optimizeDepsMut.rolldownOptions ?? {}) as { external?: string[] };\n\n rolldownOpts.external = Array.from(\n new Set([...(rolldownOpts.external ?? []), ...integrationVirtualModules])\n );\n optimizeDepsMut.rolldownOptions = rolldownOpts;\n\n return finalConfig;\n};\n\nfunction mergeEnvPrefixes(\n existing: string | string[] | undefined,\n additionalPrefix: string\n): string[] {\n const prefixes = Array.isArray(existing) ? existing : existing ? [existing] : [];\n\n return Array.from(new Set([...prefixes, additionalPrefix]));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,oCAAoC,cAA6B;AAC/E,QAAM,mBAAmB,gBAAgB,CAAC;AAE1C,SAAO,0BAA0B;AAAA,IAC/B,YAAY;AAAA,IACZ,iBAAiB;AAAA,IACjB,OAAO;AACL,aAAO,iBACJ,OAAO,CAAC,gBAAgB,YAAY,qBAAqB,EACzD;AAAA,QACC,CAAC,gBACC,eAAe,YAAY,IAAI,UAAU,YAA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KA,QAAM,4BAA4B;AAAA,IAChC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAGA,MAAI,CAAC,YAAY,aAAa,gBAAgB;AAC5C,gBAAY,aAAa,iBAAiB,CAAC;AAAA,EAC7C;AACA,MAAI,CAAC,YAAY,aAAa,eAAe,UAAU;AACrD,gBAAY,aAAa,eAAe,WAAW,CAAC;AAAA,EACtD;AACA,aAAW,OAAO,2BAA2B;AAC3C,QAAI,CAAC,YAAY,aAAa,eAAe,SAAS,SAAS,GAAG,GAAG;AACnE,kBAAY,aAAa,eAAe,SAAS,KAAK,GAAG;AAAA,IAC3D;AAAA,EACF;AAIA,QAAM,kBAAkB,YAAY;AACpC,QAAM,eAAgB,gBAAgB,mBAAmB,CAAC;AAE1D,eAAa,WAAW,MAAM;AAAA,IAC5B,oBAAI,IAAI,CAAC,GAAI,aAAa,YAAY,CAAC,GAAI,GAAG,yBAAyB,CAAC;AAAA,EAC1E;AACA,kBAAgB,kBAAkB;AAElC,SAAO;AACT;AAEA,SAAS,iBACP,UACA,kBACU;AACV,QAAM,WAAW,MAAM,QAAQ,QAAQ,IAAI,WAAW,WAAW,CAAC,QAAQ,IAAI,CAAC;AAE/E,SAAO,MAAM,KAAK,oBAAI,IAAI,CAAC,GAAG,UAAU,gBAAgB,CAAC,CAAC;AAC5D;","names":["require","readdir","resolve","mergeConfig","mergeConfig","resolve","collectTrackedSpecifiers","isClientEntrypoint","toStaticVirtualId","collectHydratableSourceModules","toComponentVirtualId","buildStaticModuleMap","toPublicPath","readdir","isHydratableSourceFile","isNonHydratableSourceFile"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/portable-stories.ts"],"sourcesContent":["// @ts-ignore - Storybook internal modules have complex module resolution\nimport type {\n Args,\n ComponentAnnotations,\n NamedOrDefaultProjectAnnotations,\n NormalizedProjectAnnotations,\n ProjectAnnotations,\n StoryAnnotationsOrFn,\n WebRenderer,\n} from 'storybook/internal/types';\n// @ts-ignore - Storybook internal modules have complex module resolution\nimport {\n composeStory as originalComposeStory,\n composeStories as originalComposeStories,\n setProjectAnnotations as originalSetProjectAnnotations,\n} from 'storybook/internal/preview-api';\n\n// Define the AstroRenderer type to match other frameworks\nexport interface AstroRenderer extends WebRenderer {\n component: any;\n storyResult: any;\n}\n\n// Create a render function for testing that mimics Storybook's render behavior\nconst render = (args: Args, context?: any) => {\n const Component = context?.component;\n const renderer = context?.parameters?.renderer;\n const id = context?.id || 'test-story';\n \n // Renderers that are known to not work in the current integration\n const brokenRenderers: string[] = [];\n \n // Mimic the renderer detection logic from the main renderer\n if (renderer && brokenRenderers.includes(renderer)) {\n throw new Error(`Renderer '${renderer}' not found. Available renderers: react, vue, svelte, solid, preact`);\n }\n \n // For Astro components and working integrations, return a renderable object\n if (!Component) {\n throw new Error(`Unable to render story ${id} as the component annotation is missing from the default export`);\n }\n \n // Astro components can be identified by isAstroComponentFactory\n if (typeof Component === 'function' && (Component as any).isAstroComponentFactory) {\n // This is an Astro component - return it for server-side rendering\n return Component;\n }\n \n // For framework components that have working integrations\n if (typeof Component === 'function') {\n if (renderer && !brokenRenderers.includes(renderer)) {\n // This would delegate to working framework renderer\n return Component;\n }\n \n // If no renderer specified for function component\n if (!renderer) {\n throw new Error(\n `Component appears to be a framework component but no renderer is specified. ` +\n `Add 'parameters: { renderer: \"framework-name\" }' to your story configuration.`\n );\n }\n }\n \n // Return a basic representation for testing\n return {\n component: Component,\n args: args,\n renderer: renderer || 'astro'\n };\n};\n\n/**\n * Function that sets the globalConfig of your storybook. The global config is the preview module of\n * your .storybook folder.\n *\n * It should be run a single time, so that your global config (e.g. decorators) is applied to your\n * stories when using `composeStories` or `composeStory`.\n *\n * Example:\n *\n * ```jsx\n * // setup-file.js\n * import { setProjectAnnotations } from '@storybook-astro/framework';\n * import projectAnnotations from './.storybook/preview';\n *\n * setProjectAnnotations(projectAnnotations);\n * ```\n *\n * @param projectAnnotations - E.g. (import projectAnnotations from '../.storybook/preview')\n */\nexport function setProjectAnnotations(\n projectAnnotations:\n | NamedOrDefaultProjectAnnotations<AstroRenderer>\n | NamedOrDefaultProjectAnnotations<AstroRenderer>[]\n): NormalizedProjectAnnotations<AstroRenderer> {\n return originalSetProjectAnnotations<AstroRenderer>(projectAnnotations);\n}\n\n/**\n * Function that will receive a story along with meta (e.g. a default export from a .stories file)\n * and optionally projectAnnotations e.g. (import * as projectAnnotations from '../.storybook/preview')\n * and will return a composed component that has all args/parameters/decorators/etc combined and applied to it.\n *\n * It's very useful for reusing a story in scenarios outside of Storybook like unit testing.\n *\n * Example:\n * ```jsx\n * import { render } from '@testing-library/react';\n * import { composeStory } from '@storybook-astro/framework';\n * import meta, { Primary as PrimaryStory } from './Button.stories';\n *\n * const Primary = composeStory(PrimaryStory, meta);\n *\n * test('renders primary button', () => {\n * const { getByRole } = render(<Primary>Hello world</Primary>);\n * expect(getByRole('button')).toBeInTheDocument();\n * });\n * ```\n *\n * @param story - E.g. (import { Primary } from './Button.stories')\n * @param componentAnnotations - E.g. (import meta from './Button.stories')\n * @param projectAnnotations - E.g. (import * as projectAnnotations from '../.storybook/preview') this can be applied automatically if you use `setProjectAnnotations` in your setup files.\n * @param exportsName - In case your story does not contain a name and you want it to have a name.\n */\nexport function composeStory<TArgs extends Args = Args>(\n story: StoryAnnotationsOrFn<AstroRenderer, TArgs>,\n componentAnnotations: ComponentAnnotations<AstroRenderer, TArgs>,\n projectAnnotations?: ProjectAnnotations<AstroRenderer>,\n exportsName?: string\n) {\n // Merge project annotations with Astro renderer\n const mergedProjectAnnotations: any = projectAnnotations ? {\n ...projectAnnotations,\n render: projectAnnotations.render || render\n } : {\n render\n };\n \n return originalComposeStory<AstroRenderer, TArgs>(\n story as any,\n componentAnnotations,\n mergedProjectAnnotations as any,\n exportsName as any\n );\n}\n\n/**\n * Function that will receive a stories import (e.g. `import * as stories from './Button.stories'`)\n * and optionally a globalConfig (e.g. `import * from '../.storybook/preview`)\n * and will return an object containing all the stories passed, but now as a composed component that has all args/parameters/decorators/etc combined and applied to it.\n *\n * It's very useful for reusing stories in scenarios outside of Storybook like unit testing.\n *\n * Example:\n * ```jsx\n * import { render } from '@testing-library/react';\n * import { composeStories } from '@storybook-astro/framework';\n * import * as stories from './Button.stories';\n *\n * const { Primary, Secondary } = composeStories(stories);\n *\n * test('renders primary button', () => {\n * const { getByRole } = render(<Primary>Hello world</Primary>);\n * expect(getByRole('button')).toBeInTheDocument();\n * });\n * ```\n *\n * @param storiesImport - E.g. (import * as stories from './Button.stories')\n * @param projectAnnotations - E.g. (import * as globalConfig from '../.storybook/preview') this can be applied automatically if you use `setProjectAnnotations` in your setup files.\n */\nexport function composeStories<TModule extends Record<string, any>>(\n storiesImport: TModule,\n projectAnnotations?: ProjectAnnotations<AstroRenderer>\n): { [K in keyof Omit<TModule, 'default'>]: any } {\n // Merge project annotations with Astro renderer\n const mergedProjectAnnotations: any = projectAnnotations ? {\n ...projectAnnotations,\n render: projectAnnotations.render || render\n } : {\n render\n };\n \n return originalComposeStories(storiesImport as any, mergedProjectAnnotations as any) as { [K in keyof Omit<TModule, 'default'>]: any };\n}\n"],"mappings":";AAWA;AAAA,EACE,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,yBAAyB;AAAA,OACpB;AASP,IAAM,SAAS,CAAC,MAAY,YAAkB;AAC5C,QAAM,YAAY,SAAS;AAC3B,QAAM,WAAW,SAAS,YAAY;AACtC,QAAM,KAAK,SAAS,MAAM;AAG1B,QAAM,kBAA4B,CAAC;AAGnC,MAAI,YAAY,gBAAgB,SAAS,QAAQ,GAAG;AAClD,UAAM,IAAI,MAAM,aAAa,QAAQ,qEAAqE;AAAA,EAC5G;AAGA,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,0BAA0B,EAAE,iEAAiE;AAAA,EAC/G;AAGA,MAAI,OAAO,cAAc,cAAe,UAAkB,yBAAyB;AAEjF,WAAO;AAAA,EACT;AAGA,MAAI,OAAO,cAAc,YAAY;AACnC,QAAI,YAAY,CAAC,gBAAgB,SAAS,QAAQ,GAAG;AAEnD,aAAO;AAAA,IACT;AAGA,QAAI,CAAC,UAAU;AACb,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AAAA,EACF;AAGA,SAAO;AAAA,IACL,WAAW;AAAA,IACX;AAAA,IACA,UAAU,YAAY;AAAA,EACxB;AACF;AAqBO,SAAS,sBACd,oBAG6C;AAC7C,SAAO,8BAA6C,kBAAkB;AACxE;AA4BO,SAAS,aACd,OACA,sBACA,oBACA,aACA;AAEA,QAAM,2BAAgC,qBAAqB;AAAA,IACzD,GAAG;AAAA,IACH,QAAQ,mBAAmB,UAAU;AAAA,EACvC,IAAI;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AA0BO,SAAS,eACd,eACA,oBACgD;AAEhD,QAAM,2BAAgC,qBAAqB;AAAA,IACzD,GAAG;AAAA,IACH,QAAQ,mBAAmB,UAAU;AAAA,EACvC,IAAI;AAAA,IACF;AAAA,EACF;AAEA,SAAO,uBAAuB,eAAsB,wBAA+B;AACrF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rules.ts","../src/lib/sanitization.ts","../src/module-mocks.ts"],"sourcesContent":["import { dirname, isAbsolute, resolve } from 'node:path';\nimport type { RenderStoryInput } from './types.ts';\n\nexport type StoryRuleCleanup = () => void | Promise<void>;\ntype StoryRuleUseResult = void | StoryRuleCleanup | Promise<void | StoryRuleCleanup>;\n\nexport type StoryRuleUseContext = {\n story: StoryRuleStory;\n mock: (specifier: string, replacement: string) => void;\n};\n\nexport type StoryRuleUse = (context: StoryRuleUseContext) => StoryRuleUseResult;\n\nexport type StoryRule = {\n match: string | string[];\n use: StoryRuleUse | StoryRuleUse[];\n};\n\nexport type StoryRulesConfig = {\n rules: StoryRule[];\n};\n\nexport type StoryRuleStory = {\n id: string;\n title?: string;\n name?: string;\n keys: string[];\n};\n\nexport type StoryRuleSelectionInput = {\n configModule: unknown;\n configFilePath?: string;\n story?: RenderStoryInput;\n};\n\nexport type StoryRuleSelection = {\n moduleMocks: Map<string, string>;\n cleanups: StoryRuleCleanup[];\n};\n\ntype MutableStoryRuleSelection = {\n moduleMocks: Map<string, string>;\n cleanups: StoryRuleCleanup[];\n};\n\nexport function defineStoryRules(config: StoryRulesConfig): StoryRulesConfig {\n return config;\n}\n\nexport async function selectStoryRules(\n input: StoryRuleSelectionInput\n): Promise<StoryRuleSelection> {\n const config = normalizeRulesConfig(input.configModule);\n const story = normalizeStory(input.story);\n const selection = createEmptySelection();\n\n for (const rule of config.rules) {\n if (!isStoryRuleMatch(rule.match, story)) {\n continue;\n }\n\n const uses = Array.isArray(rule.use) ? rule.use : [rule.use];\n\n for (const use of uses) {\n if (typeof use !== 'function') {\n throw new Error('Each story rule \"use\" entry must be a function.');\n }\n\n const cleanup = await use({\n story,\n mock: (specifier, replacement) => {\n const normalizedSpecifier = normalizeMockSpecifier(specifier);\n const normalizedReplacement = normalizeMockReplacement(replacement, input.configFilePath);\n\n selection.moduleMocks.set(normalizedSpecifier, normalizedReplacement);\n }\n });\n\n if (cleanup !== undefined) {\n if (typeof cleanup !== 'function') {\n throw new Error('Story rule \"use\" must return either nothing or a cleanup function.');\n }\n\n selection.cleanups.push(cleanup);\n }\n }\n }\n\n return selection;\n}\n\nexport async function withStoryRuleCleanups<T>(\n cleanups: StoryRuleCleanup[],\n callback: () => Promise<T>\n): Promise<T> {\n let result: T | undefined;\n let callbackError: unknown;\n\n try {\n result = await callback();\n } catch (error) {\n callbackError = error;\n }\n\n try {\n await runStoryRuleCleanups(cleanups);\n } catch (cleanupError) {\n if (callbackError) {\n throw new AggregateError(\n [callbackError, cleanupError],\n 'Story rule execution and cleanup both failed.'\n );\n }\n\n throw cleanupError;\n }\n\n if (callbackError) {\n throw callbackError;\n }\n\n return result as T;\n}\n\nexport async function runStoryRuleCleanups(cleanups: StoryRuleCleanup[]): Promise<void> {\n const errors: unknown[] = [];\n\n for (let index = cleanups.length - 1; index >= 0; index -= 1) {\n try {\n await cleanups[index]();\n } catch (error) {\n errors.push(error);\n }\n }\n\n if (errors.length === 1) {\n throw errors[0];\n }\n\n if (errors.length > 1) {\n throw new AggregateError(errors, 'Story rule cleanup failed.');\n }\n}\n\nfunction normalizeRulesConfig(configModule: unknown): StoryRulesConfig {\n const configExport = getRulesConfigExport(configModule);\n\n if (configExport === undefined || configExport === null) {\n return {\n rules: []\n };\n }\n\n if (!isRecord(configExport)) {\n throw new Error(\n 'Story rules config must export an object with a \"rules\" array via a default export or named export.'\n );\n }\n\n const rules = configExport.rules;\n\n if (rules === undefined) {\n return {\n rules: []\n };\n }\n\n if (!Array.isArray(rules)) {\n throw new Error('Story rules config \"rules\" must be an array.');\n }\n\n return {\n rules: rules as StoryRule[]\n };\n}\n\nfunction getRulesConfigExport(configModule: unknown): unknown {\n if (!isRecord(configModule)) {\n return configModule;\n }\n\n if ('default' in configModule && configModule.default !== undefined) {\n return configModule.default;\n }\n\n if ('rules' in configModule) {\n return {\n rules: configModule.rules\n };\n }\n\n return undefined;\n}\n\nfunction normalizeStory(story?: RenderStoryInput): StoryRuleStory {\n const id = normalizeStoryId(story?.id);\n const title = normalizeOptionalString(story?.title);\n const name = normalizeOptionalString(story?.name);\n const keys = Array.from(resolveStoryKeys({ id, title, name }));\n\n return {\n id,\n title,\n name,\n keys\n };\n}\n\nfunction resolveStoryKeys(story: { id: string; title?: string; name?: string }) {\n const keys = new Set<string>();\n\n keys.add('');\n\n const storyId = story.id;\n const idPath = storyId ? storyId.replaceAll('--', '/') : '';\n\n if (storyId) {\n keys.add(storyId);\n keys.add(`/story/${storyId}`);\n }\n\n if (idPath) {\n keys.add(idPath);\n keys.add(`/story/${idPath}`);\n }\n\n const titlePath = story.title\n ? story.title\n .split('/')\n .map((segment) => slugify(segment))\n .filter(Boolean)\n .join('/')\n : '';\n\n const storyNamePath = story.name ? slugify(story.name) : '';\n\n if (titlePath && storyNamePath) {\n const composedPath = `${titlePath}/${storyNamePath}`;\n\n keys.add(composedPath);\n keys.add(`/story/${composedPath}`);\n }\n\n return keys;\n}\n\nfunction isStoryRuleMatch(match: string | string[], story: StoryRuleStory): boolean {\n const patterns = Array.isArray(match) ? match : [match];\n\n return patterns.some((pattern) => {\n if (typeof pattern !== 'string') {\n throw new Error('Story rule \"match\" must be a string or an array of strings.');\n }\n\n const normalizedPattern = pattern.trim();\n\n if (!normalizedPattern) {\n throw new Error('Story rule \"match\" cannot be empty.');\n }\n\n return story.keys.some((key) => isWildcardMatch(normalizedPattern, key));\n });\n}\n\nfunction isWildcardMatch(pattern: string, candidate: string): boolean {\n const escapedPattern = escapeRegExp(pattern).replaceAll('*', '.*');\n const regex = new RegExp(`^${escapedPattern}$`);\n\n return regex.test(candidate);\n}\n\nfunction normalizeStoryId(id?: string): string {\n const value = normalizeOptionalString(id) ?? '';\n\n if (!value) {\n return '';\n }\n\n return value.startsWith('/story/') ? value.slice('/story/'.length) : value;\n}\n\nfunction normalizeOptionalString(value: unknown): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n\n const normalizedValue = value.trim();\n\n return normalizedValue || undefined;\n}\n\nfunction normalizeMockSpecifier(value: unknown): string {\n if (typeof value !== 'string') {\n throw new Error('Story rule mock specifier must be a string.');\n }\n\n const normalizedValue = value.trim();\n\n if (!normalizedValue) {\n throw new Error('Story rule mock specifier cannot be empty.');\n }\n\n return normalizedValue;\n}\n\nfunction normalizeMockReplacement(value: unknown, configFilePath?: string): string {\n if (typeof value !== 'string') {\n throw new Error('Story rule mock replacement must be a string.');\n }\n\n const normalizedValue = value.trim();\n\n if (!normalizedValue) {\n throw new Error('Story rule mock replacement cannot be empty.');\n }\n\n if (isAbsolute(normalizedValue)) {\n return toPosixPath(normalizedValue);\n }\n\n if (normalizedValue.startsWith('.')) {\n if (!configFilePath) {\n throw new Error(\n 'Story rule mock replacement uses a relative path, but rules config path is unavailable.'\n );\n }\n\n return toPosixPath(resolve(dirname(configFilePath), normalizedValue));\n }\n\n return normalizedValue;\n}\n\nfunction slugify(input: string): string {\n return input\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nfunction createEmptySelection(): MutableStoryRuleSelection {\n return {\n moduleMocks: new Map(),\n cleanups: []\n };\n}\n\nfunction toPosixPath(input: string): string {\n return input.replaceAll('\\\\', '/');\n}\n\nfunction escapeRegExp(input: string) {\n return input.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n return !Array.isArray(value);\n}\n","import sanitizeHtml from 'sanitize-html';\nimport type { IOptions } from 'sanitize-html';\n\ntype SanitizationPayload = {\n args: Record<string, unknown>;\n slots: Record<string, unknown>;\n};\n\nexport type SanitizationOptions = {\n enabled?: boolean;\n args?: string[];\n slots?: string[];\n sanitizeHtml?: IOptions;\n};\n\nexport type ResolvedSanitizationOptions = {\n enabled: boolean;\n args: string[];\n slots: string[];\n sanitizeHtml: IOptions;\n};\n\nconst DEFAULT_SANITIZE_HTML_OPTIONS: IOptions = {\n allowedTags: [\n 'a',\n 'abbr',\n 'b',\n 'blockquote',\n 'br',\n 'caption',\n 'cite',\n 'code',\n 'col',\n 'colgroup',\n 'dd',\n 'details',\n 'dfn',\n 'div',\n 'dl',\n 'dt',\n 'em',\n 'figcaption',\n 'figure',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'hr',\n 'i',\n 'img',\n 'kbd',\n 'li',\n 'mark',\n 'ol',\n 'p',\n 'pre',\n 'q',\n 'rp',\n 'rt',\n 'ruby',\n 's',\n 'samp',\n 'small',\n 'span',\n 'strong',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'tfoot',\n 'th',\n 'thead',\n 'time',\n 'tr',\n 'u',\n 'ul',\n 'var',\n 'wbr'\n ],\n allowedAttributes: {\n '*': [\n 'aria-describedby',\n 'aria-hidden',\n 'aria-label',\n 'aria-labelledby',\n 'class',\n 'id',\n 'lang',\n 'role',\n 'title'\n ],\n a: ['href', 'name', 'target', 'rel'],\n img: ['src', 'srcset', 'alt', 'title', 'width', 'height', 'loading', 'decoding'],\n td: ['colspan', 'rowspan'],\n th: ['colspan', 'rowspan', 'scope'],\n time: ['datetime']\n },\n allowedSchemes: ['http', 'https', 'mailto', 'tel', 'data'],\n allowedSchemesByTag: {\n a: ['http', 'https', 'mailto', 'tel'],\n img: ['http', 'https', 'data']\n },\n allowedSchemesAppliedToAttributes: ['href', 'src', 'cite', 'srcset'],\n allowProtocolRelative: false,\n disallowedTagsMode: 'discard',\n enforceHtmlBoundary: true,\n parseStyleAttributes: false\n};\n\nexport function resolveSanitizationOptions(options?: SanitizationOptions): ResolvedSanitizationOptions {\n if (!options) {\n return {\n enabled: true,\n args: [],\n slots: ['**'],\n sanitizeHtml: mergeSanitizeHtmlOptions()\n };\n }\n\n const enabled = options.enabled ?? true;\n const args = normalizePathList(options.args, 'framework.options.sanitization.args');\n const slots =\n options.slots === undefined\n ? ['**']\n : normalizePathList(options.slots, 'framework.options.sanitization.slots');\n\n return {\n enabled,\n args,\n slots,\n sanitizeHtml: mergeSanitizeHtmlOptions(options.sanitizeHtml)\n };\n}\n\nexport function sanitizeRenderPayload(\n payload: SanitizationPayload,\n options: ResolvedSanitizationOptions\n): SanitizationPayload {\n if (!options.enabled) {\n return payload;\n }\n\n const sanitizedArgs =\n options.args.length > 0\n ? sanitizeRecord(payload.args, options.args, options.sanitizeHtml)\n : payload.args;\n\n const sanitizedSlots =\n options.slots.length > 0\n ? sanitizeRecord(payload.slots, options.slots, options.sanitizeHtml)\n : payload.slots;\n\n return {\n args: sanitizedArgs,\n slots: sanitizedSlots\n };\n}\n\nexport function serializeSanitizationOptions(options?: SanitizationOptions): string {\n if (!options) {\n return 'undefined';\n }\n\n assertNoFunctions(options.sanitizeHtml, 'framework.options.sanitization.sanitizeHtml');\n\n const state = {\n seen: new WeakSet<object>()\n };\n\n return serializeValue(options, 'framework.options.sanitization', state);\n}\n\nfunction mergeSanitizeHtmlOptions(userOptions?: IOptions): IOptions {\n const merged: IOptions = {\n ...DEFAULT_SANITIZE_HTML_OPTIONS,\n ...userOptions\n };\n\n if (\n isRecord(DEFAULT_SANITIZE_HTML_OPTIONS.allowedAttributes) &&\n isRecord(userOptions?.allowedAttributes)\n ) {\n merged.allowedAttributes = {\n ...DEFAULT_SANITIZE_HTML_OPTIONS.allowedAttributes,\n ...userOptions.allowedAttributes\n };\n }\n\n if (isRecord(userOptions?.allowedClasses)) {\n merged.allowedClasses = {\n ...(isRecord(DEFAULT_SANITIZE_HTML_OPTIONS.allowedClasses)\n ? DEFAULT_SANITIZE_HTML_OPTIONS.allowedClasses\n : {}),\n ...userOptions.allowedClasses\n };\n }\n\n if (isRecord(userOptions?.allowedStyles)) {\n merged.allowedStyles = {\n ...(isRecord(DEFAULT_SANITIZE_HTML_OPTIONS.allowedStyles)\n ? DEFAULT_SANITIZE_HTML_OPTIONS.allowedStyles\n : {}),\n ...userOptions.allowedStyles\n };\n }\n\n return merged;\n}\n\nfunction normalizePathList(value: unknown, path: string): string[] {\n if (value === undefined) {\n return [];\n }\n\n if (!Array.isArray(value)) {\n throw new Error(`${path} must be an array of dot-path patterns.`);\n }\n\n const unique = new Set<string>();\n\n value.forEach((entry, index) => {\n if (typeof entry !== 'string') {\n throw new Error(`${path}[${index}] must be a string.`);\n }\n\n const normalized = entry.trim();\n\n if (!normalized) {\n throw new Error(`${path}[${index}] cannot be an empty string.`);\n }\n\n unique.add(normalized);\n });\n\n return Array.from(unique);\n}\n\nfunction sanitizeRecord(\n record: Record<string, unknown>,\n patterns: string[],\n options: IOptions\n): Record<string, unknown> {\n const sanitized: Record<string, unknown> = {};\n\n Object.entries(record).forEach(([key, value]) => {\n sanitized[key] = sanitizeValue(value, key, patterns, options);\n });\n\n return sanitized;\n}\n\nfunction sanitizeValue(\n value: unknown,\n currentPath: string,\n patterns: string[],\n options: IOptions\n): unknown {\n if (typeof value === 'string') {\n if (shouldSanitizePath(currentPath, patterns)) {\n return sanitizeHtml(value, options);\n }\n\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map((item, index) => {\n const nextPath = `${currentPath}.${index}`;\n\n return sanitizeValue(item, nextPath, patterns, options);\n });\n }\n\n if (isRecord(value)) {\n const sanitized: Record<string, unknown> = {};\n\n Object.entries(value).forEach(([key, nestedValue]) => {\n const nextPath = `${currentPath}.${key}`;\n\n sanitized[key] = sanitizeValue(nestedValue, nextPath, patterns, options);\n });\n\n return sanitized;\n }\n\n return value;\n}\n\nfunction shouldSanitizePath(path: string, patterns: string[]): boolean {\n return patterns.some((pattern) => matchesPathPattern(path, pattern));\n}\n\nfunction matchesPathPattern(path: string, pattern: string): boolean {\n const pathSegments = path.split('.');\n const patternSegments = pattern.split('.');\n\n return matchSegments(pathSegments, patternSegments);\n}\n\nfunction serializeValue(value: unknown, path: string, state: { seen: WeakSet<object> }): string {\n if (value === null) {\n return 'null';\n }\n\n if (value === undefined) {\n return 'undefined';\n }\n\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n\n if (value instanceof RegExp) {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n const serializedItems = value.map((item, index) =>\n serializeValue(item, `${path}[${index}]`, state)\n );\n\n return `[${serializedItems.join(', ')}]`;\n }\n\n if (isRecord(value)) {\n if (state.seen.has(value)) {\n throw new Error(`${path} contains a circular reference.`);\n }\n\n state.seen.add(value);\n\n const serializedEntries = Object.entries(value)\n .filter(([, nestedValue]) => nestedValue !== undefined)\n .map(([key, nestedValue]) => {\n const serializedNestedValue = serializeValue(nestedValue, `${path}.${key}`, state);\n\n return `${JSON.stringify(key)}: ${serializedNestedValue}`;\n });\n\n return `{ ${serializedEntries.join(', ')} }`;\n }\n\n throw new Error(\n `${path} contains an unsupported value of type ${typeof value}. ` +\n 'Only plain objects, arrays, primitives, and regular expressions are supported.'\n );\n}\n\nfunction assertNoFunctions(value: unknown, path: string): void {\n const state = {\n seen: new WeakSet<object>()\n };\n\n assertNoFunctionsRecursive(value, path, state);\n}\n\nfunction assertNoFunctionsRecursive(\n value: unknown,\n path: string,\n state: { seen: WeakSet<object> }\n): void {\n if (typeof value === 'function') {\n throw new Error(\n `${path} cannot contain functions. ` +\n 'Function-valued sanitization hooks are not supported in framework options.'\n );\n }\n\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n assertNoFunctionsRecursive(item, `${path}[${index}]`, state);\n });\n\n return;\n }\n\n if (isRecord(value)) {\n if (state.seen.has(value)) {\n return;\n }\n\n state.seen.add(value);\n\n Object.entries(value).forEach(([key, nestedValue]) => {\n assertNoFunctionsRecursive(nestedValue, `${path}.${key}`, state);\n });\n }\n}\n\nfunction matchSegments(pathSegments: string[], patternSegments: string[]): boolean {\n if (patternSegments.length === 0) {\n return pathSegments.length === 0;\n }\n\n const [patternHead, ...patternTail] = patternSegments;\n\n if (patternHead === '**') {\n if (patternTail.length === 0) {\n return true;\n }\n\n for (let index = 0; index <= pathSegments.length; index += 1) {\n const remainingPath = pathSegments.slice(index);\n\n if (matchSegments(remainingPath, patternTail)) {\n return true;\n }\n }\n\n return false;\n }\n\n if (pathSegments.length === 0) {\n return false;\n }\n\n const [pathHead, ...pathTail] = pathSegments;\n\n if (patternHead === '*' || patternHead === pathHead) {\n return matchSegments(pathTail, patternTail);\n }\n\n return false;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n if (Array.isArray(value) || value instanceof RegExp) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n\n return prototype === Object.prototype || prototype === null;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nexport type StoryModuleMocks = Map<string, string>;\n\nconst moduleMockStorage = new AsyncLocalStorage<StoryModuleMocks>();\n\nexport async function withStoryModuleMocks<T>(\n moduleMocks: StoryModuleMocks,\n callback: () => Promise<T>\n): Promise<T> {\n return moduleMockStorage.run(moduleMocks, callback);\n}\n\nexport function resolveStoryModuleMock(specifier: string): string | undefined {\n return moduleMockStorage.getStore()?.get(specifier);\n}\n"],"mappings":";AAAA,SAAS,SAAS,YAAY,eAAe;AA6CtC,SAAS,iBAAiB,QAA4C;AAC3E,SAAO;AACT;AAEA,eAAsB,iBACpB,OAC6B;AAC7B,QAAM,SAAS,qBAAqB,MAAM,YAAY;AACtD,QAAM,QAAQ,eAAe,MAAM,KAAK;AACxC,QAAM,YAAY,qBAAqB;AAEvC,aAAW,QAAQ,OAAO,OAAO;AAC/B,QAAI,CAAC,iBAAiB,KAAK,OAAO,KAAK,GAAG;AACxC;AAAA,IACF;AAEA,UAAM,OAAO,MAAM,QAAQ,KAAK,GAAG,IAAI,KAAK,MAAM,CAAC,KAAK,GAAG;AAE3D,eAAW,OAAO,MAAM;AACtB,UAAI,OAAO,QAAQ,YAAY;AAC7B,cAAM,IAAI,MAAM,iDAAiD;AAAA,MACnE;AAEA,YAAM,UAAU,MAAM,IAAI;AAAA,QACxB;AAAA,QACA,MAAM,CAAC,WAAW,gBAAgB;AAChC,gBAAM,sBAAsB,uBAAuB,SAAS;AAC5D,gBAAM,wBAAwB,yBAAyB,aAAa,MAAM,cAAc;AAExF,oBAAU,YAAY,IAAI,qBAAqB,qBAAqB;AAAA,QACtE;AAAA,MACF,CAAC;AAED,UAAI,YAAY,QAAW;AACzB,YAAI,OAAO,YAAY,YAAY;AACjC,gBAAM,IAAI,MAAM,oEAAoE;AAAA,QACtF;AAEA,kBAAU,SAAS,KAAK,OAAO;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEA,eAAsB,sBACpB,UACA,UACY;AACZ,MAAI;AACJ,MAAI;AAEJ,MAAI;AACF,aAAS,MAAM,SAAS;AAAA,EAC1B,SAAS,OAAO;AACd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