@fedify/cfworkers 1.9.0-dev.1461

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,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ <!-- deno-fmt-ignore-file -->
2
+
3
+ @fedify/cfworkers: Adapt Fedify with Cloudflare Workers
4
+ ======================================================
5
+
6
+ [![JSR][JSR badge]][JSR]
7
+ [![npm][npm badge]][npm]
8
+ [![Follow @fedify@hollo.social][@fedify@hollo.social badge]][@fedify@hollo.social]
9
+
10
+ *This package is available since Fedify 1.9.0.*
11
+
12
+ This package provides [Fedify]'s [`KvStore`] and [`MessageQueue`]
13
+ implementations for [Cloudflare Workers]:
14
+
15
+ - [`WorkersKvStore`]
16
+ - [`WorkersMessageQueue`]
17
+
18
+ ~~~~ typescript
19
+ import type { Federation } from "@fedify/fedify";
20
+ import { WorkersKvStore, WorkersMessageQueue } from "@fedify/cfworkers";
21
+
22
+ export default {
23
+ async fetch(request, env, ctx) {
24
+ const federation = createFederation({
25
+ kv: new WorkersKvStore(env.KV_BINDING),
26
+ queue: new WorkersMessageQueue(env.QUEUE_BINDING),
27
+ // ... other options
28
+ });
29
+
30
+ return federation.handle(request, { contextData: env });
31
+ },
32
+
33
+ async queue(batch, env, ctx) {
34
+ const federation = createFederation({
35
+ kv: new WorkersKvStore(env.KV_BINDING),
36
+ queue: new WorkersMessageQueue(env.QUEUE_BINDING),
37
+ // ... other options
38
+ });
39
+
40
+ for (const message of batch.messages) {
41
+ await federation.processQueuedTask(message.body);
42
+ }
43
+ }
44
+ } satisfies ExportedHandler<{
45
+ KV_BINDING: KVNamespace<string>;
46
+ QUEUE_BINDING: Queue;
47
+ }>;
48
+ ~~~~
49
+
50
+ `WorkersKvStore`
51
+ ----------------
52
+
53
+ `WorkersKvStore` is a key–value store implementation for [Cloudflare Workers]
54
+ that uses Cloudflare's built-in [Cloudflare Workers KV] API. It provides
55
+ persistent storage and good performance for Cloudflare Workers environments.
56
+ It's suitable for production use in Cloudflare Workers applications.
57
+
58
+ `WorkersMessageQueue`
59
+ ---------------------
60
+
61
+ `WorkersMessageQueue` is a message queue implementation for [Cloudflare Workers]
62
+ that uses Cloudflare's built-in [Cloudflare Queues] API. It provides
63
+ scalability and high performance, making it suitable for production use in
64
+ Cloudflare Workers environments. It requires a Cloudflare Queues setup and
65
+ management.
66
+
67
+ > [!NOTE]
68
+ > Since your `KVNamespace` and `Queue` are not bound to global variables, but rather
69
+ > passed as arguments to the `fetch()` and `queue()` methods, you need to instantiate
70
+ > your `Federation` object inside these methods, rather than at the top level.
71
+ >
72
+ > For better organization, you probably want to use a builder pattern to
73
+ > register your dispatchers and listeners before instantiating the `Federation`
74
+ > object.
75
+
76
+ > [!NOTE]
77
+ > The [Cloudflare Queues] API does not provide a way to poll messages from
78
+ > the queue, so `WorkersMessageQueue.listen()` method always throws
79
+ > a `TypeError` when invoked. Instead, you should define a `queue()` method
80
+ > in your Cloudflare worker, which will be called by the Cloudflare Queues
81
+ > API when new messages are available in the queue. Inside the `queue()`
82
+ > method, you need to call `Federation.processQueuedTask()` method to manually
83
+ > process the messages. The `queue()` method is the only way to consume
84
+ > messages from the queue in Cloudflare Workers.
85
+
86
+ Installation
87
+ ------------
88
+
89
+ ~~~~ sh
90
+ deno add jsr:@fedify/cfworkers # Deno
91
+ npm add @fedify/cfworkers # npm
92
+ pnpm add @fedify/cfworkers # pnpm
93
+ yarn add @fedify/cfworkers # Yarn
94
+ bun add @fedify/cfworkers # Bun
95
+ ~~~~
96
+
97
+ [JSR]: https://jsr.io/@fedify/cfworkers
98
+ [JSR badge]: https://jsr.io/badges/@fedify/cfworkers
99
+ [npm]: https://www.npmjs.com/package/@fedify/cfworkers
100
+ [npm badge]: https://img.shields.io/npm/v/@fedify/cfworkers?logo=npm
101
+ [@fedify@hollo.social badge]: https://fedi-badge.deno.dev/@fedify@hollo.social/followers.svg
102
+ [@fedify@hollo.social]: https://hollo.social/@fedify
103
+ [Fedify]: https://fedify.dev/
104
+ [`KvStore`]: https://jsr.io/@fedify/fedify/doc/federation/~/KvStore
105
+ [`MessageQueue`]: https://jsr.io/@fedify/fedify/doc/federation/~/MessageQueue
106
+ [`WorkersKvStore`]: https://jsr.io/@fedify/cfworkers/doc/~/WorkersKvStore
107
+ [`WorkersMessageQueue`]: https://jsr.io/@fedify/cfworkers/doc/~/WorkersMessageQueue
108
+ [Cloudflare Workers]: https://workers.cloudflare.com/
109
+ [Cloudflare Workers KV]: https://developers.cloudflare.com/kv/
110
+ [Cloudflare Queues]: https://developers.cloudflare.com/queues/
package/dist/mod.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { KVNamespace, Queue } from "@cloudflare/workers-types/experimental";
2
+ import { KvKey, KvStore, KvStoreSetOptions, MessageQueue, MessageQueueEnqueueOptions, MessageQueueListenOptions } from "@fedify/fedify/federation";
3
+
4
+ //#region src/mod.d.ts
5
+
6
+ /**
7
+ * Implementation of the {@link KvStore} interface for Cloudflare Workers KV
8
+ * binding. This class provides a wrapper around Cloudflare's KV namespace to
9
+ * store and retrieve JSON-serializable values using structured keys.
10
+ *
11
+ * Note that this implementation does not support the {@link KvStore.cas}
12
+ * operation, as Cloudflare Workers KV does not support atomic compare-and-swap
13
+ * operations. If you need this functionality, consider using a different
14
+ * key–value store that supports atomic operations.
15
+ * @since 1.9.0
16
+ */
17
+ declare class WorkersKvStore implements KvStore {
18
+ #private;
19
+ constructor(namespace: KVNamespace<string>);
20
+ get<T = unknown>(key: KvKey): Promise<T | undefined>;
21
+ set(key: KvKey, value: unknown, options?: KvStoreSetOptions): Promise<void>;
22
+ delete(key: KvKey): Promise<void>;
23
+ }
24
+ /**
25
+ * Implementation of the {@link MessageQueue} interface for Cloudflare
26
+ * Workers Queues binding. This class provides a wrapper around Cloudflare's
27
+ * Queues to send messages to a queue.
28
+ *
29
+ * Note that this implementation does not support the `listen()` method,
30
+ * as Cloudflare Workers Queues do not support message consumption in the same
31
+ * way as other message queue systems. Instead, you should use
32
+ * the {@link Federation.processQueuedTask} method to process messages
33
+ * passed to the queue.
34
+ * @since 1.9.0
35
+ */
36
+ declare class WorkersMessageQueue implements MessageQueue {
37
+ #private;
38
+ /**
39
+ * Cloudflare Queues provide automatic retry with exponential backoff
40
+ * and Dead Letter Queues.
41
+ * @since 1.7.0
42
+ */
43
+ readonly nativeRetrial = true;
44
+ constructor(queue: Queue);
45
+ enqueue(message: any, options?: MessageQueueEnqueueOptions): Promise<void>;
46
+ enqueueMany(messages: any[], options?: MessageQueueEnqueueOptions): Promise<void>;
47
+ listen(_handler: (message: any) => Promise<void> | void, _options?: MessageQueueListenOptions): Promise<void>;
48
+ }
49
+ //#endregion
50
+ export { WorkersKvStore, WorkersMessageQueue };
package/dist/mod.js ADDED
@@ -0,0 +1,80 @@
1
+ //#region src/mod.ts
2
+ /**
3
+ * Implementation of the {@link KvStore} interface for Cloudflare Workers KV
4
+ * binding. This class provides a wrapper around Cloudflare's KV namespace to
5
+ * store and retrieve JSON-serializable values using structured keys.
6
+ *
7
+ * Note that this implementation does not support the {@link KvStore.cas}
8
+ * operation, as Cloudflare Workers KV does not support atomic compare-and-swap
9
+ * operations. If you need this functionality, consider using a different
10
+ * key–value store that supports atomic operations.
11
+ * @since 1.9.0
12
+ */
13
+ var WorkersKvStore = class {
14
+ #namespace;
15
+ constructor(namespace) {
16
+ this.#namespace = namespace;
17
+ }
18
+ #encodeKey(key) {
19
+ return JSON.stringify(key);
20
+ }
21
+ async get(key) {
22
+ const encodedKey = this.#encodeKey(key);
23
+ const { value, metadata } = await this.#namespace.getWithMetadata(encodedKey, "json");
24
+ return metadata == null || metadata.expires < Date.now() ? void 0 : value;
25
+ }
26
+ async set(key, value, options) {
27
+ const encodedKey = this.#encodeKey(key);
28
+ const metadata = options?.ttl == null ? {} : { expires: Date.now() + options.ttl.total("milliseconds") };
29
+ await this.#namespace.put(encodedKey, JSON.stringify(value), options?.ttl == null ? { metadata } : {
30
+ expirationTtl: Math.max(options.ttl.total("seconds"), 60),
31
+ metadata
32
+ });
33
+ }
34
+ delete(key) {
35
+ return this.#namespace.delete(this.#encodeKey(key));
36
+ }
37
+ };
38
+ /**
39
+ * Implementation of the {@link MessageQueue} interface for Cloudflare
40
+ * Workers Queues binding. This class provides a wrapper around Cloudflare's
41
+ * Queues to send messages to a queue.
42
+ *
43
+ * Note that this implementation does not support the `listen()` method,
44
+ * as Cloudflare Workers Queues do not support message consumption in the same
45
+ * way as other message queue systems. Instead, you should use
46
+ * the {@link Federation.processQueuedTask} method to process messages
47
+ * passed to the queue.
48
+ * @since 1.9.0
49
+ */
50
+ var WorkersMessageQueue = class {
51
+ #queue;
52
+ /**
53
+ * Cloudflare Queues provide automatic retry with exponential backoff
54
+ * and Dead Letter Queues.
55
+ * @since 1.7.0
56
+ */
57
+ nativeRetrial = true;
58
+ constructor(queue) {
59
+ this.#queue = queue;
60
+ }
61
+ enqueue(message, options) {
62
+ return this.#queue.send(message, {
63
+ contentType: "json",
64
+ delaySeconds: options?.delay?.total("seconds") ?? 0
65
+ });
66
+ }
67
+ enqueueMany(messages, options) {
68
+ const requests = messages.map((msg) => ({
69
+ body: msg,
70
+ contentType: "json"
71
+ }));
72
+ return this.#queue.sendBatch(requests, { delaySeconds: options?.delay?.total("seconds") ?? 0 });
73
+ }
74
+ listen(_handler, _options) {
75
+ throw new TypeError("WorkersMessageQueue does not support listen(). Use Federation.processQueuedTask() method instead.");
76
+ }
77
+ };
78
+
79
+ //#endregion
80
+ export { WorkersKvStore, WorkersMessageQueue };
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@fedify/cfworkers",
3
+ "version": "1.9.0-dev.1461+7957aafe",
4
+ "description": "Adapt Fedify with Cloudflare Workers",
5
+ "keywords": [
6
+ "Fedify",
7
+ "ActivityPub",
8
+ "Fediverse",
9
+ "Cloudflare Workers"
10
+ ],
11
+ "author": {
12
+ "name": "Hong Minhee",
13
+ "email": "hong@minhee.org",
14
+ "url": "https://hongminhee.org/"
15
+ },
16
+ "homepage": "https://fedify.dev/",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/fedify-dev/fedify.git",
20
+ "directory": "packages/cfworkers"
21
+ },
22
+ "license": "MIT",
23
+ "bugs": {
24
+ "url": "https://github.com/fedify-dev/fedify/issues"
25
+ },
26
+ "funding": [
27
+ "https://opencollective.com/fedify",
28
+ "https://github.com/sponsors/dahlia"
29
+ ],
30
+ "type": "module",
31
+ "main": "./dist/mod.js",
32
+ "module": "./dist/mod.js",
33
+ "types": "./dist/mod.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "require": {
37
+ "types": "./dist/mod.d.ts",
38
+ "import": "./dist/mod.js",
39
+ "default": "./dist/mod.js"
40
+ },
41
+ "import": {
42
+ "types": "./dist/mod.d.ts",
43
+ "import": "./dist/mod.js",
44
+ "default": "./dist/mod.js"
45
+ }
46
+ },
47
+ "./package.json": "./package.json"
48
+ },
49
+ "files": [
50
+ "dist/",
51
+ "package.json"
52
+ ],
53
+ "peerDependencies": {
54
+ "@cloudflare/workers-types": "^4.20250529.0",
55
+ "@fedify/fedify": "1.9.0-dev.1461+7957aafe"
56
+ },
57
+ "devDependencies": {
58
+ "tsdown": "^0.12.9",
59
+ "typescript": "^5.9.2"
60
+ },
61
+ "scripts": {
62
+ "build": "tsdown",
63
+ "prepublish": "tsdown",
64
+ "test": "deno task codegen && tsdown && cd dist/ && node --test"
65
+ }
66
+ }