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

import { fileURLToPath } from "node:url";
/**
 * `@alchemy.run/frontend-frameworks/waku/aws` — the AWS Lambda deploy target for
 * the Waku integration.
 *
 * Waku's AWS story is a plain-Node waku build with this package's forked
 * aws-lambda adapter selected via `unstable_adapter`: `dist/server` is the
 * self-contained server bundle and `dist/public` holds the static assets
 * (SSG pages included) for the CDN. What this target owns:
 *
 * - **`adapter`** — this package's fork of waku's aws-lambda adapter
 *   (`@alchemy.run/frontend-frameworks/waku/aws-adapter`): behavior-identical to
 *   upstream except the Lambda wrapper is this package's own streaming
 *   adapter (`@alchemy.run/frontend-frameworks/aws-lambda`) instead of
 *   `hono/aws-lambda`, and the serve entry is written by this target's
 *   finishing pass instead of upstream's build enhancer.
 * - **`vitePlugins`** — none: a plain-Node waku build needs no bundler
 *   plugin (there is no workerd runtime to host dev/build environments in).
 * - **`finish`** — writes the Lambda serve entry
 *   (`dist/server/serve-aws-lambda.mjs`, importing the built server chunk's
 *   `INTERNAL_runFetch` and wrapping it via the adapter's handler-wrapper
 *   global — no bare imports, so the shipped directory needs no
 *   `node_modules`) plus a `package.json` marking the directory ESM, and
 *   pins the serve entry as `serverModules[0]`.
 * - **`entry`** — surfaces `config.main` as the generic user-entry carriage.
 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
 *   (the Lambda Node.js runtime ships SDK v3) for callers that post-process
 *   server code.
 */
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type { Config as WakuConfig } from "waku/config";
import { runBuildChild } from "../core/BuildChild.ts";
import {
  DeployTargetError,
  makeDeployTarget,
  toOutputFile,
  type BuildOutput,
} from "../core/index.ts";
import { AWS_LAMBDA_HANDLE_GLOBAL } from "./aws-shared.ts";
import { make, type WakuTarget, type WakuTargetBuildContext } from "./Waku.ts";

export type { WakuTarget, WakuTargetContext } from "./Waku.ts";

/** The serve entry the finishing pass writes into `dist/server`. */
export const SERVE_ENTRY_NAME = "serve-aws-lambda.mjs";

/** Configuration accepted by the AWS deploy target. */
export interface WakuAwsTargetConfig {
  /**
   * The user's own server entry module (the deploy-target user-entry seam):
   * a module that wraps waku's handler (imported from
   * `virtual:waku/server-entry`) and re-exports extras. Absolute, or
   * relative to the project root.
   */
  readonly main?: string | undefined;
  /**
   * Whether the emitted Lambda handler streams its response
   * (`awslambda.streamifyResponse`, requires a Function URL with
   * `invokeMode: RESPONSE_STREAM`). Set `false` for the buffered
   * payload-v2 handler (`invokeMode: BUFFERED` / API Gateway HTTP APIs).
   * @default true
   */
  readonly streaming?: boolean | undefined;
}

/**
 * The content of the generated Lambda serve entry: imports the built server
 * chunk (whose module evaluation runs the adapter setup and publishes the
 * handler-wrapper global), then exports the wrapped `handler`.
 */
export const makeServeEntrySource = (streaming: boolean): string =>
  `// Generated by @alchemy.run/frontend-frameworks/waku/aws — the Lambda entry.
import { INTERNAL_runFetch } from "./index.js";

const handle = globalThis.${AWS_LAMBDA_HANDLE_GLOBAL};
if (typeof handle !== "function") {
  throw new Error(
    "The waku AWS adapter did not register its Lambda handler wrapper — " +
      "the server bundle was not built with @alchemy.run/frontend-frameworks/waku/aws-adapter.",
  );
}

export const handler = handle(
  (req, ...args) => INTERNAL_runFetch(process.env, req, ...args),
  { streaming: ${streaming} },
);
`;

/**
 * The adapter-driven target — the shape the framework's regular
 * build/finish pipeline consumes. Used directly in the build child (where
 * `cwd === root` holds); {@link makeWakuAwsTarget} wraps it with the
 * wholesale `build` hook that spawns the child.
 */
