alchemy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Alchemy

Alchemy

Alchemy is a TypeScript-native Infrastructure-as-Code framework. This skill provides comprehensive knowledge of Alchemy's APIs, patterns, and conventions.
Load
references/alchemy-concepts.md
for full details on any topic below.
Alchemy是一款原生支持TypeScript的基础设施即代码(IaC)框架。本技能提供关于Alchemy的API、模式与约定的全面知识。
**加载
references/alchemy-concepts.md
**以获取以下任意主题的详细信息。

Quick Start

快速开始

New Project

新项目

bash
alchemy create my-app --template vite
bash
alchemy create my-app --template vite

Add to Existing Project

添加到现有项目

bash
alchemy init
bash
alchemy init

Core File:
alchemy.run.ts

核心文件:
alchemy.run.ts

ts
import alchemy from "alchemy";
import { Worker, KVNamespace } from "alchemy/cloudflare";

const app = await alchemy("my-app");

const kv = await KVNamespace("cache", { title: "my-cache" });

const worker = await Worker("api", {
  entrypoint: "./src/worker.ts",
  bindings: {
    CACHE: kv,
    API_KEY: alchemy.secret(process.env.API_KEY),
    STAGE: app.stage,
  },
});

await app.finalize();
ts
import alchemy from "alchemy";
import { Worker, KVNamespace } from "alchemy/cloudflare";

const app = await alchemy("my-app");

const kv = await KVNamespace("cache", { title: "my-cache" });

const worker = await Worker("api", {
  entrypoint: "./src/worker.ts",
  bindings: {
    CACHE: kv,
    API_KEY: alchemy.secret(process.env.API_KEY),
    STAGE: app.stage,
  },
});

await app.finalize();

Commands

命令

bash
alchemy deploy              # deploy (default stage = $USER)
alchemy deploy --stage prod # deploy to prod
alchemy dev                 # local dev with hot reload
alchemy destroy             # tear down all resources
bash
alchemy deploy              # 部署(默认环境 = $USER)
alchemy deploy --stage prod # 部署到生产环境
alchemy dev                 # 本地开发(支持热重载)
alchemy destroy             # 销毁所有资源

Task Routing

任务路由

Based on what the user asks, determine which knowledge to load:
User RequestWhat to Do
Set up Alchemy in a projectUse
alchemy create
or
alchemy init
, create
alchemy.run.ts
Add a Worker
import { Worker } from "alchemy/cloudflare"
, configure with entrypoint + bindings
Add a database/KV/R2/queueImport from
alchemy/cloudflare
, create resource, bind to Worker
Use secrets
alchemy.secret(process.env.X)
for input,
Secret.unwrap()
in custom resources
Set up dev mode
alchemy dev
, configure framework adapter/plugin
Use a framework (Vite/Astro/etc.)Load
references/alchemy-concepts.md
§11 for framework adapters
Deploy to production
alchemy deploy --stage prod
, see CI guide patterns
Use Neon/Stripe/AWS/other providerLoad
references/alchemy-concepts.md
§13 for provider list
Build a custom resourceLoad
references/resource-patterns.md
for implementation patterns
Build a new provider for AlchemyRun the full Provider Development Workflow below
根据用户的问题,确定需要加载的知识:
用户请求操作指引
在项目中搭建Alchemy使用
alchemy create
alchemy init
,创建
alchemy.run.ts
添加Worker
alchemy/cloudflare
导入
Worker
,配置入口文件与绑定
添加数据库/KV/R2/队列
alchemy/cloudflare
导入,创建资源并绑定到Worker
使用密钥输入时使用
alchemy.secret(process.env.X)
,自定义资源中使用
Secret.unwrap()
设置开发模式使用
alchemy dev
,配置框架适配器/插件
使用框架(Vite/Astro等)加载
references/alchemy-concepts.md
第11节关于框架适配器的内容
部署到生产环境使用
alchemy deploy --stage prod
,查看CI指南模式
使用Neon/Stripe/AWS或其他提供商加载
references/alchemy-concepts.md
第13节的提供商列表
构建自定义资源加载
references/resource-patterns.md
获取实现模式
为Alchemy构建新提供商遵循以下完整的提供商开发工作流

Key Concepts

核心概念

Resources

资源

Resources are memoized async functions with create/update/delete lifecycle. Every resource takes an ID and props:
ts
const db = await D1Database("my-db", { name: "my-db" });
资源是带有创建/更新/删除生命周期的记忆化异步函数。每个资源接收一个ID和属性:
ts
const db = await D1Database("my-db", { name: "my-db" });

Bindings

绑定

Connect resources to Workers with type-safe bindings:
ts
const worker = await Worker("api", {
  entrypoint: "./src/worker.ts",
  bindings: { DB: db, KV: kv, SECRET: alchemy.secret("value") },
});
Access in worker code with type inference:
ts
import type { worker } from "../alchemy.run";
export default {
  async fetch(req: Request, env: typeof worker.Env) {
    await env.DB.prepare("SELECT 1").run();
  },
};
通过类型安全的绑定将资源连接到Worker:
ts
const worker = await Worker("api", {
  entrypoint: "./src/worker.ts",
  bindings: { DB: db, KV: kv, SECRET: alchemy.secret("value") },
});
在Worker代码中通过类型推断访问:
ts
import type { worker } from "../alchemy.run";
export default {
  async fetch(req: Request, env: typeof worker.Env) {
    await env.DB.prepare("SELECT 1").run();
  },
};

