@fedify/botkit 0.3.0-dev.111 → 0.3.0-dev.113

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.
@@ -1 +1 @@
1
- {"version":3,"file":"repository.js","names":["kv: KvStore","prefixes?: KvStoreRepositoryPrefixes","keyPairs: CryptoKeyPair[]","pairs: KeyPair[]","pair: KeyPair","id: Uuid","activity: Create | Announce","messageKey: KvKey","lockKey: KvKey","listKey: KvKey","updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>","kvKey: KvKey","Create","Announce","options: RepositoryGetMessagesOptions","activity: Activity","followRequestId: URL","follower: Actor","followerKey: KvKey","followRequestKey: KvKey","actorId: URL","follower: Object","followerId: URL","options: RepositoryGetFollowersOptions","actor: Object","follow: Follow","followeeId: URL","uuid: string","followId: URL","underlying: Repository","cache?: MemoryRepository","options?: RepositoryGetMessagesOptions","options?: RepositoryGetFollowersOptions"],"sources":["../src/repository.ts"],"sourcesContent":["// BotKit by Fedify: A framework for creating ActivityPub bots\n// Copyright (C) 2025 Hong Minhee <https://hongminhee.org/>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport type { KvKey, KvStore } from \"@fedify/fedify/federation\";\nimport { exportJwk, importJwk } from \"@fedify/fedify/sig\";\nimport {\n Activity,\n type Actor,\n Announce,\n Create,\n Follow,\n isActor,\n Object,\n} from \"@fedify/fedify/vocab\";\nexport type { KvKey, KvStore } from \"@fedify/fedify/federation\";\nexport { Announce, Create } from \"@fedify/fedify/vocab\";\n\n/**\n * A UUID (universally unique identifier).\n * @since 0.3.0\n */\nexport type Uuid = ReturnType<typeof crypto.randomUUID>;\n\n/**\n * A repository for storing bot data.\n * @since 0.3.0\n */\nexport interface Repository {\n /**\n * Sets the key pairs of the bot actor.\n * @param keyPairs The key pairs to set.\n */\n setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void>;\n\n /**\n * Gets the key pairs of the bot actor.\n * @returns The key pairs of the bot actor. If the key pairs do not exist,\n * `undefined` will be returned.\n */\n getKeyPairs(): Promise<CryptoKeyPair[] | undefined>;\n\n /**\n * Adds a message to the repository.\n * @param id The UUID of the message.\n * @param activity The activity to add.\n */\n addMessage(id: Uuid, activity: Create | Announce): Promise<void>;\n\n /**\n * Updates a message in the repository.\n * @param id The UUID of the message.\n * @param updater The function to update the message. The function will be\n * called with the existing message, and the return value will\n * be the new message. If the function returns a promise, the\n * promise will be awaited. If the function returns either\n * `undefined` or a promise that resolves to `undefined`,\n * the message will not be updated. If the message does not\n * exist, the updater will not be called.\n * @returns `true` if the message was updated, `false` if the message does not\n * exist.\n */\n updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean>;\n\n /**\n * Removes a message from the repository.\n * @param id The UUID of the message to remove.\n * @returns The removed activity. If the message does not exist, `undefined`\n * will be returned.\n */\n removeMessage(id: Uuid): Promise<Create | Announce | undefined>;\n\n /**\n * Gets messages from the repository.\n * @param options The options for getting messages.\n * @returns An async iterable of message activities.\n */\n getMessages(\n options?: RepositoryGetMessagesOptions,\n ): AsyncIterable<Create | Announce>;\n\n /**\n * Gets a message from the repository.\n * @param id The UUID of the message to get.\n * @returns The message activity, or `undefined` if the message does not\n * exist.\n */\n getMessage(id: Uuid): Promise<Create | Announce | undefined>;\n\n /**\n * Counts the number of messages in the repository.\n * @returns The number of messages in the repository.\n */\n countMessages(): Promise<number>;\n\n /**\n * Adds a follower to the repository.\n * @param followId The URL of the follow request.\n * @param follower The actor who follows the bot.\n */\n addFollower(followId: URL, follower: Actor): Promise<void>;\n\n /**\n * Removes a follower from the repository.\n * @param followId The URL of the follow request.\n * @param followerId The ID of the actor to remove.\n * @returns The removed actor. If the follower does not exist or the follow\n * request is not about the follower, `undefined` will be returned.\n */\n removeFollower(followId: URL, followerId: URL): Promise<Actor | undefined>;\n\n /**\n * Checks if the repository has a follower.\n * @param followerId The ID of the follower to check.\n * @returns `true` if the repository has the follower, `false` otherwise.\n */\n hasFollower(followerId: URL): Promise<boolean>;\n\n /**\n * Gets followers from the repository.\n * @param options The options for getting followers.\n * @returns An async iterable of actors who follow the bot.\n */\n getFollowers(options?: RepositoryGetFollowersOptions): AsyncIterable<Actor>;\n\n /**\n * Counts the number of followers in the repository.\n * @returns The number of followers in the repository.\n */\n countFollowers(): Promise<number>;\n\n /**\n * Adds a sent follow request to the repository.\n * @param id The UUID of the follow request.\n * @param follow The follow activity to add.\n */\n addSentFollow(id: Uuid, follow: Follow): Promise<void>;\n\n /**\n * Removes a sent follow request from the repository.\n * @param id The UUID of the follow request to remove.\n * @returns The removed follow activity. If the follow request does not\n * exist, `undefined` will be returned.\n */\n removeSentFollow(id: Uuid): Promise<Follow | undefined>;\n\n /**\n * Gets a sent follow request from the repository.\n * @param id The UUID of the follow request to get.\n * @returns The `Follow` activity, or `undefined` if the follow request does\n * not exist.\n */\n getSentFollow(id: Uuid): Promise<Follow | undefined>;\n\n /**\n * Adds a followee to the repository.\n * @param followeeId The ID of the followee to add.\n * @param follow The follow activity to add.\n */\n addFollowee(followeeId: URL, follow: Follow): Promise<void>;\n\n /**\n * Removes a followee from the repository.\n * @param followeeId The ID of the followee to remove.\n * @returns The `Follow` activity that was removed. If the followee does not\n * exist, `undefined` will be returned.\n */\n removeFollowee(followeeId: URL): Promise<Follow | undefined>;\n\n /**\n * Gets a followee from the repository.\n * @param followeeId The ID of the followee to get.\n * @returns The `Follow` activity, or `undefined` if the followee does not\n * exist.\n */\n getFollowee(followeeId: URL): Promise<Follow | undefined>;\n}\n\n/**\n * Options for getting messages from the repository.\n * @since 0.3.0\n */\nexport interface RepositoryGetMessagesOptions {\n /**\n * The order of the messages. If omitted, `\"newest\"` will be used.\n * @default `\"newest\"`\n */\n readonly order?: \"oldest\" | \"newest\";\n\n /**\n * The timestamp to get messages created at or before this time.\n * If omitted, no limit will be applied.\n */\n readonly until?: Temporal.Instant;\n\n /**\n * The timestamp to get messages created at or after this time.\n * If omitted, no limit will be applied.\n */\n readonly since?: Temporal.Instant;\n\n /**\n * The maximum number of messages to get. If omitted, no limit will be\n * applied.\n */\n readonly limit?: number;\n}\n\n/**\n * Options for getting followers from the repository.\n * @since 0.3.0\n */\nexport interface RepositoryGetFollowersOptions {\n /**\n * The offset of the followers to get. If omitted, 0 will be used.\n * @default `0`\n */\n readonly offset?: number;\n\n /**\n * The limit of the followers to get. If omitted, no limit will be applied.\n */\n readonly limit?: number;\n}\n\n/**\n * The prefixes for key-value store keys used by the bot.\n * @since 0.3.0\n */\nexport interface KvStoreRepositoryPrefixes {\n /**\n * The key prefix used for storing the key pairs of the bot actor.\n * @default `[\"_botkit\", \"keyPairs\"]`\n */\n readonly keyPairs: KvKey;\n\n /**\n * The key prefix used for storing published messages.\n * @default `[\"_botkit\", \"messages\"]`\n */\n readonly messages: KvKey;\n\n /**\n * The key prefix used for storing followers.\n * @default `[\"_botkit\", \"followers\"]`\n */\n readonly followers: KvKey;\n\n /**\n * The key prefix used for storing incoming follow requests.\n * @default `[\"_botkit\", \"followRequests\"]`\n */\n readonly followRequests: KvKey;\n\n /**\n * The key prefix used for storing followees.\n * @default `[\"_botkit\", \"followees\"]`\n */\n readonly followees: KvKey;\n\n /**\n * The key prefix used for storing outgoing follow requests.\n * @default `[\"_botkit\", \"follows\"]`\n */\n readonly follows: KvKey;\n}\n\n/**\n * A repository for storing bot data using a key-value store.\n */\nexport class KvRepository implements Repository {\n readonly kv: KvStore;\n readonly prefixes: KvStoreRepositoryPrefixes;\n\n /**\n * Creates a new key-value store repository.\n * @param kv The key-value store to use.\n * @param prefixes The prefixes for key-value store keys.\n */\n constructor(kv: KvStore, prefixes?: KvStoreRepositoryPrefixes) {\n this.kv = kv;\n this.prefixes = {\n keyPairs: [\"_botkit\", \"keyPairs\"],\n messages: [\"_botkit\", \"messages\"],\n followers: [\"_botkit\", \"followers\"],\n followRequests: [\"_botkit\", \"followRequests\"],\n followees: [\"_botkit\", \"followees\"],\n follows: [\"_botkit\", \"follows\"],\n ...prefixes ?? {},\n };\n }\n\n async setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n const pairs: KeyPair[] = [];\n for (const keyPair of keyPairs) {\n const pair: KeyPair = {\n private: await exportJwk(keyPair.privateKey),\n public: await exportJwk(keyPair.publicKey),\n };\n pairs.push(pair);\n }\n await this.kv.set(this.prefixes.keyPairs, pairs);\n }\n\n async getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n const keyPairs = await this.kv.get<KeyPair[]>(this.prefixes.keyPairs);\n if (keyPairs == null) return undefined;\n const promises = keyPairs.map(async (pair) => ({\n privateKey: await importJwk(pair.private, \"private\"),\n publicKey: await importJwk(pair.public, \"public\"),\n }));\n return await Promise.all(promises);\n }\n\n async addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n const messageKey: KvKey = [...this.prefixes.messages, id];\n await this.kv.set(\n messageKey,\n await activity.toJsonLd({ format: \"compact\" }),\n );\n const lockKey: KvKey = [...this.prefixes.messages, \"lock\"];\n const listKey: KvKey = this.prefixes.messages;\n do {\n await this.kv.set(lockKey, id);\n const set = new Set(await this.kv.get<string[]>(listKey) ?? []);\n set.add(id);\n const list = [...set];\n list.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== id);\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n const kvKey: KvKey = [...this.prefixes.messages, id];\n const createJson = await this.kv.get(kvKey);\n if (createJson == null) return false;\n const activity = await Activity.fromJsonLd(createJson);\n if (!(activity instanceof Create || activity instanceof Announce)) {\n return false;\n }\n const newActivity = await updater(activity);\n if (newActivity == null) return false;\n await this.kv.set(\n kvKey,\n await newActivity.toJsonLd({ format: \"compact\" }),\n );\n return true;\n }\n\n async removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const listKey: KvKey = this.prefixes.messages;\n const lockKey: KvKey = [...listKey, \"lock\"];\n const lockId = `${id}:delete`;\n do {\n await this.kv.set(lockKey, lockId);\n const set = new Set(await this.kv.get<string[]>(listKey) ?? []);\n set.delete(id);\n const list = [...set];\n list.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== lockId);\n const messageKey: KvKey = [...listKey, id];\n const activityJson = await this.kv.get(messageKey);\n if (activityJson == null) return;\n await this.kv.delete(messageKey);\n const activity = await Activity.fromJsonLd(activityJson);\n if (activity instanceof Create || activity instanceof Announce) {\n return activity;\n }\n return undefined;\n }\n\n async *getMessages(\n options: RepositoryGetMessagesOptions = {},\n ): AsyncIterable<Create | Announce> {\n const { order, until, since, limit } = options;\n const untilTs = until == null ? null : until.epochMilliseconds;\n const sinceTs = since == null ? null : since.epochMilliseconds;\n let messageIds = await this.kv.get<string[]>(this.prefixes.messages) ?? [];\n if (sinceTs != null) {\n const offset = messageIds.findIndex((id) =>\n extractTimestamp(id) >= sinceTs\n );\n messageIds = messageIds.slice(offset);\n }\n if (untilTs != null) {\n const offset = messageIds.findLastIndex((id) =>\n extractTimestamp(id) <= untilTs\n );\n messageIds = messageIds.slice(0, offset + 1);\n }\n if (order == null || order === \"newest\") {\n messageIds = messageIds.toReversed();\n }\n if (limit != null) {\n messageIds = messageIds.slice(0, limit);\n }\n for (const id of messageIds) {\n const messageJson = await this.kv.get([...this.prefixes.messages, id]);\n if (messageJson == null) continue;\n try {\n const activity = await Activity.fromJsonLd(messageJson);\n if (activity instanceof Create || activity instanceof Announce) {\n yield activity;\n }\n } catch {\n continue;\n }\n }\n }\n\n async getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const json = await this.kv.get([...this.prefixes.messages, id]);\n if (json == null) return undefined;\n let activity: Activity;\n try {\n activity = await Activity.fromJsonLd(json);\n } catch (e) {\n if (e instanceof TypeError) return undefined;\n throw e;\n }\n if (activity instanceof Create || activity instanceof Announce) {\n return activity;\n }\n return undefined;\n }\n\n async countMessages(): Promise<number> {\n const messageIds = await this.kv.get<string[]>(this.prefixes.messages) ??\n [];\n return messageIds.length;\n }\n\n async addFollower(followRequestId: URL, follower: Actor): Promise<void> {\n if (follower.id == null) {\n throw new TypeError(\"The follower ID is missing.\");\n }\n const followerKey: KvKey = [...this.prefixes.followers, follower.id.href];\n await this.kv.set(\n followerKey,\n await follower.toJsonLd({ format: \"compact\" }),\n );\n const lockKey: KvKey = [...this.prefixes.followers, \"lock\"];\n const listKey: KvKey = this.prefixes.followers;\n do {\n await this.kv.set(lockKey, follower.id.href);\n const list = await this.kv.get<string[]>(listKey) ?? [];\n if (!list.includes(follower.id.href)) list.push(follower.id.href);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== follower.id.href);\n const followRequestKey: KvKey = [\n ...this.prefixes.followRequests,\n followRequestId.href,\n ];\n await this.kv.set(followRequestKey, follower.id.href);\n }\n\n async removeFollower(\n followRequestId: URL,\n actorId: URL,\n ): Promise<Actor | undefined> {\n const followRequestKey: KvKey = [\n ...this.prefixes.followRequests,\n followRequestId.href,\n ];\n const followerId = await this.kv.get<string>(followRequestKey);\n if (followerId == null) return undefined;\n const followerKey: KvKey = [...this.prefixes.followers, followerId];\n if (followerId !== actorId.href) return undefined;\n const followerJson = await this.kv.get(followerKey);\n if (followerJson == null) return undefined;\n let follower: Object;\n try {\n follower = await Object.fromJsonLd(followerJson);\n } catch {\n return undefined;\n }\n if (!isActor(follower)) return undefined;\n const lockKey: KvKey = [...this.prefixes.followers, \"lock\"];\n const listKey: KvKey = this.prefixes.followers;\n do {\n await this.kv.set(lockKey, followerId);\n let list = await this.kv.get<string[]>(listKey) ?? [];\n list = list.filter((id) => id !== followerId);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== followerId);\n await this.kv.delete(followerKey);\n await this.kv.delete(followRequestKey);\n return follower;\n }\n\n async hasFollower(followerId: URL): Promise<boolean> {\n return await this.kv.get<unknown>([\n ...this.prefixes.followers,\n followerId.href,\n ]) != null;\n }\n\n async *getFollowers(\n options: RepositoryGetFollowersOptions = {},\n ): AsyncIterable<Actor> {\n const { offset = 0, limit } = options;\n let followerIds = await this.kv.get<string[]>(this.prefixes.followers) ??\n [];\n followerIds = followerIds.slice(offset);\n if (limit != null) {\n followerIds = followerIds.slice(0, limit);\n }\n for (const id of followerIds) {\n const json = await this.kv.get([...this.prefixes.followers, id]);\n let actor: Object;\n try {\n actor = await Object.fromJsonLd(json);\n } catch (e) {\n if (e instanceof TypeError) continue;\n throw e;\n }\n if (isActor(actor)) yield actor;\n }\n }\n\n async countFollowers(): Promise<number> {\n const followerIds = await this.kv.get<string[]>(this.prefixes.followers) ??\n [];\n return followerIds.length;\n }\n\n async addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n await this.kv.set(\n [...this.prefixes.follows, id],\n await follow.toJsonLd({ format: \"compact\" }),\n );\n }\n\n async removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const follow = await this.getSentFollow(id);\n if (follow == null) return undefined;\n await this.kv.delete([...this.prefixes.follows, id]);\n return follow;\n }\n\n async getSentFollow(id: Uuid): Promise<Follow | undefined> {\n const followJson = await this.kv.get([...this.prefixes.follows, id]);\n if (followJson == null) return undefined;\n try {\n return await Follow.fromJsonLd(followJson);\n } catch {\n return undefined;\n }\n }\n\n async addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n await this.kv.set(\n [...this.prefixes.followees, followeeId.href],\n await follow.toJsonLd({ format: \"compact\" }),\n );\n }\n\n async removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const follow = await this.getFollowee(followeeId);\n if (follow == null) return undefined;\n await this.kv.delete([...this.prefixes.followees, followeeId.href]);\n return follow;\n }\n\n async getFollowee(followeeId: URL): Promise<Follow | undefined> {\n const json = await this.kv.get([\n ...this.prefixes.followees,\n followeeId.href,\n ]);\n if (json == null) return undefined;\n try {\n return await Follow.fromJsonLd(json);\n } catch {\n return undefined;\n }\n }\n}\n\ninterface KeyPair {\n private: JsonWebKey;\n public: JsonWebKey;\n}\n\n/**\n * Extracts the timestamp from a UUIDv7.\n * @param uuid The UUIDv7 string to extract the timestamp from.\n * @return The timestamp in milliseconds since the Unix epoch.\n * @internal\n */\nfunction extractTimestamp(uuid: string): number {\n // UUIDv7 format: xxxxxxxx-xxxx-7xxx-yxxx-xxxxxxxxxxxx\n // The timestamp is in the first 6 bytes (48 bits) of the UUID.\n if (uuid.length !== 36 || uuid[14] !== \"7\") {\n throw new TypeError(\"Invalid UUIDv7 format.\");\n }\n const timestampHex = uuid.slice(0, 8) + uuid.slice(9, 13);\n return parseInt(timestampHex, 16);\n}\n\n/**\n * A repository for storing bot data in memory. This repository is not\n * persistent and is only suitable for testing or development.\n */\nexport class MemoryRepository implements Repository {\n keyPairs?: CryptoKeyPair[];\n messages: Map<Uuid, Create | Announce> = new Map();\n followers: Map<string, Actor> = new Map();\n followRequests: Record<string, string> = {};\n sentFollows: Record<string, Follow> = {};\n followees: Record<string, Follow> = {};\n\n setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n this.keyPairs = keyPairs;\n return Promise.resolve();\n }\n\n getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n return Promise.resolve(this.keyPairs);\n }\n\n addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n this.messages.set(id, activity);\n return Promise.resolve();\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n const existing = this.messages.get(id);\n if (existing == null) return false;\n const newActivity = await updater(existing);\n if (newActivity == null) return false;\n this.messages.set(id, newActivity);\n return true;\n }\n\n removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const activity = this.messages.get(id);\n this.messages.delete(id);\n return Promise.resolve(activity);\n }\n\n async *getMessages(\n options: RepositoryGetMessagesOptions = {},\n ): AsyncIterable<Create | Announce> {\n const { order, until, since, limit } = options;\n let messages = [...this.messages.values()];\n if (since != null) {\n messages = messages.filter((message) =>\n message.published != null &&\n Temporal.Instant.compare(message.published, since) >= 0\n );\n }\n if (until != null) {\n messages = messages.filter((message) =>\n message.published != null &&\n Temporal.Instant.compare(message.published, until) <= 0\n );\n }\n if (order === \"oldest\") {\n messages.sort((a, b) =>\n (a.published?.epochMilliseconds ?? 0) -\n (b.published?.epochMilliseconds ?? 0)\n );\n } else {\n messages.sort((a, b) =>\n (b.published?.epochMilliseconds ?? 0) -\n (a.published?.epochMilliseconds ?? 0)\n );\n }\n if (limit != null) {\n messages.slice(0, limit);\n }\n for (const message of messages) yield message;\n }\n\n getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n return Promise.resolve(this.messages.get(id));\n }\n\n countMessages(): Promise<number> {\n return Promise.resolve(this.messages.size);\n }\n\n addFollower(followId: URL, follower: Actor): Promise<void> {\n if (follower.id == null) {\n throw new TypeError(\"The follower ID is missing.\");\n }\n this.followers.set(follower.id.href, follower);\n this.followRequests[followId.href] = follower.id.href;\n return Promise.resolve();\n }\n\n removeFollower(followId: URL, followerId: URL): Promise<Actor | undefined> {\n const existing = this.followRequests[followId.href];\n if (existing == null || existing !== followerId.href) {\n return Promise.resolve(undefined);\n }\n delete this.followRequests[followId.href];\n const follower = this.followers.get(followerId.href);\n this.followers.delete(followerId.href);\n return Promise.resolve(follower);\n }\n\n hasFollower(followerId: URL): Promise<boolean> {\n return Promise.resolve(this.followers.has(followerId.href));\n }\n\n async *getFollowers(\n options: RepositoryGetFollowersOptions = {},\n ): AsyncIterable<Actor> {\n const { offset = 0, limit } = options;\n let followers = [...this.followers.values()];\n followers.sort((a, b) => b.id!.href.localeCompare(a.id!.href) ?? 0);\n if (offset > 0) {\n followers = followers.slice(offset);\n }\n if (limit != null) {\n followers = followers.slice(0, limit);\n }\n for (const follower of followers) {\n yield follower;\n }\n }\n\n countFollowers(): Promise<number> {\n return Promise.resolve(this.followers.size);\n }\n\n addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n this.sentFollows[id] = follow;\n return Promise.resolve();\n }\n\n removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const follow = this.sentFollows[id];\n delete this.sentFollows[id];\n return Promise.resolve(follow);\n }\n\n getSentFollow(id: Uuid): Promise<Follow | undefined> {\n return Promise.resolve(this.sentFollows[id]);\n }\n\n addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n this.followees[followeeId.href] = follow;\n return Promise.resolve();\n }\n\n removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const follow = this.followees[followeeId.href];\n delete this.followees[followeeId.href];\n return Promise.resolve(follow);\n }\n\n getFollowee(followeeId: URL): Promise<Follow | undefined> {\n return Promise.resolve(this.followees[followeeId.href]);\n }\n}\n\n/**\n * A repository decorator that adds an in-memory cache layer on top of another\n * repository. This is useful for improving performance by reducing the number\n * of accesses to the underlying persistent storage, but it increases memory\n * usage. The cache is not persistent and will be lost when the process exits.\n *\n * Note: List operations like `getMessages` and `getFollowers`, and count\n * operations like `countMessages` and `countFollowers` are not cached and\n * always delegate to the underlying repository.\n * @since 0.3.0\n */\nexport class MemoryCachedRepository implements Repository {\n private underlying: Repository;\n private cache: MemoryRepository;\n\n /**\n * Creates a new memory-cached repository.\n * @param underlying The underlying repository to cache.\n * @param cache An optional `MemoryRepository` instance to use as the cache.\n * If not provided, a new one will be created internally.\n */\n constructor(underlying: Repository, cache?: MemoryRepository) {\n this.underlying = underlying;\n this.cache = cache ?? new MemoryRepository();\n }\n\n async setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n await this.underlying.setKeyPairs(keyPairs);\n await this.cache.setKeyPairs(keyPairs);\n }\n\n async getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n let keyPairs = await this.cache.getKeyPairs();\n if (keyPairs === undefined) {\n keyPairs = await this.underlying.getKeyPairs();\n if (keyPairs !== undefined) await this.cache.setKeyPairs(keyPairs);\n }\n return keyPairs;\n }\n\n async addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n await this.underlying.addMessage(id, activity);\n await this.cache.addMessage(id, activity);\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n // Apply update to underlying first\n const updated = await this.underlying.updateMessage(id, updater);\n if (updated) {\n // If successful, fetch the updated message and update the cache\n const updatedMessage = await this.underlying.getMessage(id);\n if (updatedMessage) {\n await this.cache.addMessage(id, updatedMessage); // Use addMessage which acts like set\n } else {\n // Should not happen if updateMessage returned true, but handle defensively\n await this.cache.removeMessage(id);\n }\n }\n return updated;\n }\n\n async removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const removedActivity = await this.underlying.removeMessage(id);\n if (removedActivity !== undefined) {\n await this.cache.removeMessage(id);\n }\n return removedActivity;\n }\n\n // getMessages is not cached due to complexity with options\n getMessages(\n options?: RepositoryGetMessagesOptions,\n ): AsyncIterable<Create | Announce> {\n return this.underlying.getMessages(options);\n }\n\n async getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n let message = await this.cache.getMessage(id);\n if (message === undefined) {\n message = await this.underlying.getMessage(id);\n if (message !== undefined) {\n await this.cache.addMessage(id, message); // Use addMessage which acts like set\n }\n }\n return message;\n }\n\n // countMessages is not cached\n countMessages(): Promise<number> {\n return this.underlying.countMessages();\n }\n\n async addFollower(followId: URL, follower: Actor): Promise<void> {\n await this.underlying.addFollower(followId, follower);\n await this.cache.addFollower(followId, follower);\n }\n\n async removeFollower(\n followId: URL,\n followerId: URL,\n ): Promise<Actor | undefined> {\n const removedFollower = await this.underlying.removeFollower(\n followId,\n followerId,\n );\n if (removedFollower !== undefined) {\n await this.cache.removeFollower(followId, followerId);\n }\n return removedFollower;\n }\n\n async hasFollower(followerId: URL): Promise<boolean> {\n // Check cache first for potentially faster response\n if (await this.cache.hasFollower(followerId)) {\n return true;\n }\n // If not in cache, check underlying and update cache if found\n const exists = await this.underlying.hasFollower(followerId);\n // Note: We don't automatically add to cache here, as we don't have the Actor object\n // It will be cached if addFollower is called or if getFollowers iterates over it (though getFollowers isn't cached)\n return exists;\n }\n\n // getFollowers is not cached due to complexity with options\n getFollowers(options?: RepositoryGetFollowersOptions): AsyncIterable<Actor> {\n // We could potentially cache followers as they are iterated,\n // but for simplicity, delegate directly for now.\n return this.underlying.getFollowers(options);\n }\n\n // countFollowers is not cached\n countFollowers(): Promise<number> {\n return this.underlying.countFollowers();\n }\n\n async addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n await this.underlying.addSentFollow(id, follow);\n await this.cache.addSentFollow(id, follow);\n }\n\n async removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const removedFollow = await this.underlying.removeSentFollow(id);\n if (removedFollow !== undefined) {\n await this.cache.removeSentFollow(id);\n }\n return removedFollow;\n }\n\n async getSentFollow(id: Uuid): Promise<Follow | undefined> {\n let follow = await this.cache.getSentFollow(id);\n if (follow === undefined) {\n follow = await this.underlying.getSentFollow(id);\n if (follow !== undefined) {\n await this.cache.addSentFollow(id, follow);\n }\n }\n return follow;\n }\n\n async addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n await this.underlying.addFollowee(followeeId, follow);\n await this.cache.addFollowee(followeeId, follow);\n }\n\n async removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const removedFollow = await this.underlying.removeFollowee(followeeId);\n if (removedFollow !== undefined) {\n await this.cache.removeFollowee(followeeId);\n }\n return removedFollow;\n }\n\n async getFollowee(followeeId: URL): Promise<Follow | undefined> {\n let follow = await this.cache.getFollowee(followeeId);\n if (follow === undefined) {\n follow = await this.underlying.getFollowee(followeeId);\n if (follow !== undefined) {\n await this.cache.addFollowee(followeeId, follow);\n }\n }\n return follow;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8RA,IAAa,eAAb,MAAgD;CAC9C,AAAS;CACT,AAAS;;;;;;CAOT,YAAYA,IAAaC,UAAsC;AAC7D,OAAK,KAAK;AACV,OAAK,WAAW;GACd,UAAU,CAAC,WAAW,UAAW;GACjC,UAAU,CAAC,WAAW,UAAW;GACjC,WAAW,CAAC,WAAW,WAAY;GACnC,gBAAgB,CAAC,WAAW,gBAAiB;GAC7C,WAAW,CAAC,WAAW,WAAY;GACnC,SAAS,CAAC,WAAW,SAAU;GAC/B,GAAG,YAAY,CAAE;EAClB;CACF;CAED,MAAM,YAAYC,UAA0C;EAC1D,MAAMC,QAAmB,CAAE;AAC3B,OAAK,MAAM,WAAW,UAAU;GAC9B,MAAMC,OAAgB;IACpB,SAAS,MAAM,UAAU,QAAQ,WAAW;IAC5C,QAAQ,MAAM,UAAU,QAAQ,UAAU;GAC3C;AACD,SAAM,KAAK,KAAK;EACjB;AACD,QAAM,KAAK,GAAG,IAAI,KAAK,SAAS,UAAU,MAAM;CACjD;CAED,MAAM,cAAoD;EACxD,MAAM,WAAW,MAAM,KAAK,GAAG,IAAe,KAAK,SAAS,SAAS;AACrE,MAAI,YAAY,KAAM;EACtB,MAAM,WAAW,SAAS,IAAI,OAAO,UAAU;GAC7C,YAAY,MAAM,UAAU,KAAK,SAAS,UAAU;GACpD,WAAW,MAAM,UAAU,KAAK,QAAQ,SAAS;EAClD,GAAE;AACH,SAAO,MAAM,QAAQ,IAAI,SAAS;CACnC;CAED,MAAM,WAAWC,IAAUC,UAA4C;EACrE,MAAMC,aAAoB,CAAC,GAAG,KAAK,SAAS,UAAU,EAAG;AACzD,QAAM,KAAK,GAAG,IACZ,YACA,MAAM,SAAS,SAAS,EAAE,QAAQ,UAAW,EAAC,CAC/C;EACD,MAAMC,UAAiB,CAAC,GAAG,KAAK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YAA8C;EACjE,MAAM,gBAAgB,MAAM,KAAK,WAAW,eAAe,WAAW;AACtE,MAAI,yBACF,OAAM,KAAK,MAAM,eAAe,WAAW;AAE7C,SAAO;CACR;CAED,MAAM,YAAYA,YAA8C;EAC9D,IAAI,SAAS,MAAM,KAAK,MAAM,YAAY,WAAW;AACrD,MAAI,mBAAsB;AACxB,YAAS,MAAM,KAAK,WAAW,YAAY,WAAW;AACtD,OAAI,kBACF,OAAM,KAAK,MAAM,YAAY,YAAY,OAAO;EAEnD;AACD,SAAO;CACR;AACF"}
1
+ {"version":3,"file":"repository.js","names":["kv: KvStore","prefixes?: KvStoreRepositoryPrefixes","keyPairs: CryptoKeyPair[]","pairs: KeyPair[]","pair: KeyPair","id: Uuid","activity: Create | Announce","messageKey: KvKey","lockKey: KvKey","listKey: KvKey","updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>","kvKey: KvKey","Create","Announce","options: RepositoryGetMessagesOptions","activity: Activity","followRequestId: URL","follower: Actor","followerKey: KvKey","followRequestKey: KvKey","actorId: URL","follower: Object","followerId: URL","options: RepositoryGetFollowersOptions","actor: Object","follow: Follow","followeeId: URL","uuid: string","followId: URL","underlying: Repository","cache?: MemoryRepository","options?: RepositoryGetMessagesOptions","options?: RepositoryGetFollowersOptions"],"sources":["../src/repository.ts"],"sourcesContent":["// BotKit by Fedify: A framework for creating ActivityPub bots\n// Copyright (C) 2025 Hong Minhee <https://hongminhee.org/>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport type { KvKey, KvStore } from \"@fedify/fedify/federation\";\nimport { exportJwk, importJwk } from \"@fedify/fedify/sig\";\nimport {\n Activity,\n type Actor,\n Announce,\n Create,\n Follow,\n isActor,\n Object,\n} from \"@fedify/fedify/vocab\";\nexport type { KvKey, KvStore } from \"@fedify/fedify/federation\";\nexport { Announce, Create } from \"@fedify/fedify/vocab\";\n\n/**\n * A UUID (universally unique identifier).\n * @since 0.3.0\n */\nexport type Uuid = ReturnType<typeof crypto.randomUUID>;\n\n/**\n * A repository for storing bot data.\n * @since 0.3.0\n */\nexport interface Repository {\n /**\n * Sets the key pairs of the bot actor.\n * @param keyPairs The key pairs to set.\n */\n setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void>;\n\n /**\n * Gets the key pairs of the bot actor.\n * @returns The key pairs of the bot actor. If the key pairs do not exist,\n * `undefined` will be returned.\n */\n getKeyPairs(): Promise<CryptoKeyPair[] | undefined>;\n\n /**\n * Adds a message to the repository.\n * @param id The UUID of the message.\n * @param activity The activity to add.\n */\n addMessage(id: Uuid, activity: Create | Announce): Promise<void>;\n\n /**\n * Updates a message in the repository.\n * @param id The UUID of the message.\n * @param updater The function to update the message. The function will be\n * called with the existing message, and the return value will\n * be the new message. If the function returns a promise, the\n * promise will be awaited. If the function returns either\n * `undefined` or a promise that resolves to `undefined`,\n * the message will not be updated. If the message does not\n * exist, the updater will not be called.\n * @returns `true` if the message was updated, `false` if the message does not\n * exist.\n */\n updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean>;\n\n /**\n * Removes a message from the repository.\n * @param id The UUID of the message to remove.\n * @returns The removed activity. If the message does not exist, `undefined`\n * will be returned.\n */\n removeMessage(id: Uuid): Promise<Create | Announce | undefined>;\n\n /**\n * Gets messages from the repository.\n * @param options The options for getting messages.\n * @returns An async iterable of message activities.\n */\n getMessages(\n options?: RepositoryGetMessagesOptions,\n ): AsyncIterable<Create | Announce>;\n\n /**\n * Gets a message from the repository.\n * @param id The UUID of the message to get.\n * @returns The message activity, or `undefined` if the message does not\n * exist.\n */\n getMessage(id: Uuid): Promise<Create | Announce | undefined>;\n\n /**\n * Counts the number of messages in the repository.\n * @returns The number of messages in the repository.\n */\n countMessages(): Promise<number>;\n\n /**\n * Adds a follower to the repository.\n * @param followId The URL of the follow request.\n * @param follower The actor who follows the bot.\n */\n addFollower(followId: URL, follower: Actor): Promise<void>;\n\n /**\n * Removes a follower from the repository.\n * @param followId The URL of the follow request.\n * @param followerId The ID of the actor to remove.\n * @returns The removed actor. If the follower does not exist or the follow\n * request is not about the follower, `undefined` will be returned.\n */\n removeFollower(followId: URL, followerId: URL): Promise<Actor | undefined>;\n\n /**\n * Checks if the repository has a follower.\n * @param followerId The ID of the follower to check.\n * @returns `true` if the repository has the follower, `false` otherwise.\n */\n hasFollower(followerId: URL): Promise<boolean>;\n\n /**\n * Gets followers from the repository.\n * @param options The options for getting followers.\n * @returns An async iterable of actors who follow the bot.\n */\n getFollowers(options?: RepositoryGetFollowersOptions): AsyncIterable<Actor>;\n\n /**\n * Counts the number of followers in the repository.\n * @returns The number of followers in the repository.\n */\n countFollowers(): Promise<number>;\n\n /**\n * Adds a sent follow request to the repository.\n * @param id The UUID of the follow request.\n * @param follow The follow activity to add.\n */\n addSentFollow(id: Uuid, follow: Follow): Promise<void>;\n\n /**\n * Removes a sent follow request from the repository.\n * @param id The UUID of the follow request to remove.\n * @returns The removed follow activity. If the follow request does not\n * exist, `undefined` will be returned.\n */\n removeSentFollow(id: Uuid): Promise<Follow | undefined>;\n\n /**\n * Gets a sent follow request from the repository.\n * @param id The UUID of the follow request to get.\n * @returns The `Follow` activity, or `undefined` if the follow request does\n * not exist.\n */\n getSentFollow(id: Uuid): Promise<Follow | undefined>;\n\n /**\n * Adds a followee to the repository.\n * @param followeeId The ID of the followee to add.\n * @param follow The follow activity to add.\n */\n addFollowee(followeeId: URL, follow: Follow): Promise<void>;\n\n /**\n * Removes a followee from the repository.\n * @param followeeId The ID of the followee to remove.\n * @returns The `Follow` activity that was removed. If the followee does not\n * exist, `undefined` will be returned.\n */\n removeFollowee(followeeId: URL): Promise<Follow | undefined>;\n\n /**\n * Gets a followee from the repository.\n * @param followeeId The ID of the followee to get.\n * @returns The `Follow` activity, or `undefined` if the followee does not\n * exist.\n */\n getFollowee(followeeId: URL): Promise<Follow | undefined>;\n}\n\n/**\n * Options for getting messages from the repository.\n * @since 0.3.0\n */\nexport interface RepositoryGetMessagesOptions {\n /**\n * The order of the messages. If omitted, `\"newest\"` will be used.\n * @default `\"newest\"`\n */\n readonly order?: \"oldest\" | \"newest\";\n\n /**\n * The timestamp to get messages created at or before this time.\n * If omitted, no limit will be applied.\n */\n readonly until?: Temporal.Instant;\n\n /**\n * The timestamp to get messages created at or after this time.\n * If omitted, no limit will be applied.\n */\n readonly since?: Temporal.Instant;\n\n /**\n * The maximum number of messages to get. If omitted, no limit will be\n * applied.\n */\n readonly limit?: number;\n}\n\n/**\n * Options for getting followers from the repository.\n * @since 0.3.0\n */\nexport interface RepositoryGetFollowersOptions {\n /**\n * The offset of the followers to get. If omitted, 0 will be used.\n * @default `0`\n */\n readonly offset?: number;\n\n /**\n * The limit of the followers to get. If omitted, no limit will be applied.\n */\n readonly limit?: number;\n}\n\n/**\n * The prefixes for key-value store keys used by the bot.\n * @since 0.3.0\n */\nexport interface KvStoreRepositoryPrefixes {\n /**\n * The key prefix used for storing the key pairs of the bot actor.\n * @default `[\"_botkit\", \"keyPairs\"]`\n */\n readonly keyPairs: KvKey;\n\n /**\n * The key prefix used for storing published messages.\n * @default `[\"_botkit\", \"messages\"]`\n */\n readonly messages: KvKey;\n\n /**\n * The key prefix used for storing followers.\n * @default `[\"_botkit\", \"followers\"]`\n */\n readonly followers: KvKey;\n\n /**\n * The key prefix used for storing incoming follow requests.\n * @default `[\"_botkit\", \"followRequests\"]`\n */\n readonly followRequests: KvKey;\n\n /**\n * The key prefix used for storing followees.\n * @default `[\"_botkit\", \"followees\"]`\n */\n readonly followees: KvKey;\n\n /**\n * The key prefix used for storing outgoing follow requests.\n * @default `[\"_botkit\", \"follows\"]`\n */\n readonly follows: KvKey;\n}\n\n/**\n * A repository for storing bot data using a key-value store.\n */\nexport class KvRepository implements Repository {\n readonly kv: KvStore;\n readonly prefixes: KvStoreRepositoryPrefixes;\n\n /**\n * Creates a new key-value store repository.\n * @param kv The key-value store to use.\n * @param prefixes The prefixes for key-value store keys.\n */\n constructor(kv: KvStore, prefixes?: KvStoreRepositoryPrefixes) {\n this.kv = kv;\n this.prefixes = {\n keyPairs: [\"_botkit\", \"keyPairs\"],\n messages: [\"_botkit\", \"messages\"],\n followers: [\"_botkit\", \"followers\"],\n followRequests: [\"_botkit\", \"followRequests\"],\n followees: [\"_botkit\", \"followees\"],\n follows: [\"_botkit\", \"follows\"],\n ...prefixes ?? {},\n };\n }\n\n async setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n const pairs: KeyPair[] = [];\n for (const keyPair of keyPairs) {\n const pair: KeyPair = {\n private: await exportJwk(keyPair.privateKey),\n public: await exportJwk(keyPair.publicKey),\n };\n pairs.push(pair);\n }\n await this.kv.set(this.prefixes.keyPairs, pairs);\n }\n\n async getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n const keyPairs = await this.kv.get<KeyPair[]>(this.prefixes.keyPairs);\n if (keyPairs == null) return undefined;\n const promises = keyPairs.map(async (pair) => ({\n privateKey: await importJwk(pair.private, \"private\"),\n publicKey: await importJwk(pair.public, \"public\"),\n }));\n return await Promise.all(promises);\n }\n\n async addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n const messageKey: KvKey = [...this.prefixes.messages, id];\n await this.kv.set(\n messageKey,\n await activity.toJsonLd({ format: \"compact\" }),\n );\n const lockKey: KvKey = [...this.prefixes.messages, \"lock\"];\n const listKey: KvKey = this.prefixes.messages;\n do {\n await this.kv.set(lockKey, id);\n const set = new Set(await this.kv.get<string[]>(listKey) ?? []);\n set.add(id);\n const list = [...set];\n list.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== id);\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n const kvKey: KvKey = [...this.prefixes.messages, id];\n const createJson = await this.kv.get(kvKey);\n if (createJson == null) return false;\n const activity = await Activity.fromJsonLd(createJson);\n if (!(activity instanceof Create || activity instanceof Announce)) {\n return false;\n }\n const newActivity = await updater(activity);\n if (newActivity == null) return false;\n await this.kv.set(\n kvKey,\n await newActivity.toJsonLd({ format: \"compact\" }),\n );\n return true;\n }\n\n async removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const listKey: KvKey = this.prefixes.messages;\n const lockKey: KvKey = [...listKey, \"lock\"];\n const lockId = `${id}:delete`;\n do {\n await this.kv.set(lockKey, lockId);\n const set = new Set(await this.kv.get<string[]>(listKey) ?? []);\n set.delete(id);\n const list = [...set];\n list.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== lockId);\n const messageKey: KvKey = [...listKey, id];\n const activityJson = await this.kv.get(messageKey);\n if (activityJson == null) return;\n await this.kv.delete(messageKey);\n const activity = await Activity.fromJsonLd(activityJson);\n if (activity instanceof Create || activity instanceof Announce) {\n return activity;\n }\n return undefined;\n }\n\n async *getMessages(\n options: RepositoryGetMessagesOptions = {},\n ): AsyncIterable<Create | Announce> {\n const { order, until, since, limit } = options;\n const untilTs = until == null ? null : until.epochMilliseconds;\n const sinceTs = since == null ? null : since.epochMilliseconds;\n let messageIds = await this.kv.get<string[]>(this.prefixes.messages) ?? [];\n if (sinceTs != null) {\n const offset = messageIds.findIndex((id) =>\n extractTimestamp(id) >= sinceTs\n );\n messageIds = messageIds.slice(offset);\n }\n if (untilTs != null) {\n const offset = messageIds.findLastIndex((id) =>\n extractTimestamp(id) <= untilTs\n );\n messageIds = messageIds.slice(0, offset + 1);\n }\n if (order == null || order === \"newest\") {\n messageIds = messageIds.toReversed();\n }\n if (limit != null) {\n messageIds = messageIds.slice(0, limit);\n }\n for (const id of messageIds) {\n const messageJson = await this.kv.get([...this.prefixes.messages, id]);\n if (messageJson == null) continue;\n try {\n const activity = await Activity.fromJsonLd(messageJson);\n if (activity instanceof Create || activity instanceof Announce) {\n yield activity;\n }\n } catch {\n continue;\n }\n }\n }\n\n async getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const json = await this.kv.get([...this.prefixes.messages, id]);\n if (json == null) return undefined;\n let activity: Activity;\n try {\n activity = await Activity.fromJsonLd(json);\n } catch (e) {\n if (e instanceof TypeError) return undefined;\n throw e;\n }\n if (activity instanceof Create || activity instanceof Announce) {\n return activity;\n }\n return undefined;\n }\n\n async countMessages(): Promise<number> {\n const messageIds = await this.kv.get<string[]>(this.prefixes.messages) ??\n [];\n return messageIds.length;\n }\n\n async addFollower(followRequestId: URL, follower: Actor): Promise<void> {\n if (follower.id == null) {\n throw new TypeError(\"The follower ID is missing.\");\n }\n const followerKey: KvKey = [...this.prefixes.followers, follower.id.href];\n await this.kv.set(\n followerKey,\n await follower.toJsonLd({ format: \"compact\" }),\n );\n const lockKey: KvKey = [...this.prefixes.followers, \"lock\"];\n const listKey: KvKey = this.prefixes.followers;\n do {\n await this.kv.set(lockKey, follower.id.href);\n const list = await this.kv.get<string[]>(listKey) ?? [];\n if (!list.includes(follower.id.href)) list.push(follower.id.href);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== follower.id.href);\n const followRequestKey: KvKey = [\n ...this.prefixes.followRequests,\n followRequestId.href,\n ];\n await this.kv.set(followRequestKey, follower.id.href);\n }\n\n async removeFollower(\n followRequestId: URL,\n actorId: URL,\n ): Promise<Actor | undefined> {\n const followRequestKey: KvKey = [\n ...this.prefixes.followRequests,\n followRequestId.href,\n ];\n const followerId = await this.kv.get<string>(followRequestKey);\n if (followerId == null) return undefined;\n const followerKey: KvKey = [...this.prefixes.followers, followerId];\n if (followerId !== actorId.href) return undefined;\n const followerJson = await this.kv.get(followerKey);\n if (followerJson == null) return undefined;\n let follower: Object;\n try {\n follower = await Object.fromJsonLd(followerJson);\n } catch {\n return undefined;\n }\n if (!isActor(follower)) return undefined;\n const lockKey: KvKey = [...this.prefixes.followers, \"lock\"];\n const listKey: KvKey = this.prefixes.followers;\n do {\n await this.kv.set(lockKey, followerId);\n let list = await this.kv.get<string[]>(listKey) ?? [];\n list = list.filter((id) => id !== followerId);\n await this.kv.set(listKey, list);\n } while (await this.kv.get(lockKey) !== followerId);\n await this.kv.delete(followerKey);\n await this.kv.delete(followRequestKey);\n return follower;\n }\n\n async hasFollower(followerId: URL): Promise<boolean> {\n return await this.kv.get<unknown>([\n ...this.prefixes.followers,\n followerId.href,\n ]) != null;\n }\n\n async *getFollowers(\n options: RepositoryGetFollowersOptions = {},\n ): AsyncIterable<Actor> {\n const { offset = 0, limit } = options;\n let followerIds = await this.kv.get<string[]>(this.prefixes.followers) ??\n [];\n followerIds = followerIds.slice(offset);\n if (limit != null) {\n followerIds = followerIds.slice(0, limit);\n }\n for (const id of followerIds) {\n const json = await this.kv.get([...this.prefixes.followers, id]);\n let actor: Object;\n try {\n actor = await Object.fromJsonLd(json);\n } catch (e) {\n if (e instanceof TypeError) continue;\n throw e;\n }\n if (isActor(actor)) yield actor;\n }\n }\n\n async countFollowers(): Promise<number> {\n const followerIds = await this.kv.get<string[]>(this.prefixes.followers) ??\n [];\n return followerIds.length;\n }\n\n async addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n await this.kv.set(\n [...this.prefixes.follows, id],\n await follow.toJsonLd({ format: \"compact\" }),\n );\n }\n\n async removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const follow = await this.getSentFollow(id);\n if (follow == null) return undefined;\n await this.kv.delete([...this.prefixes.follows, id]);\n return follow;\n }\n\n async getSentFollow(id: Uuid): Promise<Follow | undefined> {\n const followJson = await this.kv.get([...this.prefixes.follows, id]);\n if (followJson == null) return undefined;\n try {\n return await Follow.fromJsonLd(followJson);\n } catch {\n return undefined;\n }\n }\n\n async addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n await this.kv.set(\n [...this.prefixes.followees, followeeId.href],\n await follow.toJsonLd({ format: \"compact\" }),\n );\n }\n\n async removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const follow = await this.getFollowee(followeeId);\n if (follow == null) return undefined;\n await this.kv.delete([...this.prefixes.followees, followeeId.href]);\n return follow;\n }\n\n async getFollowee(followeeId: URL): Promise<Follow | undefined> {\n const json = await this.kv.get([\n ...this.prefixes.followees,\n followeeId.href,\n ]);\n if (json == null) return undefined;\n try {\n return await Follow.fromJsonLd(json);\n } catch {\n return undefined;\n }\n }\n}\n\ninterface KeyPair {\n private: JsonWebKey;\n public: JsonWebKey;\n}\n\n/**\n * Extracts the timestamp from a UUIDv7.\n * @param uuid The UUIDv7 string to extract the timestamp from.\n * @return The timestamp in milliseconds since the Unix epoch.\n * @internal\n */\nfunction extractTimestamp(uuid: string): number {\n // UUIDv7 format: xxxxxxxx-xxxx-7xxx-xxxx-xxxxxxxxxxxx\n // The timestamp is in the first 6 bytes (48 bits) of the UUID.\n if (uuid.length !== 36 || uuid[14] !== \"7\") {\n throw new TypeError(\"Invalid UUIDv7 format.\");\n }\n const timestampHex = uuid.slice(0, 8) + uuid.slice(9, 13);\n return parseInt(timestampHex, 16);\n}\n\n/**\n * A repository for storing bot data in memory. This repository is not\n * persistent and is only suitable for testing or development.\n */\nexport class MemoryRepository implements Repository {\n keyPairs?: CryptoKeyPair[];\n messages: Map<Uuid, Create | Announce> = new Map();\n followers: Map<string, Actor> = new Map();\n followRequests: Record<string, string> = {};\n sentFollows: Record<string, Follow> = {};\n followees: Record<string, Follow> = {};\n\n setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n this.keyPairs = keyPairs;\n return Promise.resolve();\n }\n\n getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n return Promise.resolve(this.keyPairs);\n }\n\n addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n this.messages.set(id, activity);\n return Promise.resolve();\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n const existing = this.messages.get(id);\n if (existing == null) return false;\n const newActivity = await updater(existing);\n if (newActivity == null) return false;\n this.messages.set(id, newActivity);\n return true;\n }\n\n removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const activity = this.messages.get(id);\n this.messages.delete(id);\n return Promise.resolve(activity);\n }\n\n async *getMessages(\n options: RepositoryGetMessagesOptions = {},\n ): AsyncIterable<Create | Announce> {\n const { order, until, since, limit } = options;\n let messages = [...this.messages.values()];\n if (since != null) {\n messages = messages.filter((message) =>\n message.published != null &&\n Temporal.Instant.compare(message.published, since) >= 0\n );\n }\n if (until != null) {\n messages = messages.filter((message) =>\n message.published != null &&\n Temporal.Instant.compare(message.published, until) <= 0\n );\n }\n if (order === \"oldest\") {\n messages.sort((a, b) =>\n (a.published?.epochMilliseconds ?? 0) -\n (b.published?.epochMilliseconds ?? 0)\n );\n } else {\n messages.sort((a, b) =>\n (b.published?.epochMilliseconds ?? 0) -\n (a.published?.epochMilliseconds ?? 0)\n );\n }\n if (limit != null) {\n messages.slice(0, limit);\n }\n for (const message of messages) yield message;\n }\n\n getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n return Promise.resolve(this.messages.get(id));\n }\n\n countMessages(): Promise<number> {\n return Promise.resolve(this.messages.size);\n }\n\n addFollower(followId: URL, follower: Actor): Promise<void> {\n if (follower.id == null) {\n throw new TypeError(\"The follower ID is missing.\");\n }\n this.followers.set(follower.id.href, follower);\n this.followRequests[followId.href] = follower.id.href;\n return Promise.resolve();\n }\n\n removeFollower(followId: URL, followerId: URL): Promise<Actor | undefined> {\n const existing = this.followRequests[followId.href];\n if (existing == null || existing !== followerId.href) {\n return Promise.resolve(undefined);\n }\n delete this.followRequests[followId.href];\n const follower = this.followers.get(followerId.href);\n this.followers.delete(followerId.href);\n return Promise.resolve(follower);\n }\n\n hasFollower(followerId: URL): Promise<boolean> {\n return Promise.resolve(this.followers.has(followerId.href));\n }\n\n async *getFollowers(\n options: RepositoryGetFollowersOptions = {},\n ): AsyncIterable<Actor> {\n const { offset = 0, limit } = options;\n let followers = [...this.followers.values()];\n followers.sort((a, b) => b.id!.href.localeCompare(a.id!.href) ?? 0);\n if (offset > 0) {\n followers = followers.slice(offset);\n }\n if (limit != null) {\n followers = followers.slice(0, limit);\n }\n for (const follower of followers) {\n yield follower;\n }\n }\n\n countFollowers(): Promise<number> {\n return Promise.resolve(this.followers.size);\n }\n\n addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n this.sentFollows[id] = follow;\n return Promise.resolve();\n }\n\n removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const follow = this.sentFollows[id];\n delete this.sentFollows[id];\n return Promise.resolve(follow);\n }\n\n getSentFollow(id: Uuid): Promise<Follow | undefined> {\n return Promise.resolve(this.sentFollows[id]);\n }\n\n addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n this.followees[followeeId.href] = follow;\n return Promise.resolve();\n }\n\n removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const follow = this.followees[followeeId.href];\n delete this.followees[followeeId.href];\n return Promise.resolve(follow);\n }\n\n getFollowee(followeeId: URL): Promise<Follow | undefined> {\n return Promise.resolve(this.followees[followeeId.href]);\n }\n}\n\n/**\n * A repository decorator that adds an in-memory cache layer on top of another\n * repository. This is useful for improving performance by reducing the number\n * of accesses to the underlying persistent storage, but it increases memory\n * usage. The cache is not persistent and will be lost when the process exits.\n *\n * Note: List operations like `getMessages` and `getFollowers`, and count\n * operations like `countMessages` and `countFollowers` are not cached and\n * always delegate to the underlying repository.\n * @since 0.3.0\n */\nexport class MemoryCachedRepository implements Repository {\n private underlying: Repository;\n private cache: MemoryRepository;\n\n /**\n * Creates a new memory-cached repository.\n * @param underlying The underlying repository to cache.\n * @param cache An optional `MemoryRepository` instance to use as the cache.\n * If not provided, a new one will be created internally.\n */\n constructor(underlying: Repository, cache?: MemoryRepository) {\n this.underlying = underlying;\n this.cache = cache ?? new MemoryRepository();\n }\n\n async setKeyPairs(keyPairs: CryptoKeyPair[]): Promise<void> {\n await this.underlying.setKeyPairs(keyPairs);\n await this.cache.setKeyPairs(keyPairs);\n }\n\n async getKeyPairs(): Promise<CryptoKeyPair[] | undefined> {\n let keyPairs = await this.cache.getKeyPairs();\n if (keyPairs === undefined) {\n keyPairs = await this.underlying.getKeyPairs();\n if (keyPairs !== undefined) await this.cache.setKeyPairs(keyPairs);\n }\n return keyPairs;\n }\n\n async addMessage(id: Uuid, activity: Create | Announce): Promise<void> {\n await this.underlying.addMessage(id, activity);\n await this.cache.addMessage(id, activity);\n }\n\n async updateMessage(\n id: Uuid,\n updater: (\n existing: Create | Announce,\n ) => Create | Announce | undefined | Promise<Create | Announce | undefined>,\n ): Promise<boolean> {\n // Apply update to underlying first\n const updated = await this.underlying.updateMessage(id, updater);\n if (updated) {\n // If successful, fetch the updated message and update the cache\n const updatedMessage = await this.underlying.getMessage(id);\n if (updatedMessage) {\n await this.cache.addMessage(id, updatedMessage); // Use addMessage which acts like set\n } else {\n // Should not happen if updateMessage returned true, but handle defensively\n await this.cache.removeMessage(id);\n }\n }\n return updated;\n }\n\n async removeMessage(id: Uuid): Promise<Create | Announce | undefined> {\n const removedActivity = await this.underlying.removeMessage(id);\n if (removedActivity !== undefined) {\n await this.cache.removeMessage(id);\n }\n return removedActivity;\n }\n\n // getMessages is not cached due to complexity with options\n getMessages(\n options?: RepositoryGetMessagesOptions,\n ): AsyncIterable<Create | Announce> {\n return this.underlying.getMessages(options);\n }\n\n async getMessage(id: Uuid): Promise<Create | Announce | undefined> {\n let message = await this.cache.getMessage(id);\n if (message === undefined) {\n message = await this.underlying.getMessage(id);\n if (message !== undefined) {\n await this.cache.addMessage(id, message); // Use addMessage which acts like set\n }\n }\n return message;\n }\n\n // countMessages is not cached\n countMessages(): Promise<number> {\n return this.underlying.countMessages();\n }\n\n async addFollower(followId: URL, follower: Actor): Promise<void> {\n await this.underlying.addFollower(followId, follower);\n await this.cache.addFollower(followId, follower);\n }\n\n async removeFollower(\n followId: URL,\n followerId: URL,\n ): Promise<Actor | undefined> {\n const removedFollower = await this.underlying.removeFollower(\n followId,\n followerId,\n );\n if (removedFollower !== undefined) {\n await this.cache.removeFollower(followId, followerId);\n }\n return removedFollower;\n }\n\n async hasFollower(followerId: URL): Promise<boolean> {\n // Check cache first for potentially faster response\n if (await this.cache.hasFollower(followerId)) {\n return true;\n }\n // If not in cache, check underlying and update cache if found\n const exists = await this.underlying.hasFollower(followerId);\n // Note: We don't automatically add to cache here, as we don't have the Actor object\n // It will be cached if addFollower is called or if getFollowers iterates over it (though getFollowers isn't cached)\n return exists;\n }\n\n // getFollowers is not cached due to complexity with options\n getFollowers(options?: RepositoryGetFollowersOptions): AsyncIterable<Actor> {\n // We could potentially cache followers as they are iterated,\n // but for simplicity, delegate directly for now.\n return this.underlying.getFollowers(options);\n }\n\n // countFollowers is not cached\n countFollowers(): Promise<number> {\n return this.underlying.countFollowers();\n }\n\n async addSentFollow(id: Uuid, follow: Follow): Promise<void> {\n await this.underlying.addSentFollow(id, follow);\n await this.cache.addSentFollow(id, follow);\n }\n\n async removeSentFollow(id: Uuid): Promise<Follow | undefined> {\n const removedFollow = await this.underlying.removeSentFollow(id);\n if (removedFollow !== undefined) {\n await this.cache.removeSentFollow(id);\n }\n return removedFollow;\n }\n\n async getSentFollow(id: Uuid): Promise<Follow | undefined> {\n let follow = await this.cache.getSentFollow(id);\n if (follow === undefined) {\n follow = await this.underlying.getSentFollow(id);\n if (follow !== undefined) {\n await this.cache.addSentFollow(id, follow);\n }\n }\n return follow;\n }\n\n async addFollowee(followeeId: URL, follow: Follow): Promise<void> {\n await this.underlying.addFollowee(followeeId, follow);\n await this.cache.addFollowee(followeeId, follow);\n }\n\n async removeFollowee(followeeId: URL): Promise<Follow | undefined> {\n const removedFollow = await this.underlying.removeFollowee(followeeId);\n if (removedFollow !== undefined) {\n await this.cache.removeFollowee(followeeId);\n }\n return removedFollow;\n }\n\n async getFollowee(followeeId: URL): Promise<Follow | undefined> {\n let follow = await this.cache.getFollowee(followeeId);\n if (follow === undefined) {\n follow = await this.underlying.getFollowee(followeeId);\n if (follow !== undefined) {\n await this.cache.addFollowee(followeeId, follow);\n }\n }\n return follow;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8RA,IAAa,eAAb,MAAgD;CAC9C,AAAS;CACT,AAAS;;;;;;CAOT,YAAYA,IAAaC,UAAsC;AAC7D,OAAK,KAAK;AACV,OAAK,WAAW;GACd,UAAU,CAAC,WAAW,UAAW;GACjC,UAAU,CAAC,WAAW,UAAW;GACjC,WAAW,CAAC,WAAW,WAAY;GACnC,gBAAgB,CAAC,WAAW,gBAAiB;GAC7C,WAAW,CAAC,WAAW,WAAY;GACnC,SAAS,CAAC,WAAW,SAAU;GAC/B,GAAG,YAAY,CAAE;EAClB;CACF;CAED,MAAM,YAAYC,UAA0C;EAC1D,MAAMC,QAAmB,CAAE;AAC3B,OAAK,MAAM,WAAW,UAAU;GAC9B,MAAMC,OAAgB;IACpB,SAAS,MAAM,UAAU,QAAQ,WAAW;IAC5C,QAAQ,MAAM,UAAU,QAAQ,UAAU;GAC3C;AACD,SAAM,KAAK,KAAK;EACjB;AACD,QAAM,KAAK,GAAG,IAAI,KAAK,SAAS,UAAU,MAAM;CACjD;CAED,MAAM,cAAoD;EACxD,MAAM,WAAW,MAAM,KAAK,GAAG,IAAe,KAAK,SAAS,SAAS;AACrE,MAAI,YAAY,KAAM;EACtB,MAAM,WAAW,SAAS,IAAI,OAAO,UAAU;GAC7C,YAAY,MAAM,UAAU,KAAK,SAAS,UAAU;GACpD,WAAW,MAAM,UAAU,KAAK,QAAQ,SAAS;EAClD,GAAE;AACH,SAAO,MAAM,QAAQ,IAAI,SAAS;CACnC;C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,kBACF,OAAM,KAAK,MAAM,cAAc,IAAI,OAAO;EAE7C;AACD,SAAO;CACR;CAED,MAAM,YAAYqB,YAAiBD,QAA+B;AAChE,QAAM,KAAK,WAAW,YAAY,YAAY,OAAO;AACrD,QAAM,KAAK,MAAM,YAAY,YAAY,OAAO;CACjD;CAED,MAAM,eAAeC,YAA8C;EACjE,MAAM,gBAAgB,MAAM,KAAK,WAAW,eAAe,WAAW;AACtE,MAAI,yBACF,OAAM,KAAK,MAAM,eAAe,WAAW;AAE7C,SAAO;CACR;CAED,MAAM,YAAYA,YAA8C;EAC9D,IAAI,SAAS,MAAM,KAAK,MAAM,YAAY,WAAW;AACrD,MAAI,mBAAsB;AACxB,YAAS,MAAM,KAAK,WAAW,YAAY,WAAW;AACtD,OAAI,kBACF,OAAM,KAAK,MAAM,YAAY,YAAY,OAAO;EAEnD;AACD,SAAO;CACR;AACF"}
@@ -1,8 +1,8 @@
1
1
  import { Temporal, toTemporalInstant } from "@js-temporal/polyfill";
2
2
  Date.prototype.toTemporalInstant = toTemporalInstant;
3
3
  import { Text } from "./text.js";
4
- import { AuthorizedMessage, Message, MessageClass } from "./message.js";
5
- import { Session, SessionGetOutboxOptions, SessionPublishOptions, SessionPublishOptionsWithClass } from "./session.js";
4
+ import { AuthorizedMessage, Message, MessageClass, Question } from "./message.js";
5
+ import { Session, SessionGetOutboxOptions, SessionPublishOptions, SessionPublishOptionsWithClass, SessionPublishOptionsWithQuestion } from "./session.js";
6
6
  import { BotImpl } from "./bot-impl.js";
7
7
  import { Actor, Context, Note } from "@fedify/fedify";
8
8
 
@@ -11,6 +11,7 @@ interface SessionImplPublishOptions<TContextData> extends SessionPublishOptions<
11
11
  replyTarget?: Message<MessageClass, TContextData>;
12
12
  }
13
13
  interface SessionImplPublishOptionsWithClass<T extends MessageClass, TContextData> extends SessionPublishOptionsWithClass<T, TContextData>, SessionImplPublishOptions<TContextData> {}
14
+ interface SessionImplPublishOptionsWithQuestion<TContextData> extends SessionPublishOptionsWithQuestion<TContextData>, SessionImplPublishOptionsWithClass<Question, TContextData> {}
14
15
  declare class SessionImpl<TContextData> implements Session<TContextData> {
15
16
  readonly bot: BotImpl<TContextData>;
16
17
  readonly context: Context<TContextData>;
@@ -23,10 +24,11 @@ declare class SessionImpl<TContextData> implements Session<TContextData> {
23
24
  follows(actor: Actor | URL | string): Promise<boolean>;
24
25
  publish(content: Text<"block", TContextData>, options?: SessionImplPublishOptions<TContextData>): Promise<AuthorizedMessage<Note, TContextData>>;
25
26
  publish<T extends MessageClass>(content: Text<"block", TContextData>, options: SessionImplPublishOptionsWithClass<T, TContextData>): Promise<AuthorizedMessage<T, TContextData>>;
27
+ publish(content: Text<"block", TContextData>, options: SessionImplPublishOptionsWithQuestion<TContextData>): Promise<AuthorizedMessage<Question, TContextData>>;
26
28
  getOutbox(options?: SessionGetOutboxOptions): AsyncIterable<AuthorizedMessage<MessageClass, TContextData>>;
27
29
  }
28
30
  //# sourceMappingURL=session-impl.d.ts.map
29
31
 
30
32
  //#endregion
31
- export { SessionImpl, SessionImplPublishOptions, SessionImplPublishOptionsWithClass };
33
+ export { SessionImpl, SessionImplPublishOptions, SessionImplPublishOptionsWithClass, SessionImplPublishOptionsWithQuestion };
32
34
  //# sourceMappingURL=session-impl.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-impl.d.ts","names":[],"sources":["../src/session-impl.ts"],"sourcesContent":[],"mappings":";;;;;;;;;UA4CiB,gDACP,sBAAsB;gBAChB,QAAQ,cAAc;;UAGrB,6CACL,oCAGV,+BAA+B,GAAG,eAClC,0BAA0B;cAGf,qCAAqC,QAAQ;EAbzC,SAAA,GAAA,EAcD,OAdC,CAcO,YAdkB,CAAA;EAAA,SAAA,OAAA,EAetB,OAfsB,CAed,YAfc,CAAA;EAAA,WACV,CAAA,GAAA,EAgBb,OAhBa,CAgBL,YAhBK,CAAA,EAAA,OAAA,EAgBmB,OAhBnB,CAgB2B,YAhB3B,CAAA;EAAY,IACpB,OAAA,CAA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AAA,CAAA,EAgK/B,OAhK+B,CAgKvB,iBAhKuB,CAgKL,CAhKK,EAgKF,YAhKE,CAAA,CAAA;EAAY,OACpB,CAAA,OAAA,EAiKf,IAjKe,CAAA,OAAA,EAiKD,YAjKC,CAAA,EAAA,OAAA,EAkKf,qCAlKe,CAkKuB,YAlKvB,CAAA,CAAA,EAmKvB,OAnKuB,CAmKf,iBAnKe,CAmKG,QAnKH,EAmKa,YAnKb,CAAA,CAAA;EAAY,SADtC,CAAA,OAAA,CAAA,EAmUW,uBAnUX,CAAA,EAoUG,aApUH,CAoUiB,iBApUjB,CAoUmC,YApUnC,EAoUiD,YApUjD,CAAA,CAAA;;AACyB"}
@@ -3,7 +3,8 @@
3
3
  Date.prototype.toTemporalInstant = toTemporalInstant;
4
4
 
5
5
  import { createMessage, isMessageObject } from "./message-impl.js";
6
- import { Follow, Link, Undo } from "@fedify/fedify/vocab";
6
+ import { Question } from "./message.js";
7
+ import { Collection, Follow, Link, Undo } from "@fedify/fedify/vocab";
7
8
  import { Create as Create$1, LanguageString, Mention as Mention$1, Note as Note$1, PUBLIC_COLLECTION as PUBLIC_COLLECTION$1, isActor as isActor$1 } from "@fedify/fedify";
8
9
  import { getLogger } from "@logtape/logtape";
9
10
  import { encode } from "html-entities";
@@ -115,6 +116,20 @@ var SessionImpl = class {
115
116
  name: `RE: ${url.href}`
116
117
  }));