const makeAwsAdapterTarget = (
  config?: WakuAwsTargetConfig,
): WakuTarget<WakuAwsTargetConfig | undefined> =>
  makeDeployTarget({
    platform: "aws",
    config,
    entry: config?.main !== undefined ? { main: config.main } : undefined,
    bundle: {
      conditions: ["node", "import", "module"],
      external: ["@aws-sdk/"],
    },
    adapter: () =>
      Effect.try({
        try: () =>
          fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/waku/aws-adapter")),
        catch: (cause) =>
          new DeployTargetError({
            platform: "aws",
            message:
              "Failed to resolve the @alchemy.run/frontend-frameworks/waku AWS adapter module",
            cause,
          }),
      }),
    vitePlugins: () => Effect.sync(() => []),
    finish: (output, _context) =>
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        const path = yield* Path.Path;
        const fail = (message: string) => (cause?: unknown) =>
          new DeployTargetError({ platform: "aws", message, cause });

        if (output.distDirectory === undefined) {
          return yield* fail("The waku build produced no dist directory")(undefined);
        }
        const serverDir = path.join(output.distDirectory, "server");
        const serverIndex = path.join(serverDir, "index.js");
        const hasServerIndex = yield* fs
          .exists(serverIndex)
          .pipe(Effect.mapError(fail("Failed to probe the built server entry")));
        if (!hasServerIndex) {
          return yield* fail(`The waku build produced no server entry at ${serverIndex}`)(
            undefined,
          );
        }

        const serveSource = makeServeEntrySource(config?.streaming ?? true);
        // `dist/server` ships to Lambda as-is (no project package.json in the
        // archive), so the directory must carry its own ESM marker for
        // `./index.js` to parse as a module.
        yield* Effect.all(
          [
            fs.writeFileString(path.join(serverDir, SERVE_ENTRY_NAME), serveSource),
            fs.writeFileString(
              path.join(serverDir, "package.json"),
              `${JSON.stringify({ type: "module" }, null, 2)}\n`,
            ),
          ],
          { concurrency: "unbounded" },
        ).pipe(Effect.mapError(fail("Failed to write the Lambda serve entry")));

        const serveModule = yield* toOutputFile(`server/${SERVE_ENTRY_NAME}`, serveSource);
        // The serve entry becomes `serverModules[0]` — the module alchemy's
        // Server resource deploys as the Lambda `main`.
        const serverModules = [
          serveModule,
          ...(output.serverModules ?? []).filter((module_) => module_.name !== serveModule.name),
        ];
        return { ...output, serverModules } satisfies BuildOutput;
      }),
  });

/**
 * Waku assumes `process.cwd()` is the project root in several places (the
 * html-shell plugin's `index.html` input resolves against the cwd, and
 * rolldown resolves relative inputs from the cwd), so the framework build
 * chdirs to the root — which must never happen in the engine process (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 framework's own
 * chdir is a no-op there. The shared `core/BuildChildRunner` entry imports
 * this module in the child and calls the exported {@link buildInChild}.
 */
export interface WakuAwsBuildChildConfig {
  readonly rootDir: string;
  /** The (JSON-serializable) target config the parent was created with. */
  readonly config: WakuAwsTargetConfig | undefined;
  /**
   * The inline waku options the framework was constructed with
   * (`WakuFrameworkOptions.waku`, carried through the build context). Only
   * JSON-serializable fields cross the process boundary.
   */
  readonly waku: WakuConfig | undefined;
}

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

/**
 * Build the AWS Lambda {@link WakuTarget}. See the module doc for the seams.
 */
export const makeWakuAwsTarget = (
  config?: WakuAwsTargetConfig,
): WakuTarget<WakuAwsTargetConfig | undefined> => ({
  ...makeAwsAdapterTarget(config),
  build: (context: WakuTargetBuildContext) =>
    runBuildChild({
      runtime: "node",
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "waku",
      config: {
        rootDir: context.root,
        config,
        waku: context.waku,
      } satisfies WakuAwsBuildChildConfig,
    }).pipe(
      Effect.mapError(
        (error) =>
          new DeployTargetError({
            platform: "aws",
            message: error.message,
            cause: 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 = makeWakuAwsTarget;

export default makeWakuAwsTarget;