{"version":3,"file":"preset.cjs","names":["require","input: I","__dirname","core: StorybookConfig['core']","viteFinal: StorybookConfig['viteFinal']","devServer: ViteDevServer | undefined","server: ViteDevServer","sep","id: string","file: string","ctx: HmrContext","previewAnnotations: StorybookConfig['previewAnnotations']","result: string[]"],"sources":["../src/preset.ts"],"sourcesContent":["/**\n * we can't prefix the Node.js imports with `node:` because it will break\n * within Storybook due to its Vite setup.\n */\nimport { readFileSync, utimesSync } from 'fs';\nimport { createRequire } from 'module';\nimport { dirname, join, resolve, sep } from 'path';\nimport { getComponentStyleDependencies, stencilBuildEvents } from '@stencil-community/unplugin-stencil';\nimport stencil from '@stencil-community/unplugin-stencil/vite';\nimport { fileURLToPath } from 'url';\nimport type { HmrContext, Plugin, ViteDevServer } from 'vite';\nimport { mergeConfig } from 'vite';\nimport { StorybookConfig } from './types';\n\nconst require = createRequire(import.meta.url);\nconst getAbsolutePath = <I extends string>(input: I): I => dirname(require.resolve(join(input, 'package.json'))) as any;\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst renderer = join(__dirname, 'entry-preview.js');\n\nconst UNPLUGIN_STENCIL_NAME = '@stencil-community/unplugin-stencil';\n\nexport const core: StorybookConfig['core'] = {\n  builder: join(getAbsolutePath('@storybook/builder-vite'), 'dist', 'index.js'),\n  renderer,\n};\n\nexport const viteFinal: StorybookConfig['viteFinal'] = async (defaultConfig, { configType }) => {\n  const config = mergeConfig(defaultConfig, {\n    build: {\n      target: 'es2020',\n    },\n    plugins: [\n      stencil({\n        rootPath: defaultConfig.root,\n      }),\n    ],\n  });\n  if (configType === 'DEVELOPMENT') {\n    return mergeConfig(config, {\n      build: {\n        rollupOptions: {\n          external: ['@stencil/core'],\n        },\n      },\n      // Don't let Vite watch this plugin's own `dist/`. `tsdown --watch`\n      // rewrites those files during plugin development; if Vite picks the\n      // change up it re-optimizes deps, bumping the React chunk hash and\n      // leaving previously-imported chunks pointing at a torn-down React\n      // (`useEffect` becomes null in <DocsContainer>).\n      server: {\n        watch: {\n          ignored: [join(__dirname, '**')],\n        },\n      },\n      plugins: [stencilPreviewReloadPlugin()],\n    });\n  }\n\n  return config;\n};\n\n/**\n * Forces a full preview reload when a Stencil component changes.\n *\n * `customElements.define()` is permanent, so HMR can't swap the new class in —\n * the iframe must reload. We use a custom HMR event (instead of Vite's\n * `full-reload`) because Storybook's story-index watcher races us with its own\n * `vite-app.js` HMR update and cancels plain reloads.\n *\n * - Eager: the .tsx is in Vite's graph; our `transform` hook fires after\n *   unplugin-stencil and emits the reload.\n * - Lazy: the .tsx isn't imported, so we run unplugin-stencil ourselves, then\n *   reload once `@stencil-community/unplugin-stencil` reports the build\n *   finished (its `stencilBuildEvents` emitter, instead of polling dist/esm).\n * - Styles: `@stencil-community/unplugin-stencil` exposes a `style → component`\n *   map built from each component's `@Component` decorator (AST-parsed, covers\n *   `styleUrl`, `styleUrls` array, and `styleUrls` mode object). When a tracked\n *   style file changes we touch every dependent `.tsx` so the eager/lazy paths\n *   above pick up the rebuild.\n * - Global style: the same package resolves `stencil.config#globalStyle`; when\n *   it changes we touch every known component `.tsx`.\n */\nfunction stencilPreviewReloadPlugin(): Plugin {\n  let devServer: ViteDevServer | undefined;\n  let lazyBuildPending = false;\n\n  const sendReload = (server: ViteDevServer) => {\n    server.ws.send({ type: 'custom', event: 'stencil:reload' });\n  };\n\n  // Match dist/esm module ids on both POSIX and Windows.\n  const distEsmFragment = `${sep}dist${sep}esm${sep}`;\n\n  const isComponentSource = (id: string): boolean =>\n    id.endsWith('.tsx') &&\n    !id.endsWith('.stories.tsx') &&\n    !id.includes(`${sep}node_modules${sep}`) &&\n    !id.includes(`${sep}.storybook${sep}`);\n\n  // dist/esm lives outside Vite's watched root, so its module cache never\n  // invalidates on its own. Drop it before reloading.\n  const invalidateDistEsm = (server: ViteDevServer): void => {\n    for (const cached of server.moduleGraph.idToModuleMap.values()) {\n      if (cached.id && cached.id.includes(distEsmFragment) && cached.id.endsWith('.js')) {\n        server.moduleGraph.invalidateModule(cached);\n      }\n    }\n  };\n\n  // Touch a file's mtime so unplugin-stencil recompiles it. The resulting\n  // `change` event re-enters the watcher handler and rides the eager/lazy path.\n  const touch = (file: string): void => {\n    try {\n      const now = new Date();\n      utimesSync(file, now, now);\n    } catch {\n      // ignore: best-effort touch\n    }\n  };\n\n  return {\n    name: 'stencil-preview-reload',\n\n    configureServer(server) {\n      devServer = server;\n\n      // When unplugin-stencil finishes a (project-wide) Stencil build, the\n      // fresh dist/esm chunks are on disk but Vite still has the old versions\n      // cached. If we kicked a lazy rebuild, invalidate + reload now.\n      stencilBuildEvents.on('buildFinished', () => {\n        if (!lazyBuildPending || !devServer) return;\n        lazyBuildPending = false;\n        invalidateDistEsm(devServer);\n        sendReload(devServer);\n      });\n\n      server.watcher.on('change', async (file: string) => {\n        // unplugin-stencil seeds this map at buildStart, so it's populated from\n        // the first watcher event for eager, lazy, and globalStyle alike.\n        const { byStyle, byComponent, globalStyle } = getComponentStyleDependencies();\n        const resolved = resolve(file);\n\n        // Global style: baked into every component, so touch every component\n        // we know about and let the eager/lazy paths reload.\n        if (globalStyle && resolved === globalStyle) {\n          for (const componentId of byComponent.keys()) touch(componentId);\n          return;\n        }\n\n        // Component-style change: re-route to every dependent .tsx. Each touch\n        // produces a fresh `change` event that flows through the logic below.\n        const dependents = byStyle.get(resolved);\n        if (dependents && dependents.size > 0) {\n          for (const componentId of dependents) touch(componentId);\n          return;\n        }\n\n        if (!file.endsWith('.tsx') || file.endsWith('.stories.tsx')) return;\n\n        const mod = server.moduleGraph.getModuleById(file);\n        // Eager components are handled by the `transform` hook below.\n        if (mod && mod.importers.size > 0) return;\n\n        // Lazy: trigger Stencil's build manually. unplugin-stencil's transform\n        // resolves before the build flushes to disk, so we set a flag and wait\n        // for `stencilBuildEvents.buildFinished` (above) to do the reload.\n        const stencilPlugin = server.config.plugins.find((p) => p.name === UNPLUGIN_STENCIL_NAME);\n        if (!stencilPlugin || typeof stencilPlugin.transform !== 'function') return;\n\n        lazyBuildPending = true;\n        try {\n          const code = readFileSync(file, 'utf-8');\n          await (stencilPlugin.transform as any).call({ resolve: (): null => null }, code, file);\n        } catch {\n          lazyBuildPending = false;\n        }\n      });\n    },\n\n    // Always reload (never HMR) for component .tsx files. Eager modules still\n    // need to flow through Vite so unplugin-stencil rebuilds dist.\n    handleHotUpdate(ctx: HmrContext) {\n      const { file, modules } = ctx;\n      if (!file.endsWith('.tsx') || file.endsWith('.stories.tsx')) return;\n      const mod = modules[0];\n      if (mod && mod.importers?.size > 0) return;\n      return [];\n    },\n\n    async transform(_code, id) {\n      if (!devServer) return;\n      const cleanId = id.split('?')[0];\n      if (!isComponentSource(cleanId)) return;\n      if (lazyBuildPending) return;\n      sendReload(devServer);\n    },\n  };\n}\n\nexport const previewAnnotations: StorybookConfig['previewAnnotations'] = async (input = [], options) => {\n  const docsEnabled = Object.keys(await options.presets.apply('docs', {}, options)).length > 0;\n  const result: string[] = [];\n\n  return result\n    .concat(input)\n    .concat([renderer, join(__dirname, 'entry-preview-argtypes.js')])\n    .concat(docsEnabled ? [join(__dirname, 'entry-preview-docs.js')] : []);\n};\n"],"mappings":";;;;;;;;;;AAcA,MAAMA,YAAU,0EAA8B;AAC9C,MAAM,kBAAkB,CAAmBC,UAAgB,kBAAQ,UAAQ,QAAQ,eAAK,OAAO,eAAe,CAAC,CAAC;AAEhH,MAAMC,cAAY,kBAAQ,qEAA8B,CAAC;AAEzD,MAAM,WAAW,eAAKA,aAAW,mBAAmB;AAEpD,MAAM,wBAAwB;AAE9B,MAAaC,OAAgC;CAC3C,SAAS,eAAK,gBAAgB,0BAA0B,EAAE,QAAQ,WAAW;CAC7E;AACD;AAED,MAAaC,YAA0C,OAAO,eAAe,EAAE,YAAY,KAAK;CAC9F,MAAM,SAAS,sBAAY,eAAe;EACxC,OAAO,EACL,QAAQ,SACT;EACD,SAAS,CACP,uDAAQ,EACN,UAAU,cAAc,KACzB,EAAC,AACH;CACF,EAAC;AACF,KAAI,eAAe,cACjB,QAAO,sBAA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