{"version":3,"file":"index.mjs","names":[],"sources":["../src/lock.ts","../src/compiler.ts","../src/ids.ts","../src/index.ts"],"sourcesContent":["/**\n * Serializes compilations: the vanilla-extract css adapter is handed to the evaluated modules\n * through a global, so only one `.css.ts` module may be evaluated at a time. Ported from\n * `@vanilla-extract/compiler` (MIT licensed, Copyright (c) 2021 SEEK).\n * @internal\n */\nlet queue: Promise<unknown> = Promise.resolve()\n\nexport function lock<T>(fn: () => Promise<T>): Promise<T> {\n  const result = queue.then(fn)\n  queue = result.catch(() => undefined)\n  return result\n}\n","/**\n * A caching vanilla-extract compiler on Vite 8's Environment API: a port of\n * `@vanilla-extract/compiler` (MIT licensed, Copyright (c) 2021 SEEK) with Vite's own\n * `ModuleRunner` (`createServerModuleRunner`) replacing the legacy `vite-node` runner, and the\n * css adapter handed to the evaluated modules through `globalThis` instead of a vite-node\n * context injection.\n *\n * `.css.ts` modules are evaluated through an internal Vite dev server, so results are cached in\n * its module graph across rebuilds and invalidated per-file on change — unlike the per-file\n * rolldown `compile()` of `@sanity/vanilla-extract-integration` (used for one-shot library\n * builds by `@sanity/vanilla-extract-rolldown-plugin`), which re-bundles a module's whole\n * dependency graph on every call.\n */\nimport {isAbsolute, join} from 'node:path'\nimport {\n  cssFileFilter,\n  getPackageInfo,\n  normalizePath,\n  serializeVanillaModule,\n  transform,\n  type IdentifierOption,\n} from '@sanity/vanilla-extract-integration'\nimport type {Adapter} from '@vanilla-extract/css'\nimport {transformCss} from '@vanilla-extract/css/transformCss'\nimport {\n  createServer,\n  createServerModuleRunner,\n  type EnvironmentModuleNode,\n  type UserConfig as ViteUserConfig,\n} from 'vite'\nimport type {EvaluatedModuleNode, ModuleRunner} from 'vite/module-runner'\nimport {lock} from './lock.ts'\n\ntype Css = Parameters<Adapter['appendCss']>[0]\ntype Composition = Parameters<Adapter['registerComposition']>[0]\n\n/**\n * The evaluated `.css.ts` modules call `setAdapter(globalThis[...])` (spliced in by the\n * filescope transform below), binding whichever copy of `@vanilla-extract/css` the project\n * resolves to the adapter of the compilation in progress. The module runner evaluates modules\n * in-process, so `globalThis` is shared with the host — compilations are serialized by\n * {@link lock}, so the global never sees two adapters at once.\n */\nconst GLOBAL_ADAPTER_KEY = '__sanity_vanillaExtractCssAdapter__'\nconst globalAdapterIdentifier = `globalThis[${JSON.stringify(GLOBAL_ADAPTER_KEY)}]`\n\nconst globalAdapterStore = globalThis as typeof globalThis & {\n  [GLOBAL_ADAPTER_KEY]?: Adapter\n}\n\ninterface ModuleScanResult {\n  cssDeps: string[]\n  watchFiles: Set<string>\n}\n\n/**\n * Walks a module's import graph, collecting its vanilla-extract dependencies in import order\n * (dependencies before their importers) and every file to watch. Memoized per scan.\n */\nfunction createModuleScanner() {\n  const cache = new Map<string, ModuleScanResult>()\n\n  const scanModule = (moduleNode: EnvironmentModuleNode, path: string[] = []): ModuleScanResult => {\n    const watchFiles = new Set<string>()\n    const cacheKey = moduleNode.id ?? moduleNode.file\n\n    if (!cacheKey || moduleNode.id?.includes('@vanilla-extract/') || path.includes(cacheKey)) {\n      return {cssDeps: [], watchFiles}\n    }\n\n    const cached = cache.get(cacheKey)\n    if (cached) return cached\n\n    cache.set(cacheKey, {cssDeps: [], watchFiles})\n\n    const cssDeps = new Set<string>()\n    const currentPath = [...path, cacheKey]\n\n    for (const dependencyNode of moduleNode.importedModules) {\n      const {cssDeps: dependencyCssDeps, watchFiles: dependencyWatchFiles} = scanModule(\n        dependencyNode,\n        currentPath,\n      )\n      for (const file of dependencyCssDeps) cssDeps.add(file)\n      for (const file of dependencyWatchFiles) watchFiles.add(file)\n    }\n\n    const cssDepsArray = [...cssDeps]\n    if (moduleNode.id && cssFileFilter.test(moduleNode.id)) {\n      cssDepsArray.push(moduleNode.id)\n    }\n    if (moduleNode.file) {\n      watchFiles.add(moduleNode.file)\n    }\n\n    const scanResult = {cssDeps: cssDepsArray, watchFiles}\n    cache.set(cacheKey, scanResult)\n    return scanResult\n  }\n\n  return scanModule\n}\n\n/** A map keyed by normalized absolute file paths, tolerating relative and Windows inputs. */\nclass NormalizedMap<V> extends Map<string, V> {\n  readonly root: string\n\n  constructor(root: string) {\n    super()\n    this.root = root\n  }\n\n  #normalizePath(filePath: string) {\n    return normalizePath(isAbsolute(filePath) ? filePath : join(this.root, filePath))\n  }\n\n  override get(filePath: string): V | undefined {\n    return super.get(this.#normalizePath(filePath))\n  }\n\n  override set(filePath: string, value: V): this {\n    return super.set(this.#normalizePath(filePath), value)\n  }\n\n  override delete(filePath: string): boolean {\n    return super.delete(this.#normalizePath(filePath))\n  }\n}\n\n/** @public */\nexport interface ProcessedVanillaFile {\n  /** The serialized JS module: virtual CSS imports followed by the evaluated exports. */\n  source: string\n  /** Files the `.css.ts` module (transitively) depends on. */\n  watchFiles: Set<string>\n}\n\n/** @public */\nexport interface Compiler {\n  /**\n   * Evaluates a `.css.ts` module (through the internal Vite server, cached in its module graph)\n   * and returns its serialized JS along with the files it depends on. The extracted CSS is\n   * retrievable per file through {@link Compiler.getCssForFile}.\n   */\n  processVanillaFile(\n    filePath: string,\n    options?: {outputCss?: boolean},\n  ): Promise<ProcessedVanillaFile>\n  /** The extracted CSS of a previously processed `.css.ts` file, if any. */\n  getCssForFile(filePath: string): {filePath: string; css: string} | undefined\n  /**\n   * All extracted CSS known to the compiler, e.g. to inline into HTML during dev SSR\n   * (`mode: 'inlineCssInDev'`).\n   *\n   * Ordering contract (matching upstream `@vanilla-extract/compiler`): per-file CSS is\n   * concatenated in first-evaluation order — within a single compilation that follows the\n   * module graph (dependencies before their importers), across compilations it follows the\n   * order the dev server first requested each `.css.ts` module. The order is stable across\n   * recompiles (re-setting a key keeps its Map position). It is a FOUC stopgap, not the\n   * authoritative cascade: the same CSS also loads through Vite's CSS pipeline in module-graph\n   * order, and those later style tags win over the head-prepended inline block for\n   * equal-specificity rules.\n   */\n  getAllCss(): string\n  /**\n   * The transitive importer tree of a file, from the compiler's own module graph (the consuming\n   * dev server's graph gets rewritten by the plugin transform, so it can't reconstruct the\n   * original chain). Stops at processed vanilla-extract module boundaries.\n   */\n  findImporterTree(\n    filePath: string,\n    transformedVanillaModules: ReadonlySet<string>,\n  ): Promise<Set<EnvironmentModuleNode>>\n  /**\n   * Invalidates every non-`node_modules` module in the compiler's module graph and runner\n   * cache, forcing the next {@link Compiler.processVanillaFile} to re-evaluate. The extracted\n   * CSS of previous compilations intentionally stays available (like upstream\n   * `@vanilla-extract/compiler`) until it's replaced by the re-evaluation: already-served\n   * modules keep importing their virtual CSS, so dropping it would break those loads.\n   */\n  invalidateAllModules(): Promise<void>\n  close(): Promise<void>\n}\n\n/** @public */\nexport interface CreateCompilerOptions {\n  root: string\n  identifiers?: IdentifierOption\n  /**\n   * Maps a `.css.ts` file path to the virtual CSS module specifier imported by its compiled JS.\n   */\n  cssImportSpecifier?: (filePath: string) => string\n  /** Vite config forwarded to the internal compiler server (resolve options, plugins, etc). */\n  viteConfig?: ViteUserConfig\n  /**\n   * The compiler watches the files it evaluates and invalidates its caches on change. Disable\n   * during production builds, where nothing changes mid-build.\n   * @defaultValue true\n   */\n  enableFileWatcher?: boolean\n}\n\n/** Invalidates the runner's evaluated modules for a changed file, and their importers. */\nfunction invalidateRunnerFile(runner: ModuleRunner, filePath: string): void {\n  const seen = new Set<EvaluatedModuleNode>()\n  const stack = [...(runner.evaluatedModules.getModulesByFile(normalizePath(filePath)) ?? [])]\n  for (let node = stack.pop(); node; node = stack.pop()) {\n    if (seen.has(node)) continue\n    seen.add(node)\n    for (const importerId of node.importers) {\n      const importer = runner.evaluatedModules.getModuleById(importerId)\n      if (importer) stack.push(importer)\n    }\n    runner.evaluatedModules.invalidateModule(node)\n  }\n}\n\nasync function createCompilerServer({\n  root,\n  identifiers,\n  viteConfig,\n  enableFileWatcher,\n  onFileRemoved,\n}: Required<\n  Pick<CreateCompilerOptions, 'root' | 'identifiers' | 'viteConfig' | 'enableFileWatcher'>\n> & {\n  /** Called when the watcher reports a deleted file, so the compiler can prune its caches. */\n  onFileRemoved: (filePath: string) => void\n}) {\n  const pkg = getPackageInfo(root)\n\n  // The compiler evaluates `.css.ts` modules in Node, so its module resolution must stay\n  // Node-shaped regardless of what the consuming app's config says — `ssr` and `environments`\n  // are deliberately not forwarded (destructured off), and the resolve conditions are pinned:\n  //\n  // - `ssr.resolve.externalConditions` must prefer the `module` (ESM) builds of externalized\n  //   dependencies. Vite's default (`['node', 'module-sync']`) falls through to the `default`\n  //   (CJS) exports of the `@vanilla-extract/*` packages, whose wrappers pick their dev or\n  //   prod build off `NODE_ENV` at first load. A CLI host (e.g. `sanity build`) typically\n  //   imports this plugin before `vite build` flips `NODE_ENV` to `production`, so the host\n  //   and the module runner would otherwise load two different copies of\n  //   `@vanilla-extract/css/adapter` — the evaluated modules then bind the compilation\n  //   adapter to one copy while `style()` appends CSS through the other (the mock adapter),\n  //   silently dropping all CSS while the class-name exports keep working.\n  // - The parent `ssr` options must not leak in: `ssr.noExternal: true` (set e.g. by the\n  //   `sanity schema extract` worker) would inline CJS dependencies, which Vite's native\n  //   `ModuleRunner` (unlike the legacy `vite-node`) cannot evaluate, and\n  //   `ssr.target: 'webworker'` would flip the SSR environment to browser-leaning resolution.\n  //\n  // Covered end-to-end by the `@integration/vanilla-extract-studio` suite, which compares\n  // `sanity dev` / `sanity build` / `sanity schema extract` output against\n  // `@vanilla-extract/vite-plugin`.\n  const {ssr: _ssr, environments: _environments, ...inheritedViteConfig} = viteConfig\n  const nodeResolveConditions = ['node', 'import', 'module', 'default']\n\n  const server = await createServer({\n    ...inheritedViteConfig,\n    // The compiler server should not rewrite imported asset URLs within vanilla-extract\n    // stylesheets. Doing so interferes with Vite's resolution and bundling of these assets at\n    // build time.\n    base: undefined,\n    configFile: false,\n    root,\n    // Don't include HTML middlewares\n    appType: 'custom',\n    // Forward the consumer's server options (e.g. `fs.allow`, needed to evaluate files outside\n    // the workspace root), overriding only what the compiler manages itself: HMR stays off (the\n    // compiler drives its own invalidation), and watching is disabled entirely for builds\n    server: {\n      ...viteConfig.server,\n      hmr: false,\n      watch: enableFileWatcher ? viteConfig.server?.watch : null,\n    },\n    logLevel: 'silent',\n    optimizeDeps: {\n      noDiscovery: true,\n    },\n    build: {\n      assetsInlineLimit: viteConfig.build?.assetsInlineLimit,\n    },\n    resolve: {\n      ...viteConfig.resolve,\n      conditions: nodeResolveConditions,\n      mainFields: ['module', 'jsnext:main', 'jsnext', 'main'],\n    },\n    ssr: {\n      resolve: {\n        conditions: nodeResolveConditions,\n        externalConditions: nodeResolveConditions,\n      },\n    },\n    // Vite's default SSR externalization applies: project files and linked packages are\n    // evaluated through the runner (so they're cached in the module graph), while node_modules\n    // dependencies are externalized to real Node imports — required for CJS dependencies,\n    // which Vite's native `ModuleRunner` (unlike the legacy `vite-node`) cannot inline, and\n    // for the `@vanilla-extract/*` packages, which must resolve to the same instances the\n    // adapter of the compilation binds to (the plugin below forces the latter even in setups\n    // that would otherwise inline them).\n    plugins: [\n      {\n        name: 'sanity-vanilla-extract-externalize',\n        enforce: 'pre',\n        async resolveId(source, importer) {\n          if (source.startsWith('@vanilla-extract/')) {\n            const result = await this.resolve(source, importer, {skipSelf: true})\n            return result ? {...result, external: true} : null\n          }\n          return null\n        },\n      },\n      {\n        name: 'sanity-vanilla-extract-transform',\n        async transform(code, id) {\n          if (!cssFileFilter.test(id)) return null\n          // Inject the file scope and the adapter binding: the spliced\n          // `setAdapter(globalThis[...])` call binds the project's own copy of\n          // `@vanilla-extract/css` to the adapter of the compilation in progress\n          return transform({\n            source: code,\n            rootPath: root,\n            filePath: id,\n            packageName: pkg.name,\n            identOption: identifiers,\n            globalAdapterIdentifier,\n          })\n        },\n      },\n      ...(viteConfig.plugins ?? []),\n    ],\n  })\n\n  // Initialize the plugin pipeline of the environment the runner executes through\n  await server.environments.ssr.pluginContainer.buildStart({})\n\n  const runner = createServerModuleRunner(server.environments.ssr, {hmr: false})\n\n  if (enableFileWatcher) {\n    // The server invalidates its own module graph on change; the runner's evaluated-module\n    // cache is normally invalidated through the HMR channel, which is disabled here\n    server.watcher.on('change', (filePath) => {\n      invalidateRunnerFile(runner, filePath)\n    })\n    server.watcher.on('unlink', (filePath) => {\n      invalidateRunnerFile(runner, filePath)\n      // A re-evaluation overwrites the compiler caches on change, but nothing re-evaluates a\n      // deleted module - prune its entries so e.g. `getAllCss()` stops serving its CSS\n      onFileRemoved(filePath)\n    })\n  }\n\n  return {server, runner}\n}\n\n/** @public */\nexport function createCompiler({\n  root,\n  identifiers = 'debug',\n  cssImportSpecifier = (filePath) => `${filePath}.vanilla.css`,\n  viteConfig = {},\n  enableFileWatcher = true,\n}: CreateCompilerOptions): Compiler {\n  const processVanillaFileCache = new Map<\n    string,\n    {lastInvalidationTimestamp: number; result: ProcessedVanillaFile}\n  >()\n\n  const cssCache = new NormalizedMap<{css: string}>(root)\n  const classRegistrationsByModuleId = new NormalizedMap<{\n    localClassNames: Set<string>\n    composedClassLists: Composition[]\n  }>(root)\n\n  const serverPromise = createCompilerServer({\n    root,\n    identifiers,\n    viteConfig,\n    enableFileWatcher,\n    onFileRemoved(filePath) {\n      cssCache.delete(filePath)\n      classRegistrationsByModuleId.delete(filePath)\n      const moduleId = normalizePath(filePath)\n      for (const cacheKey of processVanillaFileCache.keys()) {\n        if (cacheKey.startsWith(`${moduleId}|`)) {\n          processVanillaFileCache.delete(cacheKey)\n        }\n      }\n    },\n  })\n\n  return {\n    async processVanillaFile(filePath, options = {}) {\n      const {server, runner} = await serverPromise\n\n      filePath = normalizePath(isAbsolute(filePath) ? filePath : join(root, filePath))\n      const outputCss = options.outputCss ?? true\n      const moduleGraph = server.environments.ssr.moduleGraph\n\n      const cacheKey = `${filePath}|outputCss=${outputCss}`\n      const cachedFile = processVanillaFileCache.get(cacheKey)\n      if (cachedFile) {\n        const moduleNode = moduleGraph.getModuleById(normalizePath(filePath))\n        if (cachedFile.lastInvalidationTimestamp === moduleNode?.lastInvalidationTimestamp) {\n          return cachedFile.result\n        }\n      }\n\n      const cssByModuleId = new NormalizedMap<Css[]>(root)\n      const localClassNames = new Set<string>()\n      const composedClassLists: Composition[] = []\n\n      const cssAdapter: Adapter = {\n        getIdentOption: () => identifiers,\n        onBeginFileScope: (fileScope) => {\n          // Before evaluating a file, reset the cache for it\n          const moduleId = normalizePath(fileScope.filePath)\n          cssByModuleId.set(moduleId, [])\n          classRegistrationsByModuleId.set(moduleId, {\n            localClassNames: new Set(),\n            composedClassLists: [],\n          })\n        },\n        onEndFileScope: (fileScope) => {\n          // Ensure the cache is populated even for files without any CSS, so `cssDeps` below\n          // can tell \"processed, no styles\" apart from \"never processed\"\n          const moduleId = normalizePath(fileScope.filePath)\n          cssByModuleId.set(moduleId, cssByModuleId.get(moduleId) ?? [])\n        },\n        registerClassName: (className, fileScope) => {\n          if (!fileScope) {\n            throw new Error(\n              'Your version of @vanilla-extract/css must be at least v1.10.0. Please update to a compatible version.',\n            )\n          }\n          localClassNames.add(className)\n          classRegistrationsByModuleId.get(fileScope.filePath)?.localClassNames.add(className)\n        },\n        registerComposition: (composedClassList, fileScope) => {\n          if (!fileScope) {\n            throw new Error(\n              'Your version of @vanilla-extract/css must be at least v1.10.0. Please update to a compatible version.',\n            )\n          }\n          composedClassLists.push(composedClassList)\n          classRegistrationsByModuleId\n            .get(fileScope.filePath)\n            ?.composedClassLists.push(composedClassList)\n        },\n        markCompositionUsed: () => {\n          // This compiler currently retains all composition classes\n        },\n        appendCss: (css, fileScope) => {\n          const moduleId = normalizePath(fileScope.filePath)\n          const cssObjs = cssByModuleId.get(moduleId) ?? []\n          cssObjs.push(css)\n          cssByModuleId.set(moduleId, cssObjs)\n        },\n      }\n\n      const {fileExports, cssImports, watchFiles, lastInvalidationTimestamp} = await lock(\n        async () => {\n          globalAdapterStore[GLOBAL_ADAPTER_KEY] = cssAdapter\n          let evaluatedExports: Record<string, unknown>\n          try {\n            evaluatedExports = await runner.import<Record<string, unknown>>(filePath)\n          } finally {\n            delete globalAdapterStore[GLOBAL_ADAPTER_KEY]\n          }\n\n          const moduleId = normalizePath(filePath)\n          const moduleNode = moduleGraph.getModuleById(moduleId)\n          if (!moduleNode) {\n            throw new Error(`[vanilla-extract] Can't find module for ${filePath}`)\n          }\n\n          const collectedCssImports: string[] = []\n          const orderedComposedClassLists: Composition[] = []\n\n          const scanModule = createModuleScanner()\n          const {cssDeps, watchFiles: scannedWatchFiles} = scanModule(moduleNode)\n\n          for (const cssDep of cssDeps) {\n            const cssDepModuleId = normalizePath(cssDep)\n            const cssObjs = cssByModuleId.get(cssDepModuleId)\n            const cachedCss = cssCache.get(cssDepModuleId)\n            const cachedClassRegistrations = classRegistrationsByModuleId.get(cssDepModuleId)\n\n            if (cachedClassRegistrations) {\n              orderedComposedClassLists.push(...cachedClassRegistrations.composedClassLists)\n            }\n\n            if (!cssObjs && !cachedCss && !cachedClassRegistrations) {\n              continue\n            }\n\n            if (cssObjs) {\n              // The dependency was (re-)evaluated during this compilation: transform its CSS\n              const cssRules =\n                cssObjs.length > 0\n                  ? transformCss({\n                      localClassNames: [...localClassNames],\n                      composedClassLists: orderedComposedClassLists,\n                      cssObjs,\n                    })\n                  : []\n              cssCache.set(cssDepModuleId, {css: cssRules.join('\\n')})\n            } else if (cachedClassRegistrations) {\n              // The dependency was served from the runner's cache: replay its class\n              // registrations so compositions in downstream files keep resolving\n              for (const localClassName of cachedClassRegistrations.localClassNames) {\n                localClassNames.add(localClassName)\n              }\n              composedClassLists.push(...cachedClassRegistrations.composedClassLists)\n            }\n\n            const {css = ''} = cssCache.get(cssDepModuleId) ?? {}\n\n            // Check the transformed CSS, not `cssObjs.length`: a module can register CSS\n            // objects that transform to nothing (e.g. `recipe()` calls `style({})` for a\n            // default base class). Emitting an import for empty CSS leaves a dangling virtual\n            // module that bundlers fail to resolve.\n            if (css) {\n              collectedCssImports.push(`import '${cssImportSpecifier(cssDepModuleId)}';`)\n            }\n          }\n\n          return {\n            fileExports: evaluatedExports,\n            cssImports: outputCss ? collectedCssImports : [],\n            watchFiles: scannedWatchFiles,\n            lastInvalidationTimestamp: moduleNode.lastInvalidationTimestamp,\n          }\n        },\n      )\n\n      const result: ProcessedVanillaFile = {\n        source: serializeVanillaModule(\n          cssImports,\n          fileExports,\n          null, // This compiler currently retains all composition classes\n        ),\n        watchFiles,\n      }\n\n      processVanillaFileCache.set(cacheKey, {lastInvalidationTimestamp, result})\n\n      return result\n    },\n\n    getCssForFile(filePath) {\n      filePath = isAbsolute(filePath) ? filePath : join(root, filePath)\n      const result = cssCache.get(normalizePath(filePath))\n      if (!result) return undefined\n      return {css: result.css, filePath}\n    },\n\n    getAllCss() {\n      let allCss = ''\n      for (const {css} of cssCache.values()) {\n        if (css) allCss += `${css}\\n`\n      }\n      return allCss\n    },\n\n    async findImporterTree(filePath, transformedVanillaModules) {\n      const {server} = await serverPromise\n\n      // The compiler's module graph is always a subset of the consuming dev server's module\n      // graph, so this early exit is hit for any module unrelated to vanilla-extract\n      const moduleNode = server.environments.ssr.moduleGraph.getModuleById(normalizePath(filePath))\n      if (!moduleNode) return new Set()\n\n      return findImporterTree(moduleNode, transformedVanillaModules)\n    },\n\n    async invalidateAllModules() {\n      const {server, runner} = await serverPromise\n\n      for (const [id, node] of runner.evaluatedModules.idToModuleMap) {\n        if (!id.includes('node_modules')) {\n          runner.evaluatedModules.invalidateModule(node)\n        }\n      }\n\n      const moduleGraph = server.environments.ssr.moduleGraph\n      for (const [id, moduleNode] of moduleGraph.idToModuleMap) {\n        if (!id.includes('node_modules')) {\n          moduleGraph.invalidateModule(moduleNode)\n        }\n      }\n    },\n\n    async close() {\n      const {server} = await serverPromise\n      await server.close()\n    },\n  }\n}\n\nfunction findImporterTree(\n  moduleNode: EnvironmentModuleNode,\n  transformedVanillaModules: ReadonlySet<string>,\n  visited = new Set<string>(),\n): Set<EnvironmentModuleNode> {\n  const result = new Set<EnvironmentModuleNode>()\n  if (!moduleNode.id || visited.has(moduleNode.id)) {\n    return result\n  }\n\n  // Include the starting module in the tree\n  result.add(moduleNode)\n  visited.add(moduleNode.id)\n\n  // Stop at processed vanilla-extract modules: they're a boundary that doesn't need to be\n  // invalidated past\n  if (transformedVanillaModules.has(moduleNode.id)) {\n    return result\n  }\n\n  for (const importer of moduleNode.importers) {\n    for (const mod of findImporterTree(importer, transformedVanillaModules, visited)) {\n      result.add(mod)\n    }\n  }\n\n  return result\n}\n","/**\n * Module id normalization ported from `@vanilla-extract/vite-plugin`\n * (MIT licensed, Copyright (c) 2021 SEEK).\n */\nimport {posix} from 'node:path'\nimport {normalizePath} from '@sanity/vanilla-extract-integration'\n\n// Vite wraps module ids that aren't valid browser import specifiers with\n// `/@id/` in dev mode. The leading slash is sometimes already stripped.\nconst viteIdPrefix = /^\\/?@id\\//\n\n// Vite emits posix separators and sometimes prefixes a Windows drive letter\n// with a slash, e.g. a resolved id like `/C:/...`.\nconst slashPrefixedDrive = /^\\/([a-zA-Z]:\\/)/\n\n// A Windows drive path (`C:/...`) is unambiguously a real absolute path\n// unlike a posix `/...` path, which may be an SSR root-relative id.\nconst windowsAbsolutePathRegex = /^[a-zA-Z]:\\//\n\nconst isWindowsAbsolutePath = (filePath: string) => windowsAbsolutePathRegex.test(filePath)\n\nconst isAbsolutePath = (filePath: string) =>\n  posix.isAbsolute(filePath) || isWindowsAbsolutePath(filePath)\n\n/** Strip Vite's `@id/` wrapper and any slash it prefixes onto a Windows drive. */\nfunction unwrapViteId(id: string): string {\n  const unwrapped = id.replace(viteIdPrefix, '').replace(slashPrefixedDrive, '$1')\n\n  // If unwrapping didn't yield an absolute path, the `@id/` prefix wasn't a\n  // path wrapper, so keep the original id.\n  return isAbsolutePath(unwrapped) ? unwrapped : id\n}\n\n/**\n * Resolves the absolute filesystem path behind a Vite module id: unwraps the dev-server `@id/`\n * wrapper, keeps real absolute paths (including Windows drive paths and monorepo paths outside\n * `root`), and joins SSR root-relative ids (`/app/styles.css.ts`) onto `root`.\n * @internal\n */\nexport function getAbsoluteId({filePath, root}: {filePath: string; root: string}): string {\n  const resolvedId = unwrapViteId(filePath)\n\n  if (\n    // A Windows drive path is always a real absolute path.\n    isWindowsAbsolutePath(resolvedId) ||\n    resolvedId.startsWith(root) ||\n    // In monorepos the absolute path is outside of `root`, so we check they\n    // share a filesystem root. Vite paths always use posix separators.\n    (posix.isAbsolute(resolvedId) && resolvedId.split(posix.sep)[1] === root.split(posix.sep)[1])\n  ) {\n    return normalizePath(resolvedId)\n  }\n\n  // In SSR mode we can have root-relative paths like `/app/styles.css.ts`. Note that unlike\n  // `posix.resolve`, `posix.join` concatenates even when the second segment starts with `/`:\n  // `posix.join('/root', '/app/styles.css.ts')` is `/root/app/styles.css.ts`.\n  return normalizePath(posix.join(root, resolvedId))\n}\n","/**\n * A Vite 8 plugin for vanilla-extract: a port of `@vanilla-extract/vite-plugin` (MIT licensed,\n * Copyright (c) 2021 SEEK) with plugin hook filters, the environment-aware `hotUpdate` hook,\n * and a caching compiler on Vite's Environment API / `ModuleRunner` instead of `vite-node`.\n */\nimport {\n  cssFileFilter,\n  normalizePath,\n  type IdentifierOption,\n} from '@sanity/vanilla-extract-integration'\nimport {\n  loadConfigFromFile,\n  type ConfigEnv,\n  type EnvironmentModuleNode,\n  type Plugin,\n  type PluginOption,\n  type ResolvedConfig,\n  type TransformResult,\n  type UserConfig,\n} from 'vite'\nimport {createCompiler, type Compiler} from './compiler.ts'\nimport {getAbsoluteId} from './ids.ts'\n\nexport {createCompiler} from './compiler.ts'\nexport type {Compiler, CreateCompilerOptions, ProcessedVanillaFile} from './compiler.ts'\n\nconst PLUGIN_NAMESPACE = 'sanity-vanilla-extract'\n\nconst virtualExtCss = '.vanilla.css'\n\nconst isVirtualId = (id: string) => id.endsWith(virtualExtCss)\nconst fileIdToVirtualId = (id: string) => `${id}${virtualExtCss}`\nconst virtualIdToFileId = (virtualId: string) => virtualId.slice(0, -virtualExtCss.length)\n\n/**\n * Matches `.css.ts` (and sibling extensions) module ids, tolerating id queries (`?t=…` after an\n * HMR invalidation, `?v=…` for optimized ids) that the query-less `cssFileFilter` of\n * `@sanity/vanilla-extract-integration` would reject. The handlers still test the\n * query-stripped id against `cssFileFilter` itself.\n */\nconst CSS_FILE_ID_FILTER = /\\.css\\.(js|cjs|mjs|jsx|ts|tsx)(\\?|$)/\n\n/** Matches the ids of the virtual CSS modules emitted by the compiler, with or without query. */\nconst VIRTUAL_CSS_ID_FILTER = /\\.vanilla\\.css(\\?|$)/\n\nconst isPluginObject = (plugin: PluginOption): plugin is Plugin =>\n  typeof plugin === 'object' && plugin !== null && 'name' in plugin\n\n/**\n * Flattens arbitrarily nested `PluginOption` arrays (presets return plugin groups) into plain\n * plugin objects; falsy entries and promises are dropped, like upstream.\n */\nfunction flattenPluginObjects(option: PluginOption): Plugin[] {\n  if (Array.isArray(option)) return option.flatMap(flattenPluginObjects)\n  return isPluginObject(option) ? [option] : []\n}\n\n/**\n * Decides which of the consumer's Vite plugins are forwarded to the internal compiler server\n * that evaluates the `.css.ts` modules.\n * @public\n */\nexport type PluginFilter = (filterProps: {\n  /** The name of the plugin. */\n  name: string\n  /**\n   * The `mode` Vite is running in.\n   * @see https://vite.dev/guide/env-and-mode.html#modes\n   */\n  mode: string\n}) => boolean\n\n/**\n * Options for {@link vanillaExtractPlugin}.\n * @public\n */\nexport interface Options {\n  /**\n   * Different formatting of identifiers (e.g. class names, keyframes, CSS Vars, etc).\n   * @defaultValue `'short'` when `mode` is `'production'`, `'debug'` otherwise\n   */\n  identifiers?: IdentifierOption\n  /**\n   * Which of the consumer's Vite plugins are re-instantiated inside the compiler server that\n   * evaluates the `.css.ts` modules. By default **no** plugins are forwarded (and the\n   * filtering work is skipped entirely) — most plugins don't affect `.css.ts` evaluation, and\n   * forwarding them would run every transform twice. Vite's own options (including the\n   * built-in\n   * [`resolve.tsconfigPaths`](https://vite.dev/config/shared-options#resolve-tsconfigpaths),\n   * which replaces the `vite-tsconfig-paths` plugin on Vite 8) still apply to the compiler\n   * server through the forwarded config.\n   */\n  pluginFilter?: PluginFilter\n  /**\n   * How the extracted CSS reaches the page during development:\n   *\n   * - `'emitCss'` (the default) serves each `.css.ts` module's CSS as a virtual `.vanilla.css`\n   *   module through Vite's CSS pipeline.\n   * - `'inlineCssInDev'` additionally inlines all extracted CSS into a `<style>` tag in the\n   *   served HTML, preventing a flash of unstyled content in dev SSR setups where the virtual\n   *   CSS modules only load client-side.\n   *\n   * Builds behave the same in both modes.\n   * @defaultValue 'emitCss'\n   */\n  mode?: 'emitCss' | 'inlineCssInDev'\n}\n\n/**\n * A Vite 8 plugin that compiles vanilla-extract `.css.ts` modules and feeds their CSS into\n * Vite's own CSS pipeline (PostCSS, code-splitting, HMR, SSR) as virtual `.vanilla.css`\n * modules — the application-side counterpart to the library-build extraction of\n * `@sanity/vanilla-extract-rolldown-plugin`.\n *\n * Compared to `@vanilla-extract/vite-plugin` it declares\n * [plugin hook filters](https://vite.dev/guide/rolldown#hook-filter-feature) on its\n * `transform`/`resolveId`/`load` hooks (so rolldown-based Vite skips the Rust ↔ JS roundtrip\n * for unrelated modules, see\n * [vanilla-extract#1641](https://github.com/vanilla-extract-css/vanilla-extract/issues/1641)),\n * uses the environment-aware `hotUpdate` hook, and evaluates `.css.ts` modules through a\n * caching compiler built on Vite's Environment API / `ModuleRunner` instead of the legacy\n * `vite-node`.\n * @public\n */\nexport function vanillaExtractPlugin({\n  identifiers,\n  pluginFilter,\n  mode = 'emitCss',\n}: Options = {}): Plugin[] {\n  let config: ResolvedConfig\n  let configEnv: ConfigEnv\n  let isBuild: boolean\n  let compiler: Compiler | undefined\n  let compilerReady: Promise<void> | undefined\n\n  /** Normalized ids of the `.css.ts` modules processed so far (vanilla-extract boundaries). */\n  const transformedModules = new Set<string>()\n\n  const getIdentOption = () => identifiers ?? (config.mode === 'production' ? 'short' : 'debug')\n\n  const initializeCompiler = async () => {\n    let configForCompiler: UserConfig | undefined\n\n    if (config.configFile) {\n      // The user has a vite config file: re-load it to get fresh plugin instances for the\n      // compiler server (plugin objects are stateful and can't be shared between servers)\n      const configFile = await loadConfigFromFile(\n        {\n          command: config.command,\n          mode: config.mode,\n          isSsrBuild: configEnv.isSsrBuild,\n        },\n        config.configFile,\n      )\n      configForCompiler = configFile?.config\n    } else {\n      // The user is using a vite-based framework that has a custom config file\n      configForCompiler = config.inlineConfig\n    }\n\n    // Without a `pluginFilter`, no consumer plugins are re-instantiated in the compiler\n    // server, and the flatten/filter work is skipped entirely. Vite's own options — including\n    // the built-in `resolve.tsconfigPaths`, which replaces the `vite-tsconfig-paths` plugin on\n    // Vite 8 — still apply through the forwarded config.\n    const viteConfig = {\n      ...configForCompiler,\n      plugins: pluginFilter\n        ? flattenPluginObjects(configForCompiler?.plugins ?? [])\n            // Never forward this plugin itself into its own compiler server\n            .filter((plugin) => !plugin.name.startsWith(PLUGIN_NAMESPACE))\n            .filter((plugin) => pluginFilter({name: plugin.name, mode: config.mode}))\n        : undefined,\n    }\n\n    compiler = createCompiler({\n      root: config.root,\n      identifiers: getIdentOption(),\n      cssImportSpecifier: fileIdToVirtualId,\n      viteConfig,\n      enableFileWatcher: !isBuild,\n    })\n  }\n\n  /**\n   * Lazily creates the compiler, memoizing the initialization promise. `buildStart` kicks this\n   * off eagerly, but `transform` also awaits it: `transform` can run before `buildStart` has\n   * finished when another plugin emits an additional entry whose module graph is transformed\n   * concurrently.\n   */\n  const ensureCompiler = () => {\n    compilerReady ??= initializeCompiler()\n    return compilerReady\n  }\n\n  /**\n   * Virtual `*.vanilla.css` modules are only populated after the parent `.css.ts` has been\n   * `processVanillaFile`'d. That normally happens in `transform`, but Vite can serve the parent\n   * without re-running `transform` (notably 304 Not Modified after a server restart with a warm\n   * browser cache), leaving the compiler CSS cache empty when the virtual module is requested.\n   * On miss, process the parent so virtual CSS is self-sufficient.\n   *\n   * Ported from `@vanilla-extract/vite-plugin` 5.2.6\n   * ([vanilla-extract#1776](https://github.com/vanilla-extract-css/vanilla-extract/pull/1776)).\n   * Adapted for this fork's soft-read `getCssForFile` (returns `undefined` on miss instead of\n   * throwing).\n   *\n   * Always goes through {@link Compiler.processVanillaFile} for real `.css.ts` parents rather\n   * than short-circuiting on a warm `getCssForFile` hit: `processVanillaFile` is\n   * invalidation-aware and refreshes the CSS cache when a shared dependency changed. After a\n   * cache-miss populate the parent was never `transform`ed in the consuming server (so\n   * `addWatchFile` never wired dependency edits back to a retransform), and returning the\n   * stale cache entry would keep serving outdated virtual CSS across HMR.\n   */\n  const ensureCssForVirtualId = async (absoluteVirtualId: string): Promise<string | null> => {\n    const fileId = virtualIdToFileId(absoluteVirtualId)\n\n    // Authored `.vanilla.css` files aren't vanilla-extract parents — don't spin up the compiler\n    // for them. Only serve if a previous compilation already put CSS in the cache.\n    if (!cssFileFilter.test(fileId)) {\n      if (!compiler) return null\n      return compiler.getCssForFile(fileId)?.css || null\n    }\n\n    await ensureCompiler()\n    if (!compiler) return null\n\n    await compiler.processVanillaFile(fileId, {outputCss: true})\n    // Same absolute id the `transform` path records, so `hotUpdate`'s `findImporterTree`\n    // boundary check matches after a cache-miss populate\n    transformedModules.add(fileId)\n    return compiler.getCssForFile(fileId)?.css || null\n  }\n\n  return [\n    {\n      name: `${PLUGIN_NAMESPACE}-inline-dev-css`,\n      apply: (_config, {command}) => command === 'serve' && mode === 'inlineCssInDev',\n      transformIndexHtml: () => {\n        // Intentionally no `ensureCompiler()` here: an uninitialized compiler means no\n        // `.css.ts` module has been transformed yet, so a freshly-created one would have no\n        // CSS to inline either. In the dev SSR flows this mode exists for, module evaluation\n        // (during render) precedes the HTML transform, so the CSS is already collected - and\n        // the un-inlined fallback is Vite's own CSS pipeline, not missing styles.\n        const allCss = compiler?.getAllCss()\n        if (!allCss) return []\n        return [\n          {\n            tag: 'style',\n            children: allCss,\n            attrs: {\n              'type': 'text/css',\n              'data-vanilla-extract-inline-dev-css': true,\n            },\n            injectTo: 'head-prepend',\n          },\n        ]\n      },\n    },\n    {\n      name: PLUGIN_NAMESPACE,\n\n      config(_userConfig, env) {\n        configEnv = env\n        return {\n          ssr: {\n            // The evaluated `.css.ts` modules must share the project's `@vanilla-extract/*`\n            // instances with the compiler, so keep them external in SSR environments\n            external: [\n              '@vanilla-extract/css',\n              '@vanilla-extract/css/fileScope',\n              '@vanilla-extract/css/adapter',\n            ],\n          },\n        }\n      },\n\n      configResolved(resolvedConfig) {\n        config = resolvedConfig\n        isBuild = config.command === 'build' && !config.build.watch\n      },\n\n      configureServer(server) {\n        server.watcher.on('unlink', (file) => {\n          transformedModules.delete(normalizePath(file))\n        })\n        // Close the compiler (and with it its internal Vite server and file watcher) when the\n        // dev server shuts down. This is the only shutdown signal under bundled dev mode,\n        // where `buildEnd` must not close the compiler (see below) and environment close\n        // skips the plugin container; without it the lingering handles keep the process\n        // alive after `server.close()`. In unbundled dev `buildEnd` also fires on shutdown —\n        // closing twice is harmless.\n        server.httpServer?.once('close', () => {\n          void compiler?.close()\n        })\n      },\n\n      async buildStart() {\n        // Ensure the compiler instance is re-used between builds, e.g. in watch mode\n        await ensureCompiler()\n      },\n\n      buildEnd() {\n        // `buildEnd` fires at different times per pipeline: after a one-shot build, after\n        // every rebuild in watch mode (where the compiler outlives builds and `closeWatcher`\n        // closes it), when the plugin container closes on dev-server shutdown (unbundled\n        // dev) — and, under Vite's experimental bundled dev mode\n        // (`experimental.bundledDev`, e.g. `sanity dev` with `unstable_bundledDev`), already\n        // when the initial in-server bundle finishes, while the server keeps serving and\n        // compiles lazy chunks on demand. Closing the compiler there tears down the\n        // hot-channel invoke listeners its `ModuleRunner` transport depends on, so the next\n        // `processVanillaFile` (the first `.css.ts`-matching module in an on-demand chunk)\n        // would hang in `fetchModule` until the 60s transport timeout and crash the dev\n        // server — see the bundled-dev test of `@integration/vanilla-extract-studio`.\n        const isServingBundledDev =\n          config.command === 'serve' && (config.experimental?.bundledDev ?? false)\n        if (!config.build.watch && !isServingBundledDev) {\n          void compiler?.close()\n        }\n      },\n\n      closeWatcher() {\n        return compiler?.close()\n      },\n\n      transform: {\n        filter: {id: CSS_FILE_ID_FILTER},\n        async handler(_code, id, options) {\n          const [validId = id] = id.split('?')\n          if (!cssFileFilter.test(validId)) return null\n\n          // `transform` can run before `buildStart` has finished creating the compiler;\n          // `ensureCompiler` is memoized, so this is a no-op once the compiler exists\n          await ensureCompiler()\n          if (!compiler) return null\n\n          const absoluteId = getAbsoluteId({filePath: validId, root: config.root})\n\n          const {source, watchFiles} = await compiler.processVanillaFile(absoluteId, {\n            outputCss: true,\n          })\n\n          // Store the same absolute id the compiler's module graph uses (`validId` may be\n          // root-relative in SSR or `/@id/`-wrapped), so the `findImporterTree` boundary\n          // check in `hotUpdate` matches\n          transformedModules.add(absoluteId)\n\n          const result: TransformResult = {\n            code: source,\n            map: {mappings: ''},\n          }\n\n          // Watching files and invalidating modules only matters for the dev client pipeline\n          if (isBuild || options?.ssr) {\n            return result\n          }\n\n          for (const file of watchFiles) {\n            if (!file.includes('node_modules') && normalizePath(file) !== absoluteId) {\n              this.addWatchFile(file)\n            }\n          }\n\n          return result\n        },\n      },\n\n      // The compiler's module graph is always a subset of the consuming dev server's module\n      // graph, so the early exit is hit for any file unrelated to vanilla-extract modules.\n      // Fires once per environment; each invalidates the virtual CSS modules of its own graph.\n      async hotUpdate({file, timestamp}) {\n        if (!compiler) return\n\n        const importerChain = await compiler.findImporterTree(\n          normalizePath(file),\n          transformedModules,\n        )\n        if (importerChain.size === 0) return\n\n        const {moduleGraph} = this.environment\n        const seen = new Set<EnvironmentModuleNode>()\n\n        for (const mod of importerChain) {\n          if (!mod.id) continue\n          if (cssFileFilter.test(mod.id)) {\n            // A vanilla-extract module: its CSS lives in the virtual module, invalidate that\n            for (const virtualModule of moduleGraph.getModulesByFile(fileIdToVirtualId(mod.id)) ??\n              []) {\n              moduleGraph.invalidateModule(virtualModule, seen, timestamp, true)\n            }\n          } else {\n            // `mod` is from the compiler's own module graph: look up the corresponding module\n            // in this environment's graph by id\n            const environmentModule = moduleGraph.getModuleById(mod.id)\n            if (environmentModule) {\n              moduleGraph.invalidateModule(environmentModule, seen, timestamp, true)\n            }\n          }\n        }\n      },\n\n      resolveId: {\n        filter: {id: VIRTUAL_CSS_ID_FILTER},\n        async handler(source) {\n          const [validId = source, query] = source.split('?')\n          if (!isVirtualId(validId)) return undefined\n\n          const absoluteId = getAbsoluteId({filePath: validId, root: config.root})\n          const css = await ensureCssForVirtualId(absoluteId)\n          if (!css) return undefined\n\n          // Keep the original query string for HMR\n          return absoluteId + (query ? `?${query}` : '')\n        },\n      },\n\n      load: {\n        filter: {id: VIRTUAL_CSS_ID_FILTER},\n        async handler(id) {\n          const [validId = id] = id.split('?')\n          if (!isVirtualId(validId)) return undefined\n\n          const absoluteId = getAbsoluteId({filePath: validId, root: config.root})\n          const css = await ensureCssForVirtualId(absoluteId)\n          if (!css) return undefined\n\n          // Vite's CSS pipeline owns the module from here (PostCSS, minification,\n          // code-splitting, HMR style injection)\n          return css\n        },\n      },\n    },\n  ]\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAI,QAA0B,QAAQ,QAAQ;AAE9C,SAAgB,KAAQ,IAAkC;CACxD,IAAM,SAAS,MAAM,KAAK,EAAE;CAE5B,OADA,QAAQ,OAAO,YAAY,KAAA,CAAS,GAC7B;AACT;;;;;;;;;;;;;;;;;;;;;AC+BA,MAAM,qBAAqB,uCACrB,0BAA0B,cAAc,KAAK,UAAU,kBAAkB,EAAE,IAE3E,qBAAqB;;;;;AAa3B,SAAS,sBAAsB;CAC7B,IAAM,wBAAQ,IAAI,IAA8B,GAE1C,cAAc,YAAmC,OAAiB,CAAC,MAAwB;EAC/F,IAAM,6BAAa,IAAI,IAAY,GAC7B,WAAW,WAAW,MAAM,WAAW;EAE7C,IAAI,CAAC,YAAY,WAAW,IAAI,SAAS,mBAAmB,KAAK,KAAK,SAAS,QAAQ,GACrF,OAAO;GAAC,SAAS,CAAC;GAAG;EAAU;EAGjC,IAAM,SAAS,MAAM,IAAI,QAAQ;EACjC,IAAI,QAAQ,OAAO;EAEnB,MAAM,IAAI,UAAU;GAAC,SAAS,CAAC;GAAG;EAAU,CAAC;EAE7C,IAAM,0BAAU,IAAI,IAAY,GAC1B,cAAc,CAAC,GAAG,MAAM,QAAQ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