sailfork / t3code-github / .repos/ alchemy-effect/ packages/ frontend-frameworks/ src/ tanstack-start/ aws.ts

import { fileURLToPath } from "node:url";
/**
 * `@alchemy.run/frontend-frameworks/tanstack-start/aws` — the AWS Lambda
 * deploy target for the TanStack Start integration.
 *
 * TanStack Start is pure Vite: `tanstackStart()` in the project's
 * `vite.config.ts` builds a `client` environment into `<outDir>/client` and
 * an `ssr` environment into `<outDir>/server`, whose entry module
 * default-exports `{ fetch }` — a web-standard fetch handler. There is no
 * adapter to select and no deployment preset; what this target owns is the
 * Lambda packaging:
 *
 * - **`serverEntryFileName`** — `server.js`, the chunk the SSR environment
 *   emits for the resolved server entry; the finishing pass wraps it.
 * - **`finish`** — emits the Lambda deployment surface next to the entry:
 *   a `package.json` (`type: "module"` — the Lambda Node.js runtime
 *   classifies `.js` by the nearest manifest, and `<outDir>/server` ships
 *   without one), a copy of this package's self-contained `aws-lambda` web
 *   adapter, and `index.mjs` exporting `handler` — the fetch handler wrapped
 *   with `awslambda.streamifyResponse` (or the buffered payload-v2 wrapper
 *   with `streaming: false`). The rewritten `BuildOutput` puts
 *   `server/index.mjs` first, so it becomes the deployed Lambda entry.
 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
 *   (the Lambda Node.js runtime ships SDK v3) for callers that post-process
 *   server code.
 *
 * No `devPlatform`: `dev` runs TanStack Start's own Vite dev server, which
 * is already the AWS Lambda programming model (plain Node).
 */
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { runBuildChild } from "../core/BuildChild.ts";
import {
  DeployTargetError,
  makeDeployTarget,
  readServerModulesFromDisk,
  sortServerModules,
  type BuildOutput,
  type DeployTargetFinishContext,
} from "../core/index.ts";
import {
  DEFAULT_SERVER_ENTRY_FILE_NAME,
  make,
  type TanStackStartTarget,
  type TanStackStartTargetConfig,
} from "./TanStackStart.ts";

/** The server entry file name the SSR environment emits. */
export const SERVER_ENTRY_FILE_NAME = DEFAULT_SERVER_ENTRY_FILE_NAME;

/** The Lambda entry module the finishing pass emits beside the server entry. */
export const LAMBDA_ENTRY_FILE_NAME = "index.mjs";

/** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
export const LAMBDA_ADAPTER_FILE_NAME = "tanstack-start-aws-lambda.mjs";

/** AWS-specific knobs carried on the shared {@link TanStackStartTargetConfig}. */
export interface TanStackStartAwsTargetConfig extends TanStackStartTargetConfig {
  /**
   * Whether the emitted Lambda handler streams its response
   * (`awslambda.streamifyResponse`, requires a Function URL with
   * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
   * APIGW/Function-URL events with a complete response object.
   * @default true
   */
  readonly streaming?: boolean | undefined;
}

const fail = (message: string, cause?: unknown) =>
  new DeployTargetError({ platform: "aws", message, cause });

/**
 * The generated Lambda entry: imports TanStack Start's server entry and
 * exports its fetch handler wrapped for the Lambda Node.js runtime.
 *
 * The entry module default-exports `{ fetch }` (the shape
 * `createServerEntry` produces). A project whose custom server entry
 * default-exports the bare fetch function is accepted too.
 */
export const generateLambdaEntry = (options: {
  readonly streaming: boolean;
  readonly serverEntryFileName: string;
}): string => {
  const wrap = options.streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
  return `// Auto-generated by @alchemy.run/frontend-frameworks/tanstack-start/aws — do not edit.
import * as serverEntry from "./${options.serverEntryFileName}";
import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";

const entry = serverEntry.default ?? serverEntry;
const fetchHandler =
  typeof entry === "function"
    ? entry
    : (request) => entry.fetch(request);

export const handler = ${wrap}(fetchHandler);
`;
};

/**
 * Resolve this package's built, self-contained `aws-lambda` adapter module
 * on disk (it has no imports of its own, so a byte copy deploys as-is).
 */
const resolveLambdaAdapterPath = Effect.try({
  try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
  catch: (cause) =>
    fail(
      'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
      cause,
    ),
});

