sailfork / t3code-github / .repos/ alchemy-effect/ packages/ frontend-frameworks/ src/ nextjs/ source.ts

import * as NodeCrypto from "node:crypto";
import { createRequire } from "node:module";
/**
 * The alchemy Worker source-provider entry for Next.js
 * (`@alchemy.run/frontend-frameworks/nextjs/source`).
 *
 * The default export implements alchemy's `WorkerSourceModule` contract
 * (`packages/cloudflare/src/Workers/Source.ts`) **structurally** —
 * this package deliberately does not import alchemy types. The shapes
 * mirrored here are:
 *
 * - `WorkerSourceModule` — `{ make(options) => Effect<SourceProvider> }`
 * - `SourceProvider` — `{ ownsAssets, build(ctx), hash(ctx, previous), dev(ctx) }`
 * - `SourceBuildOutput` — `{ bundle: { files, hash }, assets: AssetReadResult, hash }`
 * - `AssetReadResult` — the manifest shape alchemy's asset uploader consumes
 *   (per-file hash = sha256 hex truncated to 32 chars, the Workers Assets
 *   API's content-address format)
 *
 * `build()` wraps this package's `Framework` service (the OpenNext-based,
 * wrangler-free pipeline in `Nextjs.ts`): server modules become the worker
 * bundle (entry first), `.open-next/assets` becomes the static-assets
 * manifest, and the project tree is content-hashed for rebuild-free diffs.
 * `hash()` never builds — it recomputes the input-tree hash (including this
 * package's version, so an adapter upgrade busts the memo). `dev()` is v1
 * preview parity: the built worker served under cloudflare-runtime (workerd);
 * ISR revalidation writes are a documented no-op (read-only static-assets
 * incremental cache).
 */
import type { BindingHooks, RuntimeWorker } from "@alchemy.run/cloudflare-runtime/core";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type { PlatformError } from "effect/PlatformError";
import type * as Scope from "effect/Scope";
import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts";
import * as FrameworkCore from "../core/index.ts";
import * as Nextjs from "./Nextjs.ts";
import * as Runner from "./Runner.ts";

const packageVersion: string = createRequire(import.meta.url)("../../package.json").version;

const PROVIDER = "@alchemy.run/frontend-frameworks/nextjs/source";

// ─────────────────────────────────────────────────────────────────────
// Structural mirrors of alchemy's Source.ts contract
// ─────────────────────────────────────────────────────────────────────

/**
 * Structural mirror of alchemy's `Cloudflare.Workers.SourceProviderError`
 * (same `_tag`, so alchemy-side `Effect.catchTag` handles it as its own).
 */
export class SourceProviderError extends Data.TaggedError(
  "Cloudflare.Workers.SourceProviderError",
)<{
  readonly provider: string;
  readonly message: string;
  readonly cause?: unknown;
}> {}

/** Mirror of alchemy's `SourceHash` (the Worker `hash` attribute slots). */
export interface SourceHash {
  readonly bundle: string | undefined;
  readonly assets: string | undefined;
  readonly input: string | undefined;
  readonly additionalWorkspaces: Array<string> | undefined;
}

/** Mirror of alchemy's `Bundle.BundleFile`. */
export interface SourceBundleFile {
  readonly path: string;
  readonly content: string | Uint8Array;
  readonly hash: string;
}

/** Mirror of alchemy's `AssetReadResult` (Workers Assets manifest shape). */
export interface SourceAssets {
  directory: string;
  config: Record<string, unknown> | undefined;
  manifest: Record<string, { hash: string; size: number }>;
  _headers: string | undefined;
  _redirects: string | undefined;
  hash: string;
}

/** Mirror of alchemy's `SourceBuildOutput`. */
export interface SourceBuildOutput {
  readonly bundle: { readonly files: Array<SourceBundleFile>; readonly hash: string } | undefined;
  readonly assets: SourceAssets | undefined;
  readonly hash: SourceHash;
}

/** The subset of alchemy's `SourceContext` this provider consumes. */
export interface SourceContext {
  readonly dotAlchemy?: string;
  readonly id: string;
  readonly workerName: string;
  readonly compatibility: {
    readonly date: string;
    readonly flags: Array<string>;
  };
  readonly env?: Record<string, unknown> | undefined;
  readonly assets?: string | Record<string, unknown> | undefined;
}

type WorkerWiring = Omit<
  RuntimeWorker<BindingHooks>,
  "compatibilityDate" | "compatibilityFlags" | "modules"
>;

/** The subset of alchemy's `DevContext` this provider consumes. */
export interface DevContext extends SourceContext {
  readonly worker: {
    readonly bindings: NonNullable<WorkerWiring["bindings"]>;
    readonly durableObjectNamespaces: NonNullable<WorkerWiring["durableObjectNamespaces"]>;
    readonly hyperdrives: NonNullable<WorkerWiring["hyperdrives"]>;
    readonly queueConsumers: Effect.Effect<NonNullable<WorkerWiring["queueConsumers"]>>;
    readonly assets: WorkerWiring["assets"] | undefined;
    /**
     * The Worker's other runtime settings (crons, Workflows, tail consumers,
     * Cache API, `request.cf`, zone, Access), spread whole into the runtime
     * Worker.
     */
    readonly options: Pick<
      RuntimeWorker,
      "workflows" | "crons" | "tails" | "streamingTails" | "cache" | "cf" | "zone" | "access"
    >;
  };
  /**
   * The host's runtime stack (a `Context.Context<RuntimeServices>`) — the
   * dev binding proxy is hosted in it instead of the credential-free
   * internal layer, so `Alchemy.remote()` bindings resolve in dev.
   */
  readonly runtimeContext: unknown;
}

