@drfed/graphql 0.0.0-stage → 0.1.0-dev.561

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.
Files changed (45) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +254 -2
  3. package/dist/account.d.mts +6 -0
  4. package/dist/account.d.mts.map +1 -0
  5. package/dist/account.mjs +168 -0
  6. package/dist/account.mjs.map +1 -0
  7. package/dist/activity-delivery/entry.d.mts +6 -0
  8. package/dist/activity-delivery/entry.d.mts.map +1 -0
  9. package/dist/activity-delivery/entry.mjs +291 -0
  10. package/dist/activity-delivery/entry.mjs.map +1 -0
  11. package/dist/actor-BJvviz6Q.mjs +600 -0
  12. package/dist/actor-BJvviz6Q.mjs.map +1 -0
  13. package/dist/actor.d.mts +7 -0
  14. package/dist/actor.d.mts.map +1 -0
  15. package/dist/actor.mjs +2 -0
  16. package/dist/builder-BLioFAdv.mjs +152 -0
  17. package/dist/builder-BLioFAdv.mjs.map +1 -0
  18. package/dist/builder-CSxRffRp.d.mts +134 -0
  19. package/dist/builder-CSxRffRp.d.mts.map +1 -0
  20. package/dist/builder.d.mts +2 -0
  21. package/dist/builder.mjs +2 -0
  22. package/dist/classification.d.mts +62 -0
  23. package/dist/classification.d.mts.map +1 -0
  24. package/dist/classification.mjs +65 -0
  25. package/dist/classification.mjs.map +1 -0
  26. package/dist/index.d.mts +55 -0
  27. package/dist/index.d.mts.map +1 -0
  28. package/dist/index.mjs +86 -0
  29. package/dist/index.mjs.map +1 -0
  30. package/dist/instance.d.mts +32 -0
  31. package/dist/instance.d.mts.map +1 -0
  32. package/dist/instance.mjs +176 -0
  33. package/dist/instance.mjs.map +1 -0
  34. package/dist/object.d.mts +6 -0
  35. package/dist/object.d.mts.map +1 -0
  36. package/dist/object.mjs +321 -0
  37. package/dist/object.mjs.map +1 -0
  38. package/dist/readable-CSN0MPlO.mjs +140 -0
  39. package/dist/readable-CSN0MPlO.mjs.map +1 -0
  40. package/dist/schema-ZeV-COPn.mjs +275 -0
  41. package/dist/schema-ZeV-COPn.mjs.map +1 -0
  42. package/dist/schema.d.mts +11 -0
  43. package/dist/schema.d.mts.map +1 -0
  44. package/dist/schema.mjs +2 -0
  45. package/package.json +154 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actor-BJvviz6Q.mjs","names":["and","eq","uuid"],"sources":["../src/resource.ts","../src/actor.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\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 published by\n// the Free Software Foundation, either version 3 of the License, or\n// (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/>.\n\nimport { activitySelection, objectSelection } from \"@drfed/federation/object\";\nimport { schema } from \"@drfed/models\";\nimport type { Resource as ResourceRow } from \"@drfed/models/schema\";\nimport { type Uuid, validateUuid } from \"@drfed/models/uuid\";\nimport { PothosValidationError } from \"@pothos/core\";\nimport { resolveCursorConnection } from \"@pothos/plugin-relay\";\nimport { type SQL, type SQLWrapper, and, eq, sql } from \"drizzle-orm\";\n\nimport builder, { type DrFedObjectRef } from \"./builder.ts\";\nimport {\n classificationAuthor,\n classificationInput,\n classifyMastodon,\n classifyMisskey,\n} from \"./classification.ts\";\nimport {\n type Viewer,\n isReadableResource,\n readableResource,\n} from \"./readable.ts\";\n\nexport const ResourceKind = builder.enumType(\"ResourceKind\", {\n values: schema.resourceKindEnum.enumValues,\n});\nexport const ResourceDetail = builder.unionType(\"ResourceDetail\", {\n types: () => [Activity, Collection],\n resolveType: async (value, ctx) => {\n const { id } = value as { id: Uuid };\n const row = await ctx.db.query.resources.findFirst({ where: { id } });\n if (row == null || row.kind === \"unknown\") {\n throw new Error(\"Missing typed resource.\");\n }\n return (\n {\n actor: \"Actor\",\n object: \"Object\",\n activity: \"Activity\",\n collection: \"Collection\",\n } as const\n )[row.kind];\n },\n});\nconst ResourceRef = builder.drizzleNode(\"resources\", {\n name: \"Resource\",\n id: { column: (row) => row.id },\n fields: (t) => ({\n iri: t.expose(\"iri\", { type: \"URL\" }),\n kind: t.expose(\"kind\", { type: ResourceKind }),\n detail: t.field({\n type: ResourceDetail,\n nullable: true,\n description:\n \"Typed details, or null while unknown, when the typed row or its author/owner is deleted, or when the viewer may not read it.\",\n select: { columns: { id: true, iri: true, kind: true } },\n resolve: (row, _, ctx) => resolveResource(ctx, row),\n }),\n }),\n});\nexport const Resource: DrFedObjectRef = ResourceRef;\n\n/**\n * Loads the typed record so union fragments see the complete entity.\n * @returns The typed entity, or null when it or its author is deleted, or when\n * the viewer may not read it.\n */\nexport async function resolveResource(\n viewer: Viewer,\n row: ResourceRow,\n): Promise<{ id: Uuid } | null> {\n const { db } = viewer;\n const visible = await db.query.resources.findFirst({\n where: {\n id: row.id,\n RAW: (table) =>\n and(visibleResource(table.id), readableResource(viewer, table.id))!,\n },\n columns: { id: true },\n });\n if (visible == null) return null;\n if (row.kind === \"unknown\") return null;\n const where = { id: row.id };\n const result =\n row.kind === \"actor\"\n ? await db.query.actors.findFirst({ where })\n : row.kind === \"object\"\n ? await db.query.objects.findFirst({ where })\n : row.kind === \"activity\"\n ? await db.query.activities.findFirst({ where })\n : await db.query.collections.findFirst({ where });\n if (result == null) {\n throw new Error(`Missing ${row.kind} record for ${row.iri}.`);\n }\n return result;\n}\n\nexport function registerAddressingFields(\n table: \"objects\" | \"activities\",\n): void {\n for (const property of schema.addressingPropertyEnum.enumValues) {\n builder.drizzleObjectField(table, property, (t) =>\n t.field({\n type: [Resource],\n description: `Stored ${property} occurrences, in original order including duplicates.`,\n select: { columns: { id: true } },\n resolve: async (row, _, ctx) =>\n (\n await ctx.db.query.addressing.findMany({\n where: { sourceId: row.id, property },\n orderBy: { position: \"asc\" },\n with: { targetResource: true },\n })\n ).map((entry) => entry.targetResource),\n }),\n );\n }\n}\n\nconst CollectionType = builder.enumType(\"CollectionType\", {\n values: schema.collectionTypeEnum.enumValues,\n});\nconst CollectionRef = builder.drizzleNode(\"collections\", {\n name: \"Collection\",\n select: {\n columns: { id: true },\n with: { ownerActor: { columns: { deleted: true } } },\n },\n id: { column: (row) => row.id },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n type: t.expose(\"type\", { type: CollectionType }),\n owner: t.relation(\"ownerActor\", {\n nullable: true,\n query: { where: { deleted: { isNull: true } } },\n }),\n declaredTotalItems: t.exposeInt(\"totalItems\", {\n nullable: true,\n description:\n \"The `totalItems` reported by the collection document. It can differ from the locally observed count and is null for local collections. Unlike `totalCount` and `items`, this value is not recalculated when deleted actors, deleted objects, or resources authored by deleted actors are excluded.\",\n }),\n totalCount: t.int({\n description:\n \"The number of locally stored, visible members. It can differ from `declaredTotalItems`. Deleted actors, deleted objects, resources authored by deleted actors, and resources the viewer may not read are excluded from this count and `items`.\",\n select: { columns: { id: true } },\n resolve: (row, _, ctx) =>\n ctx.db.$count(\n schema.collectionItems,\n and(\n eq(schema.collectionItems.collectionId, row.id),\n visibleResource(schema.collectionItems.itemId),\n readableResource(ctx, schema.collectionItems.itemId),\n ),\n ),\n }),\n items: t.connection({\n type: Resource,\n description:\n \"The locally stored, visible members. Deleted actors, deleted objects, resources authored by deleted actors, and resources the viewer may not read are excluded from this connection and `totalCount`.\",\n select: { columns: { id: true } },\n resolve: (row, args, ctx) => {\n const positions = new Map<Uuid, number | null>();\n return resolveCursorConnection<Promise<ResourceRow[]>>(\n {\n args,\n toCursor: (item: ResourceRow) => {\n if (!positions.has(item.id)) {\n throw new Error(\"Missing collection item position.\");\n }\n return encodeCollectionCursor({\n position: positions.get(item.id)!,\n itemId: item.id,\n });\n },\n },\n async ({ before, after, limit, inverted }) => {\n const parsedBefore =\n before == null ? undefined : parseCollectionCursor(before);\n const parsedAfter =\n after == null ? undefined : parseCollectionCursor(after);\n const items = await ctx.db.query.collectionItems.findMany({\n where: {\n collectionId: row.id,\n RAW: (table) =>\n and(\n visibleResource(table.itemId),\n readableResource(ctx, table.itemId),\n collectionCursorPredicate(\n table.position,\n table.itemId,\n parsedBefore,\n parsedAfter,\n ),\n )!,\n },\n orderBy: collectionItemsOrder(inverted),\n limit,\n with: { item: true },\n });\n for (const item of items) {\n positions.set(item.itemId, item.position);\n }\n return items.map((item) => item.item);\n },\n );\n },\n }),\n }),\n});\nexport const Collection: DrFedObjectRef = CollectionRef;\n\ninterface CollectionCursor {\n position: number | null;\n itemId: Uuid;\n}\n\nconst BASE64_PATTERN =\n /^(?:[A-Za-z\\d+/]{4})*(?:[A-Za-z\\d+/]{2}==|[A-Za-z\\d+/]{3}=)?$/u;\n\nfunction encodeCollectionCursor(cursor: CollectionCursor): string {\n return Buffer.from(JSON.stringify([cursor.position, cursor.itemId])).toString(\n \"base64\",\n );\n}\n\nfunction parseCollectionCursor(cursor: string): CollectionCursor {\n if (cursor === \"\" || !BASE64_PATTERN.test(cursor)) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n const decoded = Buffer.from(cursor, \"base64\");\n if (decoded.toString(\"base64\") !== cursor) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n let value: unknown;\n try {\n value = JSON.parse(decoded.toString(\"utf8\"));\n } catch {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n if (!Array.isArray(value) || value.length !== 2) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n const [position, itemId] = value;\n if (\n (position !== null &&\n (!Number.isInteger(position) ||\n position < -2_147_483_648 ||\n position > 2_147_483_647)) ||\n !validateUuid(itemId)\n ) {\n throw new PothosValidationError(\"Invalid collection cursor.\");\n }\n return { position, itemId };\n}\n\nfunction collectionCursorPredicate(\n positionColumn: SQLWrapper,\n itemIdColumn: SQLWrapper,\n before?: CollectionCursor,\n after?: CollectionCursor,\n): SQL | undefined {\n return and(\n after == null\n ? undefined\n : after.position == null\n ? sql`${positionColumn} is null and ${itemIdColumn} > ${after.itemId}`\n : sql`(\n ${positionColumn} > ${after.position}\n or (${positionColumn} = ${after.position} and ${itemIdColumn} > ${after.itemId})\n or ${positionColumn} is null\n )`,\n before == null\n ? undefined\n : before.position == null\n ? sql`(\n ${positionColumn} is not null\n or (${positionColumn} is null and ${itemIdColumn} < ${before.itemId})\n )`\n : sql`(\n ${positionColumn} < ${before.position}\n or (${positionColumn} = ${before.position} and ${itemIdColumn} < ${before.itemId})\n )`,\n );\n}\n\nfunction collectionItemsOrder(inverted: boolean): {\n position: \"asc\" | \"desc\";\n itemId: \"asc\" | \"desc\";\n} {\n // The keyset predicates rely on PostgreSQL's default ASC NULLS LAST and\n // DESC NULLS FIRST ordering.\n const direction = inverted ? \"desc\" : \"asc\";\n return { position: direction, itemId: direction };\n}\n\nconst Implementation = builder.enumType(\"Implementation\", {\n values: [\"MASTODON\", \"MISSKEY\"] as const,\n});\nconst ExpectedClassification = builder.objectRef<\n ReturnType<typeof classifyMastodon>\n>(\"ExpectedClassification\");\nExpectedClassification.implement({\n description:\n \"Expected classification; actual access depends on receiver state and policy.\",\n fields: (t) => ({\n implementation: t.expose(\"implementation\", { type: Implementation }),\n version: t.exposeString(\"version\"),\n classification: t.exposeString(\"classification\"),\n reason: t.exposeString(\"reason\"),\n }),\n});\nexport const ActivityType = builder.enumType(\"ActivityType\", {\n values: schema.activityTypeEnum.enumValues,\n});\nconst ActivityRef = builder.drizzleNode(\"activities\", {\n name: \"Activity\",\n description:\n \"Represents an ActivityPub activity. An activity of a local actor is \" +\n \"readable whatever its addressing. One of a remote actor is readable \" +\n \"only when it is addressed to the public, by members of the local \" +\n \"instances that received it, and by administrators; otherwise it is \" +\n \"left out as if it did not exist.\",\n select: {\n columns: { id: true },\n with: { actor: { columns: { deleted: true } } },\n },\n id: { column: (row) => row.id },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n type: t.expose(\"type\", { type: ActivityType }),\n actor: t.relation(\"actor\"),\n object: t.field({\n type: Resource,\n nullable: true,\n description:\n \"The resource the activity acts on, or null when there is none or \" +\n \"the viewer may not read it.\",\n select: { with: { object: true } },\n resolve: async (row, _, ctx) =>\n row.object != null && (await isReadableResource(ctx, row.object.id))\n ? row.object\n : null,\n }),\n expectedClassifications: t.field({\n type: [ExpectedClassification],\n description:\n \"Expected classifications for this activity and its Object. Empty if the object is absent, hidden, or not an Object.\",\n select: { columns: { id: true } },\n resolve: async (activity, _, ctx) => {\n const row = await ctx.db.query.activities.findFirst({\n where: { id: activity.id },\n with: activitySelection,\n });\n // As hidden from this viewer as `object` is, its addressing included.\n if (\n row?.objectId == null ||\n !(await isReadableResource(ctx, row.objectId))\n ) {\n return [];\n }\n const object = await ctx.db.query.objects.findFirst({\n where: {\n id: row.objectId,\n deleted: { isNull: true },\n actor: { deleted: { isNull: true } },\n },\n with: {\n ...objectSelection,\n actor: {\n with: {\n resource: true,\n collectionReferences: {\n with: { collection: { with: { resource: true } } },\n },\n },\n },\n },\n });\n if (object == null) return [];\n const addressing = classificationInput(object);\n const input = classificationInput(row);\n const author = classificationAuthor(object.actor);\n return [\n classifyMastodon(addressing, input, author),\n classifyMisskey(addressing, input, author),\n ];\n },\n }),\n published: t.expose(\"published\", { type: \"DateTime\" }),\n document: t.expose(\"document\", { type: \"JSON\", nullable: true }),\n }),\n});\nexport const Activity: DrFedObjectRef = ActivityRef;\nregisterAddressingFields(\"activities\");\n\n/**\n * Excludes deleted actors and objects, including resources authored or\n * owned by deleted actors.\n * @returns A predicate for a resource ID in an outer query.\n */\nfunction visibleResource(id: SQLWrapper): SQL {\n return sql`not exists (\n select 1 from ${schema.actors}\n where ${schema.actors.id} = ${id} and ${schema.actors.deleted} is not null\n ) and not exists (\n select 1 from ${schema.objects}\n join ${schema.actors} on ${schema.actors.id} = ${schema.objects.actorId}\n where ${schema.objects.id} = ${id}\n and (${schema.objects.deleted} is not null or ${schema.actors.deleted} is not null)\n ) and not exists (\n select 1 from ${schema.activities}\n join ${schema.actors} on ${schema.actors.id} = ${schema.activities.actorId}\n where ${schema.activities.id} = ${id} and ${schema.actors.deleted} is not null\n ) and not exists (\n select 1 from ${schema.collections}\n join ${schema.actors} on ${schema.actors.id} = ${schema.collections.ownerActorId}\n where ${schema.collections.id} = ${id} and ${schema.actors.deleted} is not null\n )`;\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\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 published by\n// the Free Software Foundation, either version 3 of the License, or\n// (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/>.\n\n// oxlint-disable max-lines-per-function eslint/max-lines\n\n// Keep dependent database writes and observations sequential.\n// oxlint-disable no-await-in-loop\n\nimport { enqueueActorKeyGeneration } from \"@drfed/federation\";\nimport { type Database, promoteResource, schema } from \"@drfed/models\";\nimport { type CollectionRole, actorTypeEnum } from \"@drfed/models/schema\";\nimport { type Uuid, uuidV7 as uuid } from \"@drfed/models/uuid\";\nimport { faker } from \"@faker-js/faker\";\nimport type { Context } from \"@fedify/fedify\";\nimport { drizzleConnectionHelpers } from \"@pothos/plugin-drizzle\";\nimport type { PgInsertValue } from \"drizzle-orm/pg-core\";\nimport { and, eq, gt, isNotNull, isNull } from \"drizzle-orm/sql/expressions\";\n\nimport builder, { type DrFedObjectRef } from \"./builder.ts\";\nimport { Instance } from \"./instance.ts\";\nimport { Collection, ResourceDetail } from \"./resource.ts\";\n\nconst ActorType = builder.enumType(\"ActorType\", {\n values: actorTypeEnum.enumValues,\n});\n\nconst ACTOR_TYPES_DOC = actorTypeEnum.enumValues\n .map((t) => `\\`${t}\\``)\n .join(\" | \");\n\nasync function resolveActorCollection(\n db: Database,\n actorId: Uuid,\n role: CollectionRole,\n) {\n const reference = await db.query.actorCollectionReferences.findFirst({\n where: { actorId, role },\n with: {\n collection: {\n with: { ownerActor: { columns: { deleted: true } } },\n },\n },\n });\n const collection = reference?.collection;\n return collection?.ownerActor?.deleted == null ? (collection ?? null) : null;\n}\n\nconst USERNAME_DOC =\n \"The username of the `Actor`. A remote actor's is its \" +\n \"`preferredUsername` as received, which is null when it has none and \" +\n \"need not be unique.\";\n\nconst ActorRef = builder.drizzleNode(\"actors\", {\n name: \"Actor\",\n description: \"Represents an `Actor` in the DrFed platform.\",\n id: {\n column: ({ id }) => id,\n description: \"The unique identifier of the `Actor`.\",\n },\n fields: (t) => ({\n resource: t.relation(\"resource\"),\n iri: t.field({\n type: \"URL\",\n select: { with: { resource: true } },\n resolve: (row) => row.resource.iri,\n }),\n uuid: t.expose(\"id\", {\n type: \"UUID\",\n description: \"The UUID of the `Actor`.\",\n }),\n handle: t.field({\n type: \"String\",\n nullable: true,\n description:\n \"The handle of the `Actor`, its `username` and its `Instance`'s \" +\n \"host. For a remote actor, this is not a verified WebFinger \" +\n \"address. Null when `username` is.\",\n select: {\n columns: { username: true },\n with: { instance: { columns: { host: true } } },\n },\n resolve: ({ instance, username }) =>\n username == null ? null : `@${username}@${instance.host}`,\n }),\n type: t.expose(\"type\", {\n type: ActorType,\n description: `The type of the \\`Actor\\`: ${ACTOR_TYPES_DOC}`,\n }),\n username: t.exposeString(\"username\", {\n nullable: true,\n description: USERNAME_DOC,\n }),\n instance: t.relation(\"instance\", {\n description: \"The `Instance` that the `Actor` belongs to.\",\n }),\n local: t.relation(\"localActor\", {\n nullable: true,\n description: \"The local details of the `Actor`, or null if it is remote.\",\n }),\n inboxUrl: t.expose(\"inboxUrl\", {\n type: \"URL\",\n description: \"The inbox URL of the `Actor`.\",\n }),\n outbox: t.field({\n type: Collection,\n nullable: true,\n description:\n \"The stored outbox collection. For local actors, it contains every stored `Create` activity regardless of addressing and retains activities whose objects are deleted so their recorded history remains inspectable. The ActivityPub outbox serves only activities with Public addressing whose objects are not deleted.\",\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"outbox\"),\n }),\n avatarUrl: t.expose(\"avatarUrl\", {\n type: \"URL\",\n description: \"The avatar URL of the `Actor`.\",\n nullable: true,\n }),\n followers: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"followers\"),\n }),\n following: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"following\"),\n }),\n headerUrl: t.expose(\"headerUrl\", {\n type: \"URL\",\n description: \"The header URL of the `Actor`.\",\n nullable: true,\n }),\n profileUrl: t.expose(\"profileUrl\", {\n type: \"URL\",\n description: \"The profile URL of the `Actor`.\",\n nullable: true,\n }),\n featured: t.field({\n type: Collection,\n nullable: true,\n select: { columns: { id: true } },\n resolve: (actor, _, ctx) =>\n resolveActorCollection(ctx.db, actor.id, \"featured\"),\n }),\n created: t.expose(\"created\", {\n type: \"DateTime\",\n description: \"The creation date/time of the `Actor`.\",\n }),\n }),\n});\n\nexport const Actor: DrFedObjectRef = ActorRef;\nResourceDetail.addTypes([Actor]);\n\nconst LocalActorRef = builder.drizzleNode(\"localActors\", {\n name: \"LocalActor\",\n select: {\n columns: { id: true },\n with: { actor: { columns: { deleted: true } } },\n },\n description: \"Represents the local details of an `Actor`.\",\n id: {\n column: ({ id }) => id,\n description: \"The unique identifier of the local actor details.\",\n },\n fields: (t) => ({\n uuid: t.expose(\"id\", {\n type: \"UUID\",\n description: \"The UUID of the local actor details.\",\n }),\n avatar: t.exposeString(\"avatar\", {\n nullable: true,\n description: \"The profile image of the actor.\",\n }),\n header: t.exposeString(\"header\", {\n nullable: true,\n description: \"The profile banner image of the actor.\",\n }),\n }),\n});\n\nexport const LocalActor: DrFedObjectRef = LocalActorRef;\n\ninterface CreateActorsSuccess {\n readonly actors: readonly (typeof ActorRef.$inferType)[];\n}\n\nconst CreateActorsSuccessRef = builder.objectRef<CreateActorsSuccess>(\n \"CreateActorsSuccess\",\n);\n\nCreateActorsSuccessRef.implement({\n fields: (t) => ({\n actors: t.field({\n type: [ActorRef],\n resolve: ({ actors }) => actors,\n }),\n }),\n});\n\nconst INVALID_SIZE = \"InvalidSize\" as const;\nconst INSTANCE_NOT_FOUND = \"InstanceNotFound\" as const;\nconst INVALID_INSTANCE_HOST = \"InvalidInstanceHost\" as const;\nconst TOO_MANY_ACTORS = \"TooManyActors\" as const;\nconst CreateActorsErrors = [\n INVALID_SIZE,\n INSTANCE_NOT_FOUND,\n INVALID_INSTANCE_HOST,\n TOO_MANY_ACTORS,\n] as const;\n\nconst CreateActorsErrorType = builder.enumType(\"CreateActorsErrorType\", {\n values: CreateActorsErrors,\n});\n\ninterface CreateActorsError {\n readonly type: typeof CreateActorsErrorType.$inferType;\n readonly message: string;\n}\n\nconst CreateActorsErrorRef =\n builder.objectRef<CreateActorsError>(\"CreateActorsError\");\n\nCreateActorsErrorRef.implement({\n description: \"Represents an error that occurred while creating an `Actor`.\",\n fields: (t) => ({\n type: t.expose(\"type\", {\n type: CreateActorsErrorType,\n description:\n \"The type of the error. Use this for programmatic error handling.\",\n }),\n message: t.exposeString(\"message\", {\n description:\n \"A human-readable message describing the error. \" +\n \"Don't use this for programmatic error handling, \" +\n \"use the `type` field instead.\",\n }),\n }),\n});\n\nconst CreateActorsResult = builder.unionType(\"CreateActorsResult\", {\n types: [CreateActorsSuccessRef, CreateActorsErrorRef],\n resolveType(value) {\n if (\"message\" in value) return CreateActorsErrorRef;\n return CreateActorsSuccessRef;\n },\n});\n\nbuilder.mutationFields((t) => ({\n generateActors: t.field({\n type: CreateActorsResult,\n description: \"Create actors.\",\n authScopes: { authenticated: true },\n args: {\n instance: t.arg.globalID({\n for: Instance,\n required: true,\n description: \"The ID of the target instance\",\n }),\n size: t.arg({\n type: \"Int\",\n required: true,\n description: \"How many actors to generate\",\n }),\n },\n async resolve(_query, { instance: { id: instanceId }, size }, ctx) {\n if (size < 1) {\n return {\n type: INVALID_SIZE,\n message: `${size} is too small. At least 1 or more.`,\n };\n }\n if (ctx.account == null) {\n // Note that the following error is not expected to be thrown,\n // because the `authScopes` option above should prevent this resolver\n throw new Error(\"You must be authenticated to create actors.\");\n }\n const { account } = ctx;\n // Relay decodes global IDs as strings; Instance uses UUID identifiers.\n const targetInstanceId = instanceId as Uuid;\n\n let createdOrigin: URL | undefined;\n const result = await ctx.db.transaction(async (tx) => {\n // Find the instance that the account is included\n const [instance] = await tx\n .select({\n host: schema.instances.host,\n maxActors: schema.localInstances.maxActors,\n })\n .from(schema.instanceMembers)\n .for(\"update\", { of: schema.localInstances })\n .innerJoin(\n schema.instances,\n eq(schema.instanceMembers.instanceId, schema.instances.id),\n )\n .innerJoin(\n schema.localInstances,\n eq(schema.instances.localId, schema.localInstances.id),\n )\n .where(\n and(\n eq(schema.instanceMembers.accountId, account.id),\n gt(schema.localInstances.expires, Temporal.Now.instant()),\n eq(schema.instances.id, targetInstanceId),\n isNotNull(schema.instanceMembers.accepted),\n ),\n )\n .limit(1);\n if (instance == null) {\n return {\n type: INSTANCE_NOT_FOUND,\n message: \"Can't find the instance.\",\n };\n }\n // Read the stored authority rather than recomposing it from the\n // slug, so that actor URIs cannot drift from the instance the rest of\n // the fediverse already knows.\n const { host, maxActors } = instance;\n const instanceUrl = `${ctx.rootOrigin.protocol}//${host}`;\n // Stored authorities can outlive the runtime that accepted them.\n if (!URL.canParse(instanceUrl)) {\n return {\n type: INVALID_INSTANCE_HOST,\n message:\n `The instance host ${JSON.stringify(host)} cannot be parsed by ` +\n \"this server. Contact the server administrator.\",\n };\n }\n const currActors = await tx.$count(\n schema.actors,\n eq(schema.actors.instanceId, targetInstanceId),\n );\n\n if (size + currActors > maxActors) {\n return {\n type: TOO_MANY_ACTORS,\n message: `${size} is too big. The maximum number of actors of ${\n host\n } is ${maxActors} and the current number of actors is ${\n currActors\n }.`,\n };\n }\n // Create actors\n createdOrigin = new URL(instanceUrl);\n const fedCtx = ctx.federation.createContext(\n new URL(instanceUrl),\n undefined,\n );\n const ids = Array.from({ length: size }, () => ({ id: uuid() }));\n await tx.insert(schema.localActors).values(ids);\n const createdActors = [];\n for (const { id } of ids) {\n const actor = await promoteResource(\n tx,\n fedCtx.getActorUri(id).href,\n \"actor\",\n async (inner, resource) => {\n for (let attempt = 0; attempt < 10; attempt += 1) {\n const [createdActor] = await inner\n .insert(schema.actors)\n .values(generateActor(resource.id, targetInstanceId, fedCtx))\n .onConflictDoNothing({\n target: [schema.actors.username, schema.actors.instanceId],\n // Only the partial index of local actors' usernames.\n where: isNotNull(schema.actors.localId),\n })\n .returning();\n if (createdActor != null) {\n return createdActor;\n }\n }\n throw new Error(\"Actor insertion returned no row.\");\n },\n id,\n );\n for (const [role, iri] of [\n [\"followers\", fedCtx.getFollowersUri(id).href],\n [\"following\", fedCtx.getFollowingUri(id).href],\n [\"featured\", fedCtx.getFeaturedUri(id).href],\n [\"outbox\", fedCtx.getOutboxUri(id).href],\n ] as const) {\n await promoteResource(\n tx,\n iri,\n \"collection\",\n async (inner, resource) => {\n await inner.insert(schema.collections).values({\n id: resource.id,\n type: \"OrderedCollection\",\n ownerActorId: actor.id,\n });\n await inner.insert(schema.actorCollectionReferences).values({\n actorId: actor.id,\n role,\n collectionId: resource.id,\n });\n },\n );\n }\n createdActors.push(actor);\n }\n return { actors: createdActors };\n });\n if (\"actors\" in result && createdOrigin != null) {\n await enqueueActorKeyGeneration(\n ctx.federation.createContext(createdOrigin, undefined),\n result.actors.map((actor) => actor.id),\n );\n }\n return result;\n },\n }),\n}));\n\nfunction generateActor(\n id: Uuid,\n instanceId: Uuid,\n fedCtx: Context<unknown>,\n): PgInsertValue<typeof schema.actors> {\n const username = faker.internet\n .username()\n .toLowerCase()\n .replace(/[^a-z0-9_]/gu, \"_\");\n\n return {\n id,\n localId: id,\n username,\n instanceId,\n type: \"Person\",\n inboxUrl: fedCtx.getInboxUri(id).href,\n profileUrl: new URL(`/@${username}`, fedCtx.origin).href,\n };\n}\n\nconst actorsConnection = drizzleConnectionHelpers(builder, \"actors\", {\n query: { orderBy: { created: \"desc\", id: \"desc\" } },\n});\n\nbuilder.drizzleObjectField(\"instances\", \"actors\", (t) =>\n t.connection(\n {\n type: Actor,\n description: \"The `Actor`s that belong to the `Instance`.\",\n select(args, ctx, nestedSelection) {\n return {\n with: {\n actors: actorsConnection.getQuery(args, ctx, nestedSelection),\n },\n };\n },\n resolve(instance, args, ctx) {\n return {\n ...actorsConnection.resolve(instance.actors, args, ctx, instance),\n totalCount() {\n return ctx.db.$count(\n schema.actors,\n and(\n eq(schema.actors.instanceId, instance.id),\n isNull(schema.actors.deleted),\n ),\n );\n },\n };\n },\n },\n {\n fields(fb) {\n return {\n totalCount: fb.int({\n description:\n \"The total number of `Actor`s that belong to the `Instance`.\",\n resolve(connection) {\n return connection.totalCount();\n },\n }),\n };\n },\n },\n {\n fields(fb) {\n return {\n created: fb.expose(\"created\", {\n type: \"DateTime\",\n description:\n \"The date/time when the `Actor` was added to the `Instance`.\",\n }),\n type: fb.expose(\"type\", {\n type: ActorType,\n description: `The type of the \\`Actor\\`: ${ACTOR_TYPES_DOC}`,\n }),\n username: fb.exposeString(\"username\", {\n nullable: true,\n description: USERNAME_DOC,\n }),\n };\n },\n },\n ),\n);\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAa,eAAe,QAAQ,SAAS,gBAAgB,EAC3D,QAAQ,OAAO,iBAAiB,WAClC,CAAC;AACD,MAAa,iBAAiB,QAAQ,UAAU,kBAAkB;CAChE,aAAa,C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,OAAO,IAAI;CACT,OAAO;EACL,SAAS,GAAG,OAAO,WAAW;GAC5B,MAAM;GACN,aACE;EACJ,CAAC;EACD,MAAM,GAAG,OAAO,QAAQ;GACtB,MAAM;GACN,aAAa,8BAA8B;EAC7C,CAAC;EACD,UAAU,GAAG,aAAa,YAAY;GACpC,UAAU;GACV,aAAa;EACf,CAAC;CACH;AACF,EACF,CACF,CACF"}