117
118
  }
119
+ let inclusiveOptions = [];
120
+ let exclusiveOptions = [];
121
+ let voters = null;
122
+ let endTime = null;
123
+ if ("class" in options && options.class === Question && "poll" in options) {
124
+ const pollOptions = options.poll.options.map((option) => new Note$1({
125
+ name: option,
126
+ replies: new Collection({ totalItems: 0 })
127
+ }));
128
+ if (options.poll.multiple) inclusiveOptions = pollOptions;
129
+ else exclusiveOptions = pollOptions;
130
+ voters = 0;
131
+ endTime = options.poll.endTime;
132
+ }
118
133
  const msg = new cls({
119
134
  id: this.context.getObjectUri(cls, { id }),
120
135
  contents: options.language == null ? [contentHtml] : [new LanguageString(contentHtml, options.language), contentHtml],
@@ -123,6 +138,10 @@ var SessionImpl = class {
123
138
  tags,
124
139
  attribution: this.context.getActorUri(this.bot.identifier),
125
140
  attachments: options.attachments ?? [],
141
+ inclusiveOptions,
142
+ exclusiveOptions,
143
+ voters,
144
+ endTime,
126
145
  tos: visibility === "public" ? [PUBLIC_COLLECTION$1, ...mentionedActorIds] : visibility === "unlisted" || visibility === "followers" ? [this.context.getFollowersUri(this.bot.identifier), ...mentionedActorIds] : mentionedActorIds,
127
146
  ccs: visibility === "public" ? [this.context.getFollowersUri(this.bot.identifier)] : visibility === "unlisted" ? [PUBLIC_COLLECTION$1] : [],
128
147
  published: published.toTemporalInstant(),
@@ -1 +1 @@
1
- {"version":3,"file":"session-impl.js","names":["bot: BotImpl<TContextData>","context: Context<TContextData>","actor: Actor | URL | string","actorId: URL","content: Text<\"block\", TContextData>","options:\n | SessionImplPublishOptions<TContextData>\n | SessionImplPublishOptionsWithClass<MessageClass, TContextData>","Note","mentionedActorIds: URL[]","Mention","PUBLIC_COLLECTION","Create","cachedObjects: Record<string, Object>","promises: Promise<Object | null>[]","isActor","options: SessionGetOutboxOptions","object: Object | null"],"sources":["../src/session-impl.ts"],"sourcesContent":["// BotKit by Fedify: A framework for creating ActivityPub bots\n// Copyright (C) 2025 Hong Minhee <https://hongminhee.org/>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport {\n type Actor,\n type Context,\n Create,\n isActor,\n LanguageString,\n Mention,\n Note,\n type Object,\n PUBLIC_COLLECTION,\n} from \"@fedify/fedify\";\nimport { Follow, Link, Undo } from \"@fedify/fedify/vocab\";\nimport { getLogger } from \"@logtape/logtape\";\nimport { encode } from \"html-entities\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport type { BotImpl } from \"./bot-impl.ts\";\nimport { createMessage, isMessageObject } from \"./message-impl.ts\";\nimport type { AuthorizedMessage, Message, MessageClass } from \"./message.ts\";\nimport type { Uuid } from \"./repository.ts\";\nimport type {\n Session,\n SessionGetOutboxOptions,\n SessionPublishOptions,\n SessionPublishOptionsWithClass,\n} from \"./session.ts\";\nimport type { Text } from \"./text.ts\";\n\nconst logger = getLogger([\"botkit\", \"session\"]);\n\nexport interface SessionImplPublishOptions<TContextData>\n extends SessionPublishOptions<TContextData> {\n replyTarget?: Message<MessageClass, TContextData>;\n}\n\nexport interface SessionImplPublishOptionsWithClass<\n T extends MessageClass,\n TContextData,\n> extends\n SessionPublishOptionsWithClass<T, TContextData>,\n SessionImplPublishOptions<TContextData> {\n}\n\nexport class SessionImpl<TContextData> implements Session<TContextData> {\n readonly bot: BotImpl<TContextData>;\n readonly context: Context<TContextData>;\n\n constructor(bot: BotImpl<TContextData>, context: Context<TContextData>) {\n this.bot = bot;\n this.context = context;\n }\n\n get actorId() {\n return this.context.getActorUri(this.bot.identifier);\n }\n\n get actorHandle() {\n return `@${this.bot.username}@${this.context.host}` as const;\n }\n\n async getActor(): Promise<Actor> {\n return (await this.bot.dispatchActor(this.context, this.bot.identifier))!;\n }\n\n async follow(actor: Actor | URL | string): Promise<void> {\n if (actor instanceof URL || typeof actor === \"string\") {\n if (\n actor instanceof URL && actor.href === this.actorId.href ||\n typeof actor === \"string\" &&\n (actor === this.actorId.href || actor === this.actorHandle)\n ) {\n throw new TypeError(\"The bot cannot follow itself.\");\n }\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const object = await this.context.lookupObject(actor, { documentLoader });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n actor = object;\n }\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n } else if (actor.id.href === this.actorId.href) {\n throw new TypeError(\"The bot cannot follow itself.\");\n }\n const followee = await this.bot.repository.getFollowee(actor.id);\n if (followee != null) {\n logger.warn(\n \"The bot is already following the actor {actor}.\",\n { actor: actor.id.href },\n );\n return;\n }\n const id = uuidv7() as Uuid;\n const follow = new Follow({\n id: this.context.getObjectUri(Follow, { id }),\n actor: this.context.getActorUri(this.bot.identifier),\n object: actor.id,\n to: actor.id,\n });\n await this.bot.repository.addSentFollow(id, follow);\n await this.context.sendActivity(\n this.bot,\n actor,\n follow,\n { excludeBaseUris: [new URL(this.context.origin)] },\n );\n }\n\n async unfollow(actor: Actor | URL | string): Promise<void> {\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n if (actor instanceof URL || typeof actor === \"string\") {\n if (\n actor instanceof URL && actor.href === this.actorId.href ||\n typeof actor === \"string\" &&\n (actor === this.actorId.href || actor === this.actorHandle)\n ) {\n throw new TypeError(\"The bot cannot unfollow itself.\");\n }\n const object = await this.context.lookupObject(actor, { documentLoader });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n actor = object;\n }\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n } else if (actor.id.href === this.actorId.href) {\n throw new TypeError(\"The bot cannot unfollow itself.\");\n }\n const follow = await this.bot.repository.getFollowee(actor.id);\n if (follow == null) {\n logger.warn(\n \"The bot is not following the actor {actor}.\",\n { actor: actor.id.href },\n );\n return;\n }\n await this.bot.repository.removeFollowee(actor.id);\n if (follow.id != null && follow.objectId?.href === actor.id.href) {\n await this.context.sendActivity(\n this.bot,\n actor,\n new Undo({\n id: new URL(\"#undo\", follow.id),\n actor: this.context.getActorUri(this.bot.identifier),\n object: follow,\n to: actor.id,\n }),\n { excludeBaseUris: [new URL(this.context.origin)] },\n );\n }\n }\n\n async follows(actor: Actor | URL | string): Promise<boolean> {\n let actorId: URL;\n if (isActor(actor)) {\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n }\n actorId = actor.id;\n } else if (actor instanceof URL) {\n actorId = actor;\n } else {\n if (actor.startsWith(\"http://\") || actor.startsWith(\"https://\")) {\n actorId = new URL(actor);\n } else {\n if (actor === this.actorHandle) return false;\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const object = await this.context.lookupObject(actor, {\n documentLoader,\n });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n if (object.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n }\n actorId = object.id;\n }\n }\n if (actorId.href === this.actorId.href) return false;\n const follow = await this.bot.repository.getFollowee(actorId);\n return follow != null;\n }\n\n async publish(\n content: Text<\"block\", TContextData>,\n options?: SessionImplPublishOptions<TContextData>,\n ): Promise<AuthorizedMessage<Note, TContextData>>;\n async publish<T extends MessageClass>(\n content: Text<\"block\", TContextData>,\n options: SessionImplPublishOptionsWithClass<T, TContextData>,\n ): Promise<AuthorizedMessage<T, TContextData>>;\n async publish(\n content: Text<\"block\", TContextData>,\n options:\n | SessionImplPublishOptions<TContextData>\n | SessionImplPublishOptionsWithClass<MessageClass, TContextData> = {},\n ): Promise<AuthorizedMessage<MessageClass, TContextData>> {\n const published = new Date();\n const id = uuidv7({ msecs: +published }) as Uuid;\n const cls = \"class\" in options ? options.class : Note;\n const visibility = options.visibility ?? \"public\";\n let contentHtml = \"\";\n for await (const chunk of content.getHtml(this)) {\n contentHtml += chunk;\n }\n const tags = await Array.fromAsync(content.getTags(this));\n const mentionedActorIds: URL[] = [];\n for (const tag of tags) {\n if (tag instanceof Mention && tag.href != null) {\n mentionedActorIds.push(tag.href);\n }\n }\n if (options.quoteTarget != null) {\n let url = options.quoteTarget.raw.url ?? options.quoteTarget.id;\n if (url instanceof Link) url = url.href ?? options.quoteTarget.id;\n contentHtml += `\\n\\n<p class=\"quote-inline\"><br>RE: <a href=\"${\n encode(url.href)\n }\">${encode(url.href)}</a></p>`;\n tags.push(\n new Link({\n mediaType:\n 'application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"',\n rel: \"https://misskey-hub.net/ns#_misskey_quote\",\n href: options.quoteTarget.id,\n name: `RE: ${url.href}`,\n }),\n );\n }\n const msg = new cls({\n id: this.context.getObjectUri<MessageClass>(cls, { id }),\n contents: options.language == null\n ? [contentHtml]\n : [new LanguageString(contentHtml, options.language), contentHtml],\n replyTarget: options.replyTarget?.id,\n quoteUrl: options.quoteTarget?.id,\n tags,\n attribution: this.context.getActorUri(this.bot.identifier),\n attachments: options.attachments ?? [],\n tos: visibility === \"public\"\n ? [PUBLIC_COLLECTION, ...mentionedActorIds]\n : visibility === \"unlisted\" || visibility === \"followers\"\n ? [\n this.context.getFollowersUri(this.bot.identifier),\n ...mentionedActorIds,\n ]\n : mentionedActorIds,\n ccs: visibility === \"public\"\n ? [this.context.getFollowersUri(this.bot.identifier)]\n : visibility === \"unlisted\"\n ? [PUBLIC_COLLECTION]\n : [],\n published: published.toTemporalInstant(),\n url: new URL(`/message/${id}`, this.context.origin),\n });\n const activity = new Create({\n id: this.context.getObjectUri(Create, { id }),\n actors: msg.attributionIds,\n tos: msg.toIds,\n ccs: msg.ccIds,\n object: msg,\n published: published.toTemporalInstant(),\n });\n await this.bot.repository.addMessage(id, activity);\n const preferSharedInbox = visibility === \"public\" ||\n visibility === \"unlisted\" || visibility === \"followers\";\n const excludeBaseUris = [new URL(this.context.origin)];\n if (preferSharedInbox) {\n await this.context.sendActivity(\n this.bot,\n \"followers\",\n activity,\n { preferSharedInbox, excludeBaseUris },\n );\n }\n const cachedObjects: Record<string, Object> = {};\n for (const cachedObject of content.getCachedObjects()) {\n if (cachedObject.id == null) continue;\n cachedObjects[cachedObject.id.href] = cachedObject;\n }\n if (mentionedActorIds.length > 0) {\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const promises: Promise<Object | null>[] = [];\n for (const mentionedActorId of mentionedActorIds) {\n const cachedObject = cachedObjects[mentionedActorId.href];\n const promise = cachedObject == null\n ? this.context.lookupObject(\n mentionedActorId,\n { documentLoader },\n )\n : Promise.resolve(cachedObject);\n promises.push(promise);\n }\n const objects = await Promise.all(promises);\n const mentionedActors = objects.filter(isActor);\n await this.context.sendActivity(\n this.bot,\n mentionedActors,\n activity,\n { preferSharedInbox, excludeBaseUris },\n );\n }\n if (options.replyTarget != null) {\n await this.context.sendActivity(\n this.bot,\n options.replyTarget.actor,\n activity,\n { preferSharedInbox, excludeBaseUris, fanout: \"skip\" },\n );\n }\n if (options.quoteTarget != null) {\n await this.context.sendActivity(\n this.bot,\n options.quoteTarget.actor,\n activity,\n { preferSharedInbox, excludeBaseUris, fanout: \"skip\" },\n );\n }\n return await createMessage(\n msg,\n this,\n cachedObjects,\n options.replyTarget,\n options.quoteTarget,\n true,\n );\n }\n\n async *getOutbox(\n options: SessionGetOutboxOptions = {},\n ): AsyncIterable<AuthorizedMessage<MessageClass, TContextData>> {\n for await (const activity of this.bot.repository.getMessages(options)) {\n let object: Object | null;\n try {\n object = await activity.getObject(this.context);\n } catch {\n continue;\n }\n if (object == null || !isMessageObject(object)) continue;\n const message = await createMessage(object, this, {});\n yield message;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,MAAM,SAAS,UAAU,CAAC,UAAU,SAAU,EAAC;AAe/C,IAAa,cAAb,MAAwE;CACtE,AAAS;CACT,AAAS;CAET,YAAYA,KAA4BC,SAAgC;AACtE,OAAK,MAAM;AACX,OAAK,UAAU;CAChB;CAED,IAAI,UAAU;AACZ,SAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,WAAW;CACrD;CAED,IAAI,cAAc;AAChB,UAAQ,GAAG,KAAK,IAAI,SAAS,GAAG,KAAK,QAAQ,KAAK;CACnD;CAED,MAAM,WAA2B;AAC/B,SAAQ,MAAM,KAAK,IAAI,cAAc,KAAK,SAAS,KAAK,IAAI,WAAW;CACxE;CAED,MAAM,OAAOC,OAA4C;AACvD,MAAI,iBAAiB,cAAc,UAAU,UAAU;AACrD,OACE,iBAAiB,OAAO,MAA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gB,EACnB,GACC,QAAQ,QAAQ,aAAa;AACjC,aAAS,KAAK,QAAQ;GACvB;GACD,MAAM,UAAU,MAAM,QAAQ,IAAI,SAAS;GAC3C,MAAM,kBAAkB,QAAQ,OAAOC,UAAQ;AAC/C,SAAM,KAAK,QAAQ,aACjB,KAAK,KACL,iBACA,UACA;IAAE;IAAmB;GAAiB,EACvC;EACF;AACD,MAAI,QAAQ,eAAe,KACzB,OAAM,KAAK,QAAQ,aACjB,KAAK,KACL,QAAQ,YAAY,OACpB,UACA;GAAE;GAAmB;GAAiB,QAAQ;EAAQ,EACvD;AAEH,MAAI,QAAQ,eAAe,KACzB,OAAM,KAAK,QAAQ,aACjB,KAAK,KACL,QAAQ,YAAY,OACpB,UACA;GAAE;GAAmB;GAAiB,QAAQ;EAAQ,EACvD;AAEH,SAAO,MAAM,cACX,KACA,MACA,eACA,QAAQ,aACR,QAAQ,aACR,KACD;CACF;CAED,OAAO,UACLC,UAAmC,CAAE,GACyB;AAC9D,aAAW,MAAM,YAAY,KAAK,IAAI,WAAW,YAAY,QAAQ,EAAE;GACrE,IAAIC;AACJ,OAAI;AACF,aAAS,MAAM,SAAS,UAAU,KAAK,QAAQ;GAChD,QAAO;AACN;GACD;AACD,OAAI,UAAU,SAAS,gBAAgB,OAAO,CAAE;GAChD,MAAM,UAAU,MAAM,cAAc,QAAQ,MAAM,CAAE,EAAC;AACrD,SAAM;EACP;CACF;AACF"}
1
+ {"version":3,"file":"session-impl.js","names":["bot: BotImpl<TContextData>","context: Context<TContextData>","actor: Actor | URL | string","actorId: URL","content: Text<\"block\", TContextData>","options:\n | SessionImplPublishOptions<TContextData>\n | SessionImplPublishOptionsWithClass<MessageClass, TContextData>\n | SessionImplPublishOptionsWithQuestion<TContextData>","Note","mentionedActorIds: URL[]","Mention","inclusiveOptions: Note[]","exclusiveOptions: Note[]","voters: number | null","endTime: Temporal.Instant | null","PUBLIC_COLLECTION","Create","cachedObjects: Record<string, Object>","promises: Promise<Object | null>[]","isActor","options: SessionGetOutboxOptions","object: Object | null"],"sources":["../src/session-impl.ts"],"sourcesContent":["// BotKit by Fedify: A framework for creating ActivityPub bots\n// Copyright (C) 2025 Hong Minhee <https://hongminhee.org/>\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as\n// published by the Free Software Foundation, either version 3 of the\n// License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\nimport {\n type Actor,\n type Context,\n Create,\n isActor,\n LanguageString,\n Mention,\n Note,\n type Object,\n PUBLIC_COLLECTION,\n} from \"@fedify/fedify\";\nimport { Collection, Follow, Link, Undo } from \"@fedify/fedify/vocab\";\nimport { getLogger } from \"@logtape/logtape\";\nimport { encode } from \"html-entities\";\nimport { v7 as uuidv7 } from \"uuid\";\nimport type { BotImpl } from \"./bot-impl.ts\";\nimport { createMessage, isMessageObject } from \"./message-impl.ts\";\nimport {\n type AuthorizedMessage,\n type Message,\n type MessageClass,\n Question,\n} from \"./message.ts\";\nimport type { Uuid } from \"./repository.ts\";\nimport type {\n Session,\n SessionGetOutboxOptions,\n SessionPublishOptions,\n SessionPublishOptionsWithClass,\n SessionPublishOptionsWithQuestion,\n} from \"./session.ts\";\nimport type { Text } from \"./text.ts\";\n\nconst logger = getLogger([\"botkit\", \"session\"]);\n\nexport interface SessionImplPublishOptions<TContextData>\n extends SessionPublishOptions<TContextData> {\n replyTarget?: Message<MessageClass, TContextData>;\n}\n\nexport interface SessionImplPublishOptionsWithClass<\n T extends MessageClass,\n TContextData,\n> extends\n SessionPublishOptionsWithClass<T, TContextData>,\n SessionImplPublishOptions<TContextData> {\n}\n\nexport interface SessionImplPublishOptionsWithQuestion<TContextData>\n extends\n SessionPublishOptionsWithQuestion<TContextData>,\n SessionImplPublishOptionsWithClass<Question, TContextData> {\n}\n\nexport class SessionImpl<TContextData> implements Session<TContextData> {\n readonly bot: BotImpl<TContextData>;\n readonly context: Context<TContextData>;\n\n constructor(bot: BotImpl<TContextData>, context: Context<TContextData>) {\n this.bot = bot;\n this.context = context;\n }\n\n get actorId() {\n return this.context.getActorUri(this.bot.identifier);\n }\n\n get actorHandle() {\n return `@${this.bot.username}@${this.context.host}` as const;\n }\n\n async getActor(): Promise<Actor> {\n return (await this.bot.dispatchActor(this.context, this.bot.identifier))!;\n }\n\n async follow(actor: Actor | URL | string): Promise<void> {\n if (actor instanceof URL || typeof actor === \"string\") {\n if (\n actor instanceof URL && actor.href === this.actorId.href ||\n typeof actor === \"string\" &&\n (actor === this.actorId.href || actor === this.actorHandle)\n ) {\n throw new TypeError(\"The bot cannot follow itself.\");\n }\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const object = await this.context.lookupObject(actor, { documentLoader });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n actor = object;\n }\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n } else if (actor.id.href === this.actorId.href) {\n throw new TypeError(\"The bot cannot follow itself.\");\n }\n const followee = await this.bot.repository.getFollowee(actor.id);\n if (followee != null) {\n logger.warn(\n \"The bot is already following the actor {actor}.\",\n { actor: actor.id.href },\n );\n return;\n }\n const id = uuidv7() as Uuid;\n const follow = new Follow({\n id: this.context.getObjectUri(Follow, { id }),\n actor: this.context.getActorUri(this.bot.identifier),\n object: actor.id,\n to: actor.id,\n });\n await this.bot.repository.addSentFollow(id, follow);\n await this.context.sendActivity(\n this.bot,\n actor,\n follow,\n { excludeBaseUris: [new URL(this.context.origin)] },\n );\n }\n\n async unfollow(actor: Actor | URL | string): Promise<void> {\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n if (actor instanceof URL || typeof actor === \"string\") {\n if (\n actor instanceof URL && actor.href === this.actorId.href ||\n typeof actor === \"string\" &&\n (actor === this.actorId.href || actor === this.actorHandle)\n ) {\n throw new TypeError(\"The bot cannot unfollow itself.\");\n }\n const object = await this.context.lookupObject(actor, { documentLoader });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n actor = object;\n }\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n } else if (actor.id.href === this.actorId.href) {\n throw new TypeError(\"The bot cannot unfollow itself.\");\n }\n const follow = await this.bot.repository.getFollowee(actor.id);\n if (follow == null) {\n logger.warn(\n \"The bot is not following the actor {actor}.\",\n { actor: actor.id.href },\n );\n return;\n }\n await this.bot.repository.removeFollowee(actor.id);\n if (follow.id != null && follow.objectId?.href === actor.id.href) {\n await this.context.sendActivity(\n this.bot,\n actor,\n new Undo({\n id: new URL(\"#undo\", follow.id),\n actor: this.context.getActorUri(this.bot.identifier),\n object: follow,\n to: actor.id,\n }),\n { excludeBaseUris: [new URL(this.context.origin)] },\n );\n }\n }\n\n async follows(actor: Actor | URL | string): Promise<boolean> {\n let actorId: URL;\n if (isActor(actor)) {\n if (actor.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n }\n actorId = actor.id;\n } else if (actor instanceof URL) {\n actorId = actor;\n } else {\n if (actor.startsWith(\"http://\") || actor.startsWith(\"https://\")) {\n actorId = new URL(actor);\n } else {\n if (actor === this.actorHandle) return false;\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const object = await this.context.lookupObject(actor, {\n documentLoader,\n });\n if (!isActor(object)) {\n throw new TypeError(\"The resolved object is not an Actor.\");\n }\n if (object.id == null) {\n throw new TypeError(\"The actor does not have an ID.\");\n }\n actorId = object.id;\n }\n }\n if (actorId.href === this.actorId.href) return false;\n const follow = await this.bot.repository.getFollowee(actorId);\n return follow != null;\n }\n\n async publish(\n content: Text<\"block\", TContextData>,\n options?: SessionImplPublishOptions<TContextData>,\n ): Promise<AuthorizedMessage<Note, TContextData>>;\n async publish<T extends MessageClass>(\n content: Text<\"block\", TContextData>,\n options: SessionImplPublishOptionsWithClass<T, TContextData>,\n ): Promise<AuthorizedMessage<T, TContextData>>;\n async publish(\n content: Text<\"block\", TContextData>,\n options: SessionImplPublishOptionsWithQuestion<TContextData>,\n ): Promise<AuthorizedMessage<Question, TContextData>>;\n async publish(\n content: Text<\"block\", TContextData>,\n options:\n | SessionImplPublishOptions<TContextData>\n | SessionImplPublishOptionsWithClass<MessageClass, TContextData>\n | SessionImplPublishOptionsWithQuestion<TContextData> = {},\n ): Promise<AuthorizedMessage<MessageClass, TContextData>> {\n const published = new Date();\n const id = uuidv7({ msecs: +published }) as Uuid;\n const cls = \"class\" in options ? options.class : Note;\n const visibility = options.visibility ?? \"public\";\n let contentHtml = \"\";\n for await (const chunk of content.getHtml(this)) {\n contentHtml += chunk;\n }\n const tags = await Array.fromAsync(content.getTags(this));\n const mentionedActorIds: URL[] = [];\n for (const tag of tags) {\n if (tag instanceof Mention && tag.href != null) {\n mentionedActorIds.push(tag.href);\n }\n }\n if (options.quoteTarget != null) {\n let url = options.quoteTarget.raw.url ?? options.quoteTarget.id;\n if (url instanceof Link) url = url.href ?? options.quoteTarget.id;\n contentHtml += `\\n\\n<p class=\"quote-inline\"><br>RE: <a href=\"${\n encode(url.href)\n }\">${encode(url.href)}</a></p>`;\n tags.push(\n new Link({\n mediaType:\n 'application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"',\n rel: \"https://misskey-hub.net/ns#_misskey_quote\",\n href: options.quoteTarget.id,\n name: `RE: ${url.href}`,\n }),\n );\n }\n let inclusiveOptions: Note[] = [];\n let exclusiveOptions: Note[] = [];\n let voters: number | null = null;\n let endTime: Temporal.Instant | null = null;\n if (\"class\" in options && options.class === Question && \"poll\" in options) {\n const pollOptions = options.poll.options.map((option) =>\n new Note({\n name: option,\n replies: new Collection({ totalItems: 0 }),\n })\n );\n if (options.poll.multiple) inclusiveOptions = pollOptions;\n else exclusiveOptions = pollOptions;\n voters = 0;\n endTime = options.poll.endTime;\n }\n const msg = new cls({\n id: this.context.getObjectUri<MessageClass>(cls, { id }),\n contents: options.language == null\n ? [contentHtml]\n : [new LanguageString(contentHtml, options.language), contentHtml],\n replyTarget: options.replyTarget?.id,\n quoteUrl: options.quoteTarget?.id,\n tags,\n attribution: this.context.getActorUri(this.bot.identifier),\n attachments: options.attachments ?? [],\n inclusiveOptions,\n exclusiveOptions,\n voters,\n endTime,\n tos: visibility === \"public\"\n ? [PUBLIC_COLLECTION, ...mentionedActorIds]\n : visibility === \"unlisted\" || visibility === \"followers\"\n ? [\n this.context.getFollowersUri(this.bot.identifier),\n ...mentionedActorIds,\n ]\n : mentionedActorIds,\n ccs: visibility === \"public\"\n ? [this.context.getFollowersUri(this.bot.identifier)]\n : visibility === \"unlisted\"\n ? [PUBLIC_COLLECTION]\n : [],\n published: published.toTemporalInstant(),\n url: new URL(`/message/${id}`, this.context.origin),\n });\n const activity = new Create({\n id: this.context.getObjectUri(Create, { id }),\n actors: msg.attributionIds,\n tos: msg.toIds,\n ccs: msg.ccIds,\n object: msg,\n published: published.toTemporalInstant(),\n });\n await this.bot.repository.addMessage(id, activity);\n const preferSharedInbox = visibility === \"public\" ||\n visibility === \"unlisted\" || visibility === \"followers\";\n const excludeBaseUris = [new URL(this.context.origin)];\n if (preferSharedInbox) {\n await this.context.sendActivity(\n this.bot,\n \"followers\",\n activity,\n { preferSharedInbox, excludeBaseUris },\n );\n }\n const cachedObjects: Record<string, Object> = {};\n for (const cachedObject of content.getCachedObjects()) {\n if (cachedObject.id == null) continue;\n cachedObjects[cachedObject.id.href] = cachedObject;\n }\n if (mentionedActorIds.length > 0) {\n const documentLoader = await this.context.getDocumentLoader(this.bot);\n const promises: Promise<Object | null>[] = [];\n for (const mentionedActorId of mentionedActorIds) {\n const cachedObject = cachedObjects[mentionedActorId.href];\n const promise = cachedObject == null\n ? this.context.lookupObject(\n mentionedActorId,\n { documentLoader },\n )\n : Promise.resolve(cachedObject);\n promises.push(promise);\n }\n const objects = await Promise.all(promises);\n const mentionedActors = objects.filter(isActor);\n await this.context.sendActivity(\n this.bot,\n mentionedActors,\n activity,\n { preferSharedInbox, excludeBaseUris },\n );\n }\n if (options.replyTarget != null) {\n await this.context.sendActivity(\n this.bot,\n options.replyTarget.actor,\n activity,\n { preferSharedInbox, excludeBaseUris, fanout: \"skip\" },\n );\n }\n if (options.quoteTarget != null) {\n await this.context.sendActivity(\n this.bot,\n options.quoteTarget.actor,\n activity,\n { preferSharedInbox, excludeBaseUris, fanout: \"skip\" },\n );\n }\n return await createMessage(\n msg,\n this,\n cachedObjects,\n options.replyTarget,\n options.quoteTarget,\n true,\n );\n }\n\n async *getOutbox(\n options: SessionGetOutboxOptions = {},\n ): AsyncIterable<AuthorizedMessage<MessageClass, TContextData>> {\n for await (const activity of this.bot.repository.getMessages(options)) {\n let object: Object | null;\n try {\n object = await activity.getObject(this.context);\n } catch {\n continue;\n }\n if (object == null || !isMessageObject(object)) continue;\n const message = await createMessage(object, this, {});\n yield message;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgDA,MAAM,SAAS,UAAU,CAAC,UAAU,SAAU,EAAC;AAqB/C,IAAa,cAAb,MAAwE;CACtE,AAAS;CACT,AAAS;CAET,YAAYA,KAA4BC,SAAgC;AACtE,OAAK,MAAM;AACX,OAAK,UAAU;CAChB;CAED,IAAI,UAAU;AACZ,SAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,WAAW;CACrD;CAED,IAAI,cAAc;AAChB,UAAQ,GAAG,KAAK,IAAI,SAAS,GAAG,KAAK,QAAQ,KAAK;CACnD;CAED,MAAM,WAA2B;AAC/B,SAAQ,MAAM,KAAK,IAAI,cAAc,KAAK,SAAS,KAAK,IAAI,WAAW;CACxE;CAED,MAAM,OAAOC,OAA4C;AACvD,MAAI,iBAAiB,cAAc,UAAU,UAAU;AACrD,OACE,iBAAiB,OAAO,MAAM,SAAS,KAAK,QAAQ,eAC7C,UAAU,aACd,UAAU,KAAK,QAAQ,QAAQ,UAAU,KAAK,aAEjD,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"session-impl.test.d.ts","names":[],"sources":["../src/session-impl.test.ts"],"sourcesContent":[],"mappings":";;;;;;;UAwqBiB,YAAA;4BACW;YAChB;;UAGK,WAAA,SAAoB;kBACnB;AANlB;AAA6B,iBASb,iBAAA,CATa,GAAA,EAUtB,OAVsB,CAAA,IAAA,CAAA,EAAA,MAAA,EAWnB,GAXmB,GAAA,MAAA,CAAA,EAY1B,WAZ0B"}
1
+ {"version":3,"file":"session-impl.test.d.ts","names":[],"sources":["../src/session-impl.test.ts"],"sourcesContent":[],"mappings":";;;;;;;UAw2BiB,YAAA;4BACW;YAChB;;UAGK,WAAA,SAAoB;kBACnB;AANlB;AAA6B,iBASb,iBAAA,CATa,GAAA,EAUtB,OAVsB,CAAA,IAAA,CAAA,EAAA,MAAA,EAWnB,GAXmB,GAAA,MAAA,CAAA,EAY1B,WAZ0B"}
@@ -8,7 +8,7 @@ import { SessionImpl } from "./session-impl.js";
8
8
  import { BotImpl } from "./bot-impl.js";
9
9
  import { mention, text } from "./text.js";
10
10
  import { MemoryKvStore } from "@fedify/fedify/federation";
11
- import { Create, Follow, Note, PUBLIC_COLLECTION, Person, Undo } from "@fedify/fedify/vocab";
11
+ import { Create, Follow, Note, PUBLIC_COLLECTION, Person, Question, Undo } from "@fedify/fedify/vocab";
12
12
  import assert from "node:assert";
13
13
  import { describe, test } from "node:test";
14
14
 
@@ -312,6 +312,165 @@ test("SessionImpl.publish()", async (t) => {
312
312
  assert.deepStrictEqual(quote.visibility, "public");
313
313
  assert.deepStrictEqual(quote.quoteTarget?.id, originalMsg.id);
314
314
  });
315
+ await t.test("poll single choice", async () => {
316
+ ctx.sentActivities = [];
317
+ const endTime = Temporal.Now.instant().add({ hours: 24 });
318
+ const poll = await session.publish(text`What's your favorite color?`, {
319
+ class: Question,
320
+ poll: {
321
+ multiple: false,
322
+ options: [
323
+ "Red",
324
+ "Blue",
325
+ "Green"
326
+ ],
327
+ endTime
328
+ }
329
+ });
330
+ assert.deepStrictEqual(ctx.sentActivities.length, 1);
331
+ const { recipients, activity } = ctx.sentActivities[0];
332
+ assert.deepStrictEqual(recipients, "followers");
333
+ assert.ok(activity instanceof Create);
334
+ assert.deepStrictEqual(activity.actorId, ctx.getActorUri(bot.identifier));
335
+ assert.deepStrictEqual(activity.toIds, [PUBLIC_COLLECTION]);
336
+ assert.deepStrictEqual(activity.ccIds, [ctx.getFollowersUri(bot.identifier)]);
337
+ const object = await activity.getObject(ctx);
338
+ assert.ok(object instanceof Question);
339
+ assert.deepStrictEqual(object.attributionId, ctx.getActorUri(bot.identifier));
340
+ assert.deepStrictEqual(object.toIds, [PUBLIC_COLLECTION]);
341
+ assert.deepStrictEqual(object.ccIds, [ctx.getFollowersUri(bot.identifier)]);
342
+ assert.deepStrictEqual(object.content, "<p>What&apos;s your favorite color?</p>");
343
+ assert.deepStrictEqual(object.endTime, endTime);
344
+ assert.deepStrictEqual(object.voters, 0);
345
+ assert.deepStrictEqual(object.inclusiveOptionIds, []);
346
+ const exclusiveOptions = await Array.fromAsync(object.getExclusiveOptions(ctx));
347
+ assert.deepStrictEqual(exclusiveOptions.length, 3);
348
+ assert.ok(exclusiveOptions[0] instanceof Note);
349
+ assert.deepStrictEqual(exclusiveOptions[0].name?.toString(), "Red");
350
+ assert.ok(exclusiveOptions[1] instanceof Note);
351
+ assert.deepStrictEqual(exclusiveOptions[1].name?.toString(), "Blue");
352
+ assert.ok(exclusiveOptions[2] instanceof Note);
353
+ assert.deepStrictEqual(exclusiveOptions[2].name?.toString(), "Green");
354
+ for (const option of exclusiveOptions) {
355
+ const replies = await option.getReplies(ctx);
356
+ assert.deepStrictEqual(replies?.totalItems, 0);
357
+ }
358
+ assert.deepStrictEqual(poll.id, object.id);
359
+ assert.deepStrictEqual(poll.text, "What's your favorite color?");
360
+ assert.deepStrictEqual(poll.html, "<p>What&apos;s your favorite color?</p>");
361
+ assert.deepStrictEqual(poll.visibility, "public");
362
+ });
363
+ await t.test("poll multiple choice", async () => {
364
+ ctx.sentActivities = [];
365
+ const endTime = Temporal.Now.instant().add({ hours: 24 * 7 });
366
+ const poll = await session.publish(text`Which programming languages do you know?`, {
367
+ class: Question,
368
+ poll: {
369
+ multiple: true,
370
+ options: [
371
+ "JavaScript",
372
+ "TypeScript",
373
+ "Python",
374
+ "Rust"
375
+ ],
376
+ endTime
377
+ },
378
+ visibility: "unlisted"
379
+ });
380
+ assert.deepStrictEqual(ctx.sentActivities.length, 1);
381
+ const { recipients, activity } = ctx.sentActivities[0];
382
+ assert.deepStrictEqual(recipients, "followers");
383
+ assert.ok(activity instanceof Create);
384
+ const object = await activity.getObject(ctx);
385
+ assert.ok(object instanceof Question);
386
+ assert.deepStrictEqual(object.endTime, endTime);
387
+ assert.deepStrictEqual(object.voters, 0);
388
+ assert.deepStrictEqual(object.exclusiveOptionIds, []);
389
+ const inclusiveOptions = await Array.fromAsync(object.getInclusiveOptions(ctx));
390
+ assert.deepStrictEqual(inclusiveOptions.length, 4);
391
+ assert.ok(inclusiveOptions[0] instanceof Note);
392
+ assert.deepStrictEqual(inclusiveOptions[0].name?.toString(), "JavaScript");
393
+ assert.ok(inclusiveOptions[1] instanceof Note);
394
+ assert.deepStrictEqual(inclusiveOptions[1].name?.toString(), "TypeScript");
395
+ assert.ok(inclusiveOptions[2] instanceof Note);
396
+ assert.deepStrictEqual(inclusiveOptions[2].name?.toString(), "Python");
397
+ assert.ok(inclusiveOptions[3] instanceof Note);
398
+ assert.deepStrictEqual(inclusiveOptions[3].name?.toString(), "Rust");
399
+ assert.deepStrictEqual(poll.visibility, "unlisted");
400
+ assert.deepStrictEqual(activity.toIds, [ctx.getFollowersUri(bot.identifier)]);
401
+ assert.deepStrictEqual(activity.ccIds, [PUBLIC_COLLECTION]);
402
+ });
403
+ await t.test("poll with direct visibility", async () => {
404
+ const mentioned = new Person({
405
+ id: new URL("https://example.com/ap/actor/alice"),
406
+ preferredUsername: "alice"
407
+ });
408
+ ctx.sentActivities = [];
409
+ const endTime = Temporal.Now.instant().add({ hours: 12 });
410
+ const poll = await session.publish(text`Hey ${mention(mentioned)}, what do you think?`, {
411
+ class: Question,
412
+ poll: {
413
+ multiple: false,
414
+ options: [
415
+ "Good",
416
+ "Bad",
417
+ "Neutral"
418
+ ],
419
+ endTime
420
+ },
421
+ visibility: "direct"
422
+ });
423
+ assert.deepStrictEqual(ctx.sentActivities.length, 1);
424
+ const { recipients, activity } = ctx.sentActivities[0];
425
+ assert.deepStrictEqual(recipients, [mentioned]);
426
+ assert.ok(activity instanceof Create);
427
+ const object = await activity.getObject(ctx);
428
+ assert.ok(object instanceof Question);
429
+ assert.deepStrictEqual(object.toIds, [mentioned.id]);
430
+ assert.deepStrictEqual(object.ccIds, []);
431
+ assert.deepStrictEqual(poll.visibility, "direct");
432
+ });
433
+ await t.test("poll end-to-end workflow", async () => {
434
+ const freshRepository = new MemoryRepository();
435
+ const freshBot = new BotImpl({
436
+ kv: new MemoryKvStore(),
437
+ repository: freshRepository,
438
+ username: "testbot"
439
+ });
440
+ const freshCtx = createMockContext(freshBot, "https://example.com");
441
+ const freshSession = new SessionImpl(freshBot, freshCtx);
442
+ const endTime = Temporal.Now.instant().add({ hours: 1 });
443
+ const poll = await freshSession.publish(text`What should we have for lunch?`, {
444
+ class: Question,
445
+ poll: {
446
+ multiple: false,
447
+ options: [
448
+ "Pizza",
449
+ "Burgers",
450
+ "Salad"
451
+ ],
452
+ endTime
453
+ }
454
+ });
455
+ assert.deepStrictEqual(freshCtx.sentActivities.length, 1);
456
+ const { activity: createActivity } = freshCtx.sentActivities[0];
457
+ assert.ok(createActivity instanceof Create);
458
+ const pollObject = await createActivity.getObject(freshCtx);
459
+ assert.ok(pollObject instanceof Question);
460
+ assert.deepStrictEqual(pollObject.endTime, endTime);
461
+ const options = await Array.fromAsync(pollObject.getExclusiveOptions(freshCtx));
462
+ assert.deepStrictEqual(options.length, 3);
463
+ assert.deepStrictEqual(options[0].name?.toString(), "Pizza");
464
+ assert.deepStrictEqual(options[1].name?.toString(), "Burgers");
465
+ assert.deepStrictEqual(options[2].name?.toString(), "Salad");
466
+ const outbox = freshSession.getOutbox({ order: "newest" });
467
+ const messages = await Array.fromAsync(outbox);
468
+ assert.deepStrictEqual(messages.length, 1);
469
+ assert.deepStrictEqual(messages[0].id, poll.id);
470
+ assert.deepStrictEqual(messages[0].text, "What should we have for lunch?");
471
+ assert.deepStrictEqual(poll.visibility, "public");
472
+ assert.deepStrictEqual(poll.mentions, []);
473
+ });
315
474
  });
316
475
  test("SessionImpl.getOutbox()", async (t) => {
317
476
  const repository = new MemoryRepository();