export type SourceDevHandle = {
  readonly mode: "server";
  readonly url: URL;
  readonly serviceBinding?: "http";
};

export type SourceError = SourceProviderError | PlatformError;

export type SourceServices = FileSystem.FileSystem | Path.Path;

/** Mirror of alchemy's `SourceProvider` (the arms this module implements). */
export interface SourceProvider {
  readonly ownsAssets: boolean;
  readonly build: (
    ctx: SourceContext,
  ) => Effect.Effect<SourceBuildOutput, SourceError, SourceServices>;
  readonly hash: (
    ctx: SourceContext,
    previous: SourceHash | undefined,
  ) => Effect.Effect<Partial<SourceHash>, SourceError, SourceServices>;
  readonly dev: (
    ctx: DevContext,
  ) => Effect.Effect<SourceDevHandle, SourceError, SourceServices | Scope.Scope>;
}

// ─────────────────────────────────────────────────────────────────────
// Options
// ─────────────────────────────────────────────────────────────────────

/**
 * Controls which project files are content-hashed to decide whether the
 * OpenNext build needs to re-run. Mirrors the semantics of alchemy's
 * `MemoOptions` (`Command/Memo.ts`) with a built-in glob matcher:
 * `**` crosses directory boundaries, `*`/`?` stay within a segment.
 */
export interface NextjsMemoOptions {
  /** Glob patterns of files to hash, relative to the project root. @default all files */
  readonly include?: Array<string> | undefined;
  /** Glob patterns to exclude from hashing. Build outputs (`.next`, `.open-next`, `dist`) and `node_modules` are always excluded. */
  readonly exclude?: Array<string> | undefined;
  /**
   * Include the nearest package-manager lockfile in the hash, even when it
   * lives above the project root (e.g. a monorepo root).
   * @default true when both `include` and `exclude` are unset; false otherwise
   */
  readonly lockfile?: boolean | undefined;
}

/**
 * The JSON-serializable options of the `@alchemy.run/frontend-frameworks/nextjs/source`
 * descriptor (`WorkerProps.source.options`). Must stay JSON-stable — the
 * descriptor persists in state and participates in the Worker metadata hash.
 */
export interface NextjsSourceOptions {
  /** The Next.js project root. Defaults to the process working directory. */
  readonly root?: string | undefined;
  /** Rebuild-scope configuration (which files bust the build memo). */
  readonly memo?: NextjsMemoOptions | undefined;
  /** Optional explicit config; otherwise discover `open-next.config.ts`, falling back to generated defaults. */
  readonly configPath?: string | undefined;
  /** Resource-selected cache adapters. Defaults to the read-only static-assets cache. */
  readonly cache?: "static-assets" | "kv" | undefined;
  /**
   * The command the OpenNext pipeline runs to build the Next.js app.
   * Takes precedence over an explicitly supplied OpenNext config.
   * @default "npx next build"
   */
  readonly buildCommand?: string | undefined;
  /** Skip the internal `next build` (reuse an existing `.next`). */
  readonly skipNextBuild?: boolean | undefined;
  /** Minify the OpenNext bundling steps and the final bundle pass. */
  readonly minify?: boolean | undefined;
  /** Enable OpenNext debug logging (and verbose workerd output in dev). */
  readonly debug?: boolean | undefined;
  /** Dev-server behavior (JSON-stable; does not affect the build). */
  readonly dev?:
    | {
        /**
         * - `"preview"` (default): build the OpenNext worker and serve it
         *   under `cloudflare-runtime` (workerd) — production parity, no HMR.
         * - `"hmr"`: run the real `next dev` (Turbopack HMR) in Node with the
         *   worker's bindings proxied from `cloudflare-runtime` onto
         *   OpenNext's `getCloudflareContext()` contract. App code runs in
         *   Node, not workerd — CF-specific runtime behavior and ISR/caching
         *   semantics still need `"preview"`.
         * @default "preview"
         */
        readonly mode?: "preview" | "hmr" | undefined;
      }
    | undefined;
}

// ─────────────────────────────────────────────────────────────────────
// Hashing helpers (mirroring alchemy's Memo.ts / Assets.ts semantics)
// ─────────────────────────────────────────────────────────────────────

const sha256Hex = (input: string | Uint8Array): Effect.Effect<string> =>
  Effect.sync(() => NodeCrypto.createHash("sha256").update(input).digest("hex"));

/** JSON.stringify with recursively sorted object keys (stable across runs). */
const stableStringify = (value: unknown): string => {
  const stable = (v: unknown): unknown => {
    if (Array.isArray(v)) return v.map(stable);
    if (v !== null && typeof v === "object") {
      return Object.fromEntries(
        Object.entries(v as Record<string, unknown>)
          .filter(([, entry]) => entry !== undefined)
          .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
          .map(([k, entry]) => [k, stable(entry)]),
      );
    }
    return v;
  };
  return JSON.stringify(stable(value ?? null));
};

