{"version":3,"file":"compilers.cjs","sources":["../../src/compilers.ts"],"sourcesContent":["import * as babel from '@babel/core'\nimport { isIdentifier, isVariableDeclarator } from '@babel/types'\nimport { codeFrameColumns } from '@babel/code-frame'\nimport {\n  deadCodeElimination,\n  findReferencedIdentifiers,\n} from 'babel-dead-code-elimination'\nimport path from 'pathe'\nimport { generateFromAst, parseAst } from '@tanstack/router-utils'\nimport type { GeneratorResult, ParseAstOptions } from '@tanstack/router-utils'\n\nexport interface DirectiveFn {\n  nodePath: SupportedFunctionPath\n  functionName: string\n  functionId: string\n  extractedFilename: string\n  filename: string\n  chunkName: string\n  /**\n   * True when this function was discovered by the client build.\n   * Used to restrict HTTP access to only client-referenced functions.\n   */\n  isClientReferenced?: boolean\n}\n\nexport type SupportedFunctionPath =\n  | babel.NodePath<babel.types.FunctionDeclaration>\n  | babel.NodePath<babel.types.FunctionExpression>\n  | babel.NodePath<babel.types.ArrowFunctionExpression>\n\nexport type GenerateFunctionIdFn = (opts: {\n  filename: string\n  functionName: string\n  extractedFilename: string\n}) => string\n\nexport type ReplacerFn = (opts: {\n  fn: string\n  extractedFilename: string\n  filename: string\n  functionId: string\n  functionName: string\n  isSourceFn: boolean\n  /**\n   * True when this function was already discovered by a previous build (e.g., client).\n   * For SSR callers, this means the function is in the manifest and doesn't need\n   * an importer - the manifest lookup will find it.\n   */\n  isClientReferenced: boolean\n}) => string\n\n// const debug = process.env.TSR_VITE_DEBUG === 'true'\n\nexport type CompileDirectivesOpts = ParseAstOptions & {\n  directive: string\n  getRuntimeCode?: (opts: {\n    directiveFnsById: Record<string, DirectiveFn>\n  }) => string\n  generateFunctionId: GenerateFunctionIdFn\n  replacer: ReplacerFn\n  filename: string\n  root: string\n  isDirectiveSplitParam: boolean\n  directiveSplitParam: string\n  /**\n   * Previously discovered directive functions from other builds (e.g., client build).\n   * When provided, the compiler will use the canonical extractedFilename from this\n   * registry instead of computing it locally. This ensures SSR callers import from\n   * the same extracted file as the client.\n   */\n  knownDirectiveFns?: Record<string, DirectiveFn>\n  /**\n   * Whether the current environment is a client environment.\n   * Functions discovered in client environments are always client-referenced.\n   */\n  isClientEnvironment?: boolean\n}\n\nexport function compileDirectives(opts: CompileDirectivesOpts): {\n  compiledResult: GeneratorResult\n  directiveFnsById: Record<string, DirectiveFn>\n} {\n  const ast = parseAst(opts)\n  const refIdents = findReferencedIdentifiers(ast)\n  const directiveFnsById = findDirectives(ast, {\n    ...opts,\n    directiveSplitParam: opts.directiveSplitParam,\n    isDirectiveSplitParam: opts.isDirectiveSplitParam,\n  })\n\n  // Add runtime code if there are directives\n  if (Object.keys(directiveFnsById).length > 0) {\n    if (opts.getRuntimeCode) {\n      const runtimeImport = babel.template.statement(\n        opts.getRuntimeCode({ directiveFnsById }),\n      )()\n      ast.program.body.unshift(runtimeImport)\n    }\n  }\n\n  // If we are in the source file, we need to remove all exports\n  // then make sure that all of our functions are exported under their\n  // directive name\n  if (opts.isDirectiveSplitParam) {\n    safeRemoveExports(ast)\n\n    // Export a single object with all of the functions\n    // e.g. export { directiveFn1, directiveFn2 }\n    ast.program.body.push(\n      babel.types.exportNamedDeclaration(\n        undefined,\n        Object.values(directiveFnsById).map((fn) =>\n          babel.types.exportSpecifier(\n            babel.types.identifier(fn.functionName),\n            babel.types.identifier(fn.functionName),\n          ),\n        ),\n      ),\n    )\n  }\n\n  deadCodeElimination(ast, refIdents)\n\n  const compiledResult = generateFromAst(ast, {\n    sourceMaps: true,\n    sourceFileName: opts.filename,\n    filename: opts.filename,\n  })\n\n  return {\n    compiledResult,\n    directiveFnsById,\n  }\n}\n\nfunction findNearestVariableName(\n  path: babel.NodePath,\n  directive: string,\n): string {\n  let currentPath: babel.NodePath | null = path\n  const nameParts: Array<string> = []\n\n  while (currentPath) {\n    const name = (() => {\n      // Check for named function expression\n      if (\n        babel.types.isFunctionExpression(currentPath.node) &&\n        currentPath.node.id\n      ) {\n        return currentPath.node.id.name\n      }\n\n      // Handle method chains\n      if (babel.types.isCallExpression(currentPath.node)) {\n        const current = currentPath.node.callee\n        const chainParts: Array<string> = []\n\n        // Get the nearest method name (if it's a method call)\n        if (babel.types.isMemberExpression(current)) {\n          if (babel.types.isIdentifier(current.property)) {\n            chainParts.unshift(current.property.name)\n          }\n\n          // Get the base callee\n          let base = current.object\n          while (!babel.types.isIdentifier(base)) {\n            if (babel.types.isCallExpression(base)) {\n              base = base.callee as babel.types.Expression\n            } else if (babel.types.isMemberExpression(base)) {\n              base = base.object\n            } else {\n              break\n            }\n          }\n          if (babel.types.isIdentifier(base)) {\n            chainParts.unshift(base.name)\n          }\n        } else if (babel.types.isIdentifier(current)) {\n          chainParts.unshift(current.name)\n        }\n\n        if (chainParts.length > 0) {\n          return chainParts.join('_')\n        }\n      }\n\n      // Rest of the existing checks...\n      if (babel.types.isFunctionDeclaration(currentPath.node)) {\n        return currentPath.node.id?.name\n      }\n\n      if (babel.types.isIdentifier(currentPath.node)) {\n        return currentPath.node.name\n      }\n\n      if (\n        isVariableDeclarator(currentPath.node) &&\n        isIdentifier(currentPath.node.id)\n      ) {\n        return currentPath.node.id.name\n      }\n\n      if (\n        babel.types.isClassMethod(currentPath.node) ||\n        babel.types.isObjectMethod(currentPath.node)\n      ) {\n        throw new Error(\n          `\"${directive}\" in ClassMethod or ObjectMethod not supported`,\n        )\n      }\n\n      return ''\n    })()\n\n    if (name) {\n      nameParts.unshift(name)\n    }\n\n    currentPath = currentPath.parentPath\n  }\n\n  return nameParts.length > 0 ? nameParts.join('_') : 'anonymous'\n}\n\nfunction makeIdentifierSafe(identifier: string): string {\n  return identifier\n    .replace(/[^a-zA-Z0-9_$]/g, '_') // Replace unsafe chars with underscore\n    .replace(/^[0-9]/, '_$&') // Prefix leading number with underscore\n    .replace(/^\\$/, '_$') // Prefix leading $ with underscore\n    .replace(/_{2,}/g, '_') // Collapse multiple underscores\n    .replace(/^_|_$/g, '') // Trim leading/trailing underscores\n}\n\nexport function findDirectives(\n  ast: babel.types.File,\n  opts: ParseAstOptions & {\n    directive: string\n    replacer?: ReplacerFn\n    generateFunctionId: GenerateFunctionIdFn\n    directiveSplitParam: string\n    filename: string\n    root: string\n    isDirectiveSplitParam: boolean\n    knownDirectiveFns?: Record<string, DirectiveFn>\n    isClientEnvironment?: boolean\n  },\n): Record<string, DirectiveFn> {\n  const directiveFnsById: Record<string, DirectiveFn> = {}\n  const functionNameSet: Set<string> = new Set()\n\n  let programPath: babel.NodePath<babel.types.Program>\n\n  babel.traverse(ast, {\n    Program(path) {\n      programPath = path\n    },\n  })\n\n  // Does the file have the directive in the program body?\n  const hasFileDirective = ast.program.directives.some(\n    (directive) => directive.value.value === opts.directive,\n  )\n  const compileDirectiveOpts = {\n    isDirectiveSplitParam: opts.isDirectiveSplitParam,\n  }\n\n  // If the entire file has a directive, we need to compile all of the functions that are\n  // exported by the file.\n  if (hasFileDirective) {\n    // Find all of the exported functions\n    // They must be either function declarations or const function/anonymous function declarations\n    babel.traverse(ast, {\n      ExportDefaultDeclaration(path) {\n        if (babel.types.isFunctionDeclaration(path.node.declaration)) {\n          compileDirective(\n            path.get('declaration') as SupportedFunctionPath,\n            compileDirectiveOpts,\n          )\n        }\n      },\n      ExportNamedDeclaration(path) {\n        if (babel.types.isFunctionDeclaration(path.node.declaration)) {\n          compileDirective(\n            path.get('declaration') as SupportedFunctionPath,\n            compileDirectiveOpts,\n          )\n        }\n      },\n      ExportDeclaration(path) {\n        if (\n          babel.types.isExportNamedDeclaration(path.node) &&\n          babel.types.isVariableDeclaration(path.node.declaration) &&\n          (babel.types.isFunctionExpression(\n            path.node.declaration.declarations[0]?.init,\n          ) ||\n            babel.types.isArrowFunctionExpression(\n              path.node.declaration.declarations[0]?.init,\n            ))\n        ) {\n          compileDirective(\n            path.get(\n              'declaration.declarations.0.init',\n            ) as SupportedFunctionPath,\n            compileDirectiveOpts,\n          )\n        }\n      },\n    })\n  } else {\n    // Find all directives\n    babel.traverse(ast, {\n      DirectiveLiteral(nodePath) {\n        if (nodePath.node.value === opts.directive) {\n          const directiveFn = nodePath.findParent((p) => p.isFunction())\n\n          if (!directiveFn) return\n\n          // Handle class and object methods which are not supported\n          const isClassMethod = directiveFn.isClassMethod()\n          const isObjectMethod = directiveFn.isObjectMethod()\n\n          if (isClassMethod || isObjectMethod) {\n            throw codeFrameError(\n              opts.code,\n              directiveFn.node.loc,\n              `\"${opts.directive}\" in ${isClassMethod ? 'class' : isObjectMethod ? 'object method' : ''} not supported`,\n            )\n          }\n\n          // If the function is inside another block that isn't the program,\n          // Error out. This is not supported.\n          const nearestBlock = directiveFn.findParent(\n            (p) => (p.isBlockStatement() || p.isScopable()) && !p.isProgram(),\n          )\n\n          if (nearestBlock) {\n            throw codeFrameError(\n              opts.code,\n              nearestBlock.node.loc,\n              `\"${opts.directive}\" cannot be nested in other blocks or functions`,\n            )\n          }\n\n          if (\n            !directiveFn.isFunctionDeclaration() &&\n            !directiveFn.isFunctionExpression() &&\n            !(\n              directiveFn.isArrowFunctionExpression() &&\n              babel.types.isBlockStatement(directiveFn.node.body)\n            )\n          ) {\n            throw codeFrameError(\n              opts.code,\n              directiveFn.node.loc,\n              `\"${opts.directive}\" must be function declarations or function expressions`,\n            )\n          }\n\n          compileDirective(directiveFn, compileDirectiveOpts)\n        }\n      },\n    })\n  }\n\n  return directiveFnsById\n\n  function compileDirective(\n    directiveFn: SupportedFunctionPath,\n    compileDirectiveOpts: {\n      isDirectiveSplitParam: boolean\n    },\n  ) {\n    // Move the function to program level while preserving its position\n    // in the program body\n    const programBody = programPath.node.body\n\n    // Remove the directive directive from the function body\n    if (\n      babel.types.isFunction(directiveFn.node) &&\n      babel.types.isBlockStatement(directiveFn.node.body)\n    ) {\n      directiveFn.node.body.directives =\n        directiveFn.node.body.directives.filter(\n          (directive) => directive.value.value !== opts.directive,\n        )\n    }\n\n    // if the directive function is a top-level function, we need to create a const declaration\n    // using the same name as the function and replace the function with the variable declaration\n    // that points to the function\n    if (directiveFn.parentPath.isProgram()) {\n      if (!babel.types.isFunctionDeclaration(directiveFn.node)) {\n        throw new Error('Top level functions must be function declarations')\n      }\n\n      const index = programBody.indexOf(directiveFn.node)\n\n      // First get the name of the function\n      const originalFunctionName = directiveFn.node.id!.name\n\n      // Now turn the function into an anonymous function\n      directiveFn.node.id = null\n\n      const variableDeclaration = babel.types.variableDeclaration('const', [\n        babel.types.variableDeclarator(\n          babel.types.identifier(originalFunctionName),\n          babel.types.toExpression(directiveFn.node as any),\n        ),\n      ])\n\n      directiveFn.replaceWith(variableDeclaration)\n\n      directiveFn = programPath.get(\n        `body.${index}.declarations.0.init`,\n      ) as SupportedFunctionPath\n    }\n\n    // Find the nearest variable name\n    let functionName = findNearestVariableName(directiveFn, opts.directive)\n\n    const incrementFunctionNameVersion = (functionName: string) => {\n      const [realReferenceName, count] = functionName.split(/_(\\d+)$/)\n      const resolvedCount = Number(count || '0')\n      const suffix = `_${resolvedCount + 1}`\n      return makeIdentifierSafe(realReferenceName!) + suffix\n    }\n\n    while (functionNameSet.has(functionName)) {\n      functionName = incrementFunctionNameVersion(functionName)\n    }\n\n    functionNameSet.add(functionName)\n\n    while (programPath.scope.hasBinding(functionName)) {\n      functionName = incrementFunctionNameVersion(functionName)\n      programPath.scope.crawl()\n    }\n\n    functionNameSet.add(functionName)\n\n    // Use functionId to determine if this is a client-referenced function\n    const [baseFilename, ..._searchParams] = opts.filename.split('?') as [\n      string,\n      ...Array<string>,\n    ]\n    const searchParams = new URLSearchParams(_searchParams.join('&'))\n    searchParams.set(opts.directiveSplitParam, '')\n\n    const localExtractedFilename = `${baseFilename}?${searchParams.toString()}`\n\n    // Relative to have constant functionId regardless of the machine\n    // that we are executing\n    const relativeFilename = path.relative(opts.root, baseFilename)\n    const functionId = opts.generateFunctionId({\n      filename: relativeFilename,\n      functionName,\n      extractedFilename: localExtractedFilename,\n    })\n\n    // Use the canonical extracted filename from knownDirectiveFns if available.\n    // This ensures SSR callers import from the same extracted file as the client,\n    // avoiding duplicate chunks with the same server function.\n    const knownFn = opts.knownDirectiveFns?.[functionId]\n    const extractedFilename =\n      knownFn?.extractedFilename ?? localExtractedFilename\n    // A function is client-referenced if:\n    // 1. It was discovered by the client environment (isClientEnvironment), OR\n    // 2. It was already known from a previous (client) build (knownFn exists)\n    const isClientReferenced = opts.isClientEnvironment || !!knownFn\n\n    // For client-referenced functions in SSR caller files (not extracted files),\n    // we remove the second argument of .handler() because:\n    // 1. The RPC stub uses manifest lookup, which provides the implementation\n    // 2. The full implementation shouldn't be in the caller file\n    // We do this BEFORE hoisting/replacing to ensure we can still access the parent structure\n    if (isClientReferenced && !compileDirectiveOpts.isDirectiveSplitParam) {\n      // Find if this directive function is inside a .handler() call expression\n      // The structure is: .handler(directiveFn, originalImpl)\n      // We want to remove originalImpl (the second argument)\n      let currentPath: babel.NodePath | null =\n        directiveFn as babel.NodePath | null\n      while (currentPath && !currentPath.parentPath?.isProgram()) {\n        const parent: babel.NodePath | null = currentPath.parentPath\n        if (\n          parent?.isCallExpression() &&\n          babel.types.isMemberExpression(parent.node.callee) &&\n          babel.types.isIdentifier(parent.node.callee.property) &&\n          parent.node.callee.property.name === 'handler' &&\n          parent.node.arguments.length === 2\n        ) {\n          // Remove the second argument (the original implementation)\n          parent.node.arguments.pop()\n          break\n        }\n        currentPath = parent\n      }\n    }\n\n    const topParent =\n      directiveFn.findParent((p) => !!p.parentPath?.isProgram()) || directiveFn\n\n    const topParentIndex = programBody.indexOf(topParent.node as any)\n\n    // If the function has a parent that isn't the program,\n    // we need to replace it with an identifier and\n    // hoist the function to the top level as a const declaration\n    if (directiveFn.parentPath.isProgram()) {\n      throw new Error(\n        'Top level functions should have already been compiled to variable declarations by this point',\n      )\n    }\n    // Then place the function at the top level\n    programBody.splice(\n      topParentIndex,\n      0,\n      babel.types.variableDeclaration('const', [\n        babel.types.variableDeclarator(\n          babel.types.identifier(functionName),\n          babel.types.toExpression(directiveFn.node as any),\n        ),\n      ]),\n    )\n\n    // If it's an exported named function, we need to swap it with an\n    // export const originalFunctionName = functionName\n    if (\n      (babel.types.isExportNamedDeclaration(directiveFn.parentPath.node) ||\n        (compileDirectiveOpts.isDirectiveSplitParam &&\n          babel.types.isExportDefaultDeclaration(\n            directiveFn.parentPath.node,\n          ))) &&\n      (babel.types.isFunctionDeclaration(directiveFn.node) ||\n        babel.types.isFunctionExpression(directiveFn.node)) &&\n      babel.types.isIdentifier(directiveFn.node.id)\n    ) {\n      const originalFunctionName = directiveFn.node.id.name\n      programBody.splice(\n        topParentIndex + 1,\n        0,\n        babel.types.exportNamedDeclaration(\n          babel.types.variableDeclaration('const', [\n            babel.types.variableDeclarator(\n              babel.types.identifier(originalFunctionName),\n              babel.types.identifier(functionName),\n            ),\n          ]),\n        ),\n      )\n\n      directiveFn.remove()\n    } else {\n      directiveFn.replaceWith(babel.types.identifier(functionName))\n    }\n\n    directiveFn = programPath.get(\n      `body.${topParentIndex}.declarations.0.init`,\n    ) as SupportedFunctionPath\n\n    // If a replacer is provided, replace the function with the replacer\n    if (opts.replacer) {\n      const replacer = opts.replacer({\n        fn: '$$fn$$',\n        extractedFilename,\n        filename: opts.filename,\n        functionId,\n        functionName,\n        isSourceFn: !!opts.directiveSplitParam,\n        isClientReferenced,\n      })\n\n      const replacement = babel.template.expression(replacer, {\n        placeholderPattern: false,\n        placeholderWhitelist: new Set(['$$fn$$']),\n      })({\n        ...(replacer.includes('$$fn$$')\n          ? { $$fn$$: babel.types.toExpression(directiveFn.node) }\n          : {}),\n      })\n\n      directiveFn.replaceWith(replacement)\n    }\n\n    // Finally register the directive to\n    // our map of directives\n    directiveFnsById[functionId] = {\n      nodePath: directiveFn,\n      functionName,\n      functionId,\n      extractedFilename,\n      filename: opts.filename,\n      chunkName: fileNameToChunkName(opts.root, extractedFilename),\n      isClientReferenced,\n    }\n  }\n}\n\nfunction codeFrameError(\n  code: string,\n  loc:\n    | {\n        start: { line: number; column: number }\n        end: { line: number; column: number }\n      }\n    | undefined\n    | null,\n  message: string,\n) {\n  if (!loc) {\n    return new Error(`${message} at unknown location`)\n  }\n\n  const frame = codeFrameColumns(\n    code,\n    {\n      start: loc.start,\n      end: loc.end,\n    },\n    {\n      highlightCode: true,\n      message,\n    },\n  )\n\n  return new Error(frame)\n}\n\nconst safeRemoveExports = (ast: babel.types.File) => {\n  ast.program.body = ast.program.body.flatMap((node) => {\n    if (\n      babel.types.isExportNamedDeclaration(node) ||\n      babel.types.isExportDefaultDeclaration(node)\n    ) {\n      if (\n        babel.types.isFunctionDeclaration(node.declaration) ||\n        babel.types.isClassDeclaration(node.declaration) ||\n        babel.types.isVariableDeclaration(node.declaration)\n      ) {\n        // do not remove export if it is an anonymous function / class, otherwise this would produce a syntax error\n        if (\n          babel.types.isFunctionDeclaration(node.declaration) ||\n          babel.types.isClassDeclaration(node.declaration)\n        ) {\n          if (!node.declaration.id) {\n            return node\n          }\n        }\n        return node.declaration\n      } else if (node.declaration === null) {\n        // remove e.g. `export { RouteComponent as component }`\n        return []\n      }\n    }\n    return node\n  })\n}\n\nfunction fileNameToChunkName(root: string, fileName: string) {\n  // Replace anything that can't go into an import statement\n  return fileName.replace(root, '').replace(/[^a-zA-Z0-9_]/g, '_')\n}\n"],"names":["parseAst","findReferencedIdentifiers","babel","deadCodeElimination","generateFromAst","path","isVariableDeclarator","isIdentifier","compileDirectiveOpts","functionName","codeFrameColumns"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA8EO,SAAS,kBAAkB,MAGhC;AACA,QAAM,MAAMA,YAAAA,SAAS,IAAI;AACzB,QAAM,YAAYC,yBAAAA,0BAA0B,GAAG;AAC/C,QAAM,mBAAmB,eAAe,KAAK;AAAA,IAC3C,GAAG;AAAA,IACH,qBAAqB,KAAK;AAAA,IAC1B,uBAAuB,KAAK;AAAA,EAAA,CAC7B;AAGD,MAAI,OAAO,KAAK,gBAAgB,EAAE,SAAS,GAAG;AAC5C,QAAI,KAAK,gBAAgB;AACvB,YAAM,gBAAgBC,iBAAM,SAAS;AAAA,QACnC,KAAK,eAAe,EAAE,iBAAA,CAAkB;AAAA,MAAA,EAC1C;AAC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