Secrets

密钥

ts
alchemy.secret(process.env.API_KEY)  // wrap a value
alchemy.secret.env.API_KEY           // shorthand
ts
alchemy.secret(process.env.API_KEY)  // 包装值
alchemy.secret.env.API_KEY           // 简写方式

Stages

环境阶段

Isolated copies of your infrastructure. Default is
$USER
locally:
bash
alchemy deploy              # deploys to $USER stage
alchemy deploy --stage prod # deploys to prod stage
基础设施的独立副本。本地默认环境为
$USER
bash
alchemy deploy              # 部署到$USER环境
alchemy deploy --stage prod # 部署到生产环境

Dev Mode

开发模式

Local emulation with Miniflare, hot reload, framework integration:
bash
alchemy dev
基于Miniflare的本地模拟,支持热重载与框架集成:
bash
alchemy dev

Framework Adapters

框架适配器

Each framework has a resource and a Vite plugin/adapter:
FrameworkResourcePlugin/Adapter
Vite
Vite
alchemy/cloudflare/vite
Astro
Astro
alchemy/cloudflare/astro
React Router
ReactRouter
alchemy/cloudflare/react-router
SvelteKit
SvelteKit
alchemy/cloudflare/sveltekit
Nuxt
Nuxt
alchemy/cloudflare/nuxt
TanStack Start
TanStackStart
alchemy/cloudflare/tanstack-start
BunSPA
BunSPA
(no plugin needed)
Next.js
Nextjs
alchemy/cloudflare/nextjs
Redwood (RWSDK)
Redwood
alchemy/cloudflare/rwsdk
每个框架都有对应的资源和Vite插件/适配器:
框架资源插件/适配器
Vite
Vite
alchemy/cloudflare/vite
Astro
Astro
alchemy/cloudflare/astro
React Router
ReactRouter
alchemy/cloudflare/react-router
SvelteKit
SvelteKit
alchemy/cloudflare/sveltekit
Nuxt
Nuxt
alchemy/cloudflare/nuxt
TanStack Start
TanStackStart
alchemy/cloudflare/tanstack-start
BunSPA
BunSPA
(无需插件)
Next.js
Nextjs
alchemy/cloudflare/nextjs
Redwood (RWSDK)
Redwood
alchemy/cloudflare/rwsdk

Providers

提供商

Alchemy has 20+ providers. The main ones:
ProviderImportKey Resources
Cloudflare
alchemy/cloudflare
Worker, D1Database, KVNamespace, R2Bucket, Queue, DurableObjectNamespace, Hyperdrive, Zone, DnsRecords
Neon
alchemy/neon
NeonProject, NeonBranch, NeonDatabase, NeonRole
Stripe
alchemy/stripe
WebhookEndpoint, Price, Product, Coupon, and 10+ more
AWS
alchemy/aws
Function, Table, Vpc, Subnet, SecurityGroup, Bucket, Role
AWS Control
alchemy/aws/control
AWS.{Service}.{Resource}
— covers full AWS CloudFormation
GitHub
alchemy/github
GitHubSecret
Vercel
alchemy/vercel
VercelProject, VercelDnsRecord, VercelDeployment
Alchemy拥有20+个提供商。主要提供商如下:
提供商导入路径核心资源
Cloudflare
alchemy/cloudflare
Worker、D1Database、KVNamespace、R2Bucket、Queue、DurableObjectNamespace、Hyperdrive、Zone、DnsRecords
Neon
alchemy/neon
NeonProject、NeonBranch、NeonDatabase、NeonRole
Stripe
alchemy/stripe
WebhookEndpoint、Price、Product、Coupon及10+其他资源
AWS
alchemy/aws
Function、Table、Vpc、Subnet、SecurityGroup、Bucket、Role
AWS Control
alchemy/aws/control
AWS.{Service}.{Resource}
— 覆盖完整AWS CloudFormation
GitHub
alchemy/github
GitHubSecret
Vercel
alchemy/vercel
VercelProject、VercelDnsRecord、VercelDeployment

Conventions

约定

  • Default import:
    import alchemy from "alchemy"
  • Named imports from subpaths:
    import { Worker } from "alchemy/cloudflare"
  • await app.finalize()
    is always the last line of
    alchemy.run.ts
  • Physical names include app name + stage for uniqueness
  • Stage defaults to
    $USER
    locally; use
    --stage prod
    for production
  • Sensitive values always wrapped with
    alchemy.secret()
  • State stored in
    .alchemy/
    directory (add to
    .gitignore
    or commit for shared state)
  • 默认导入:
    import alchemy from "alchemy"
  • 从子路径导入命名项:
    import { Worker } from "alchemy/cloudflare"
  • await app.finalize()
    始终是
    alchemy.run.ts
    的最后一行
  • 物理名称包含应用名+环境阶段以确保唯一性
  • 本地默认环境为
    $USER
    ;生产环境使用
    --stage prod
  • 敏感值始终用
    alchemy.secret()
    包装
  • 状态存储在
    .alchemy/
    目录(添加到
    .gitignore
    或提交以共享状态)

