@di-framework/cloudflare

中文文档
6.0.30发布于 2026/11/07(MIT OR Apache-2.0)TypeScriptES Module零依赖构建来源已验证近 30 天下载 3618

Cloudflare Workers connector for binding discovery, wrangler config, and automated DI injection.

原始使用文档
文档目录7 节
  1. Features
  2. Installation
  3. Quick start
  4. Programmatic discovery
  5. Use with @di-framework/ai
  6. Custom classifiers
  7. License

@di-framework/cloudflare

Cloudflare Workers connector for @di-framework. It classifies Worker bindings, reads wrangler declarations, and injects them through the DI container.

Worker bindings arrive on the request env object. Register factories at startup, then publish env from the handler before resolving services.

Features

  • Runtime detection: CloudflareDetector matches the Workers user agent and CF_PAGES=1.
  • Binding classification for KV, D1, R2, Durable Object namespaces, Queues, service bindings, Workers AI, Hyperdrive, Vectorize, Analytics Engine, Images, Workflows, rate limits, browsers, pipelines, and plain vars.
  • Wrangler declarations for kinds whose host objects look alike: assets, email, dispatch namespaces, Secrets Store, and mTLS certificates. Also vars.
  • DI integration:
    • @CloudflareBinding('BINDING_NAME') for parameter and property injection
    • @EnableCloudflareBindings() for container-wide lazy factories
    • setCloudflareBindings(env) from the Worker handler
  • Local fallback: CLOUDFLARE_BINDINGS JSON, or an object passed as localFallback, when no Worker env is published.
  • Custom classifiers through BindingClassifierRegistry.

Installation

bun add @di-framework/cloudflare

Quick start

import { Container } from '@di-framework/core/decorators';
import {
  CloudflareBinding,
  type D1BindingInfo,
  EnableCloudflareBindings,
  type KvBindingInfo,
  setCloudflareBindings,
} from '@di-framework/cloudflare';

@EnableCloudflareBindings()
@Container()
export class OrderService {
  @CloudflareBinding('ORDERS')
  db!: D1BindingInfo;

  @CloudflareBinding('SESSIONS')
  sessions!: KvBindingInfo;

  async cart(id: string) {
    return this.sessions.binding?.get(id);
  }
}

export default {
  async fetch(request: Request, env: Record<string, unknown>) {
    setCloudflareBindings(env);
    const orders = new OrderService();
    const cart = await orders.cart(new URL(request.url).pathname);
    return new Response(cart == null ? 'empty' : String(cart));
  },
};

Call setCloudflareBindings(env) before the first read of an injected property. Property getters keep the first value they resolve.

Programmatic discovery

import { CloudflareEnvironment } from '@di-framework/cloudflare';

const cf = new CloudflareEnvironment({ bindings: env });

const db = cf.getD1Binding('ORDERS');
const sessions = cf.getKvBinding('SESSIONS');
const bucket = cf.getR2Binding();

getKvBinding() without a name returns the first KV binding in name order. The same pattern exists for D1, R2, Durable Objects, queues, service bindings, AI, Hyperdrive, Vectorize, and Analytics Engine.

Use with @di-framework/ai

WorkersAiChatModel and WorkersAiEmbeddingModel take the Workers AI binding. VectorizeVectorStore takes the Vectorize binding. A function reads the env published by setCloudflareBindings.

import { configureAi, VectorizeVectorStore, WorkersAiChatModel, WorkersAiEmbeddingModel } from '@di-framework/ai';
import { getCloudflareBindings, setCloudflareBindings } from '@di-framework/cloudflare';

configureAi({
  chatModel: new WorkersAiChatModel({
    binding: () => getCloudflareBindings()?.AI,
    model: '@cf/meta/llama-3.1-8b-instruct',
  }),
});

export default {
  fetch(request: Request, env: Record<string, unknown>) {
    setCloudflareBindings(env);
    const embeddings = WorkersAiEmbeddingModel.of(() => env.AI);
    const store = new VectorizeVectorStore({
      index: () => env.VECTORS,
      embeddingModel: embeddings,
    });
    return new Response(String(store.name));
  },
};

@CloudflareBinding('AI') injects { binding }, which both models accept directly.

String bindings are vars. Names listed in secretNames are secrets. kindHints forces a kind when the live object is ambiguous:

new CloudflareEnvironment({
  bindings: env,
  secretNames: ['API_TOKEN'],
  kindHints: { ASSETS: 'assets', SECRETS: 'secrets-store' },
});

A parsed wrangler config (JSON, not JSONC) supplies those kinds too. parseWranglerBindings(config) reads kv_namespaces, d1_databases, r2_buckets, durable_objects, queue producers, services, ai, hyperdrive, vectorize, analytics_engine_datasets, ratelimits, workflows, send_email, pipelines, dispatch_namespaces, secrets_store_secrets, mtls_certificates, browser, images, assets, and vars.

Outside Workers, a JSON object in CLOUDFLARE_BINDINGS fills the same map. Set localFallback: false to require a published Worker env.

Custom classifiers

import {
  type CloudflareBindingClassifier,
  getDefaultRegistry,
  type CloudflareBindingInfo,
} from '@di-framework/cloudflare';

class FlagClassifier implements CloudflareBindingClassifier {
  readonly kind = 'unknown' as const;

  accept(_name: string, value: unknown): boolean {
    return typeof value === 'object' && value !== null && 'flag' in value;
  }

  create(name: string, value: unknown): CloudflareBindingInfo {
    return { name, kind: 'unknown', binding: value };
  }
}

getDefaultRegistry().register(new FlagClassifier());

The default priority is high, so the classifier runs before the built-ins. { priority: 'low' } runs after them.

License

Licensed under either MIT or Apache-2.0, at your option.

版本与发布记录

@di-framework/cloudflare 共发布 26 个版本,首次发布于 2026/10/06;过去 12 个月发布了 26 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
6.0.30latest2026/11/075 天前
6.0.292026/11/066 天前
6.0.282026/11/039 天前
6.0.272026/11/0111 天前
6.0.262026/10/3012 天前
6.0.252026/10/3013 天前

关于 @di-framework/cloudflare 的常见问题

@di-framework/cloudflare 是什么?

Cloudflare Workers connector for binding discovery, wrangler config, and automated DI injection.

如何安装 @di-framework/cloudflare?

在项目目录运行 npm install @di-framework/cloudflare,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(^5 || ^6 || ^7)、@di-framework/core(^6)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@di-framework/cloudflare 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@di-framework/cloudflare 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@di-framework/cloudflare 可以商用吗?

@di-framework/cloudflare 使用 (MIT OR Apache-2.0) 许可。可在 MIT、Apache-2.0 中任选其一遵守。选择 MIT 时,宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@di-framework/cloudflare 的下载量有多少?

根据 npm 官方下载统计,@di-framework/cloudflare 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,618 次,日均约 121 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@di-framework/cloudflare 还在维护吗?

最新版本 6.0.30 发布于 2026/11/07(5 天前);至今共发布 26 个版本,其中过去 12 个月发布了 26 个;首次发布于 2026/10/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。