@@ -0,0 +1,7 @@
1
+ import { t as DrFedObjectRef } from "./builder-CSxRffRp.mjs";
2
+ //#region src/actor.d.ts
3
+ declare const Actor: DrFedObjectRef;
4
+ declare const LocalActor: DrFedObjectRef;
5
+ //#endregion
6
+ export { Actor, LocalActor };
7
+ //# sourceMappingURL=actor.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actor.d.mts","names":[],"sources":["../src/actor.ts"],"mappings":";;cAwKa,OAAO;cA8BP,YAAY"}
package/dist/actor.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { n as LocalActor, t as Actor } from "./actor-BJvviz6Q.mjs";
2
+ export { Actor, LocalActor };
@@ -0,0 +1,152 @@
1
+ import { i as memberInstances, n as hideUnreadableNodes } from "./readable-CSN0MPlO.mjs";
2
+ import { instances } from "@drfed/models/schema";
3
+ import DrizzlePlugin from "@pothos/plugin-drizzle";
4
+ import { eq } from "drizzle-orm/sql/expressions";
5
+ import { normalizeEmail, relations } from "@drfed/models";
6
+ import { Template } from "@fedify/uri-template";
7
+ import SchemaBuilder, { BasePlugin } from "@pothos/core";
8
+ import ErrorsPlugin from "@pothos/plugin-errors";
9
+ import RelayPlugin from "@pothos/plugin-relay";
10
+ import ScopeAuthPlugin from "@pothos/plugin-scope-auth";
11
+ import { getTableConfig } from "drizzle-orm/pg-core";
12
+ import { GraphQLScalarType, Kind } from "graphql";
13
+ import { JSONResolver, URLResolver, UUIDResolver } from "graphql-scalars";
14
+ //#region src/operations.ts
15
+ var OperationsPlugin = class extends BasePlugin {
16
+ wrapResolve(resolve) {
17
+ return (parent, args, context, info) => {
18
+ const { trackOperation } = context;
19
+ return trackOperation == null ? resolve(parent, args, context, info) : trackOperation(() => resolve(parent, args, context, info));
20
+ };
21
+ }
22
+ wrapResolveType(resolveType) {
23
+ return (parent, context, info, type) => {
24
+ const { trackOperation } = context;
25
+ return trackOperation == null ? resolveType(parent, context, info, type) : trackOperation(() => resolveType(parent, context, info, type));
26
+ };
27
+ }
28
+ wrapIsTypeOf(isTypeOf) {
29
+ if (isTypeOf == null) return isTypeOf;
30
+ return (parent, context, info) => {
31
+ const { trackOperation } = context;
32
+ return trackOperation == null ? isTypeOf(parent, context, info) : trackOperation(() => isTypeOf(parent, context, info));
33
+ };
34
+ }
35
+ };
36
+ SchemaBuilder.registerPlugin("drfedOperations", OperationsPlugin);
37
+ //#endregion
38
+ //#region src/builder.ts
39
+ /**
40
+ * The GraphQL schema builder.
41
+ */
42
+ const builder = new SchemaBuilder({
43
+ defaultFieldNullability: false,
44
+ drizzle: {
45
+ client(ctx) {
46
+ return ctx.db;
47
+ },
48
+ getTableConfig,
49
+ relations
50
+ },
51
+ plugins: [
52
+ "drfedOperations",
53
+ DrizzlePlugin,
54
+ RelayPlugin,
55
+ ErrorsPlugin,
56
+ ScopeAuthPlugin
57
+ ],
58
+ errors: { defaultTypes: [] },
59
+ relay: {
60
+ nodeQueryOptions: { resolve: async (_, { id }, ctx, __, resolveNode) => {
61
+ const [node] = await hideUnreadableNodes(ctx, [filterDeleted(await resolveNode(id))]);
62
+ return node;
63
+ } },
64
+ nodesQueryOptions: { resolve: async (_, { ids }, ctx, __, resolveNodes) => await hideUnreadableNodes(ctx, (await resolveNodes(ids)).map(filterDeleted)) }
65
+ },
66
+ scopeAuth: {
67
+ authorizeOnSubscribe: true,
68
+ authScopes(context) {
69
+ return {
70
+ authenticated: Boolean(context.session),
71
+ admin: Boolean(context.account?.admin),
72
+ localInstanceMember(localInstanceId) {
73
+ return isLocalInstanceMember(context, localInstanceId);
74
+ },
75
+ accountSelf(accountId) {
76
+ return context.account?.id === accountId;
77
+ }
78
+ };
79
+ }
80
+ }
81
+ });
82
+ const isDeleted = (node) => node != null && typeof node === "object" && "deleted" in node && node.deleted != null;
83
+ const OWNER_RELATIONS = ["actor", "ownerActor"];
84
+ const filterDeleted = (node) => isDeleted(node) || node != null && typeof node === "object" && OWNER_RELATIONS.some((key) => isDeleted(node[key])) ? null : node;
85
+ /**
86
+ * Determines whether the viewer is an accepted member of the `Instance` that
87
+ * the given `LocalInstance` backs. Pending members, i.e. those who have been
88
+ * invited but have not accepted yet, do not count.
89
+ *
90
+ * Pothos caches scope results per request by scope name and parameter, so this
91
+ * runs at most once per `LocalInstance` per request.
92
+ *
93
+ * @param context The request context, whose `account` is the viewer.
94
+ * @param localInstanceId The UUID of the `LocalInstance` to check.
95
+ * @returns Whether the viewer is an accepted member.
96
+ */
97
+ async function isLocalInstanceMember(context, localInstanceId) {
98
+ const { account } = context;
99
+ if (account == null) return false;
100
+ return (await memberInstances(context.db, account.id, eq(instances.localId, localInstanceId)).limit(1)).length > 0;
101
+ }
102
+ builder.scalarType("DateTime", {
103
+ description: "An ISO 8601 instant preserving sub-millisecond precision.",
104
+ serialize(value) {
105
+ if (!(value instanceof Temporal.Instant)) throw new TypeError("Expected a Temporal.Instant.");
106
+ return value.toString();
107
+ },
108
+ parseValue(value) {
109
+ if (typeof value !== "string") throw new TypeError("Expected an instant string.");
110
+ return Temporal.Instant.from(value);
111
+ },
112
+ parseLiteral(node) {
113
+ if (node.kind !== Kind.STRING) throw new TypeError("Expected an instant string.");
114
+ return Temporal.Instant.from(node.value);
115
+ }
116
+ });
117
+ builder.addScalarType("URL", new GraphQLScalarType({
118
+ ...URLResolver.toConfig(),
119
+ serialize(value) {
120
+ URLResolver.serialize(value);
121
+ return String(value);
122
+ },
123
+ parseValue(value) {
124
+ URLResolver.parseValue(value);
125
+ return String(value);
126
+ },
127
+ parseLiteral(node, variables) {
128
+ URLResolver.parseLiteral(node, variables);
129
+ if (node.kind !== Kind.STRING) throw new TypeError("Expected a URL string.");
130
+ return node.value;
131
+ }
132
+ }));
133
+ builder.addScalarType("JSON", JSONResolver);
134
+ builder.scalarType("Email", {
135
+ parseValue: (v) => normalizeEmail(String(v)),
136
+ serialize: (v) => normalizeEmail(v)
137
+ });
138
+ builder.addScalarType("UUID", UUIDResolver);
139
+ builder.scalarType("URITemplate", {
140
+ parseValue(v) {
141
+ if (v instanceof Template) return v;
142
+ return Template.parse(String(v));
143
+ },
144
+ serialize(v) {
145
+ return v.toString();
146
+ }
147
+ });
148
+ const Node = builder.nodeInterfaceRef();
149
+ //#endregion
150
+ export { builder as n, Node as t };
151
+
152
+ //# sourceMappingURL=builder-BLioFAdv.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builder-BLioFAdv.mjs","names":["OperationsPlugin"],"sources":["../src/operations.ts","../src/builder.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\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 published by\n// the Free Software Foundation, either version 3 of the License, or\n// (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/>.\n\nimport SchemaBuilder, { BasePlugin, type SchemaTypes } from \"@pothos/core\";\nimport type {\n GraphQLFieldResolver,\n GraphQLIsTypeOfFn,\n GraphQLTypeResolver,\n} from \"graphql\";\n\n/** Track the lifetime of work that may outlive a cancelled HTTP request. */\nexport type OperationTracker = <T>(\n operation: () => T | Promise<T>,\n) => Promise<T>;\n\nclass OperationsPlugin<Types extends SchemaTypes> extends BasePlugin<Types> {\n // Pothos requires an instance hook even when the wrapper has no plugin state.\n // oxlint-disable-next-line class-methods-use-this\n override wrapResolve(\n resolve: GraphQLFieldResolver<unknown, Types[\"Context\"], object>,\n ): GraphQLFieldResolver<unknown, Types[\"Context\"], object> {\n return (parent, args, context, info) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? resolve(parent, args, context, info)\n : trackOperation(() => resolve(parent, args, context, info));\n };\n }\n // Pothos dispatches abstract type resolution separately from field resolution.\n // oxlint-disable-next-line class-methods-use-this\n override wrapResolveType(\n resolveType: GraphQLTypeResolver<unknown, Types[\"Context\"]>,\n ): GraphQLTypeResolver<unknown, Types[\"Context\"]> {\n return (parent, context, info, type) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? resolveType(parent, context, info, type)\n : trackOperation(() => resolveType(parent, context, info, type));\n };\n }\n\n // ScopeAuth performs type-level authorization through this separate hook.\n // oxlint-disable-next-line class-methods-use-this\n override wrapIsTypeOf(\n isTypeOf: GraphQLIsTypeOfFn<unknown, Types[\"Context\"]> | undefined,\n ): GraphQLIsTypeOfFn<unknown, Types[\"Context\"]> | undefined {\n if (isTypeOf == null) return isTypeOf;\n return (parent, context, info) => {\n const { trackOperation } = context as {\n trackOperation?: OperationTracker;\n };\n return trackOperation == null\n ? isTypeOf(parent, context, info)\n : trackOperation(() => isTypeOf(parent, context, info));\n };\n }\n}\n\ndeclare global {\n // Pothos registers plugin types through this namespace.\n // oxlint-disable-next-line typescript/no-namespace\n namespace PothosSchemaTypes {\n interface Plugins<Types extends SchemaTypes> {\n drfedOperations: OperationsPlugin<Types>;\n }\n }\n}\n\nSchemaBuilder.registerPlugin(\"drfedOperations\", OperationsPlugin);\n\nexport default \"drfedOperations\" as const;\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\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 published by\n// the Free Software Foundation, either version 3 of the License, or\n// (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/>.\n\nimport { type Database, normalizeEmail, relations } from \"@drfed/models\";\nimport { type Account, type Session, instances } from \"@drfed/models/schema\";\nimport type { Uuid } from \"@drfed/models/uuid\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { Template } from \"@fedify/uri-template\";\nimport SchemaBuilder, { type ObjectRef } from \"@pothos/core\";\nimport DrizzlePlugin from \"@pothos/plugin-drizzle\";\nimport ErrorsPlugin from \"@pothos/plugin-errors\";\nimport RelayPlugin from \"@pothos/plugin-relay\";\nimport ScopeAuthPlugin from \"@pothos/plugin-scope-auth\";\nimport type { Transport } from \"@upyo/core\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\nimport { eq } from \"drizzle-orm/sql/expressions\";\nimport { GraphQLScalarType, Kind } from \"graphql\";\nimport { JSONResolver, URLResolver, UUIDResolver } from \"graphql-scalars\";\n\nimport OperationsPlugin, { type OperationTracker } from \"./operations.ts\";\nimport { hideUnreadableNodes, memberInstances } from \"./readable.ts\";\n\n/**\n * The context data for the GraphQL server, which includes the incoming request\n * object and any additional information needed for processing GraphQL queries\n * and mutations.\n */\nexport interface ServerContext {\n /** Combined request and runtime shutdown cancellation for active work. */\n readonly operationSignal?: AbortSignal | undefined;\n\n /** Optional runtime owner for work that survives HTTP cancellation. */\n readonly trackOperation?: OperationTracker | undefined;\n\n /**\n * The incoming HTTP request.\n */\n readonly request: Request;\n\n /**\n * The database instance.\n */\n readonly db: Database;\n\n /**\n * Email sending services.\n */\n readonly mailer: Transport;\n\n /**\n * The address login mail is sent from.\n */\n readonly emailFrom: string;\n\n /**\n * Origins for login.\n */\n readonly loginOrigins: ReadonlySet<string>;\n\n /**\n * The root origin of this deployment, which every instance's subdomain is\n * derived from. It is always equal to its own origin, i.e. it carries no\n * path, query or credentials.\n */\n readonly rootOrigin: URL;\n\n /**\n * The federation instance.\n */\n readonly federation: Federation<unknown>;\n}\n\n/**\n * The user-related context data for the GraphQL server, which include every\n * field from the {@link ServerContext}.\n */\nexport interface UserContext extends ServerContext {\n /**\n * Session information.\n */\n readonly session?: Session;\n\n /**\n * Current viewer.\n */\n readonly account?: Account;\n}\n\nexport interface SchemaTypes {\n Context: UserContext;\n Scalars: {\n JSON: { Input: unknown; Output: unknown };\n DateTime: {\n Input: Temporal.Instant;\n Output: Temporal.Instant;\n };\n Email: {\n Input: string;\n Output: string;\n };\n UUID: {\n Input: Uuid;\n Output: Uuid;\n };\n URITemplate: {\n Input: Template;\n Output: Template;\n };\n URL: {\n Input: string;\n Output: string;\n };\n };\n DefaultFieldNullability: false;\n DrizzleRelations: typeof relations;\n AuthScopes: {\n authenticated: boolean;\n admin: boolean;\n /**\n * Whether the viewer is an accepted member of the `Instance` backed by\n * the `LocalInstance` with the given UUID.\n */\n localInstanceMember: Uuid;\n /**\n * Whether the viewer is the `Account` with the given UUID.\n */\n accountSelf: Uuid;\n };\n}\n\nexport type DrFedSchemaTypes =\n PothosSchemaTypes.ExtendDefaultTypes<SchemaTypes>;\n\nexport type DrFedObjectRef<Shape = unknown, Parent = Shape> = ObjectRef<\n DrFedSchemaTypes,\n Shape,\n Parent\n>;\n\n/**\n * The GraphQL schema builder.\n */\nexport const builder = new SchemaBuilder<SchemaTypes>({\n defaultFieldNullability: false,\n drizzle: {\n client(ctx) {\n return ctx.db;\n },\n getTableConfig,\n relations,\n },\n plugins: [\n OperationsPlugin,\n DrizzlePlugin,\n RelayPlugin,\n ErrorsPlugin,\n ScopeAuthPlugin,\n ],\n errors: { defaultTypes: [] },\n relay: {\n nodeQueryOptions: {\n resolve: async (_, { id }, ctx, __, resolveNode) => {\n const [node] = await hideUnreadableNodes(ctx, [\n filterDeleted(await resolveNode(id)),\n ]);\n return node;\n },\n },\n nodesQueryOptions: {\n resolve: async (_, { ids }, ctx, __, resolveNodes) =>\n await hideUnreadableNodes(\n ctx,\n (await resolveNodes(ids)).map(filterDeleted),\n ),\n },\n },\n scopeAuth: {\n authorizeOnSubscribe: true,\n authScopes(context) {\n return {\n authenticated: Boolean(context.session),\n admin: Boolean(context.account?.admin),\n localInstanceMember(localInstanceId) {\n return isLocalInstanceMember(context, localInstanceId);\n },\n accountSelf(accountId) {\n return context.account?.id === accountId;\n },\n };\n },\n },\n});\n\nconst isDeleted = (node: unknown): boolean =>\n node != null &&\n typeof node === \"object\" &&\n \"deleted\" in node &&\n node.deleted != null;\n\n// Relations whose deletion hides the node: an object's or activity's\n// author, or a collection's owner.\nconst OWNER_RELATIONS = [\"actor\", \"ownerActor\"] as const;\n\nconst filterDeleted = (node: unknown): unknown =>\n isDeleted(node) ||\n (node != null &&\n typeof node === \"object\" &&\n OWNER_RELATIONS.some((key) =>\n isDeleted((node as Record<string, unknown>)[key]),\n ))\n ? null\n : node;\n\n/**\n * Determines whether the viewer is an accepted member of the `Instance` that\n * the given `LocalInstance` backs. Pending members, i.e. those who have been\n * invited but have not accepted yet, do not count.\n *\n * Pothos caches scope results per request by scope name and parameter, so this\n * runs at most once per `LocalInstance` per request.\n *\n * @param context The request context, whose `account` is the viewer.\n * @param localInstanceId The UUID of the `LocalInstance` to check.\n * @returns Whether the viewer is an accepted member.\n */\nasync function isLocalInstanceMember(\n context: UserContext,\n localInstanceId: Uuid,\n): Promise<boolean> {\n const { account } = context;\n if (account == null) return false;\n const rows = await memberInstances(\n context.db,\n account.id,\n eq(instances.localId, localInstanceId),\n ).limit(1);\n return rows.length > 0;\n}\n\nbuilder.scalarType(\"DateTime\", {\n description: \"An ISO 8601 instant preserving sub-millisecond precision.\",\n serialize(value) {\n if (!(value instanceof Temporal.Instant)) {\n throw new TypeError(\"Expected a Temporal.Instant.\");\n }\n return value.toString();\n },\n parseValue(value) {\n if (typeof value !== \"string\") {\n throw new TypeError(\"Expected an instant string.\");\n }\n return Temporal.Instant.from(value);\n },\n parseLiteral(node) {\n if (node.kind !== Kind.STRING) {\n throw new TypeError(\"Expected an instant string.\");\n }\n return Temporal.Instant.from(node.value);\n },\n});\nbuilder.addScalarType(\n \"URL\",\n new GraphQLScalarType({\n ...URLResolver.toConfig(),\n serialize(value) {\n URLResolver.serialize(value);\n return String(value);\n },\n // Validate URLs while preserving the caller's exact spelling.\n parseValue(value) {\n URLResolver.parseValue(value);\n return String(value);\n },\n parseLiteral(node, variables) {\n URLResolver.parseLiteral(node, variables);\n if (node.kind !== Kind.STRING) {\n throw new TypeError(\"Expected a URL string.\");\n }\n return node.value;\n },\n }),\n);\nbuilder.addScalarType(\"JSON\", JSONResolver);\n\nbuilder.scalarType(\"Email\", {\n parseValue: (v) => normalizeEmail(String(v)),\n serialize: (v) => normalizeEmail(v),\n});\n\nbuilder.addScalarType(\"UUID\", UUIDResolver);\n\nbuilder.scalarType(\"URITemplate\", {\n parseValue(v) {\n if (v instanceof Template) {\n return v;\n }\n return Template.parse(String(v));\n },\n serialize(v) {\n return v.toString();\n },\n});\n\nexport const Node = builder.nodeInterfaceRef();\n\nexport default builder;\n"],"mappings":";;;;;;;;;;;;;;AA4BA,IAAM,mBAAN,cAA0D,WAAkB;CAG1E,YACE,SACyD;EACzD,QAAQ,QAAQ,MAAM,SAAS,SAAS;GACtC,MAAM,EAAE,mBAAmB;GAG3B,OAAO,kBAAkB,OACrB,QAAQ,QAAQ,MAAM,SAAS,IAAI,IACnC,qBAAqB,QAAQ,QAAQ,MAAM,SAAS,IAAI,CAAC;EAC/D;CACF;CAGA,gBACE,aACgD;EAChD,QAAQ,QAAQ,SAAS,MAAM,SAAS;GACtC,MAAM,EAAE,mBAAmB;GAG3B,OAAO,kBAAkB,OACrB,YAAY,QAAQ,SAAS,MAAM,IAAI,IACvC,qBAAqB,YAAY,QAAQ,SAAS,MAAM,IAAI,CAAC;EACnE;CACF;CAIA,aACE,UAC0D;EAC1D,IAAI,YAAY,MAAM,OAAO;EAC7B,QAAQ,QAAQ,SAAS,SAAS;GAChC,MA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AO;EAET,OAAO,SAAS,MAAM,OAAO,CAAC,CAAC;CACjC;CACA,UAAU,GAAG;EACX,OAAO,EAAE,SAAS;CACpB;AACF,CAAC;AAED,MAAa,OAAO,QAAQ,iBAAiB"}
@@ -0,0 +1,134 @@
1
+ import { Account, Session } from "@drfed/models/schema";
2
+ import { Database, relations } from "@drfed/models";
3
+ import { Template } from "@fedify/uri-template";
4
+ import { BasePlugin, ObjectRef, SchemaTypes } from "@pothos/core";
5
+ import { GraphQLFieldResolver, GraphQLIsTypeOfFn, GraphQLTypeResolver } from "graphql";
6
+ import { Uuid } from "@drfed/models/uuid";
7
+ import { Transport } from "@upyo/core";
8
+ import { Federation } from "@fedify/fedify";
9
+ //#region src/operations.d.ts
10
+ /** Track the lifetime of work that may outlive a cancelled HTTP request. */
11
+ type OperationTracker = <T>(operation: () => T | Promise<T>) => Promise<T>;
12
+ declare class OperationsPlugin<Types extends SchemaTypes> extends BasePlugin<Types> {
13
+ wrapResolve(resolve: GraphQLFieldResolver<unknown, Types["Context"], object>): GraphQLFieldResolver<unknown, Types["Context"], object>;
14
+ wrapResolveType(resolveType: GraphQLTypeResolver<unknown, Types["Context"]>): GraphQLTypeResolver<unknown, Types["Context"]>;
15
+ wrapIsTypeOf(isTypeOf: GraphQLIsTypeOfFn<unknown, Types["Context"]> | undefined): GraphQLIsTypeOfFn<unknown, Types["Context"]> | undefined;
16
+ }
17
+ declare global {
18
+ namespace PothosSchemaTypes {
19
+ interface Plugins<Types extends SchemaTypes> {
20
+ drfedOperations: OperationsPlugin<Types>;
21
+ }
22
+ }
23
+ }
24
+ //#endregion
25
+ //#region src/builder.d.ts
26
+ /**
27
+ * The context data for the GraphQL server, which includes the incoming request
28
+ * object and any additional information needed for processing GraphQL queries
29
+ * and mutations.
30
+ */
31
+ interface ServerContext {
32
+ /** Combined request and runtime shutdown cancellation for active work. */
33
+ readonly operationSignal?: AbortSignal | undefined;
34
+ /** Optional runtime owner for work that survives HTTP cancellation. */
35
+ readonly trackOperation?: OperationTracker | undefined;
36
+ /**
37
+ * The incoming HTTP request.
38
+ */
39
+ readonly request: Request;
40
+ /**
41
+ * The database instance.
42
+ */
43
+ readonly db: Database;
44
+ /**
45
+ * Email sending services.
46
+ */
47
+ readonly mailer: Transport;
48
+ /**
49
+ * The address login mail is sent from.
50
+ */
51
+ readonly emailFrom: string;
52
+ /**
53
+ * Origins for login.
54
+ */
55
+ readonly loginOrigins: ReadonlySet<string>;
56
+ /**
57
+ * The root origin of this deployment, which every instance's subdomain is
58
+ * derived from. It is always equal to its own origin, i.e. it carries no
59
+ * path, query or credentials.
60
+ */
61
+ readonly rootOrigin: URL;
62
+ /**
63
+ * The federation instance.
64
+ */
65
+ readonly federation: Federation<unknown>;
66
+ }
67
+ /**
68
+ * The user-related context data for the GraphQL server, which include every
69
+ * field from the {@link ServerContext}.
70
+ */
71
+ interface UserContext extends ServerContext {
72
+ /**
73
+ * Session information.
74
+ */
75
+ readonly session?: Session;
76
+ /**
77
+ * Current viewer.
78
+ */
79
+ readonly account?: Account;
80
+ }
81
+ interface SchemaTypes$1 {
82
+ Context: UserContext;
83
+ Scalars: {
84
+ JSON: {
85
+ Input: unknown;
86
+ Output: unknown;
87
+ };
88
+ DateTime: {
89
+ Input: Temporal.Instant;
90
+ Output: Temporal.Instant;
91
+ };
92
+ Email: {
93
+ Input: string;
94
+ Output: string;
95
+ };
96
+ UUID: {
97
+ Input: Uuid;
98
+ Output: Uuid;
99
+ };
100
+ URITemplate: {
101
+ Input: Template;
102
+ Output: Template;
103
+ };
104
+ URL: {
105
+ Input: string;
106
+ Output: string;
107
+ };
108
+ };
109
+ DefaultFieldNullability: false;
110
+ DrizzleRelations: typeof relations;
111
+ AuthScopes: {
112
+ authenticated: boolean;
113
+ admin: boolean;
114
+ /**
115
+ * Whether the viewer is an accepted member of the `Instance` backed by
116
+ * the `LocalInstance` with the given UUID.
117
+ */
118
+ localInstanceMember: Uuid;
119
+ /**
120
+ * Whether the viewer is the `Account` with the given UUID.
121
+ */
122
+ accountSelf: Uuid;
123
+ };
124
+ }
125
+ type DrFedSchemaTypes = PothosSchemaTypes.ExtendDefaultTypes<SchemaTypes$1>;
126
+ type DrFedObjectRef<Shape = unknown, Parent = Shape> = ObjectRef<DrFedSchemaTypes, Shape, Parent>;
127
+ /**
128
+ * The GraphQL schema builder.
129
+ */
130
+ declare const builder: PothosSchemaTypes.SchemaBuilder<PothosSchemaTypes.ExtendDefaultTypes<SchemaTypes$1>>;
131
+ declare const Node: PothosSchemaTypes.InterfaceRef<PothosSchemaTypes.ExtendDefaultTypes<SchemaTypes$1>, unknown, unknown>;
132
+ //#endregion
133
+ export { ServerContext as a, OperationTracker as c, SchemaTypes$1 as i, DrFedSchemaTypes as n, UserContext as o, Node as r, builder as s, DrFedObjectRef as t };
134
+ //# sourceMappingURL=builder-CSxRffRp.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"builder-CSxRffRp.d.mts","names":[],"sources":["../src/operations.ts","../src/builder.ts"],"mappings":";;;;;;;;;;KAwBY,oBAAoB,GAC9B,iBAAiB,IAAI,QAAQ,OAC1B,QAAQ;cAEP,iBAAiB,cAAc,qBAAqB,WAAW;EAG1D,YACP,SAAS,8BAA8B,4BACtC,8BAA8B;EAYxB,gBACP,aAAa,6BAA6B,oBACzC,6BAA6B;EAavB,aACP,UAAU,2BAA2B,gCACpC,2BAA2B;;QAaxB;YAGI;cACE,QAAQ,cAAc;MAC9B,iBAAiB,iBAAiB;;;;;;;;;;;UCxCvB;;WAEN,kBAAkB;;WAGlB,iBAAiB;;;;WAKjB,SAAS;;;;WAKT,IAAI;;;;WAKJ,QAAQ;;;;WAKR;;;;WAKA,cAAc;;;;;;WAOd,YAAY;;;;WAKZ,YAAY;;;;;;UAON,oBAAoB;;;;WAI1B,UAAU;;;;WAKV,UAAU;;UAGJ;EACf,SAAS;EACT;IACE;MAAQ;MAAgB;;IACxB;MACE,OAAO,SAAS;MAChB,QAAQ,SAAS;;IAEnB;MACE;MACA;;IAEF;MACE,OAAO;MACP,QAAQ;;IAEV;MACE,OAAO;MACP,QAAQ;;IAEV;MACE;MACA;;;EAGJ;EACA,yBAAyB;EACzB;IACE;IACA;;;;;IAKA,qBAAqB;;;;IAIrB,aAAa;;;KAIL,mBACV,kBAAkB,mBAAmB;KAE3B,eAAe,iBAAiB,SAAS,SAAS,UAC5D,kBACA,OACA;;;;cAMW,SAAO,kBAAA,cAAA,kBAAA,mBAAA;cAiKP,MAAI,kBAAA,aAAA,kBAAA,mBAAA"}
@@ -0,0 +1,2 @@
1
+ import { a as ServerContext, i as SchemaTypes, n as DrFedSchemaTypes, o as UserContext, r as Node, s as builder, t as DrFedObjectRef } from "./builder-CSxRffRp.mjs";
2
+ export { DrFedObjectRef, DrFedSchemaTypes, Node, SchemaTypes, ServerContext, UserContext, builder, builder as default };
@@ -0,0 +1,2 @@
1
+ import { n as builder, t as Node } from "./builder-BLioFAdv.mjs";
2
+ export { Node, builder, builder as default };
@@ -0,0 +1,62 @@
1
+ //#region src/classification.d.ts
2
+ /** Missing/null properties permit Mastodon's activity fallback; [] does not. */
3
+ interface AddressingRows {
4
+ readonly to?: readonly string[] | null | undefined;
5
+ readonly cc?: readonly string[] | null | undefined;
6
+ }
7
+ interface ExpectedClassification {
8
+ readonly implementation: "MASTODON" | "MISSKEY";
9
+ readonly version: string;
10
+ readonly classification: string;
11
+ readonly reason: string;
12
+ }
13
+ interface Author {
14
+ readonly followersIri: string | null;
15
+ readonly iri: string;
16
+ }
17
+ /**
18
+ * Expected Mastodon classification, independent of receiver state or policy.
19
+ * @returns The expected Mastodon label, pinned revision, and applied rule.
20
+ */
21
+ declare function classifyMastodon(object: AddressingRows, activity: AddressingRows | null, author: Author): ExpectedClassification;
22
+ /**
23
+ * Expected Misskey classification; activity addressing is deliberately unused.
24
+ * @returns The expected Misskey label, pinned revision, and applied rule.
25
+ */
26
+ declare function classifyMisskey(object: AddressingRows, _activity: AddressingRows | null, author: Author): ExpectedClassification;
27
+ /**
28
+ * Converts stored addressing while preserving absent properties for fallback.
29
+ * @returns Addressing suitable for the classification rules.
30
+ */
31
+ declare function classificationInput(row: {
32
+ document: unknown;
33
+ addressing: readonly {
34
+ property: string;
35
+ position: number;
36
+ targetResource: {
37
+ iri: string;
38
+ };
39
+ }[];
40
+ }): AddressingRows;
41
+ /**
42
+ * Extracts the object author's canonical IRI and declared followers IRI: a
43
+ * local actor's followers collection, or the one a remote actor declares.
44
+ * @returns The author identifiers used by the classification rules.
45
+ */
46
+ declare function classificationAuthor(actor: {
47
+ resource: {
48
+ iri: string;
49
+ };
50
+ followersUrl: string | null;
51
+ collectionReferences: readonly {
52
+ role: string;
53
+ collection: {
54
+ resource: {
55
+ iri: string;
56
+ };
57
+ };
58
+ }[];
59
+ }): Author;
60
+ //#endregion
61
+ export { AddressingRows, ExpectedClassification, classificationAuthor, classificationInput, classifyMastodon, classifyMisskey };
62
+ //# sourceMappingURL=classification.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classification.d.mts","names":[],"sources":["../src/classification.ts"],"mappings":";;UAwBiB;WACN;WACA;;UAEM;WACN;WACA;WACA;WACA;;UAED;WACC;WACA;;;;;;iBAQK,iBACd,QAAQ,gBACR,UAAU,uBACV,QAAQ,SACP;;;;;iBAyBa,gBACd,QAAQ,gBACR,WAAW,uBACX,QAAQ,SACP;;;;;iBA0Ba,oBAAoB;EAClC;EACA;IACE;IACA;IACA;MAAkB;;;IAElB;;;;;;iBAsBY,qBAAqB;EACnC;IAAY;;EACZ;EACA;IACE;IACA;MAAc;QAAY;;;;IAE1B"}
@@ -0,0 +1,65 @@
1
+ import { t as PUBLIC_IRIS } from "./readable-CSN0MPlO.mjs";
2
+ //#region src/classification.ts
3
+ const isPublic = (iri) => PUBLIC_IRIS.includes(iri);
4
+ /**
5
+ * Expected Mastodon classification, independent of receiver state or policy.
6
+ * @returns The expected Mastodon label, pinned revision, and applied rule.
7
+ */
8
+ function classifyMastodon(object, activity, author) {
9
+ const to = object.to ?? activity?.to ?? [];
10
+ const cc = object.cc ?? activity?.cc ?? [];
11
+ const [classification, rule] = to.some(isPublic) ? ["public", "Public is in to"] : cc.some(isPublic) ? ["unlisted", "Public is in cc"] : author.followersIri != null && to.includes(author.followersIri) ? ["private", "The author's followers collection is in to"] : ["direct", "Neither Public nor the author's followers collection occurs in to, and Public is absent from cc"];
12
+ return {
13
+ implementation: "MASTODON",
14
+ version: "fba604991b404096878932691b7673c61357f65c",
15
+ classification,
16
+ reason: `Expected: ${rule}. Missing object properties fall back to the activity. Receiver state and policy can change access.`
17
+ };
18
+ }
19
+ /**
20
+ * Expected Misskey classification; activity addressing is deliberately unused.
21
+ * @returns The expected Misskey label, pinned revision, and applied rule.
22
+ */
23
+ function classifyMisskey(object, _activity, author) {
24
+ const to = object.to ?? [];
25
+ const cc = object.cc ?? [];
26
+ const followers = author.followersIri ?? `${author.iri}/followers`;
27
+ const [classification, rule] = to.some(isPublic) ? ["public", "Public is in to"] : cc.some(isPublic) ? ["home", "Public is in cc"] : [...to, ...cc].includes(followers) ? ["followers", "The author's followers collection is in to or cc"] : ["specified", "Public and the author's followers collection are absent from to and cc"];
28
+ return {
29
+ implementation: "MISSKEY",
30
+ version: "5e52f8609913a7a4f8bc76cbe26c2b99938310ae",
31
+ classification,
32
+ reason: `Expected: ${rule}. Only object addressing is considered. Receiver state and policy can change access.`
33
+ };
34
+ }
35
+ /**
36
+ * Converts stored addressing while preserving absent properties for fallback.
37
+ * @returns Addressing suitable for the classification rules.
38
+ */
39
+ function classificationInput(row) {
40
+ const property = (name) => {
41
+ const rows = row.addressing.filter((entry) => entry.property === name).toSorted((left, right) => left.position - right.position);
42
+ if (rows.length > 0) return rows.map((entry) => entry.targetResource.iri);
43
+ const { document } = row;
44
+ return document != null && typeof document === "object" && name in document && document[name] != null ? [] : void 0;
45
+ };
46
+ return {
47
+ to: property("to"),
48
+ cc: property("cc")
49
+ };
50
+ }
51
+ /**
52
+ * Extracts the object author's canonical IRI and declared followers IRI: a
53
+ * local actor's followers collection, or the one a remote actor declares.
54
+ * @returns The author identifiers used by the classification rules.
55
+ */
56
+ function classificationAuthor(actor) {
57
+ return {
58
+ iri: actor.resource.iri,
59
+ followersIri: actor.collectionReferences.find((entry) => entry.role === "followers")?.collection.resource.iri ?? actor.followersUrl ?? null
60
+ };
61
+ }
62
+ //#endregion
63
+ export { classificationAuthor, classificationInput, classifyMastodon, classifyMisskey };
64
+
65
+ //# sourceMappingURL=classification.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classification.mjs","names":[],"sources":["../src/classification.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\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 published by\n// the Free Software Foundation, either version 3 of the License, or\n// (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/>.\n\n// Rules verified at these upstream revisions:\n// mastodon/mastodon fba604991b404096878932691b7673c61357f65c\n// app/lib/activitypub/parser/status_parser.rb and app/lib/activitypub/tag_manager.rb\n// misskey-dev/misskey 5e52f8609913a7a4f8bc76cbe26c2b99938310ae\n// packages/backend/src/core/activitypub/ApAudienceService.ts\nimport { PUBLIC_IRIS } from \"./readable.ts\";\n\n/** Missing/null properties permit Mastodon's activity fallback; [] does not. */\nexport interface AddressingRows {\n readonly to?: readonly string[] | null | undefined;\n readonly cc?: readonly string[] | null | undefined;\n}\nexport interface ExpectedClassification {\n readonly implementation: \"MASTODON\" | \"MISSKEY\";\n readonly version: string;\n readonly classification: string;\n readonly reason: string;\n}\ninterface Author {\n readonly followersIri: string | null;\n readonly iri: string;\n}\nconst isPublic = (iri: string): boolean => PUBLIC_IRIS.includes(iri);\n\n/**\n * Expected Mastodon classification, independent of receiver state or policy.\n * @returns The expected Mastodon label, pinned revision, and applied rule.\n */\nexport function classifyMastodon(\n object: AddressingRows,\n activity: AddressingRows | null,\n author: Author,\n): ExpectedClassification {\n const to = object.to ?? activity?.to ?? [];\n const cc = object.cc ?? activity?.cc ?? [];\n const [classification, rule]: readonly [string, string] = to.some(isPublic)\n ? [\"public\", \"Public is in to\"]\n : cc.some(isPublic)\n ? [\"unlisted\", \"Public is in cc\"]\n : author.followersIri != null && to.includes(author.followersIri)\n ? [\"private\", \"The author's followers collection is in to\"]\n : [\n \"direct\",\n \"Neither Public nor the author's followers collection occurs in to, and Public is absent from cc\",\n ];\n return {\n implementation: \"MASTODON\",\n version: \"fba604991b404096878932691b7673c61357f65c\",\n classification,\n reason: `Expected: ${rule}. Missing object properties fall back to the activity. Receiver state and policy can change access.`,\n };\n}\n\n/**\n * Expected Misskey classification; activity addressing is deliberately unused.\n * @returns The expected Misskey label, pinned revision, and applied rule.\n */\nexport function classifyMisskey(\n object: AddressingRows,\n _activity: AddressingRows | null,\n author: Author,\n): ExpectedClassification {\n const to = object.to ?? [];\n const cc = object.cc ?? [];\n const followers = author.followersIri ?? `${author.iri}/followers`;\n const [classification, rule]: readonly [string, string] = to.some(isPublic)\n ? [\"public\", \"Public is in to\"]\n : cc.some(isPublic)\n ? [\"home\", \"Public is in cc\"]\n : [...to, ...cc].includes(followers)\n ? [\"followers\", \"The author's followers collection is in to or cc\"]\n : [\n \"specified\",\n \"Public and the author's followers collection are absent from to and cc\",\n ];\n return {\n implementation: \"MISSKEY\",\n version: \"5e52f8609913a7a4f8bc76cbe26c2b99938310ae\",\n classification,\n reason: `Expected: ${rule}. Only object addressing is considered. Receiver state and policy can change access.`,\n };\n}\n\n/**\n * Converts stored addressing while preserving absent properties for fallback.\n * @returns Addressing suitable for the classification rules.\n */\nexport function classificationInput(row: {\n document: unknown;\n addressing: readonly {\n property: string;\n position: number;\n targetResource: { iri: string };\n }[];\n}): AddressingRows {\n const property = (name: \"to\" | \"cc\"): readonly string[] | undefined => {\n const rows = row.addressing\n .filter((entry) => entry.property === name)\n .toSorted((left, right) => left.position - right.position);\n if (rows.length > 0) return rows.map((entry) => entry.targetResource.iri);\n const { document } = row;\n return document != null &&\n typeof document === \"object\" &&\n name in document &&\n document[name as keyof typeof document] != null\n ? []\n : undefined;\n };\n return { to: property(\"to\"), cc: property(\"cc\") };\n}\n\n/**\n * Extracts the object author's canonical IRI and declared followers IRI: a\n * local actor's followers collection, or the one a remote actor declares.\n * @returns The author identifiers used by the classification rules.\n */\nexport function classificationAuthor(actor: {\n resource: { iri: string };\n followersUrl: string | null;\n collectionReferences: readonly {\n role: string;\n collection: { resource: { iri: string } };\n }[];\n}): Author {\n return {\n iri: actor.resource.iri,\n followersIri:\n actor.collectionReferences.find((entry) => entry.role === \"followers\")\n ?.collection.resource.iri ??\n actor.followersUrl ??\n null,\n };\n}\n"],"mappings":";;AAsCA,MAAM,YAAY,QAAyB,YAAY,SAAS,GAAG;;;;;AAMnE,SAAgB,iBACd,QACA,UACA,QACwB;CACxB,MAAM,KAAK,OAAO,MAAM,UAAU,MAAM,CAAC;CACzC,MAAM,KAAK,OAAO,MAAM,UAAU,MAAM,CAAC;CACzC,MAAM,CAAC,gBAAgB,QAAmC,GAAG,KAAK,QAAQ,IACtE,CAAC,UAAU,iBAAiB,IAC5B,GAAG,KAAK,QAAQ,IACd,CAAC,YAAY,iBAAiB,IAC9B,OAAO,gBAAgB,QAAQ,GAAG,SAAS,OAAO,YAAY,IAC5D,CAAC,WAAW,4CAA4C,IACxD,CACE,UACA,iGACF;CACR,OAAO;EACL,gBAAgB;EAChB,SAAS;EACT;EACA,QAAQ,aAAa,KAAK;CAC5B;AACF;;;;;AAMA,SAAgB,gBACd,QACA,WACA,QACwB;CACxB,MAAM,KAAK,OAAO,MAAM,CAAC;CACzB,MAAM,KAAK,OAAO,MAAM,CAAC;CACzB,MAAM,YAAY,OAAO,gBAAgB,GAAG,OAAO,IA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