{"version":3,"file":"vite-plugin.es.mjs","names":[],"sources":["../src/vitePlugin/prefix.ts","../src/vitePlugin/scssTransformer.ts","../src/vite-plugin.ts"],"sourcesContent":["import crypto from 'crypto'\nimport fs from 'fs'\nimport path from 'path'\nimport type { UserConfig } from 'vite'\n\n/**\n * Generates a short, unique prefix based on the package name.\n * Optionally incorporates a seed to differentiate prefixes per build target.\n * Falls back to a random hash if package.json can't be read and no seed is provided.\n * @param {string} projectRoot - The root directory of the project.\n * @param {string | undefined} seed - Optional seed to salt the hash.\n * @returns {string} A unique 6-character prefix.\n */\nexport const generateUniquePrefix = (\n  projectRoot: string,\n  seed?: string,\n): string => {\n  try {\n    const packageJsonPath = path.resolve(projectRoot, 'package.json')\n    const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n    const packageName = packageJson.name || 'unknown'\n\n    const hashInput = seed ? `${packageName}::${seed}` : packageName\n\n    // Create a hash from the package name (and optional seed)\n    const hash = crypto.createHash('md5').update(hashInput).digest('hex')\n\n    // Return first 6 characters for a short but unique prefix\n    return `d${hash.substring(0, 5)}`\n  } catch {\n    if (seed) {\n      const hash = crypto.createHash('md5').update(seed).digest('hex')\n      return `d${hash.substring(0, 5)}`\n    }\n\n    // Fallback to random if package.json can't be read\n    return `d${crypto.randomBytes(3).toString('hex').substring(0, 5)}`\n  }\n}\n\n/**\n * Derives a stable seed from Vite build configuration to avoid prefix collisions\n * when building multiple widgets from the same project/package name.\n * @param {UserConfig} config - The Vite user config.\n * @returns {string} A stable seed string derived from build output and entry config.\n */\nexport const getAutoSeedFromConfig = (config: UserConfig): string => {\n  const outDir = config.build?.outDir ?? ''\n\n  const lib = config.build?.lib\n  const libEntry =\n    lib && typeof lib === 'object' && 'entry' in lib\n      ? (lib as { entry?: unknown }).entry\n      : undefined\n  const libEntryKey =\n    typeof libEntry === 'string'\n      ? path.basename(libEntry)\n      : libEntry && typeof libEntry === 'object'\n        ? Object.keys(libEntry).sort().join('|')\n        : ''\n\n  const rollupInput = config.build?.rollupOptions?.input\n  const rollupInputKey =\n    typeof rollupInput === 'string'\n      ? path.basename(rollupInput)\n      : Array.isArray(rollupInput)\n        ? rollupInput\n            .map((v) => path.basename(v))\n            .sort()\n            .join('|')\n        : rollupInput && typeof rollupInput === 'object'\n          ? Object.keys(rollupInput).sort().join('|')\n          : ''\n\n  return [outDir, libEntryKey, rollupInputKey].filter(Boolean).join('::')\n}\n","/**\n * Checks if a file is the variables module that defines $prefix.\n * @param {string} filename - The filename to check.\n * @returns {boolean} True if this is the variables module.\n */\nconst isVariablesModule = (filename: string): boolean => {\n  return (\n    filename.includes('_variables.scss') &&\n    (filename.includes('staffbaseDrawer') ||\n      filename.includes('staffbase-drawer'))\n  )\n}\n\n/**\n * Creates an additionalData function that transforms SCSS imports/uses\n * to include the prefix configuration.\n * @param {string} prefix - The prefix to inject.\n * @returns {(source: string, filename: string) => string} A function compatible with Vite's additionalData option.\n */\nexport const createAdditionalDataTransformer = (prefix: string) => {\n  /**\n   * Transform SCSS content to inject prefix configuration.\n   * For the variables module, replaces the default prefix value directly.\n   * For entry points, transforms `@forward` statements to use the configured prefix.\n   * For consumer files, transforms `@use`/`@import` statements for the package.\n   * @param {string} source - The SCSS source content.\n   * @param {string} filename - The filename being processed.\n   * @returns {string} The transformed SCSS content.\n   */\n  return (source: string, filename: string): string => {\n    // Skip non-SCSS files\n    if (!filename.endsWith('.scss') && !filename.endsWith('.sass')) {\n      return source\n    }\n\n    let transformed = source\n\n    // For the _variables.scss module itself, replace the default prefix value.\n    // This ensures that when partials do `@use 'variables' as *`, they get\n    // the configured prefix directly from the module.\n    if (isVariablesModule(filename)) {\n      transformed = transformed.replace(\n        /\\$prefix:\\s*['\"][^'\"]*['\"]\\s*!default/,\n        `$prefix: '${prefix}' !default`,\n      )\n    }\n\n    // Pattern to match @forward statements for the drawer's variables\n    // Handles both relative paths (inside the library) and package imports\n    const forwardPattern =\n      /@forward\\s+['\"]([^'\"]*staffbaseDrawer\\/variables|\\.\\/styles\\/staffbaseDrawer\\/variables)['\"]\\s*with\\s*\\(\\s*\\$prefix:\\s*['\"][^'\"]*['\"]\\s*!default\\s*\\)/g\n\n    // Replace @forward ... with ($prefix: 'default' !default) to use the configured prefix\n    transformed = transformed.replace(forwardPattern, (match, modulePath) => {\n      return `@forward '${modulePath}' with ($prefix: '${prefix}' !default)`\n    })\n\n    // Also handle @use statements that configure the main entry point\n    // Pattern: @use '@favish/staffbase-drawer/scss' with ($prefix: ...)\n    const useWithPattern =\n      /@use\\s+['\"](@favish\\/staffbase-drawer(?:\\/scss)?)['\"]\\s*with\\s*\\(\\s*\\$prefix:\\s*['\"][^'\"]*['\"]\\s*\\)/g\n\n    transformed = transformed.replace(useWithPattern, (match, modulePath) => {\n      return `@use '${modulePath}' with ($prefix: '${prefix}')`\n    })\n\n    // Handle @use without with clause (add the configuration)\n    const useWithoutPattern =\n      /@use\\s+['\"](@favish\\/staffbase-drawer(?:\\/scss)?)['\"]\\s*;/g\n\n    transformed = transformed.replace(\n      useWithoutPattern,\n      `@use '$1' with ($prefix: '${prefix}');`,\n    )\n\n    // Handle legacy @import statements (convert to @use with configuration)\n    const importPattern =\n      /@import\\s+['\"](@favish\\/staffbase-drawer(?:\\/scss)?)['\"]\\s*;/g\n\n    transformed = transformed.replace(\n      importPattern,\n      `@use '$1' with ($prefix: '${prefix}');`,\n    )\n\n    return transformed\n  }\n}\n","import type { Plugin } from 'vite'\nimport {\n  generateUniquePrefix,\n  getAutoSeedFromConfig,\n} from './vitePlugin/prefix'\nimport { createAdditionalDataTransformer } from './vitePlugin/scssTransformer'\n\n/**\n * Options for the Staffbase Drawer Vite plugin.\n */\nexport interface StaffbaseDrawerPluginOptions {\n  /**\n   * Custom prefix for drawer class names.\n   * If not provided, a unique prefix will be auto-generated based on your package name.\n   */\n  prefix?: string\n\n  /**\n   * Optional seed to make the auto-generated prefix unique per build target.\n   *\n   * Useful when you build multiple widgets from the same repository (same `package.json` name)\n   * and need different prefixes per widget build.\n   *\n   * If omitted, the plugin will try to derive a stable seed from build config (e.g. outDir/entry).\n   */\n  seed?: string\n}\n\n/**\n * Vite plugin for Staffbase Drawer that auto-configures unique class prefixes.\n *\n * This plugin automatically generates a unique prefix for your widget to prevent\n * CSS collisions when multiple widgets use the drawer on the same page.\n * @example\n * ```ts\n * // vite.config.ts\n * import { staffbaseDrawer } from '@favish/staffbase-drawer/vite-plugin'\n *\n * export default defineConfig({\n *   plugins: [\n *     react(),\n *     staffbaseDrawer()  // Auto-generates unique prefix\n *   ]\n * })\n * ```\n * @example\n * ```ts\n * // With custom prefix\n * staffbaseDrawer({ prefix: 'mywidget' })\n * ```\n * @param {StaffbaseDrawerPluginOptions} options - Plugin options.\n * @returns {Plugin} Vite plugin configuration.\n */\nexport const staffbaseDrawer = (\n  options: StaffbaseDrawerPluginOptions = {},\n): Plugin => {\n  let resolvedPrefix: string\n\n  return {\n    name: 'staffbase-drawer',\n    enforce: 'pre',\n\n    config(config, { command }) {\n      // Get project root\n      const root = config.root || process.cwd()\n\n      // Use provided prefix or auto-generate one\n      const autoSeed = options.seed ?? getAutoSeedFromConfig(config)\n      resolvedPrefix =\n        options.prefix || generateUniquePrefix(root, autoSeed || undefined)\n\n      // Log the prefix being used (helpful for debugging)\n      if (command === 'build') {\n        const seedMsg = autoSeed ? ` (seed: \"${autoSeed}\")` : ''\n        console.info(\n          `[staffbase-drawer] Using prefix: \"${resolvedPrefix}\"${seedMsg}`,\n        )\n      }\n\n      // Get existing additionalData if any\n      const existingAdditionalData =\n        config.css?.preprocessorOptions?.scss?.additionalData\n\n      // Create the transformer function\n      const transformer = createAdditionalDataTransformer(resolvedPrefix)\n\n      /**\n       * Combines existing additionalData with our transformer.\n       * @param {string} source - The SCSS source content.\n       * @param {string} filename - The filename being processed.\n       * @returns {string} The transformed SCSS content.\n       */\n      const combinedAdditionalData = (\n        source: string,\n        filename: string,\n      ): string => {\n        // First apply existing additionalData if it's a string\n        let content = source\n        if (typeof existingAdditionalData === 'string') {\n          content = existingAdditionalData + source\n        } else if (typeof existingAdditionalData === 'function') {\n          const result = existingAdditionalData(source, filename)\n          // Handle both string and object return types\n          if (typeof result === 'string') {\n            content = result\n          } else if (\n            result &&\n            typeof result === 'object' &&\n            'content' in result\n          ) {\n            content = result.content\n          }\n        }\n\n        // Then apply our transformer\n        return transformer(content, filename)\n      }\n\n      return {\n        define: {\n          ...config.define,\n          __SBAW_PREFIX__: JSON.stringify(resolvedPrefix),\n          'import.meta.env.VITE_SBAW_PREFIX': JSON.stringify(resolvedPrefix),\n        },\n        css: {\n          ...config.css,\n          preprocessorOptions: {\n            ...config.css?.preprocessorOptions,\n            scss: {\n              ...config.css?.preprocessorOptions?.scss,\n              additionalData: combinedAdditionalData,\n            },\n          },\n        },\n      }\n    },\n  }\n}\n\nexport default staffbaseDrawer\n"],"mappings":";;;;AAaA,IAAa,KACX,GACA,MACW;CACX,IAAI;EACF,IAAM,IAAkB,EAAK,QAAQ,GAAa,cAAc,GAE1D,IADc,KAAK,MAAM,EAAG,aAAa,GAAiB,OAAO,CACnD,EAAY,QAAQ,WAElC,IAAY,IAAO,GAAG,EAAY,IAAI,MAAS;EAMrD,OAAO,IAHM,EAAO,WAAW,KAAK,EAAE,OAAO,CAAS,EAAE,OAAO,KAGpD,EAAK,UAAU,GAAG,CAAC;CAChC,QAAQ;EAON,OANI,IAEK,IADM,EAAO,WAAW,KAAK,EAAE,OAAO,CAAI,EAAE,OAAO,KAC/C,EAAK,UAAU,GAAG,CAAC,MAIzB,IAAI,EAAO,YAAY,CAAC,EAAE,SAAS,KAAK,EAAE,UAAU,GAAG,CAAC;CACjE;AACF,GAQa,KAAyB,MAA+B;CACnE,IAAM,IAAS,EAAO,OAAO,UAAU,IAEjC,IAAM,EAAO,OAAO,KACpB,IACJ,KAAO,OAAO,KAAQ,YAAY,WAAW,IACxC,EAA4B,QAC7B,KAAA,GACA,IACJ,OAAO,KAAa,WAChB,EAAK,SAAS,CAAQ,IACtB,KAAY,OAAO,KAAa,WAC9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