const finish = (
  config: TanStackStartAwsTargetConfig,
  output: BuildOutput,
  context: DeployTargetFinishContext,
): Effect.Effect<BuildOutput, DeployTargetError, FileSystem.FileSystem | Path.Path> =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    if (context.entry === undefined) {
      return yield* fail("The TanStack Start build produced no on-disk server entry to finish");
    }
    const serverDir = path.dirname(context.entry);
    const serverEntryFileName = path.basename(context.entry);

    // The Lambda Node.js runtime classifies `.js` modules by the nearest
    // package.json, and the server directory ships as the deployment root
    // without one — the ESM entry and its chunks need the marker.
    yield* fs.writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n');

    const adapterPath = yield* resolveLambdaAdapterPath;
    const adapterSource = yield* fs.readFileString(adapterPath);
    yield* fs.writeFileString(
      path.join(serverDir, LAMBDA_ADAPTER_FILE_NAME),
      // Drop the sourcemap pointer — the map is not copied into the bundle.
      adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
    );

    yield* fs.writeFileString(
      path.join(serverDir, LAMBDA_ENTRY_FILE_NAME),
      generateLambdaEntry({
        streaming: config.streaming !== false,
        serverEntryFileName,
      }),
    );

    // Re-read the server directory so the emitted files are part of the
    // output, with the Lambda entry first.
    const modules = yield* readServerModulesFromDisk({
      directory: serverDir,
      prefix: "server",
    }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
    return {
      ...output,
      serverModules: sortServerModules(modules, `server/${LAMBDA_ENTRY_FILE_NAME}`),
    };
  }).pipe(
    Effect.catchTag("PlatformError", (error) =>
      Effect.fail(fail("Failed to emit the Lambda entry", error)),
    ),
  );

/**
 * The finish-only target — the shape the framework's regular build/finish
 * pipeline consumes. Used directly in the build child (where `cwd === root`
 * holds); {@link makeAwsTarget} wraps it with the wholesale `build` hook
 * that spawns the child.
 */
const makeAwsFinishTarget = (config: TanStackStartAwsTargetConfig = {}): TanStackStartTarget =>
  makeDeployTarget({
    platform: "aws",
    config,
    bundle: {
      conditions: ["node", "import", "module"],
      external: ["@aws-sdk/"],
    },
    serverEntryFileName: SERVER_ENTRY_FILE_NAME,
    finish: (output, context) => finish(config, output, context),
  });

/**
 * A TanStack Start build loads and executes the project's `vite.config.*`
 * (its `tanstackStart()` plugin crawls framework packages from
 * `process.cwd()`, and user plugins may mutate `process.env` or
 * `process.chdir`) — none of which may touch the engine process, where many
 * deploys share one event loop. This target's wholesale `build` therefore
 * runs the framework in a disposable child process whose working directory
 * IS the project root (see `core/BuildChild.ts`). The shared
 * `core/BuildChildRunner` entry imports this module in the child and calls
 * the exported {@link buildInChild}.
 */
export interface TanStackStartAwsBuildChildConfig {
  readonly rootDir: string;
  /** The (JSON-serializable) target config the parent was created with. */
  readonly config: TanStackStartAwsTargetConfig;
}

export const buildInChild = (config: TanStackStartAwsBuildChildConfig) =>
  Effect.gen(function* () {
    const framework = yield* make({
      root: config.rootDir,
      // The finish-only target: no wholesale `build` hook, so the child
      // runs the regular vite build + finish pipeline (no recursion).
      target: makeAwsFinishTarget(config.config),
      outDir: config.config.outDir,
    });
    return yield* framework.build({ root: config.rootDir });
  });

/**
 * Create the AWS Lambda {@link TanStackStartTarget}. See the module doc for
 * the seams.
 */
export const makeAwsTarget = (config: TanStackStartAwsTargetConfig = {}): TanStackStartTarget => ({
  ...makeAwsFinishTarget(config),
  build: (context) =>
    runBuildChild({
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "tanstack-start",
      config: {
        rootDir: context.root,
        config,
      } satisfies TanStackStartAwsBuildChildConfig,
    }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
});

/**
 * The deploy-target module contract (`resolveDeployTarget` accepts the
 * default export — or the named `target` export — as a value or factory).
 */
export const target = makeAwsTarget;

export default makeAwsTarget;