{"version":3,"file":"index.mjs","names":["babelParse","path","path","path","path","traverse"],"sources":["../src/component-tagger.ts","../../vite-common/src/dependencies.ts","../../vite-common/src/environment.ts","../../vite-common/src/native-addons.ts","../../vite-common/src/restart-on-install.ts","../src/prebundle.ts","../src/visual-editor/ast-analyzer.ts","../src/visual-editor/ast-transformer.ts","../src/visual-editor/index.ts","../src/index.ts"],"sourcesContent":["import { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { parse as babelParse } from \"@babel/parser\";\n// Named, not default: magic-string is ESM-only, and the CJS build's interop\n// hands require()'s whole namespace back as `default`.\nimport { MagicString } from \"magic-string\";\nimport type { Plugin, Rolldown } from \"vite\";\n\n// Types\nexport interface ComponentTaggerOptions {\n  enabled?: boolean;\n  debug?: boolean;\n  /**\n   * The data attribute to use for element identification\n   * @default \"data-component-id\"\n   */\n  dataAttribute?: string;\n}\n\n// Keep: Three.js Fiber elements that should not be tagged\nconst threeFiberElems = new Set([\n  \"object3D\",\n  \"audioListener\",\n  \"positionalAudio\",\n  \"mesh\",\n  \"batchedMesh\",\n  \"instancedMesh\",\n  \"scene\",\n  \"sprite\",\n  \"lOD\",\n  \"skinnedMesh\",\n  \"skeleton\",\n  \"bone\",\n  \"lineSegments\",\n  \"lineLoop\",\n  \"points\",\n  \"group\",\n  \"camera\",\n  \"perspectiveCamera\",\n  \"orthographicCamera\",\n  \"cubeCamera\",\n  \"arrayCamera\",\n  \"instancedBufferGeometry\",\n  \"bufferGeometry\",\n  \"boxBufferGeometry\",\n  \"circleBufferGeometry\",\n  \"coneBufferGeometry\",\n  \"cylinderBufferGeometry\",\n  \"dodecahedronBufferGeometry\",\n  \"extrudeBufferGeometry\",\n  \"icosahedronBufferGeometry\",\n  \"latheBufferGeometry\",\n  \"octahedronBufferGeometry\",\n  \"planeBufferGeometry\",\n  \"polyhedronBufferGeometry\",\n  \"ringBufferGeometry\",\n  \"shapeBufferGeometry\",\n  \"sphereBufferGeometry\",\n  \"tetrahedronBufferGeometry\",\n  \"torusBufferGeometry\",\n  \"torusKnotBufferGeometry\",\n  \"tubeBufferGeometry\",\n  \"wireframeGeometry\",\n  \"tetrahedronGeometry\",\n  \"octahedronGeometry\",\n  \"icosahedronGeometry\",\n  \"dodecahedronGeometry\",\n  \"polyhedronGeometry\",\n  \"tubeGeometry\",\n  \"torusKnotGeometry\",\n  \"torusGeometry\",\n  \"sphereGeometry\",\n  \"ringGeometry\",\n  \"planeGeometry\",\n  \"latheGeometry\",\n  \"shapeGeometry\",\n  \"extrudeGeometry\",\n  \"edgesGeometry\",\n  \"coneGeometry\",\n  \"cylinderGeometry\",\n  \"circleGeometry\",\n  \"boxGeometry\",\n  \"capsuleGeometry\",\n  \"material\",\n  \"shadowMaterial\",\n  \"spriteMaterial\",\n  \"rawShaderMaterial\",\n  \"shaderMaterial\",\n  \"pointsMaterial\",\n  \"meshPhysicalMaterial\",\n  \"meshStandardMaterial\",\n  \"meshPhongMaterial\",\n  \"meshToonMaterial\",\n  \"meshNormalMaterial\",\n  \"meshLambertMaterial\",\n  \"meshDepthMaterial\",\n  \"meshDistanceMaterial\",\n  \"meshBasicMaterial\",\n  \"meshMatcapMaterial\",\n  \"lineDashedMaterial\",\n  \"lineBasicMaterial\",\n  \"primitive\",\n  \"light\",\n  \"spotLightShadow\",\n  \"spotLight\",\n  \"pointLight\",\n  \"rectAreaLight\",\n  \"hemisphereLight\",\n  \"directionalLightShadow\",\n  \"directionalLight\",\n  \"ambientLight\",\n  \"lightShadow\",\n  \"ambientLightProbe\",\n  \"hemisphereLightProbe\",\n  \"lightProbe\",\n  \"spotLightHelper\",\n  \"skeletonHelper\",\n  \"pointLightHelper\",\n  \"hemisphereLightHelper\",\n  \"gridHelper\",\n  \"polarGridHelper\",\n  \"directionalLightHelper\",\n  \"cameraHelper\",\n  \"boxHelper\",\n  \"box3Helper\",\n  \"planeHelper\",\n  \"arrowHelper\",\n  \"axesHelper\",\n  \"texture\",\n  \"videoTexture\",\n  \"dataTexture\",\n  \"dataTexture3D\",\n  \"compressedTexture\",\n  \"cubeTexture\",\n  \"canvasTexture\",\n  \"depthTexture\",\n  \"raycaster\",\n  \"vector2\",\n  \"vector3\",\n  \"vector4\",\n  \"euler\",\n  \"matrix3\",\n  \"matrix4\",\n  \"quaternion\",\n  \"bufferAttribute\",\n  \"float16BufferAttribute\",\n  \"float32BufferAttribute\",\n  \"float64BufferAttribute\",\n  \"int8BufferAttribute\",\n  \"int16BufferAttribute\",\n  \"int32BufferAttribute\",\n  \"uint8BufferAttribute\",\n  \"uint16BufferAttribute\",\n  \"uint32BufferAttribute\",\n  \"instancedBufferAttribute\",\n  \"color\",\n  \"fog\",\n  \"fogExp2\",\n  \"shape\",\n  \"colorShiftMaterial\",\n]);\n\n// Keep: Check if element should be tagged\nfunction shouldTagElement(\n  elementName: string,\n  importsReactThree: boolean,\n  fiberImports: Set<string>,\n  googleMapsImports: Set<string>,\n): boolean {\n  if (threeFiberElems.has(elementName)) {\n    return false;\n  }\n  // @vis.gl/react-google-maps components never put these attributes in the\n  // DOM, and <Pin> passes every prop to the PinElement constructor, which\n  // throws \"Unknown property 'data-hercules-id'\" and blanks the page.\n  if (googleMapsImports.has(elementName.split(\".\")[0]!)) {\n    return false;\n  }\n  // In a file that imports @react-three/*, any component (a name that is not a\n  // lowercase intrinsic, such as drei or a wrapper spreading props into <mesh>)\n  // may render into the R3F reconciler, which throws on data-* props. Only\n  // fiber's own Canvas renders DOM.\n  if (importsReactThree && !/^[a-z][^.]*$/.test(elementName)) {\n    return fiberImports.has(elementName.split(\".\")[0]!);\n  }\n  return true;\n}\n\n// Constants\nconst validExtensions = new Set([\".jsx\", \".tsx\"]);\n\n// TanStack Router's code splitter loads each route component from a virtual\n// module, `routes/index.tsx?tsr-split=component`, and the module-level bindings\n// the pieces share from `routes/index.tsx?tsr-shared=1`. Both carry the route\n// file's own source, so they are tagged as that file.\nconst routeSplitParams = new Set([\"tsr-split\", \"tsr-shared\"]);\n\n/**\n * The source file a module id is tagged as, or null when the id is not a JSX\n * source file. Ids with any other query (`?raw`, `?url`) are left alone.\n */\nexport function taggableFilePath(id: string): string | null {\n  const queryStart = id.indexOf(\"?\");\n  const filePath = queryStart === -1 ? id : id.slice(0, queryStart);\n  if (queryStart !== -1) {\n    const params = [...new URLSearchParams(id.slice(queryStart + 1)).keys()];\n    if (params.length === 0 || !params.every((param) => routeSplitParams.has(param))) {\n      return null;\n    }\n  }\n  if (!validExtensions.has(path.extname(filePath)) || filePath.includes(\"node_modules\")) {\n    return null;\n  }\n  return filePath;\n}\n\n/**\n * Parses a `.jsx` or `.tsx` module into an ESTree-shaped tree whose nodes carry\n * `start` and `end` as UTF-16 offsets into the code, the indices MagicString\n * and JavaScript strings use. Both parsers below accept TypeScript in either\n * extension, so the two kinds of file are tagged alike.\n */\nexport type ParseModule = (code: string) => unknown;\n\nexport const parseWithBabel: ParseModule = (code) =>\n  babelParse(code, { sourceType: \"module\", plugins: [\"jsx\", \"typescript\"] });\n\n/**\n * The parser Vite already runs. Rolldown (Vite 8) parses TSX with Oxc and\n * reports the same offsets as Babel; Rollup's parser (Vite 7) has no\n * TypeScript support, so Vite 7 keeps Babel.\n */\nfunction parserOf(context: Rolldown.PluginContext): ParseModule {\n  if (!context.meta.rolldownVersion) {\n    return parseWithBabel;\n  }\n  return (code) => context.parse(code, { lang: \"tsx\", sourceType: \"module\" });\n}\n\n/**\n * Turns UTF-16 offsets into 1-based lines and 0-based columns, counting line\n * breaks as JavaScript does (`\\n`, `\\r\\n`, `\\r`, U+2028, U+2029), like Babel's\n * `loc`.\n */\nfunction lineLocator(code: string): (offset: number) => { line: number; col: number } {\n  const lineStarts = [0];\n  for (let i = 0; i < code.length; i++) {\n    const char = code.charCodeAt(i);\n    if (char === 0x0d && code.charCodeAt(i + 1) === 0x0a) {\n      i++;\n      lineStarts.push(i + 1);\n    } else if (char === 0x0a || char === 0x0d || char === 0x2028 || char === 0x2029) {\n      lineStarts.push(i + 1);\n    }\n  }\n  return (offset) => {\n    let low = 0;\n    let high = lineStarts.length - 1;\n    while (low < high) {\n      const mid = (low + high + 1) >> 1;\n      if (lineStarts[mid]! <= offset) {\n        low = mid;\n      } else {\n        high = mid - 1;\n      }\n    }\n    return { line: low + 1, col: offset - lineStarts[low]! };\n  };\n}\n\nfunction openingElementName(node: any): string | null {\n  if (node.name.type === \"JSXIdentifier\") {\n    return node.name.name;\n  }\n  if (node.name.type === \"JSXMemberExpression\") {\n    return `${node.name.object.name}.${node.name.property.name}`;\n  }\n  return null;\n}\n\ninterface ElementPosition {\n  name: string | null;\n  line: number;\n  col: number;\n}\n\n/**\n * The name and start of every JSX opening element in `code`, in walk order.\n */\nasync function openingElementPositions(\n  code: string,\n  parse: ParseModule,\n): Promise<ElementPosition[]> {\n  const ast = parse(code);\n  const locate = lineLocator(code);\n  const { walk } = await import(\"estree-walker\");\n  const positions: ElementPosition[] = [];\n  walk(ast as any, {\n    enter(node: any) {\n      if (node.type === \"JSXOpeningElement\") {\n        positions.push({ name: openingElementName(node), ...locate(node.start) });\n      }\n    },\n  });\n  return positions;\n}\n\n/**\n * Element positions taken from the source file when `code` has the same JSX\n * elements in the same order, or null when it does not. A plugin that runs\n * before this one can insert text into the file's code: TanStack devtools adds\n * a `data-tsd-source` attribute to every opening tag, which moves each later\n * element on the same line to the right. The editor looks elements up in the\n * file on disk, so their ids must carry the file's columns.\n */\nasync function sourcePositions(\n  code: string,\n  source: string,\n  parse: ParseModule,\n): Promise<ElementPosition[] | null> {\n  const [fromCode, fromSource] = await Promise.all([\n    openingElementPositions(code, parse),\n    openingElementPositions(source, parse),\n  ]);\n  if (fromCode.length !== fromSource.length) {\n    return null;\n  }\n  for (let i = 0; i < fromCode.length; i++) {\n    if (fromCode[i]!.name !== fromSource[i]!.name) {\n      return null;\n    }\n  }\n  return fromSource;\n}\n\nexport interface TransformOptions {\n  /** The file on disk. When given, ids carry its line and column instead of those of the code. */\n  source?: string;\n  /** @default parseWithBabel */\n  parse?: ParseModule;\n}\n\nexport class ComponentTagger {\n  private cwd = process.cwd();\n  private dataAttribute: string;\n\n  constructor(private options: ComponentTaggerOptions = {}) {\n    this.dataAttribute = options.dataAttribute || \"data-component-id\";\n  }\n\n  /**\n   * Tags the JSX elements of `code` with `<dataAttribute>=\"<file>:<line>:<column>\"`\n   * and `data-hercules-name`.\n   */\n  async transformCode(\n    code: string,\n    id: string,\n    { source, parse = parseWithBabel }: TransformOptions = {},\n  ): Promise<{ code: string; map: any } | null> {\n    const filePath = taggableFilePath(id);\n    if (!filePath) {\n      return null;\n    }\n\n    const relativePath = path.relative(this.cwd, filePath) || filePath;\n\n    try {\n      const ast = parse(code);\n      const locate = lineLocator(code);\n      const positions =\n        source === undefined || source === code ? null : await sourcePositions(code, source, parse);\n      let elementIndex = 0;\n      const magicString = new MagicString(code);\n      let changedElementsCount = 0;\n      let importsReactThree = false;\n      const fiberImports = new Set<string>();\n      const googleMapsImports = new Set<string>();\n\n      // Dynamic import estree-walker\n      const { walk } = await import(\"estree-walker\");\n\n      // First pass: find @react-three/* and @vis.gl/react-google-maps imports\n      walk(ast as any, {\n        enter(node) {\n          if (node.type === \"ImportDeclaration\") {\n            const source = node.source?.value;\n            if (typeof source === \"string\" && source.startsWith(\"@react-three/\")) {\n              importsReactThree = true;\n              if (source === \"@react-three/fiber\") {\n                node.specifiers.forEach((spec) => fiberImports.add(spec.local.name));\n              }\n            }\n            if (source === \"@vis.gl/react-google-maps\") {\n              node.specifiers.forEach((spec) => googleMapsImports.add(spec.local.name));\n            }\n          }\n        },\n      });\n\n      // Capture dataAttribute for use in the walker\n      const dataAttribute = this.dataAttribute;\n\n      // Second pass: tag elements\n      walk(ast as any, {\n        enter(node: any) {\n          if (node.type === \"JSXOpeningElement\") {\n            const jsxNode = node;\n            const position = positions?.[elementIndex];\n            elementIndex++;\n            const elementName = openingElementName(jsxNode);\n            if (elementName === null) {\n              return;\n            }\n\n            // Skip fragments\n            if (elementName === \"Fragment\" || elementName === \"React.Fragment\") {\n              return;\n            }\n\n            const { line, col } = position ?? locate(jsxNode.start);\n            const dataComponentId = `${relativePath}:${line}:${col}`;\n\n            const shouldTag = shouldTagElement(\n              elementName,\n              importsReactThree,\n              fiberImports,\n              googleMapsImports,\n            );\n\n            if (shouldTag) {\n              // Insert after the tag name, or after its type arguments in\n              // `<Foo<Bar>>`: an attribute between them is a syntax error\n              const endPosition = (jsxNode.typeArguments ?? jsxNode.name).end ?? 0;\n\n              // Build the attributes string\n              let attributesString = ` ${dataAttribute}=\"${dataComponentId}\" data-hercules-name=\"${elementName}\"`;\n\n              magicString.appendLeft(endPosition, attributesString);\n              changedElementsCount++;\n            }\n          }\n        },\n      });\n\n      if (this.options.debug) {\n        console.log(\n          `[Component Tagger] Processed ${relativePath}: ${changedElementsCount} elements`,\n        );\n      }\n\n      return {\n        code: magicString.toString(),\n        map: magicString.generateMap({ hires: true }),\n      };\n    } catch (error) {\n      console.error(`Error processing file ${relativePath}:`, error);\n      return null;\n    }\n  }\n}\n\n// Export Vite plugin for component tagging\nexport function componentTaggerPlugin(options: ComponentTaggerOptions = {}): Plugin {\n  const tagger = new ComponentTagger(options);\n\n  return {\n    name: \"vite-plugin-hercules-component-tagger\",\n    enforce: \"pre\",\n    // Dev-server only: tagging is editor tooling, and published sites must\n    // ship no Hercules identifiers in their markup\n    apply: \"serve\",\n\n    // TanStack route split modules are tagged when they load, from the route\n    // file on disk. In `transform` they may already be regenerated by the\n    // router plugin (when it is listed before this one), and line and column\n    // taken from that code would point at the wrong element of the route file.\n    async load(id) {\n      const filePath = taggableFilePath(id);\n      if (!filePath || filePath === id) {\n        return null;\n      }\n      let source: string;\n      try {\n        source = await readFile(filePath, \"utf8\");\n      } catch (error) {\n        // A route file deleted while a page still uses it. Vite's own loader\n        // treats a missing file as not found and answers 404; thrown from\n        // here, it was a 500 that Vite also logs in every open page as\n        // \"[vite] Internal Server Error ENOENT\".\n        if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n        throw error;\n      }\n      return tagger.transformCode(source, id, { parse: parserOf(this) });\n    },\n\n    // Plugins listed earlier may have changed the code already (TanStack\n    // devtools adds an attribute to every element), so ids take their line and\n    // column from the file on disk.\n    async transform(code, id) {\n      if (taggableFilePath(id) !== id) {\n        return null;\n      }\n      const source = await readFile(id, \"utf8\").catch(() => undefined);\n      return tagger.transformCode(code, id, { source, parse: parserOf(this) });\n    },\n  };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Dependencies of packages that ship a native addon. The optimizer cannot\n * bundle a `.node` binary, and one failing entry fails the whole run, which\n * leaves the dev server without any pre-bundled dependency.\n */\nconst NATIVE_ADDON_LOADERS: ReadonlySet<string> = new Set([\n  \"bindings\",\n  \"nan\",\n  \"node-addon-api\",\n  \"node-gyp-build\",\n  \"node-pre-gyp\",\n  \"@mapbox/node-pre-gyp\",\n  \"prebuild-install\",\n]);\n\n/**\n * Vite and its React and Tailwind plugins. They run only in Node, but a Node\n * script under `src`, such as a prerender runner, can import them, and an app\n * can list one under `dependencies`. The optimizer must neither scan nor\n * bundle them: `@tailwindcss/vite` and `@vitejs/plugin-react-swc` load native\n * binaries, which fail the whole run.\n */\nexport const BUILD_TOOL_PACKAGES: readonly string[] = [\n  \"vite\",\n  \"@tailwindcss/vite\",\n  \"@vitejs/plugin-react\",\n  \"@vitejs/plugin-react-swc\",\n];\n\n/** Platform builds of a napi-rs or sharp style package, such as `@img/sharp-linux-x64`. */\nconst PLATFORM_PACKAGE = /-(?:darwin|linux|win32|freebsd|android)-(?:x64|arm64|arm|ia32)\\b/;\n\n/** Matches what Vite's optimizer accepts as an entry, minus type declarations. */\nconst JS_ENTRY = /\\.[cm]?[jt]s$/;\n// `.d.ts` and `.d.mts`, and declarations for other file types, such as the\n// `index.d.css.ts` a fontsource package lists for its stylesheet.\nconst TYPE_DECLARATION = /\\.d\\.(?:[^./]+\\.)?[cm]?ts$/;\n\nexport interface Manifest {\n  dependencies?: Record<string, string>;\n  devDependencies?: Record<string, string>;\n  optionalDependencies?: Record<string, string>;\n  exports?: unknown;\n  module?: unknown;\n  main?: unknown;\n  browser?: unknown;\n  gypfile?: unknown;\n  binary?: unknown;\n}\n\nexport function readManifest(file: string): Manifest | undefined {\n  try {\n    return JSON.parse(readFileSync(file, \"utf8\")) as Manifest;\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * The package that owns an `optimizeDeps.include` entry:\n * `@scope/name/sub > nested` gives `@scope/name`.\n */\nexport function packageNameOf(entry: string): string {\n  const first = entry.split(\">\")[0]!.trim();\n  const parts = first.split(\"/\");\n  return first.startsWith(\"@\") ? parts.slice(0, 2).join(\"/\") : parts[0]!;\n}\n\n/** The dependency names the app's `package.json` declares, or `undefined` if it cannot be read. */\nexport function readDeclaredDependencies(root: string): Set<string> | undefined {\n  const pkg = readManifest(path.join(root, \"package.json\"));\n  if (!pkg) return undefined;\n  return new Set([\n    ...Object.keys(pkg.dependencies ?? {}),\n    ...Object.keys(pkg.devDependencies ?? {}),\n  ]);\n}\n\n/**\n * Keeps the entries whose package the app declares. An app that removes a\n * template package must not get \"Failed to resolve dependency\" on every start.\n */\nexport function onlyDeclared(\n  entries: readonly string[],\n  declared: Set<string> | undefined,\n): string[] {\n  if (!declared) return [...entries];\n  return entries.filter((entry) => declared.has(packageNameOf(entry)));\n}\n\n/** Every file path a conditional `exports` target can point at. */\nfunction exportTargets(target: unknown): string[] {\n  if (typeof target === \"string\") return [target];\n  if (Array.isArray(target)) return target.flatMap(exportTargets);\n  if (target && typeof target === \"object\") return Object.values(target).flatMap(exportTargets);\n  return [];\n}\n\nfunction isJsEntry(file: string): boolean {\n  return JS_ENTRY.test(file) && !TYPE_DECLARATION.test(file);\n}\n\n/**\n * Whether `import \"name\"` loads JavaScript. A CSS-only package such as a\n * font, a types-only package, or one that exports only subpaths has nothing\n * the optimizer can bundle under its bare name.\n */\nfunction hasJsRootEntry(manifest: Manifest, packageDir: string): boolean {\n  const { exports } = manifest;\n  if (exports !== undefined && exports !== null) {\n    if (typeof exports === \"string\" || Array.isArray(exports)) {\n      return exportTargets(exports).some(isJsEntry);\n    }\n    if (typeof exports === \"object\") {\n      const keys = Object.keys(exports);\n      const isSubpathMap = keys.some((key) => key.startsWith(\".\"));\n      const root = isSubpathMap ? (exports as Record<string, unknown>)[\".\"] : exports;\n      return exportTargets(root).some(isJsEntry);\n    }\n  }\n  for (const field of [manifest.module, manifest.main]) {\n    if (typeof field !== \"string\" || field === \"\") continue;\n    // `\"main\": \"lib/index\"` resolves like a bare path, so only reject a\n    // field that names a file of another type.\n    return isJsEntry(field) || path.extname(field) === \"\";\n  }\n  if (typeof manifest.browser === \"string\") return isJsEntry(manifest.browser);\n  return existsSync(path.join(packageDir, \"index.js\"));\n}\n\n/** Whether the package loads a compiled `.node` addon. */\nfunction hasNativeAddon(manifest: Manifest): boolean {\n  if (manifest.gypfile === true || manifest.binary !== undefined) return true;\n  const dependencies = [\n    ...Object.keys(manifest.dependencies ?? {}),\n    ...Object.keys(manifest.optionalDependencies ?? {}),\n  ];\n  return dependencies.some((name) => NATIVE_ADDON_LOADERS.has(name) || PLATFORM_PACKAGE.test(name));\n}\n\n/** Extensions a bare-name lookup from the project root tries. */\nconst ROOT_LOOKUP_EXTENSIONS: readonly string[] = [\n  \"\",\n  \".json\",\n  \".js\",\n  \".mjs\",\n  \".ts\",\n  \".mts\",\n  \".jsx\",\n  \".tsx\",\n];\n\n/**\n * Whether a file or directory in the project root has the package's name.\n * With `resolve.tsconfigPaths`, a bare name is looked up from the root first,\n * so `convex` resolves to the app's `convex.json`, and the optimizer warns\n * \"Cannot optimize dependency\" on every start.\n */\nfunction isShadowedByProjectPath(root: string, name: string): boolean {\n  return ROOT_LOOKUP_EXTENSIONS.some((extension) => existsSync(path.join(root, name + extension)));\n}\n\n/**\n * The app's runtime `dependencies` that can be bundled up front, read from\n * the installed packages, minus the names in `never`. A dependency that is\n * declared but not installed yet is left out until it is, so a restart in the\n * middle of an install does not drop it with a \"Failed to resolve dependency\"\n * warning.\n */\nexport function dependenciesToPrebundle(root: string, never: ReadonlySet<string>): string[] {\n  const pkg = readManifest(path.join(root, \"package.json\"));\n  const names = Object.keys(pkg?.dependencies ?? {}).sort();\n  return names.filter((name) => {\n    if (never.has(name) || name.startsWith(\"@types/\")) return false;\n    if (isShadowedByProjectPath(root, name)) return false;\n    const packageDir = path.join(root, \"node_modules\", name);\n    const manifest = readManifest(path.join(packageDir, \"package.json\"));\n    if (!manifest) return false;\n    return hasJsRootEntry(manifest, packageDir) && !hasNativeAddon(manifest);\n  });\n}\n\nexport interface ExportedSubpathsOptions {\n  /** Leaves out a subpath, given as its export map key, such as `./internals/noop`. */\n  exclude?: (subpath: string) => boolean;\n}\n\n/**\n * The subpath entries an installed package publishes in its `exports` map,\n * such as `@base-ui/react/dialog` for `\"./dialog\"`. A package that ships one\n * entry per component has each one treated as its own package by the\n * optimizer, so listing them all covers a component the app starts using\n * later. Left out: the root entry (a dependency like any other), pattern keys\n * such as `./*`, and subpaths that load no JavaScript, such as\n * `./package.json` or a stylesheet. Returns nothing when the package is not\n * installed.\n */\nexport function exportedSubpaths(\n  root: string,\n  name: string,\n  { exclude }: ExportedSubpathsOptions = {},\n): string[] {\n  const manifest = readManifest(path.join(root, \"node_modules\", name, \"package.json\"));\n  const { exports } = manifest ?? {};\n  if (!exports || typeof exports !== \"object\" || Array.isArray(exports)) return [];\n  return Object.entries(exports as Record<string, unknown>)\n    .filter(\n      ([key, target]) =>\n        key.startsWith(\"./\") &&\n        !key.includes(\"*\") &&\n        !exclude?.(key) &&\n        exportTargets(target).some(isJsEntry),\n    )\n    .map(([key]) => `${name}/${key.slice(2)}`);\n}\n\n/** Drops entries whose package the environment excludes from optimization. */\nexport function withoutExcluded(\n  entries: string[],\n  exclude: readonly string[] | undefined,\n): string[] {\n  if (!exclude?.length) return entries;\n  const excluded = new Set(exclude);\n  return entries.filter((entry) => !excluded.has(entry) && !excluded.has(packageNameOf(entry)));\n}\n\nexport interface SourceEntriesOptions {\n  /**\n   * Scan server modules too: `*.server.*` files and the `server` directory.\n   * An environment that never runs them leaves them out, so their Node-only\n   * imports never become optimizer entries.\n   * @default true\n   */\n  serverFiles?: boolean;\n}\n\n/**\n * `optimizeDeps.entries` globs for every source file under `srcDir`, minus\n * tests, stories and type declarations. Routes load lazily, so scanning only\n * the entry's static imports would meet a package first when a page that\n * imports it renders.\n */\nexport function sourceEntries(\n  srcDir: string,\n  { serverFiles = true }: SourceEntriesOptions = {},\n): string[] {\n  const dir = srcDir.replace(/\\/+$/, \"\");\n  return [\n    `${dir}/**/*.{js,jsx,ts,tsx,mjs,mts}`,\n    `!${dir}/**/*.d.{ts,mts}`,\n    `!${dir}/**/*.{test,spec,stories}.{js,jsx,ts,tsx,mjs,mts}`,\n    `!${dir}/**/__tests__/**`,\n    `!${dir}/**/__mocks__/**`,\n    ...(serverFiles ? [] : [`!${dir}/**/*.server.{js,jsx,ts,tsx,mjs,mts}`, `!${dir}/server/**`]),\n  ];\n}\n","/**\n * Set to `\"true\"` to switch on `@usehercules/vite-tanstack`'s dev machine\n * settings where `HERCULES_DEV_MACHINE` is not set. Nothing on the Hercules\n * platform sets it.\n */\nexport const HERCULES_DEV_SERVER_ENV = \"HERCULES_DEV_SERVER\";\n\nexport function isHerculesDevServer(env: NodeJS.ProcessEnv = process.env): boolean {\n  return env[HERCULES_DEV_SERVER_ENV] === \"true\";\n}\n\n/**\n * Set to `\"1\"` by the Hercules dev machine image, so herculesd and the dev\n * server it starts both see it. `@usehercules/vite` restarts on dependency\n * changes and `@usehercules/vite-tanstack` turns on its dev machine settings\n * when it is set.\n */\nexport const HERCULES_DEV_MACHINE_ENV = \"HERCULES_DEV_MACHINE\";\n\nexport function isHerculesDevMachine(env: NodeJS.ProcessEnv = process.env): boolean {\n  return env[HERCULES_DEV_MACHINE_ENV] === \"1\";\n}\n","import path from \"node:path\";\nimport * as vite from \"vite\";\nimport type { DepOptimizationOptions, Rolldown } from \"vite\";\n\ntype EsbuildPlugin = NonNullable<\n  NonNullable<DepOptimizationOptions[\"esbuildOptions\"]>[\"plugins\"]\n>[number];\n\n/** A relative import that names a compiled addon, such as `../build/Release/cpufeatures.node`. */\nconst ADDON_FILE = /^\\.\\.?\\/.*\\.node$/;\n\n/**\n * Leaves `.node` addon files out of the optimizer bundle. A package can reach\n * one through its own dependencies: `ssh2-sftp-client` loads `ssh2`, which\n * loads `cpu-features`, which requires `../build/Release/cpufeatures.node`.\n * The file is missing when pnpm skips the build script, and the optimizer\n * cannot bundle it when it is there, so the whole run fails and the dev\n * server exits. Kept external, the file is loaded only if that code runs, and\n * `ssh2` loads `cpu-features` inside `try`. A name that resolves to a script,\n * such as `react-dom`'s `./server.node` for `server.node.js`, is bundled as usual.\n */\nexport function nativeAddonsExternal(): Rolldown.Plugin {\n  return {\n    name: \"hercules:native-addons-external\",\n    resolveId: {\n      filter: { id: ADDON_FILE },\n      async handler(source, importer, options) {\n        const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n        if (resolved && !resolved.id.endsWith(\".node\")) return resolved;\n        const file = importer ? path.resolve(path.dirname(importer), source) : source;\n        return { id: resolved?.id ?? file, external: true };\n      },\n    },\n  };\n}\n\n/** Marks the lookup `nativeAddonsExternalEsbuild` makes, so it skips its own hook. */\nconst RESOLVING_ADDON = Symbol(\"hercules:native-addons-external\");\n\n/** `nativeAddonsExternal` for esbuild, which runs the optimizer on Vite 7. */\nexport function nativeAddonsExternalEsbuild(): EsbuildPlugin {\n  return {\n    name: \"hercules:native-addons-external\",\n    setup(build) {\n      build.onResolve({ filter: ADDON_FILE }, async (args) => {\n        if (args.pluginData === RESOLVING_ADDON) return undefined;\n        const { path: resolved, errors } = await build.resolve(args.path, {\n          kind: args.kind,\n          importer: args.importer,\n          resolveDir: args.resolveDir,\n          pluginData: RESOLVING_ADDON,\n        });\n        if (errors.length === 0 && !resolved.endsWith(\".node\")) return undefined;\n        const file = errors.length === 0 ? resolved : path.resolve(args.resolveDir, args.path);\n        return { path: file, external: true };\n      });\n    },\n  };\n}\n\n/**\n * Optimizer options that keep native addon files external. Vite 8 bundles\n * dependencies with Rolldown and Vite 7 with esbuild, and each ignores the\n * other's options. Only Vite builds on Rolldown export `rolldownVersion`.\n */\nexport function nativeAddonsOptimizerOptions(\n  usesRolldown = \"rolldownVersion\" in vite,\n): Pick<DepOptimizationOptions, \"rolldownOptions\" | \"esbuildOptions\"> {\n  return usesRolldown\n    ? { rolldownOptions: { plugins: [nativeAddonsExternal()] } }\n    : { esbuildOptions: { plugins: [nativeAddonsExternalEsbuild()] } };\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport { readManifest } from \"./dependencies\";\n\nconst LOCKFILES: readonly string[] = [\n  \"pnpm-lock.yaml\",\n  \"package-lock.json\",\n  \"yarn.lock\",\n  \"bun.lock\",\n  \"bun.lockb\",\n];\n\nfunction isManifestOrLockfile(root: string, file: string): boolean {\n  const relative = path.relative(root, file);\n  return relative === \"package.json\" || LOCKFILES.includes(relative);\n}\n\nconst RESTART_DEBOUNCE_MS = 1000;\n// pnpm can write package.json before the new package is linked. Keep checking\n// for a while so a package that lands late is still picked up.\nconst INSTALL_POLL_MS = 1000;\nconst INSTALL_POLL_LIMIT = 60;\n\nfunction isInstalled(root: string, name: string): boolean {\n  return existsSync(path.join(root, \"node_modules\", name, \"package.json\"));\n}\n\ninterface HotSender {\n  send(...args: unknown[]): void;\n}\n\n/**\n * Restarts the dev server with its HMR messages muted. Until the new server\n * listens, a message from the old one (a reload for a route file the agent\n * wrote meanwhile) sends the browser to a port that is about to close, and\n * the page stays on a connection error. Browsers reload by themselves once\n * the new server accepts their socket. A failed restart keeps the old server,\n * so it gets its messages back.\n */\nfunction restartQuietly(server: ViteDevServer): Promise<void> {\n  const { environments } = server;\n  const channels: HotSender[] = [\n    server.ws,\n    ...Object.values(environments).map((environment) => environment.hot),\n  ];\n  const sends = channels.map((channel) => [channel, channel.send] as const);\n  for (const [channel] of sends) channel.send = () => {};\n  return server.restart().finally(() => {\n    if (server.environments !== environments) return;\n    for (const [channel, send] of sends) channel.send = send;\n  });\n}\n\nexport interface WatchDependenciesOptions {\n  /** Vite root, where the app's `package.json` and `node_modules` live. */\n  root: string;\n  /** The dependencies the running server was configured to bundle. */\n  started: readonly string[];\n  /** The dependencies the server would bundle now, read from disk on each check. */\n  current: () => string[];\n}\n\n/**\n * Restarts the dev server when `package.json` or the lockfile changes and the\n * dependencies it would bundle differ from `started`, the list the running\n * server was configured with.\n */\nexport function watchDependencies(\n  server: ViteDevServer,\n  { root, started, current }: WatchDependenciesOptions,\n): void {\n  const startedKey = started.join(\"\\n\");\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let polls = 0;\n  let restarting = false;\n\n  const check = () => {\n    timer = undefined;\n    if (restarting) return;\n    if (current().join(\"\\n\") !== startedKey) {\n      restarting = true;\n      server.config.logger.info(\n        \"[hercules] dependencies changed; restarting the dev server to pre-bundle them\",\n        { timestamp: true },\n      );\n      void restartQuietly(server);\n      return;\n    }\n    const declared = Object.keys(readManifest(path.join(root, \"package.json\"))?.dependencies ?? {});\n    const pending = declared.some((name) => !isInstalled(root, name));\n    if (pending && polls < INSTALL_POLL_LIMIT) {\n      polls += 1;\n      timer = setTimeout(check, INSTALL_POLL_MS);\n    }\n  };\n\n  const schedule = (file: string) => {\n    if (!isManifestOrLockfile(root, file)) return;\n    polls = 0;\n    clearTimeout(timer);\n    timer = setTimeout(check, RESTART_DEBOUNCE_MS);\n  };\n\n  server.watcher.add([\n    path.join(root, \"package.json\"),\n    ...LOCKFILES.map((file) => path.join(root, file)),\n  ]);\n  server.watcher.on(\"add\", schedule);\n  server.watcher.on(\"change\", schedule);\n  server.httpServer?.once(\"close\", () => clearTimeout(timer));\n}\n","import path from \"node:path\";\nimport {\n  BUILD_TOOL_PACKAGES,\n  dependenciesToPrebundle,\n  isHerculesDevMachine,\n  nativeAddonsOptimizerOptions,\n  sourceEntries,\n  watchDependencies,\n  withoutExcluded,\n} from \"@usehercules/vite-common\";\nimport type { Plugin } from \"vite\";\n\n/** Vite bundles React up front by itself. */\nconst NEVER_PREBUNDLED: ReadonlySet<string> = new Set([\"react\", \"react-dom\"]);\n\n/**\n * Seeds the dependency optimizer from every source file, not just the deps\n * reachable from the entry's static import graph. Large apps import most\n * routes through `lazy(() => import(...))`; deps used only inside those lazy\n * chunks are otherwise discovered when the route is first visited, which\n * forces a mid-session re-optimize + full reload. During that reload some\n * modules stay bound to the previous optimizer generation of React while\n * react-dom loads the new one, so react-dom reads another React instance's\n * internals (null) and crashes in useContext/useMemo. Crawling all of src at\n * startup settles the optimizer once so it never re-bundles mid-session. Every\n * project HTML entry is still discovered (Vite's default), so multi-page\n * inputs are not dropped. Server-only code is kept out of the client\n * optimizer: deps under convex/ are never reached, and server modules\n * colocated in src (src/server/**, *.server.*) are excluded so their Node-only\n * imports never become optimizer roots. Vite and its plugins are excluded, so\n * a Node script in src that imports them, such as a prerender runner, does not\n * pull them into the browser bundle. Native addon files a dependency loads\n * are left out too, so they cannot fail the whole run.\n */\nexport function optimizerEntriesPlugin(): Plugin {\n  return {\n    name: \"vite-plugin-hercules\",\n    apply: \"serve\",\n    config(userConfig) {\n      // Defining `optimizeDeps.entries` overrides Vite's default of deriving\n      // entries from `build.rollupOptions.input`, so a custom/library-mode app\n      // whose configured input lives outside `src` (e.g. `app/main.ts`) would\n      // lose dep discovery. Preserve any explicitly configured input by\n      // prepending it to our crawl. `input` may be a string, string[], or a\n      // Record of alias -> path; normalize all three to a flat string[].\n      const configuredInput = userConfig.build?.rollupOptions?.input;\n      const inputEntries =\n        typeof configuredInput === \"string\"\n          ? [configuredInput]\n          : Array.isArray(configuredInput)\n            ? configuredInput\n            : configuredInput\n              ? Object.values(configuredInput)\n              : [];\n      return {\n        optimizeDeps: {\n          entries: [...inputEntries, \"**/*.html\", ...sourceEntries(\"src\", { serverFiles: false })],\n          exclude: [...BUILD_TOOL_PACKAGES],\n          ...nativeAddonsOptimizerOptions(),\n        },\n      };\n    },\n  };\n}\n\n/**\n * Bundles the app's runtime dependencies up front in the browser, so Vite\n * does not discover a package mid-session. The source crawl above only finds\n * packages the code already imports; this also covers one the agent just\n * installed and is about to use. Packages that cannot be bundled (CSS or\n * types only, native addons, or excluded by the app or another plugin) are\n * skipped. That includes Vite and its plugins, which `optimizerEntriesPlugin`\n * excludes.\n *\n * On the Hercules dev machine the dev server restarts when `package.json` or\n * the lockfile changes and the bundled set differs, so the new package is\n * bundled before any code imports it. A local `vite dev` never restarts by\n * itself.\n */\nexport function prebundleDependenciesPlugin(): Plugin {\n  let root = process.cwd();\n  // Read once per server start, so the optimizer and the watcher agree.\n  let dependencies: string[] | undefined;\n  const configuredDependencies = () =>\n    (dependencies ??= dependenciesToPrebundle(root, NEVER_PREBUNDLED));\n\n  return {\n    name: \"vite-plugin-hercules-prebundle-dependencies\",\n    apply: \"serve\",\n    // After the other plugins, so their excludes are known.\n    enforce: \"post\",\n    config(config) {\n      root = path.resolve(config.root ?? process.cwd());\n    },\n    configEnvironment(name, config) {\n      if (name !== \"client\") return;\n      return {\n        optimizeDeps: {\n          include: withoutExcluded([...configuredDependencies()], config.optimizeDeps?.exclude),\n        },\n      };\n    },\n    configureServer(server) {\n      if (!isHerculesDevMachine()) return;\n      watchDependencies(server, {\n        root,\n        started: configuredDependencies(),\n        current: () => dependenciesToPrebundle(root, NEVER_PREBUNDLED),\n      });\n    },\n  };\n}\n","import { parse } from \"@babel/parser\";\nimport * as t from \"@babel/types\";\nimport traverseModule from \"@babel/traverse\";\nimport { readFile } from \"fs/promises\";\nimport path from \"path\";\n\n// Extract the actual functions\nconst traverse = (traverseModule as any).default || traverseModule;\n\nexport interface ClassNameAnalysis {\n  type: \"static\" | \"dynamic\";\n  value?: string;\n}\n\nexport interface AnalysisResult {\n  success: boolean;\n  analysis?: ClassNameAnalysis;\n  error?: string;\n}\n\n// Helper function to analyze className expressions\nexport function analyzeClassNameExpression(node: any): ClassNameAnalysis {\n  if (!node) {\n    return { type: \"static\", value: \"\" };\n  }\n\n  // Static string literal\n  if (t.isStringLiteral(node)) {\n    return { type: \"static\", value: node.value };\n  }\n\n  // Expression container - check what's inside\n  if (t.isJSXExpressionContainer(node)) {\n    return analyzeClassNameExpression(node.expression);\n  }\n\n  // Template literal with no expressions (treat as static string)\n  if (t.isTemplateLiteral(node) && node.expressions.length === 0) {\n    return {\n      type: \"static\",\n      value: node.quasis.map((q: any) => q.value.raw).join(\"\"),\n    };\n  }\n\n  // Everything else is dynamic (not editable)\n  return { type: \"dynamic\" };\n}\n\nexport interface TextContentAnalysis {\n  type: \"static\" | \"dynamic\";\n  value?: string;\n  reason?: \"has-children\" | \"dynamic-content\";\n}\n\nexport interface ElementTypeAnalysis {\n  type: \"static\" | \"dynamic\";\n  reason?: \"conditional-expression\" | \"complex-parent\" | \"map-expression\";\n}\n\nexport interface TextAnalysisResult {\n  success: boolean;\n  analysis?: TextContentAnalysis;\n  error?: string;\n}\n\n// Unified analysis interfaces\nexport interface UnifiedElementAnalysis {\n  success: boolean;\n  componentId: string;\n  className?: ClassNameAnalysis;\n  textContent?: TextContentAnalysis;\n  elementType?: ElementTypeAnalysis;\n  error?: string;\n}\n\n// Helper to analyze if element can be safely deleted\nfunction analyzeElementDeletionSafety(path: any): ElementTypeAnalysis {\n  // Walk up the AST to check the element's context\n  let current = path.parent;\n\n  while (current) {\n    // Check if element is in a conditional expression (ternary)\n    if (t.isConditionalExpression(current)) {\n      return {\n        type: \"dynamic\",\n        reason: \"conditional-expression\",\n      };\n    }\n\n    // Check if element is in array map expressions\n    if (\n      t.isCallExpression(current) &&\n      t.isMemberExpression(current.callee) &&\n      t.isIdentifier(current.callee.property) &&\n      current.callee.property.name === \"map\"\n    ) {\n      return {\n        type: \"dynamic\",\n        reason: \"map-expression\",\n      };\n    }\n\n    // Check for other complex expressions that might make deletion unsafe\n    if (\n      t.isLogicalExpression(current) ||\n      t.isSequenceExpression(current) ||\n      t.isArrayExpression(current)\n    ) {\n      return {\n        type: \"dynamic\",\n        reason: \"complex-parent\",\n      };\n    }\n\n    // Stop checking at function/component boundaries\n    if (t.isFunction(current) || t.isArrowFunctionExpression(current) || t.isJSXElement(current)) {\n      break;\n    }\n\n    current = current.parent;\n  }\n\n  // If we didn't find any problematic parents, deletion should be safe\n  return { type: \"static\" };\n}\n\n// Helper to extract text content from JSX children\nfunction extractTextContent(children: any[]): TextContentAnalysis {\n  if (!children || children.length === 0) {\n    return { type: \"static\", value: \"\" };\n  }\n\n  // Check if has nested JSX elements or fragments\n  const hasNonTextChildren = children.some(\n    (child) => t.isJSXElement(child) || t.isJSXFragment(child),\n  );\n\n  if (hasNonTextChildren) {\n    return { type: \"dynamic\", reason: \"has-children\" };\n  }\n\n  // Check if all children are static text\n  const allStatic = children.every(\n    (child) =>\n      t.isJSXText(child) ||\n      (t.isJSXExpressionContainer(child) && t.isStringLiteral(child.expression)),\n  );\n\n  if (allStatic) {\n    const textContent = children\n      .map((child) => {\n        if (t.isJSXText(child)) {\n          return child.value;\n        } else if (t.isJSXExpressionContainer(child) && t.isStringLiteral(child.expression)) {\n          return child.expression.value;\n        }\n        return \"\";\n      })\n      .join(\"\")\n      .trim();\n\n    return { type: \"static\", value: textContent };\n  }\n\n  // Has dynamic expressions\n  return { type: \"dynamic\", reason: \"dynamic-content\" };\n}\n\n// Unified analyze function that combines className and textContent analysis\nexport async function analyzeElement(\n  componentId: string,\n  rootDir: string,\n): Promise<UnifiedElementAnalysis> {\n  try {\n    // Parse component ID format: \"path/to/file.tsx:line:col\"\n    const match = componentId.match(/^(.+):(\\d+):(\\d+)$/);\n    if (!match) {\n      return {\n        success: false,\n        componentId,\n        error: `Invalid component ID format: ${componentId}`,\n      };\n    }\n\n    const [, relativePath, lineStr, colStr] = match;\n    const line = parseInt(lineStr!, 10);\n    const col = parseInt(colStr!, 10);\n    const filePath = path.join(rootDir, relativePath!);\n\n    // Read file once\n    let code: string;\n    try {\n      code = await readFile(filePath, \"utf-8\");\n    } catch (err) {\n      return {\n        success: false,\n        componentId,\n        error: `Failed to read file ${filePath}: ${err}`,\n      };\n    }\n\n    // Parse the file once with Babel\n    let ast: any;\n    try {\n      ast = parse(code, {\n        sourceType: \"module\",\n        plugins: [\"jsx\", \"typescript\"],\n        sourceFilename: filePath,\n      });\n    } catch (parseError: any) {\n      return {\n        success: false,\n        componentId,\n        error: `Failed to parse ${filePath}: ${parseError.message}`,\n      };\n    }\n\n    let classNameAnalysis: ClassNameAnalysis | undefined;\n    let textContentAnalysis: TextContentAnalysis | undefined;\n    let elementTypeAnalysis: ElementTypeAnalysis | undefined;\n    let elementFound = false;\n\n    // Single traversal to find and analyze the element\n    traverse(ast, {\n      JSXElement(path: any) {\n        const openingElement = path.node.openingElement;\n        const loc = openingElement.loc;\n        if (!loc) return;\n\n        // Check if this is the element we're looking for\n        if (loc.start.line === line && Math.abs(loc.start.column - col) <= 5) {\n          elementFound = true;\n\n          // Analyze className from opening element\n          const attributes = openingElement.attributes;\n          const classNameAttr = attributes.find(\n            (attr: any) =>\n              t.isJSXAttribute(attr) &&\n              t.isJSXIdentifier(attr.name) &&\n              attr.name.name === \"className\",\n          ) as t.JSXAttribute | undefined;\n\n          if (classNameAttr) {\n            classNameAnalysis = analyzeClassNameExpression(classNameAttr.value);\n          } else {\n            classNameAnalysis = { type: \"static\", value: \"\" };\n          }\n\n          // Analyze text content from children\n          const children = path.node.children;\n          textContentAnalysis = extractTextContent(children);\n\n          // Analyze element deletion safety\n          elementTypeAnalysis = analyzeElementDeletionSafety(path);\n\n          path.stop();\n        }\n      },\n    });\n\n    if (elementFound) {\n      const result: UnifiedElementAnalysis = {\n        success: true,\n        componentId,\n      };\n\n      if (classNameAnalysis) {\n        result.className = classNameAnalysis;\n      }\n\n      if (textContentAnalysis) {\n        result.textContent = textContentAnalysis;\n      }\n\n      if (elementTypeAnalysis) {\n        result.elementType = elementTypeAnalysis;\n      }\n\n      return result;\n    } else {\n      return {\n        success: false,\n        componentId,\n        error: `Component not found at ${line}:${col}`,\n      };\n    }\n  } catch (error: any) {\n    console.error(\"[Visual Editor] Error analyzing element:\", error);\n    return {\n      success: false,\n      componentId,\n      error: error.message || String(error),\n    };\n  }\n}\n","import { parse } from \"@babel/parser\";\nimport * as t from \"@babel/types\";\nimport traverseModule from \"@babel/traverse\";\nimport generateModule from \"@babel/generator\";\nimport { readFile, writeFile } from \"fs/promises\";\nimport path from \"path\";\nimport { type ClassNameAnalysis, type TextContentAnalysis } from \"./ast-analyzer\";\n\n// Extract the actual functions\nconst traverse = (traverseModule as any).default || traverseModule;\nconst generate = (generateModule as any).default || generateModule;\n\nexport interface UpdateResult {\n  success: boolean;\n  filePath?: string;\n  error?: string;\n  analysis?: ClassNameAnalysis | TextContentAnalysis;\n}\n\nexport async function updateComponentElement(\n  componentId: string,\n  updates: {\n    className?: string;\n    textContent?: string;\n  },\n  rootDir: string,\n): Promise<UpdateResult> {\n  try {\n    // Parse component ID format: \"path/to/file.tsx:line:col\"\n    const match = componentId.match(/^(.+):(\\d+):(\\d+)$/);\n    if (!match) {\n      return {\n        success: false,\n        error: `Invalid component ID format: ${componentId}`,\n      };\n    }\n\n    const [, relativePath, lineStr, colStr] = match;\n    const line = parseInt(lineStr!, 10);\n    const col = parseInt(colStr!, 10);\n    const filePath = path.join(rootDir, relativePath!);\n\n    let code: string;\n    try {\n      code = await readFile(filePath, \"utf-8\");\n    } catch (err) {\n      return {\n        success: false,\n        error: `Failed to read file ${filePath}: ${err}`,\n      };\n    }\n\n    // Parse the file with Babel\n    let ast: any;\n    try {\n      ast = parse(code, {\n        sourceType: \"module\",\n        plugins: [\"jsx\", \"typescript\"],\n        sourceFilename: filePath,\n      });\n    } catch (parseError: any) {\n      return {\n        success: false,\n        error: `Failed to parse ${filePath}: ${parseError.message}`,\n      };\n    }\n\n    let modified = false;\n    let foundElements = 0;\n    const nearbyElements: Array<{ line: number; col: number; tag: string }> = [];\n\n    // Traverse the AST to find and update the JSX element\n    traverse(ast, {\n      JSXElement(path: any) {\n        const openingElement = path.node.openingElement;\n        const loc = openingElement.loc;\n        if (!loc) return;\n\n        foundElements++;\n\n        // Collect nearby elements for debugging\n        if (Math.abs(loc.start.line - line) <= 5) {\n          const tagName = openingElement.name.name || \"unknown\";\n          nearbyElements.push({\n            line: loc.start.line,\n            col: loc.start.column,\n            tag: tagName,\n          });\n        }\n\n        // Check if this is the element we're looking for\n        if (loc.start.line === line && Math.abs(loc.start.column - col) <= 5) {\n          // Update className if provided\n          if (updates.className !== undefined) {\n            const classNameAttr = openingElement.attributes.find(\n              (attr: any) => attr.name && attr.name.name === \"className\",\n            );\n\n            if (updates.className === \"\") {\n              // Remove className attribute if new value is empty\n              openingElement.attributes = openingElement.attributes.filter(\n                (attr: any) => !(attr.name && attr.name.name === \"className\"),\n              );\n            } else {\n              if (classNameAttr) {\n                // Update existing className\n                classNameAttr.value = t.stringLiteral(updates.className);\n              } else {\n                // Add new className attribute\n                openingElement.attributes.push(\n                  t.jsxAttribute(t.jsxIdentifier(\"className\"), t.stringLiteral(updates.className)),\n                );\n              }\n            }\n          }\n\n          // Update text content if provided\n          if (updates.textContent !== undefined) {\n            // Clear existing children\n            path.node.children = [];\n\n            // Add new text content as a JSXText node\n            if (updates.textContent.trim() !== \"\") {\n              path.node.children.push(t.jsxText(updates.textContent));\n            }\n          }\n\n          modified = true;\n          path.stop();\n        }\n      },\n    });\n\n    if (!modified) {\n      const debugInfo =\n        nearbyElements.length > 0\n          ? ` Found ${nearbyElements.length} nearby elements: ${JSON.stringify(nearbyElements)}`\n          : ` Total JSX elements found: ${foundElements}`;\n      return {\n        success: false,\n        error: `Component not found at ${line}:${col}.${debugInfo}`,\n      };\n    }\n\n    // Generate the updated code\n    let output: any;\n    try {\n      output = generate(\n        ast,\n        {\n          retainLines: true,\n          compact: false,\n          concise: false,\n          comments: true,\n        },\n        code,\n      );\n    } catch (genError) {\n      return { success: false, error: `Failed to generate code: ${genError}` };\n    }\n\n    // Write the updated code back to the file\n    try {\n      await writeFile(filePath, output.code, \"utf-8\");\n    } catch (writeError) {\n      return { success: false, error: `Failed to write file: ${writeError}` };\n    }\n\n    return { success: true, filePath };\n  } catch (error) {\n    return { success: false, error: `Unexpected error: ${error}` };\n  }\n}\n\nexport async function deleteComponent(componentId: string, rootDir: string): Promise<UpdateResult> {\n  try {\n    // Parse component ID format: \"path/to/file.tsx:line:col\"\n    const match = componentId.match(/^(.+):(\\d+):(\\d+)$/);\n    if (!match) {\n      return {\n        success: false,\n        error: `Invalid component ID format: ${componentId}`,\n      };\n    }\n\n    const [, relativePath, lineStr, colStr] = match;\n    const line = parseInt(lineStr!, 10);\n    const col = parseInt(colStr!, 10);\n    const filePath = path.join(rootDir, relativePath!);\n\n    let code: string;\n    try {\n      code = await readFile(filePath, \"utf-8\");\n    } catch (err) {\n      return {\n        success: false,\n        error: `Failed to read file ${filePath}: ${err}`,\n      };\n    }\n\n    // Parse the file with Babel\n    let ast: any;\n    try {\n      ast = parse(code, {\n        sourceType: \"module\",\n        plugins: [\"jsx\", \"typescript\"],\n        sourceFilename: filePath,\n      });\n    } catch (parseError: any) {\n      return {\n        success: false,\n        error: `Failed to parse ${filePath}: ${parseError.message}`,\n      };\n    }\n\n    let modified = false;\n    let foundElements = 0;\n    const nearbyElements: Array<{ line: number; col: number; tag: string }> = [];\n\n    // Traverse the AST to find and delete the JSX element\n    traverse(ast, {\n      JSXElement(path: any) {\n        const openingElement = path.node.openingElement;\n        const loc = openingElement.loc;\n        if (!loc) return;\n\n        foundElements++;\n\n        // Collect nearby elements for debugging\n        if (Math.abs(loc.start.line - line) <= 5) {\n          const tagName = openingElement.name.name || \"unknown\";\n          nearbyElements.push({\n            line: loc.start.line,\n            col: loc.start.column,\n            tag: tagName,\n          });\n        }\n\n        // Check if this is the element we're looking for\n        if (loc.start.line === line && Math.abs(loc.start.column - col) <= 5) {\n          // Remove the element from its parent\n          path.remove();\n\n          modified = true;\n          path.stop();\n        }\n      },\n      JSXFragment(path: any) {\n        const loc = path.node.loc;\n        if (!loc) return;\n\n        foundElements++;\n\n        // Check if this is the fragment we're looking for\n        if (loc.start.line === line && Math.abs(loc.start.column - col) <= 5) {\n          // Remove the fragment from its parent\n          path.remove();\n\n          modified = true;\n          path.stop();\n        }\n      },\n    });\n\n    if (!modified) {\n      const debugInfo =\n        nearbyElements.length > 0\n          ? ` Found ${nearbyElements.length} nearby elements: ${JSON.stringify(nearbyElements)}`\n          : ` Total JSX elements found: ${foundElements}`;\n      return {\n        success: false,\n        error: `Component not found at ${line}:${col}.${debugInfo}`,\n      };\n    }\n\n    // Generate the updated code\n    let output: any;\n    try {\n      output = generate(\n        ast,\n        {\n          retainLines: true,\n          compact: false,\n          concise: false,\n          comments: true,\n        },\n        code,\n      );\n    } catch (genError) {\n      return { success: false, error: `Failed to generate code: ${genError}` };\n    }\n\n    // Write the updated code back to the file\n    try {\n      await writeFile(filePath, output.code, \"utf-8\");\n    } catch (writeError) {\n      return { success: false, error: `Failed to write file: ${writeError}` };\n    }\n\n    return { success: true, filePath };\n  } catch (error) {\n    return { success: false, error: `Unexpected error: ${error}` };\n  }\n}\n","import type { Plugin, ViteDevServer } from \"vite\";\n\n// Import from extracted modules\nimport { analyzeElement } from \"./ast-analyzer\";\nimport { updateComponentElement, deleteComponent } from \"./ast-transformer\";\n\nexport interface VisualEditorOptions {\n  /**\n   * Enable debug logging\n   * @default false\n   */\n  debug?: boolean;\n}\n\n/**\n * The endpoints the visual editor calls to read, update and delete the element\n * behind a `data-hercules-id`. herculesd serves the editor's script and injects\n * it into every page.\n *\n * These endpoints, and the Babel code behind them, are moving into herculesd.\n * Remove them once a dev image with that change ships.\n */\nexport function visualEditorPlugin(options: VisualEditorOptions = {}): Plugin {\n  const { debug = false } = options;\n  let server: ViteDevServer;\n\n  return {\n    name: \"vite-plugin-hercules-visual-editor\",\n    enforce: \"pre\",\n    apply: \"serve\",\n\n    configureServer(_server) {\n      server = _server;\n\n      // Handle unified element analysis requests\n      server.middlewares.use(\"/__hercules_analyze_element\", async (req, res, next) => {\n        if (req.method === \"POST\") {\n          let body = \"\";\n          req.on(\"data\", (chunk) => (body += chunk));\n          req.on(\"end\", async () => {\n            try {\n              const { componentId } = JSON.parse(body);\n\n              const result = await analyzeElement(componentId, server.config.root);\n\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify(result));\n            } catch (error) {\n              if (debug) {\n                console.error(\"[Visual Editor] Error analyzing element:\", error);\n              }\n              res.statusCode = 500;\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify({ success: false, error: String(error) }));\n            }\n          });\n        } else {\n          next();\n        }\n      });\n\n      // Handle unified element update requests\n      server.middlewares.use(\"/__hercules_update_element\", async (req, res, next) => {\n        if (req.method === \"POST\") {\n          let body = \"\";\n          req.on(\"data\", (chunk) => (body += chunk));\n          req.on(\"end\", async () => {\n            try {\n              const data = JSON.parse(body);\n              const { componentId, className, textContent } = data;\n\n              const updates: { className?: string; textContent?: string } = {};\n              if (className !== undefined) updates.className = className;\n              if (textContent !== undefined) updates.textContent = textContent;\n\n              const result = await updateComponentElement(componentId, updates, server.config.root);\n\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify(result));\n            } catch (error) {\n              if (debug) {\n                console.error(\"[Visual Editor] Error updating element:\", error);\n              }\n              res.statusCode = 500;\n              res.end(JSON.stringify({ success: false, error: String(error) }));\n            }\n          });\n        } else {\n          next();\n        }\n      });\n\n      // Handle element deletion requests\n      server.middlewares.use(\"/__hercules_delete_element\", async (req, res, next) => {\n        if (req.method === \"POST\") {\n          let body = \"\";\n          req.on(\"data\", (chunk) => (body += chunk));\n          req.on(\"end\", async () => {\n            try {\n              const data = JSON.parse(body);\n              const { componentId } = data;\n\n              const result = await deleteComponent(componentId, server.config.root);\n\n              res.setHeader(\"Content-Type\", \"application/json\");\n              res.end(JSON.stringify(result));\n            } catch (error) {\n              if (debug) {\n                console.error(\"[Visual Editor] Error deleting element:\", error);\n              }\n              res.statusCode = 500;\n              res.end(JSON.stringify({ success: false, error: String(error) }));\n            }\n          });\n        } else {\n          next();\n        }\n      });\n    },\n  };\n}\n","import type { Plugin } from \"vite\";\nimport { componentTaggerPlugin, type ComponentTaggerOptions } from \"./component-tagger\";\nimport { optimizerEntriesPlugin, prebundleDependenciesPlugin } from \"./prebundle\";\nimport { visualEditorPlugin, type VisualEditorOptions } from \"./visual-editor\";\n\nexport interface HerculesPluginOptions {\n  /**\n   * Component tagger options\n   *\n   * Tagging attributes (`data-hercules-id` / `data-hercules-name`) are injected\n   * on the dev server only; `vite build` output never contains them.\n   *\n   * @default { enabled: true }\n   */\n  componentTagger?: ComponentTaggerOptions & { enabled?: boolean };\n\n  /**\n   * Visual editor options. Serves the endpoints the visual editor calls to\n   * change the source of a tagged element (dev server only).\n   * @default { enabled: true }\n   */\n  visualEditor?: VisualEditorOptions & { enabled?: boolean };\n\n  /**\n   * Bundle every runtime dependency in the app's `package.json` up front on\n   * the dev server, so Vite does not discover one mid-session and reload the\n   * page. On the Hercules dev machine the dev server also restarts when\n   * `package.json` or the lockfile changes, so a package the agent installs is\n   * bundled before code imports it. `@usehercules/vite-tanstack` turns this\n   * off and bundles the dependencies of both its environments itself.\n   * @default true\n   */\n  prebundleDependencies?: boolean;\n}\n\n/**\n * Hercules Vite plugin: tags JSX elements for the visual editor and keeps the\n * dependency optimizer from re-bundling mid-session. All of it runs on the dev\n * server only.\n */\nexport function hercules(options: HerculesPluginOptions = {}): Plugin[] {\n  const {\n    componentTagger = { enabled: true },\n    visualEditor = { enabled: true },\n    prebundleDependencies = true,\n  } = options;\n\n  const plugins: Plugin[] = [];\n\n  if (componentTagger.enabled) {\n    plugins.push(\n      componentTaggerPlugin({\n        dataAttribute: visualEditor.enabled ? \"data-hercules-id\" : \"data-component-id\",\n        ...componentTagger,\n      }),\n    );\n  }\n\n  if (visualEditor.enabled) {\n    plugins.push(visualEditorPlugin(visualEditor));\n  }\n\n  plugins.push(optimizerEntriesPlugin());\n  if (prebundleDependencies) plugins.push(prebundleDependenciesPlugin());\n\n  return plugins;\n}\n\n// Default export for convenience\nexport default hercules;\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,SAAS,iBACP,aACA,mBACA,cACA,mBACS;CACT,IAAI,gBAAgB,IAAI,WAAW,GACjC,OAAO;CAKT,IAAI,kBAAkB,IAAI,YAAY,MAAM,GAAG,CAAC,CAAC,EAAG,GAClD,OAAO;CAMT,IAAI,qBAAqB,CAAC,eAAe,KAAK,WAAW,GACvD,OAAO,aAAa,IAAI,YAAY,MAAM,GAAG,CAAC,CAAC,EAAG;CAEpD,OAAO;AACT;AAGA,MAAM,kCAAkB,IAAI,IAAI,CAAC,QAAQ,MAAM,CAAC;AAMhD,MAAM,mCAAmB,IAAI,IAAI,CAAC,aAAa,YAAY,CAAC;;;;;AAM5D,SAAgB,iBAAiB,IAA2B;CAC1D,MAAM,aAAa,GAAG,QAAQ,GAAG;CACjC,MAAM,WAAW,eAAe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