@ryusenkei/adapter-cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RYUSENKEI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @ryusenkei/adapter-cloudflare
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Implementations of the runtime ports with Cloudflare Workers bindings. The binding types are structural, so this package does not depend on `@cloudflare/workers-types`. Pass the bindings from `env` in your `services.ts`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @ryusenkei/adapter-cloudflare
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { cloudflareMailer, cloudflareRateLimiter, r2BlobStore } from '@ryusenkei/adapter-cloudflare';
15
+
16
+ export const servicesFromEnv = (env: Env) => ({
17
+ rateLimiter: cloudflareRateLimiter(env.INQUIRY_RATE_LIMITER),
18
+ mailer: cloudflareMailer(env.EMAIL),
19
+ blob: r2BlobStore(env.UPLOADS),
20
+ });
21
+ ```
22
+
23
+ | Function | Port | Binding |
24
+ | --- | --- | --- |
25
+ | `cloudflareRateLimiter` | [`RateLimiter`](../rate-limit) | Rate Limiting (`ratelimits` in wrangler config; limit and period are set there). Counts are per Cloudflare location, not a strict global limit |
26
+ | `cloudflareMailer` | [`Mailer`](../mail) | Email Service (`send_email`). The sender domain must be onboarded to Email Sending |
27
+ | `r2BlobStore` | [`BlobStore`](../blob) | R2 bucket. `list` follows the cursor past 1,000 keys |
28
+
29
+ Error handling:
30
+
31
+ - A missing binding throws `ConfigError`, so a misconfigured deploy returns 503 `not_configured` through `failureResponse`
32
+ - Rate Limiting and R2 failures throw `TransientError`
33
+ - Email Service error codes:
34
+ - `E_RATE_LIMIT_EXCEEDED`, `E_DAILY_LIMIT_EXCEEDED`, and `E_INTERNAL_SERVER_ERROR` throw `TransientError`
35
+ - Unverified or unavailable sender domains, a suspended account, and recipients not allowed by the binding throw `ConfigError`
36
+ - Suppressed recipients and delivery failures return `rejected`
37
+ - Validation and header errors return `invalid_input`
38
+ - Unknown codes are rethrown as is
39
+
40
+ D1 (`db`) is not here yet.
41
+
42
+ ## License
43
+
44
+ MIT
@@ -0,0 +1,3 @@
1
+ export { cloudflareMailer, type SendEmailBinding } from './mail.ts';
2
+ export { r2BlobStore, type R2BucketBinding } from './r2.ts';
3
+ export { cloudflareRateLimiter, type RateLimitBinding } from './rate-limit.ts';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { cloudflareMailer } from "./mail.js";
2
+ export { r2BlobStore } from "./r2.js";
3
+ export { cloudflareRateLimiter } from "./rate-limit.js";
package/dist/mail.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { type MailAddress, type Mailer } from '@ryusenkei/mail';
2
+ /** Email Service の `send_email` binding(使う部分だけの型) */
3
+ export type SendEmailBinding = {
4
+ send(message: {
5
+ from: MailAddress;
6
+ to: MailAddress[];
7
+ replyTo?: MailAddress;
8
+ subject: string;
9
+ text: string;
10
+ html?: string;
11
+ }): Promise<{
12
+ messageId: string;
13
+ }>;
14
+ };
15
+ /**
16
+ * Email Service(Email Sending)の binding によるメール送信
17
+ * - 送信元のドメインは Email Sending に登録済みであること(未登録は `ConfigError`)
18
+ * - 知らないエラーコードはそのまま投げる(想定外の失敗として扱う)
19
+ */
20
+ export declare function cloudflareMailer(binding: SendEmailBinding | undefined): Mailer;
package/dist/mail.js ADDED
@@ -0,0 +1,41 @@
1
+ import { ConfigError, err, ok, TransientError } from '@ryusenkei/core';
2
+ import { validateMail } from '@ryusenkei/mail';
3
+ // binding のエラーの `code` の分類(Email Service の Workers API の一覧)
4
+ const TRANSIENT = ['E_RATE_LIMIT_EXCEEDED', 'E_DAILY_LIMIT_EXCEEDED', 'E_INTERNAL_SERVER_ERROR'];
5
+ const CONFIG = ['E_SENDER_NOT_VERIFIED', 'E_SENDER_DOMAIN_NOT_AVAILABLE', 'E_ACCOUNT_SUSPENDED', 'E_RECIPIENT_NOT_ALLOWED'];
6
+ const REJECTED = ['E_RECIPIENT_SUPPRESSED', 'E_DELIVERY_FAILED'];
7
+ const INVALID = /^E_(VALIDATION_ERROR|FIELD_MISSING|TOO_MANY_RECIPIENTS|TOO_MANY_ATTACHMENTS|CONTENT_TOO_LARGE|HEADERS?_.+)$/;
8
+ /**
9
+ * Email Service(Email Sending)の binding によるメール送信
10
+ * - 送信元のドメインは Email Sending に登録済みであること(未登録は `ConfigError`)
11
+ * - 知らないエラーコードはそのまま投げる(想定外の失敗として扱う)
12
+ */
13
+ export function cloudflareMailer(binding) {
14
+ return {
15
+ async send(mail) {
16
+ if (!binding)
17
+ throw new ConfigError('send_email の binding が未設定');
18
+ const valid = validateMail(mail);
19
+ if (!valid.ok)
20
+ return valid;
21
+ try {
22
+ const { messageId } = await binding.send({ from: mail.from, to: mail.to, ...(mail.replyTo ? { replyTo: mail.replyTo } : {}), subject: mail.subject, text: mail.text, ...(mail.html ? { html: mail.html } : {}) });
23
+ return ok({ id: messageId });
24
+ }
25
+ catch (e) {
26
+ const code = e.code;
27
+ if (typeof code !== 'string')
28
+ throw e;
29
+ if (TRANSIENT.includes(code))
30
+ throw new TransientError(`メール送信の一時的な失敗: ${code}`, { cause: e });
31
+ if (CONFIG.includes(code))
32
+ throw new ConfigError(`メール送信の設定の誤り: ${code}`, { cause: e });
33
+ if (REJECTED.includes(code))
34
+ return err('rejected');
35
+ if (INVALID.test(code))
36
+ return err('invalid_input');
37
+ throw e;
38
+ }
39
+ },
40
+ };
41
+ }
package/dist/r2.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import type { BlobBody, BlobStore } from '@ryusenkei/blob';
2
+ type R2Object = {
3
+ size: number;
4
+ httpMetadata?: {
5
+ contentType?: string;
6
+ };
7
+ body: ReadableStream<Uint8Array>;
8
+ arrayBuffer(): Promise<ArrayBuffer>;
9
+ text(): Promise<string>;
10
+ };
11
+ /** R2 の bucket の binding(使う部分だけの型) */
12
+ export type R2BucketBinding = {
13
+ put(key: string, value: BlobBody, options?: {
14
+ httpMetadata?: {
15
+ contentType?: string;
16
+ };
17
+ }): Promise<unknown>;
18
+ get(key: string): Promise<R2Object | null>;
19
+ delete(key: string): Promise<void>;
20
+ list(options?: {
21
+ prefix?: string;
22
+ cursor?: string;
23
+ }): Promise<{
24
+ objects: {
25
+ key: string;
26
+ }[];
27
+ truncated: boolean;
28
+ cursor?: string;
29
+ }>;
30
+ };
31
+ /** R2 の bucket によるファイルの保存 */
32
+ export declare function r2BlobStore(bucket: R2BucketBinding | undefined): BlobStore;
33
+ export {};
package/dist/r2.js ADDED
@@ -0,0 +1,41 @@
1
+ import { ConfigError, err, ok, TransientError } from '@ryusenkei/core';
2
+ /** R2 の bucket によるファイルの保存 */
3
+ export function r2BlobStore(bucket) {
4
+ // R2 の失敗は再試行で回復しうるものとして扱う(binding の操作の例外は理由を区別できない)
5
+ const transient = async (op, run) => {
6
+ if (!bucket)
7
+ throw new ConfigError('R2 の binding が未設定');
8
+ try {
9
+ return await run(bucket);
10
+ }
11
+ catch (e) {
12
+ throw new TransientError(`R2 の ${op} の失敗`, { cause: e });
13
+ }
14
+ };
15
+ return {
16
+ async put(key, body, options = {}) {
17
+ await transient('put', (b) => b.put(key, body, options.contentType ? { httpMetadata: { contentType: options.contentType } } : {}));
18
+ },
19
+ async get(key) {
20
+ const object = await transient('get', (b) => b.get(key));
21
+ if (!object)
22
+ return err('not_found');
23
+ const blob = { size: object.size, contentType: object.httpMetadata?.contentType, body: object.body, arrayBuffer: () => object.arrayBuffer(), text: () => object.text() };
24
+ return ok(blob);
25
+ },
26
+ async delete(key) {
27
+ await transient('delete', (b) => b.delete(key));
28
+ },
29
+ // 1回の応答は最大1,000件なので、cursor で続きを取得
30
+ async list(prefix) {
31
+ const keys = [];
32
+ let cursor;
33
+ do {
34
+ const page = await transient('list', (b) => b.list({ ...(prefix ? { prefix } : {}), ...(cursor ? { cursor } : {}) }));
35
+ keys.push(...page.objects.map((o) => o.key));
36
+ cursor = page.truncated ? page.cursor : undefined;
37
+ } while (cursor);
38
+ return keys.sort();
39
+ },
40
+ };
41
+ }
@@ -0,0 +1,15 @@
1
+ import type { RateLimiter } from '@ryusenkei/rate-limit';
2
+ /** Workers の Rate Limiting の binding(使う部分だけの型。`@cloudflare/workers-types` に依存しない) */
3
+ export type RateLimitBinding = {
4
+ limit(options: {
5
+ key: string;
6
+ }): Promise<{
7
+ success: boolean;
8
+ }>;
9
+ };
10
+ /**
11
+ * Workers の Rate Limiting の binding による回数の制限
12
+ * - 上限と期間は wrangler の設定(`ratelimits`)で決める
13
+ * - 数え方は Cloudflare の拠点ごとで、厳密な全体の上限ではない
14
+ */
15
+ export declare function cloudflareRateLimiter(binding: RateLimitBinding | undefined): RateLimiter;
@@ -0,0 +1,22 @@
1
+ import { ConfigError, err, ok, TransientError } from '@ryusenkei/core';
2
+ /**
3
+ * Workers の Rate Limiting の binding による回数の制限
4
+ * - 上限と期間は wrangler の設定(`ratelimits`)で決める
5
+ * - 数え方は Cloudflare の拠点ごとで、厳密な全体の上限ではない
6
+ */
7
+ export function cloudflareRateLimiter(binding) {
8
+ return {
9
+ async limit(key) {
10
+ if (!binding)
11
+ throw new ConfigError('Rate Limiting の binding が未設定');
12
+ let result;
13
+ try {
14
+ result = await binding.limit({ key });
15
+ }
16
+ catch (e) {
17
+ throw new TransientError('Rate Limiting の binding の失敗', { cause: e });
18
+ }
19
+ return result.success ? ok() : err('rate_limited');
20
+ },
21
+ };
22
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@ryusenkei/adapter-cloudflare",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "差し込み口の Cloudflare Workers の binding による実装(回数の制限、メール送信、R2)",
5
+ "license": "MIT",
6
+ "author": "RYUSENKEI",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ryusenkei-inc/toolkit.git",
10
+ "directory": "packages/runtime/adapter-cloudflare"
11
+ },
12
+ "homepage": "https://github.com/ryusenkei-inc/toolkit/tree/main/packages/runtime/adapter-cloudflare",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "dependencies": {
29
+ "@ryusenkei/core": "^0.1.0",
30
+ "@ryusenkei/rate-limit": "^0.1.0",
31
+ "@ryusenkei/mail": "^0.1.0",
32
+ "@ryusenkei/blob": "^0.1.0"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "^5.9.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.build.json",
39
+ "typecheck": "tsc --noEmit"
40
+ }
6
41
  }