/**
 * Compile a glob to a RegExp: `**` crosses `/` boundaries, `*` and `?` stay
 * within a path segment. Enough for memo scoping (`app/**`, `package.json`);
 * not a full gitignore engine.
 */
const globToRegExp = (glob: string): RegExp => {
  let out = "";
  for (let i = 0; i < glob.length; i++) {
    const ch = glob[i]!;
    if (ch === "*") {
      if (glob[i + 1] === "*") {
        // `**/` also matches zero directories.
        if (glob[i + 2] === "/") {
          out += "(?:.*/)?";
          i += 2;
        } else {
          out += ".*";
          i += 1;
        }
      } else {
        out += "[^/]*";
      }
    } else if (ch === "?") {
      out += "[^/]";
    } else if ("\\^$.|+()[]{}".includes(ch)) {
      out += `\\${ch}`;
    } else {
      out += ch;
    }
  }
  return new RegExp(`^${out}

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/frontend-frameworks/src/nextjs/source.ts at main · sailfork/t3code-github · Sailfork
	
		
); }; /** * Directories that are never inputs: VCS metadata and this integration's own * build outputs. Pruning them is load-bearing — `build()` writes `.next`, * `.open-next`, and `dist` into the project root, so hashing them would make * every deploy dirty its own memo. */ const ALWAYS_PRUNED = new Set([ "node_modules", ".git", ".next", ".open-next", "dist", ".turbo", ".vercel", ".alchemy", ".wrangler", ]); const ALWAYS_IGNORED_FILES = new Set([".DS_Store"]); /** Recursively list files under `root` (relative, `/`-separated), pruning `prune`d directories. */ const listProjectFiles = Effect.fn(function* ( root: string, prune: ReadonlySet<string>, dotAlchemy?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const runtimeDirectory = dotAlchemy === undefined ? undefined : path.resolve(process.cwd(), dotAlchemy); const out: Array<string> = []; const walk = (relative: string): Effect.Effect<void, PlatformError, never> => Effect.gen(function* () { const absolute = relative === "" ? root : path.join(root, relative); const entries = yield* fs.readDirectory(absolute); for (const entry of entries) { const rel = relative === "" ? entry : `${relative}/${entry}`; if (runtimeDirectory !== undefined) { const runtimeRelative = path.relative(runtimeDirectory, path.join(root, rel)); if ( runtimeRelative === "" || (!path.isAbsolute(runtimeRelative) && runtimeRelative !== ".." && !runtimeRelative.startsWith(`..${path.sep}`)) ) continue; } const info = yield* fs.stat(path.join(root, rel)); if (info.type === "Directory") { if (!prune.has(entry)) { yield* walk(rel); } } else if (info.type === "File" && !ALWAYS_IGNORED_FILES.has(entry)) { out.push(rel); } } }); yield* walk(""); return out.sort(); }); const findUp = Effect.fn(function* (start: string, filenames: Array<string>) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; let dir = start; for (;;) { for (const filename of filenames) { const candidate = path.join(dir, filename); if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { return candidate; } } const parent = path.dirname(dir); if (parent === dir) return undefined; dir = parent; } }); /** * Content-hash the project's input tree. Deterministic for an unchanged tree * and machine-independent for identical bytes: only root-relative paths are * hashed, never absolute ones. The material additionally covers this * package's version and the build-affecting options, so an adapter upgrade * or an options change busts the memo without any file edit. */ const hashInputTree = Effect.fn(function* ( root: string, options: NextjsSourceOptions, dotAlchemy?: string, ) { const fs = yield* FileSystem.FileSystem; const memo = options.memo ?? {}; const include = (memo.include ?? ["**/*"]).map(globToRegExp); const exclude = (memo.exclude ?? []).map(globToRegExp); const files = (yield* listProjectFiles(root, ALWAYS_PRUNED, dotAlchemy)).filter( (file) => include.some((re) => re.test(file)) && !exclude.some((re) => re.test(file)), ); const path = yield* Path.Path; const entries = yield* Effect.forEach( files, (file) => fs.readFile(path.join(root, file)).pipe( Effect.flatMap(sha256Hex), Effect.map((hash) => `${file}:${hash}`), ), { concurrency: 16 }, ); // Mirror alchemy's Memo.ts default: the nearest lockfile participates // only when the memo scope wasn't explicitly narrowed. const includeLockfile = memo.lockfile ?? !(memo.include || memo.exclude); let lockfileHash: string | undefined; if (includeLockfile) { const lockfile = yield* findUp(root, [ "bun.lock", "bun.lockb", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", ]); if (lockfile !== undefined) { lockfileHash = yield* fs.readFile(lockfile).pipe(Effect.flatMap(sha256Hex)); } } const configPath = yield* Runner.resolveConfigPath({ appDir: root, configPath: options.configPath, }).pipe(Effect.mapError(frameworkError)); const configHash = configPath === undefined ? undefined : yield* fs.readFile(configPath).pipe(Effect.flatMap(sha256Hex)); return yield* sha256Hex( stableStringify({ version: packageVersion, config: { path: configPath === undefined ? undefined : path.relative(root, configPath).replaceAll("\\", "/"), hash: configHash, }, options: { configPath: options.configPath, cache: options.cache, buildCommand: options.buildCommand, skipNextBuild: options.skipNextBuild, minify: options.minify, }, files: entries, lockfile: lockfileHash, }), ); }); // ───────────────────────────────────────────────────────────────────── // Assets (mirror of alchemy's readAssets manifest semantics) // ───────────────────────────────────────────────────────────────────── const MAX_ASSET_SIZE = 1024 * 1024 * 25; // 25MB (Workers Assets limit) const MAX_ASSET_COUNT = 20_000; const maybeReadString = Effect.fn(function* (file: string) { const fs = yield* FileSystem.FileSystem; return yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => undefined)); }); /** * Read the client directory into the Workers Assets manifest shape alchemy's * uploader consumes: keys are `/`-prefixed paths, per-file hash is the sha256 * hex digest truncated to 32 chars (the API's content-address format), and * the aggregate `hash` covers config + manifest + `_headers`/`_redirects`. */ const readClientAssets = Effect.fn(function* ( directory: string, config: Record<string, unknown> | undefined, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const [files, _headers, _redirects] = yield* Effect.all([ // The client directory is a build product (`.open-next/assets`): every // file in it is servable, so nothing is pruned (mirroring readAssets). listProjectFiles(directory, new Set<string>()), maybeReadString(path.join(directory, "_headers")), maybeReadString(path.join(directory, "_redirects")), ]); const ignore = yield* maybeReadString(path.join(directory, ".assetsignore")); const ignored = (ignore ?? "") .split("\n") .map((line) => line.trim()) .filter((line) => line.length > 0 && !line.startsWith("#")) .map(globToRegExp); const manifest: Record<string, { hash: string; size: number }> = {}; let count = 0; yield* Effect.forEach( files, Effect.fn(function* (name) { if ( name === ".assetsignore" || name === "_headers" || name === "_redirects" || ignored.some((re) => re.test(name)) ) { return; } const file = path.join(directory, name); const stat = yield* fs.stat(file); const size = Number(stat.size); if (size > MAX_ASSET_SIZE) { return yield* new SourceProviderError({ provider: PROVIDER, message: `Asset ${name} is too large (${(size / 1024 / 1024).toFixed(1)} MB; the Workers Assets limit is 25 MB)`, }); } count++; if (count > MAX_ASSET_COUNT) { return yield* new SourceProviderError({ provider: PROVIDER, message: `Too many assets in ${directory} (the Workers Assets limit is ${MAX_ASSET_COUNT})`, }); } const hash = (yield* fs.readFile(file).pipe(Effect.flatMap(sha256Hex))).slice(0, 32); manifest[`/${name}`] = { hash, size }; }), { concurrency: 16 }, ); const sortedManifest = Object.fromEntries( Object.entries(manifest).sort(([a], [b]) => a.localeCompare(b)), ); // Like alchemy's readAssets, `directory` is deliberately excluded from the // hash material: identical bytes at a different absolute path must produce // the same hash. const hash = yield* sha256Hex( stableStringify({ config, manifest: sortedManifest, _headers, _redirects }), ); return { directory, config, manifest: sortedManifest, _headers, _redirects, hash, } satisfies SourceAssets; }); // ───────────────────────────────────────────────────────────────────── // The provider // ───────────────────────────────────────────────────────────────────── const assetsConfigOf = (ctx: SourceContext): Record<string, unknown> | undefined => ctx.assets !== undefined && typeof ctx.assets !== "string" ? (ctx.assets as Record<string, unknown>) : undefined; const frameworkError = (cause: { readonly message: string }): SourceProviderError => new SourceProviderError({ provider: PROVIDER, message: cause.message, cause, }); /** Run `use` against a freshly-built `Framework` service for `options`. */ const withFramework = <A, E, R>( options: Nextjs.NextjsFrameworkOptions, use: (framework: FrameworkCore.Framework["Service"]) => Effect.Effect<A, E, R>, ) => Effect.gen(function* () { const framework = yield* FrameworkCore.Framework; return yield* use(framework); }).pipe(Effect.provide(Nextjs.make(options))); /** * The production build runs in a disposable child process with * `cwd = project root` (see `core/BuildChild.ts`). The OpenNext pipeline * itself already runs in its own child (`runner.mjs`, nested inside this * one), but the surrounding steps — `open-next.config.ts` handling, the * final bundle pass, cache population — execute framework/user code that * must not run in the engine process either. The shared `core/BuildChildRunner` * entry imports this module in the child and calls the exported * {@link buildInChild}. */ export interface NextjsBuildChildConfig { readonly rootDir: string; readonly compatibilityDate: string; readonly compatibilityFlags: Array<string>; readonly configPath: string | undefined; readonly cache: "static-assets" | "kv" | undefined; readonly buildCommand: string | undefined; readonly skipNextBuild: boolean | undefined; readonly minify: boolean | undefined; readonly debug: boolean | undefined; } export const buildInChild = (config: NextjsBuildChildConfig) => withFramework( { root: config.rootDir, vite: { compatibilityDate: config.compatibilityDate, compatibilityFlags: config.compatibilityFlags, }, nextjs: { configPath: config.configPath, cache: config.cache, buildCommand: config.buildCommand, skipNextBuild: config.skipNextBuild, minify: config.minify, debug: config.debug, }, }, (framework) => framework.build({ root: config.rootDir }), ); const makeProvider = (options: NextjsSourceOptions): SourceProvider => { const frameworkOptions = (ctx: SourceContext): Nextjs.NextjsFrameworkOptions => ({ root: options.root, vite: { compatibilityDate: ctx.compatibility.date, compatibilityFlags: ctx.compatibility.flags, }, nextjs: { configPath: options.configPath, cache: options.cache, buildCommand: options.buildCommand, skipNextBuild: options.skipNextBuild, minify: options.minify, debug: options.debug, }, dev: options.dev, }); const resolveRoot = Effect.fn(function* () { const path = yield* Path.Path; return path.resolve(options.root ?? (yield* Effect.sync(() => process.cwd()))); }); return { ownsAssets: true, build: Effect.fn(function* (ctx) { const root = yield* resolveRoot(); const output = yield* runBuildChild({ module: import.meta.url, rootDir: root, framework: "nextjs", env: resolveBuildEnv(ctx.env), config: { rootDir: root, compatibilityDate: ctx.compatibility.date, compatibilityFlags: ctx.compatibility.flags, configPath: options.configPath, cache: options.cache, buildCommand: options.buildCommand, skipNextBuild: options.skipNextBuild, minify: options.minify, debug: options.debug, } satisfies NextjsBuildChildConfig, }).pipe(Effect.mapError(frameworkError)); if (output.serverModules === undefined || output.serverModules.length === 0) { return yield* new SourceProviderError({ provider: PROVIDER, message: "The OpenNext build produced no server modules", }); } const files = output.serverModules.map((file): SourceBundleFile => ({ path: file.name, content: file.content, hash: file.hash, })); const bundleHash = yield* sha256Hex( stableStringify(files.map(({ path, hash }) => ({ path, hash }))), ); const [assets, input] = yield* Effect.all([ output.clientDirectory !== undefined ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx)) : Effect.undefined, hashInputTree(root, options, ctx.dotAlchemy), ]); return { bundle: { files, hash: bundleHash }, assets, hash: { bundle: bundleHash, assets: assets?.hash, input, additionalWorkspaces: undefined, }, } satisfies SourceBuildOutput; }), // Rebuild-free: the input-tree hash is the change signal (like the vite // source). `previous` is never consulted — state can be stale/foreign. hash: Effect.fn(function* (ctx, _previous) { const root = yield* resolveRoot(); return { input: yield* hashInputTree(root, options, ctx.dotAlchemy) }; }), // Default ("preview"): always build on dev start (OpenNext memoizes // where possible) and serve the built worker under cloudflare-runtime // (workerd) with the alchemy-managed binding wiring. No HMR; ISR // revalidation writes are a no-op. // With `options.dev.mode: "hmr"`, the Framework instead runs the real // `next dev` (Turbopack HMR) in Node — the alchemy-managed bindings are // proxied through cloudflare-runtime's platform proxy onto OpenNext's // getCloudflareContext() contract. dev: Effect.fn(function* (ctx) { const root = yield* resolveRoot(); const queueConsumers = yield* ctx.worker.queueConsumers; const devOptions: Nextjs.NextjsFrameworkOptions = { ...frameworkOptions(ctx), // The host's runtime stack (includes remote-bindings support) — the // dev binding proxy is hosted in it instead of the credential-free // internal layer, so `Alchemy.remote()` bindings resolve in dev. services: ctx.runtimeContext, vite: { compatibilityDate: ctx.compatibility.date, compatibilityFlags: ctx.compatibility.flags, worker: { ...ctx.worker.options, name: ctx.workerName, bindings: ctx.worker.bindings, durableObjectNamespaces: ctx.worker.durableObjectNamespaces, hyperdrives: ctx.worker.hyperdrives, queueConsumers, assets: ctx.worker.assets, }, }, }; const server = yield* withFramework(devOptions, (framework) => framework.dev({ root })).pipe( Effect.mapError(frameworkError), ); return { mode: "server", url: new URL(server.url), serviceBinding: options.dev?.mode === "hmr" ? "http" : undefined, } satisfies SourceDevHandle; }), }; }; /** * The `WorkerSourceModule` implementation: validate the descriptor options * and hand back the provider. */ const make = ( options: unknown, ): Effect.Effect<SourceProvider, SourceProviderError, SourceServices> => { if (options !== undefined && (typeof options !== "object" || Array.isArray(options))) { return Effect.fail( new SourceProviderError({ provider: PROVIDER, message: "Invalid source options: expected a plain JSON object (NextjsSourceOptions)", }), ); } return Effect.succeed(makeProvider((options ?? {}) as NextjsSourceOptions)); }; export default { make };
.repos/alchemy-effect/packages/frontend-frameworks/src/nextjs/source.ts at main · sailfork/t3code-github · Sailfork
);\n};\n\n/**\n * Directories that are never inputs: VCS metadata and this integration's own\n * build outputs. Pruning them is load-bearing — `build()` writes `.next`,\n * `.open-next`, and `dist` into the project root, so hashing them would make\n * every deploy dirty its own memo.\n */\nconst ALWAYS_PRUNED = new Set([\n \"node_modules\",\n \".git\",\n \".next\",\n \".open-next\",\n \"dist\",\n \".turbo\",\n \".vercel\",\n \".alchemy\",\n \".wrangler\",\n]);\n\nconst ALWAYS_IGNORED_FILES = new Set([\".DS_Store\"]);\n\n/** Recursively list files under `root` (relative, `/`-separated), pruning `prune`d directories. */\nconst listProjectFiles = Effect.fn(function* (\n root: string,\n prune: ReadonlySet\u003cstring>,\n dotAlchemy?: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const runtimeDirectory =\n dotAlchemy === undefined ? undefined : path.resolve(process.cwd(), dotAlchemy);\n const out: Array\u003cstring> = [];\n const walk = (relative: string): Effect.Effect\u003cvoid, PlatformError, never> =>\n Effect.gen(function* () {\n const absolute = relative === \"\" ? root : path.join(root, relative);\n const entries = yield* fs.readDirectory(absolute);\n for (const entry of entries) {\n const rel = relative === \"\" ? entry : `${relative}/${entry}`;\n if (runtimeDirectory !== undefined) {\n const runtimeRelative = path.relative(runtimeDirectory, path.join(root, rel));\n if (\n runtimeRelative === \"\" ||\n (!path.isAbsolute(runtimeRelative) &&\n runtimeRelative !== \"..\" &&\n !runtimeRelative.startsWith(`..${path.sep}`))\n )\n continue;\n }\n const info = yield* fs.stat(path.join(root, rel));\n if (info.type === \"Directory\") {\n if (!prune.has(entry)) {\n yield* walk(rel);\n }\n } else if (info.type === \"File\" && !ALWAYS_IGNORED_FILES.has(entry)) {\n out.push(rel);\n }\n }\n });\n yield* walk(\"\");\n return out.sort();\n});\n\nconst findUp = Effect.fn(function* (start: string, filenames: Array\u003cstring>) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n let dir = start;\n for (;;) {\n for (const filename of filenames) {\n const candidate = path.join(dir, filename);\n if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {\n return candidate;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n});\n\n/**\n * Content-hash the project's input tree. Deterministic for an unchanged tree\n * and machine-independent for identical bytes: only root-relative paths are\n * hashed, never absolute ones. The material additionally covers this\n * package's version and the build-affecting options, so an adapter upgrade\n * or an options change busts the memo without any file edit.\n */\nconst hashInputTree = Effect.fn(function* (\n root: string,\n options: NextjsSourceOptions,\n dotAlchemy?: string,\n) {\n const fs = yield* FileSystem.FileSystem;\n const memo = options.memo ?? {};\n const include = (memo.include ?? [\"**/*\"]).map(globToRegExp);\n const exclude = (memo.exclude ?? []).map(globToRegExp);\n const files = (yield* listProjectFiles(root, ALWAYS_PRUNED, dotAlchemy)).filter(\n (file) => include.some((re) => re.test(file)) && !exclude.some((re) => re.test(file)),\n );\n const path = yield* Path.Path;\n const entries = yield* Effect.forEach(\n files,\n (file) =>\n fs.readFile(path.join(root, file)).pipe(\n Effect.flatMap(sha256Hex),\n Effect.map((hash) => `${file}:${hash}`),\n ),\n { concurrency: 16 },\n );\n // Mirror alchemy's Memo.ts default: the nearest lockfile participates\n // only when the memo scope wasn't explicitly narrowed.\n const includeLockfile = memo.lockfile ?? !(memo.include || memo.exclude);\n let lockfileHash: string | undefined;\n if (includeLockfile) {\n const lockfile = yield* findUp(root, [\n \"bun.lock\",\n \"bun.lockb\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n ]);\n if (lockfile !== undefined) {\n lockfileHash = yield* fs.readFile(lockfile).pipe(Effect.flatMap(sha256Hex));\n }\n }\n const configPath = yield* Runner.resolveConfigPath({\n appDir: root,\n configPath: options.configPath,\n }).pipe(Effect.mapError(frameworkError));\n const configHash =\n configPath === undefined\n ? undefined\n : yield* fs.readFile(configPath).pipe(Effect.flatMap(sha256Hex));\n return yield* sha256Hex(\n stableStringify({\n version: packageVersion,\n config: {\n path:\n configPath === undefined\n ? undefined\n : path.relative(root, configPath).replaceAll(\"\\\\\", \"/\"),\n hash: configHash,\n },\n options: {\n configPath: options.configPath,\n cache: options.cache,\n buildCommand: options.buildCommand,\n skipNextBuild: options.skipNextBuild,\n minify: options.minify,\n },\n files: entries,\n lockfile: lockfileHash,\n }),\n );\n});\n\n// ─────────────────────────────────────────────────────────────────────\n// Assets (mirror of alchemy's readAssets manifest semantics)\n// ─────────────────────────────────────────────────────────────────────\n\nconst MAX_ASSET_SIZE = 1024 * 1024 * 25; // 25MB (Workers Assets limit)\nconst MAX_ASSET_COUNT = 20_000;\n\nconst maybeReadString = Effect.fn(function* (file: string) {\n const fs = yield* FileSystem.FileSystem;\n return yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => undefined));\n});\n\n/**\n * Read the client directory into the Workers Assets manifest shape alchemy's\n * uploader consumes: keys are `/`-prefixed paths, per-file hash is the sha256\n * hex digest truncated to 32 chars (the API's content-address format), and\n * the aggregate `hash` covers config + manifest + `_headers`/`_redirects`.\n */\nconst readClientAssets = Effect.fn(function* (\n directory: string,\n config: Record\u003cstring, unknown> | undefined,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const [files, _headers, _redirects] = yield* Effect.all([\n // The client directory is a build product (`.open-next/assets`): every\n // file in it is servable, so nothing is pruned (mirroring readAssets).\n listProjectFiles(directory, new Set\u003cstring>()),\n maybeReadString(path.join(directory, \"_headers\")),\n maybeReadString(path.join(directory, \"_redirects\")),\n ]);\n const ignore = yield* maybeReadString(path.join(directory, \".assetsignore\"));\n const ignored = (ignore ?? \"\")\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"))\n .map(globToRegExp);\n const manifest: Record\u003cstring, { hash: string; size: number }> = {};\n let count = 0;\n yield* Effect.forEach(\n files,\n Effect.fn(function* (name) {\n if (\n name === \".assetsignore\" ||\n name === \"_headers\" ||\n name === \"_redirects\" ||\n ignored.some((re) => re.test(name))\n ) {\n return;\n }\n const file = path.join(directory, name);\n const stat = yield* fs.stat(file);\n const size = Number(stat.size);\n if (size > MAX_ASSET_SIZE) {\n return yield* new SourceProviderError({\n provider: PROVIDER,\n message: `Asset ${name} is too large (${(size / 1024 / 1024).toFixed(1)} MB; the Workers Assets limit is 25 MB)`,\n });\n }\n count++;\n if (count > MAX_ASSET_COUNT) {\n return yield* new SourceProviderError({\n provider: PROVIDER,\n message: `Too many assets in ${directory} (the Workers Assets limit is ${MAX_ASSET_COUNT})`,\n });\n }\n const hash = (yield* fs.readFile(file).pipe(Effect.flatMap(sha256Hex))).slice(0, 32);\n manifest[`/${name}`] = { hash, size };\n }),\n { concurrency: 16 },\n );\n const sortedManifest = Object.fromEntries(\n Object.entries(manifest).sort(([a], [b]) => a.localeCompare(b)),\n );\n // Like alchemy's readAssets, `directory` is deliberately excluded from the\n // hash material: identical bytes at a different absolute path must produce\n // the same hash.\n const hash = yield* sha256Hex(\n stableStringify({ config, manifest: sortedManifest, _headers, _redirects }),\n );\n return {\n directory,\n config,\n manifest: sortedManifest,\n _headers,\n _redirects,\n hash,\n } satisfies SourceAssets;\n});\n\n// ─────────────────────────────────────────────────────────────────────\n// The provider\n// ─────────────────────────────────────────────────────────────────────\n\nconst assetsConfigOf = (ctx: SourceContext): Record\u003cstring, unknown> | undefined =>\n ctx.assets !== undefined && typeof ctx.assets !== \"string\"\n ? (ctx.assets as Record\u003cstring, unknown>)\n : undefined;\n\nconst frameworkError = (cause: { readonly message: string }): SourceProviderError =>\n new SourceProviderError({\n provider: PROVIDER,\n message: cause.message,\n cause,\n });\n\n/** Run `use` against a freshly-built `Framework` service for `options`. */\nconst withFramework = \u003cA, E, R>(\n options: Nextjs.NextjsFrameworkOptions,\n use: (framework: FrameworkCore.Framework[\"Service\"]) => Effect.Effect\u003cA, E, R>,\n) =>\n Effect.gen(function* () {\n const framework = yield* FrameworkCore.Framework;\n return yield* use(framework);\n }).pipe(Effect.provide(Nextjs.make(options)));\n\n/**\n * The production build runs in a disposable child process with\n * `cwd = project root` (see `core/BuildChild.ts`). The OpenNext pipeline\n * itself already runs in its own child (`runner.mjs`, nested inside this\n * one), but the surrounding steps — `open-next.config.ts` handling, the\n * final bundle pass, cache population — execute framework/user code that\n * must not run in the engine process either. The shared `core/BuildChildRunner`\n * entry imports this module in the child and calls the exported\n * {@link buildInChild}.\n */\nexport interface NextjsBuildChildConfig {\n readonly rootDir: string;\n readonly compatibilityDate: string;\n readonly compatibilityFlags: Array\u003cstring>;\n readonly configPath: string | undefined;\n readonly cache: \"static-assets\" | \"kv\" | undefined;\n readonly buildCommand: string | undefined;\n readonly skipNextBuild: boolean | undefined;\n readonly minify: boolean | undefined;\n readonly debug: boolean | undefined;\n}\n\nexport const buildInChild = (config: NextjsBuildChildConfig) =>\n withFramework(\n {\n root: config.rootDir,\n vite: {\n compatibilityDate: config.compatibilityDate,\n compatibilityFlags: config.compatibilityFlags,\n },\n nextjs: {\n configPath: config.configPath,\n cache: config.cache,\n buildCommand: config.buildCommand,\n skipNextBuild: config.skipNextBuild,\n minify: config.minify,\n debug: config.debug,\n },\n },\n (framework) => framework.build({ root: config.rootDir }),\n );\n\nconst makeProvider = (options: NextjsSourceOptions): SourceProvider => {\n const frameworkOptions = (ctx: SourceContext): Nextjs.NextjsFrameworkOptions => ({\n root: options.root,\n vite: {\n compatibilityDate: ctx.compatibility.date,\n compatibilityFlags: ctx.compatibility.flags,\n },\n nextjs: {\n configPath: options.configPath,\n cache: options.cache,\n buildCommand: options.buildCommand,\n skipNextBuild: options.skipNextBuild,\n minify: options.minify,\n debug: options.debug,\n },\n dev: options.dev,\n });\n\n const resolveRoot = Effect.fn(function* () {\n const path = yield* Path.Path;\n return path.resolve(options.root ?? (yield* Effect.sync(() => process.cwd())));\n });\n\n return {\n ownsAssets: true,\n\n build: Effect.fn(function* (ctx) {\n const root = yield* resolveRoot();\n const output = yield* runBuildChild({\n module: import.meta.url,\n rootDir: root,\n framework: \"nextjs\",\n env: resolveBuildEnv(ctx.env),\n config: {\n rootDir: root,\n compatibilityDate: ctx.compatibility.date,\n compatibilityFlags: ctx.compatibility.flags,\n configPath: options.configPath,\n cache: options.cache,\n buildCommand: options.buildCommand,\n skipNextBuild: options.skipNextBuild,\n minify: options.minify,\n debug: options.debug,\n } satisfies NextjsBuildChildConfig,\n }).pipe(Effect.mapError(frameworkError));\n if (output.serverModules === undefined || output.serverModules.length === 0) {\n return yield* new SourceProviderError({\n provider: PROVIDER,\n message: \"The OpenNext build produced no server modules\",\n });\n }\n const files = output.serverModules.map((file): SourceBundleFile => ({\n path: file.name,\n content: file.content,\n hash: file.hash,\n }));\n const bundleHash = yield* sha256Hex(\n stableStringify(files.map(({ path, hash }) => ({ path, hash }))),\n );\n const [assets, input] = yield* Effect.all([\n output.clientDirectory !== undefined\n ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx))\n : Effect.undefined,\n hashInputTree(root, options, ctx.dotAlchemy),\n ]);\n return {\n bundle: { files, hash: bundleHash },\n assets,\n hash: {\n bundle: bundleHash,\n assets: assets?.hash,\n input,\n additionalWorkspaces: undefined,\n },\n } satisfies SourceBuildOutput;\n }),\n\n // Rebuild-free: the input-tree hash is the change signal (like the vite\n // source). `previous` is never consulted — state can be stale/foreign.\n hash: Effect.fn(function* (ctx, _previous) {\n const root = yield* resolveRoot();\n return { input: yield* hashInputTree(root, options, ctx.dotAlchemy) };\n }),\n\n // Default (\"preview\"): always build on dev start (OpenNext memoizes\n // where possible) and serve the built worker under cloudflare-runtime\n // (workerd) with the alchemy-managed binding wiring. No HMR; ISR\n // revalidation writes are a no-op.\n // With `options.dev.mode: \"hmr\"`, the Framework instead runs the real\n // `next dev` (Turbopack HMR) in Node — the alchemy-managed bindings are\n // proxied through cloudflare-runtime's platform proxy onto OpenNext's\n // getCloudflareContext() contract.\n dev: Effect.fn(function* (ctx) {\n const root = yield* resolveRoot();\n const queueConsumers = yield* ctx.worker.queueConsumers;\n const devOptions: Nextjs.NextjsFrameworkOptions = {\n ...frameworkOptions(ctx),\n // The host's runtime stack (includes remote-bindings support) — the\n // dev binding proxy is hosted in it instead of the credential-free\n // internal layer, so `Alchemy.remote()` bindings resolve in dev.\n services: ctx.runtimeContext,\n vite: {\n compatibilityDate: ctx.compatibility.date,\n compatibilityFlags: ctx.compatibility.flags,\n worker: {\n ...ctx.worker.options,\n name: ctx.workerName,\n bindings: ctx.worker.bindings,\n durableObjectNamespaces: ctx.worker.durableObjectNamespaces,\n hyperdrives: ctx.worker.hyperdrives,\n queueConsumers,\n assets: ctx.worker.assets,\n },\n },\n };\n const server = yield* withFramework(devOptions, (framework) => framework.dev({ root })).pipe(\n Effect.mapError(frameworkError),\n );\n return {\n mode: \"server\",\n url: new URL(server.url),\n serviceBinding: options.dev?.mode === \"hmr\" ? \"http\" : undefined,\n } satisfies SourceDevHandle;\n }),\n };\n};\n\n/**\n * The `WorkerSourceModule` implementation: validate the descriptor options\n * and hand back the provider.\n */\nconst make = (\n options: unknown,\n): Effect.Effect\u003cSourceProvider, SourceProviderError, SourceServices> => {\n if (options !== undefined && (typeof options !== \"object\" || Array.isArray(options))) {\n return Effect.fail(\n new SourceProviderError({\n provider: PROVIDER,\n message: \"Invalid source options: expected a plain JSON object (NextjsSourceOptions)\",\n }),\n );\n }\n return Effect.succeed(makeProvider((options ?? {}) as NextjsSourceOptions));\n};\n\nexport default { make };\n","preview":null,"history":null,"version":"7e4e3ff9bcc62327047d6f6d4c3093af821eb88f"},"/_session?shell=1":null}