Reference Files

参考文件

Load these on demand for detailed information:
  • references/alchemy-concepts.md
    — Comprehensive reference covering all Alchemy concepts: apps, stages, scopes, phases, resources, secrets, state, bindings, CLI, dev mode, profiles, framework adapters, serialization, and all 20+ providers with their resources.
  • references/resource-patterns.md
    — Implementation patterns for building custom resources (17 sections). Load when the user wants to create custom resources or contribute to Alchemy.
  • references/test-patterns.md
    — Test conventions and patterns (15 sections). Load when writing tests for custom resources.
  • references/doc-patterns.md
    — Documentation templates (10 sections). Load when writing docs for Alchemy providers.
  • references/checklist.md
    — Completeness verification checklist. Load when verifying a provider implementation.

按需加载以下文件获取详细信息:
  • references/alchemy-concepts.md
    — 涵盖所有Alchemy概念的综合参考:应用、环境阶段、作用域、阶段、资源、密钥、状态、绑定、CLI、开发模式、配置文件、框架适配器、序列化,以及所有20+个提供商及其资源。
  • references/resource-patterns.md
    — 构建自定义资源的实现模式(17节)。当用户想要创建自定义资源或为Alchemy做贡献时加载。
  • references/test-patterns.md
    — 测试约定与模式(15节)。为自定义资源编写测试时加载。
  • references/doc-patterns.md
    — 文档模板(10节)。为Alchemy提供商编写文档时加载。
  • references/checklist.md
    — 完整性验证清单。验证提供商实现时加载。

Provider Development Workflow

提供商开发工作流

Use this workflow when the user is building a new provider or custom resource for the Alchemy framework itself (not just using Alchemy in their app).
当用户为Alchemy框架本身构建新提供商或自定义资源(而非仅在应用中使用Alchemy)时,使用本工作流。

Phase 1: Research

阶段1:调研

Study the provider's API, identify CRUD-capable entities, authentication method, rate limits.
研究提供商的API,识别支持CRUD的实体、认证方式、速率限制。

Phase 2: Design

阶段2:设计

Define resource list, Props/Output interfaces, API client approach, dependency order.
定义资源列表、Props/Output接口、API客户端方案、依赖顺序。

Phase 3: API Client

阶段3:API客户端

Create
alchemy/src/{provider}/api.ts
— minimal fetch wrapper, env var auth with Secret.unwrap() fallback.
创建
alchemy/src/{provider}/api.ts
— 轻量fetch封装,环境变量认证,回退使用Secret.unwrap()。

Phase 4: Resources

阶段4:资源

Implement each resource. Load
references/resource-patterns.md
.
  • Resource("{provider}::{Resource}", ...)
    with create/update/delete lifecycle
  • Physical name:
    props.name ?? this.output?.name ?? this.scope.createPhysicalName(id)
  • Must use
    function
    declaration (not arrow), context via
    this
  • Export type guard (
    is{Resource}
    ) for binding support
实现每个资源。加载
references/resource-patterns.md
  • 使用
    Resource("{provider}::{Resource}", ...)
    并包含创建/更新/删除生命周期
  • 物理名称:
    props.name ?? this.output?.name ?? this.scope.createPhysicalName(id)
  • 必须使用
    function
    声明(而非箭头函数),通过
    this
    获取上下文
  • 导出类型守卫(
    is{Resource}
    )以支持绑定

Phase 5: Tests

阶段5:测试

Write tests. Load
references/test-patterns.md
.
  • alchemy.test(import.meta, { prefix: BRANCH_PREFIX })
  • try/finally with
    destroy(scope)
    and API verification
编写测试。加载
references/test-patterns.md
  • 使用
    alchemy.test(import.meta, { prefix: BRANCH_PREFIX })
  • 使用try/finally包裹,包含
    destroy(scope)
    与API验证

Phase 6: Documentation

阶段6:文档

Write docs, guide, examples. Load
references/doc-patterns.md
.
  • Resource docs:
    alchemy-web/src/content/docs/providers/{provider}/{resource}.md
  • Guide:
    alchemy-web/src/content/docs/guides/{provider}.mdx
  • Example:
    examples/{provider}/alchemy.run.ts
编写文档、指南与示例。加载
references/doc-patterns.md
  • 资源文档:
    alchemy-web/src/content/docs/providers/{provider}/{resource}.md
  • 指南:
    alchemy-web/src/content/docs/guides/{provider}.mdx
  • 示例:
    examples/{provider}/alchemy.run.ts

Phase 7: Verify

阶段7:验证

Run checklist. Load
references/checklist.md
.
  • bun format
    ,
    bun vitest alchemy/test/{provider}/
    ,
    bun tsc -b
运行检查清单。加载
references/checklist.md
  • bun format
    bun vitest alchemy/test/{provider}/
    bun tsc -b