@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,600 @@
1
+ import { n as builder } from "./builder-BLioFAdv.mjs";
2
+ import { a as readableResource, r as isReadableResource } from "./readable-CSN0MPlO.mjs";
3
+ import { Instance } from "./instance.mjs";
4
+ import { classificationAuthor, classificationInput, classifyMastodon, classifyMisskey } from "./classification.mjs";
5
+ import { actorTypeEnum } from "@drfed/models/schema";
6
+ import { drizzleConnectionHelpers } from "@pothos/plugin-drizzle";
7
+ import { and, eq, gt, isNotNull, isNull } from "drizzle-orm/sql/expressions";
8
+ import { promoteResource, schema } from "@drfed/models";
9
+ import { PothosValidationError } from "@pothos/core";
10
+ import { resolveCursorConnection } from "@pothos/plugin-relay";
11
+ import { uuidV7, validateUuid } from "@drfed/models/uuid";
12
+ import { and as and$1, eq as eq$1, sql } from "drizzle-orm";
13
+ import { enqueueActorKeyGeneration } from "@drfed/federation";
14
+ import { faker } from "@faker-js/faker";
15
+ import { activitySelection, objectSelection } from "@drfed/federation/object";
16
+ //#region src/resource.ts
17
+ const ResourceKind = builder.enumType("ResourceKind", { values: schema.resourceKindEnum.enumValues });
18
+ const ResourceDetail = builder.unionType("ResourceDetail", {
19
+ types: () => [Activity, Collection],
20
+ resolveType: async (value, ctx) => {
21
+ const { id } = value;
22
+ const row = await ctx.db.query.resources.findFirst({ where: { id } });
23
+ if (row == null || row.kind === "unknown") throw new Error("Missing typed resource.");
24
+ return {
25
+ actor: "Actor",
26
+ object: "Object",
27
+ activity: "Activity",
28
+ collection: "Collection"
29
+ }[row.kind];
30
+ }
31
+ });
32
+ const Resource = builder.drizzleNode("resources", {
33
+ name: "Resource",
34
+ id: { column: (row) => row.id },
35
+ fields: (t) => ({
36
+ iri: t.expose("iri", { type: "URL" }),
37
+ kind: t.expose("kind", { type: ResourceKind }),
38
+ detail: t.field({
39
+ type: ResourceDetail,
40
+ nullable: true,
41
+ description: "Typed details, or null while unknown, when the typed row or its author/owner is deleted, or when the viewer may not read it.",
42
+ select: { columns: {
43
+ id: true,
44
+ iri: true,
45
+ kind: true
46
+ } },
47
+ resolve: (row, _, ctx) => resolveResource(ctx, row)
48
+ })
49
+ })
50
+ });
51
+ /**
52
+ * Loads the typed record so union fragments see the complete entity.
53
+ * @returns The typed entity, or null when it or its author is deleted, or when
54
+ * the viewer may not read it.
55
+ */
56
+ async function resolveResource(viewer, row) {
57
+ const { db } = viewer;
58
+ if (await db.query.resources.findFirst({
59
+ where: {
60
+ id: row.id,
61
+ RAW: (table) => and$1(visibleResource(table.id), readableResource(viewer, table.id))
62
+ },
63
+ columns: { id: true }
64
+ }) == null) return null;
65
+ if (row.kind === "unknown") return null;
66
+ const where = { id: row.id };
67
+ const result = row.kind === "actor" ? await db.query.actors.findFirst({ where }) : row.kind === "object" ? await db.query.objects.findFirst({ where }) : row.kind === "activity" ? await db.query.activities.findFirst({ where }) : await db.query.collections.findFirst({ where });
68
+ if (result == null) throw new Error(`Missing ${row.kind} record for ${row.iri}.`);
69
+ return result;
70
+ }
71
+ function registerAddressingFields(table) {
72
+ for (const property of schema.addressingPropertyEnum.enumValues) builder.drizzleObjectField(table, property, (t) => t.field({
73
+ type: [Resource],
74
+ description: `Stored ${property} occurrences, in original order including duplicates.`,
75
+ select: { columns: { id: true } },
76
+ resolve: async (row, _, ctx) => (await ctx.db.query.addressing.findMany({
77
+ where: {
78
+ sourceId: row.id,
79
+ property
80
+ },
81
+ orderBy: { position: "asc" },
82
+ with: { targetResource: true }
83
+ })).map((entry) => entry.targetResource)
84
+ }));
85
+ }
86
+ const CollectionType = builder.enumType("CollectionType", { values: schema.collectionTypeEnum.enumValues });
87
+ const Collection = builder.drizzleNode("collections", {
88
+ name: "Collection",
89
+ select: {
90
+ columns: { id: true },
91
+ with: { ownerActor: { columns: { deleted: true } } }
92
+ },
93
+ id: { column: (row) => row.id },
94
+ fields: (t) => ({
95
+ resource: t.relation("resource"),
96
+ iri: t.field({
97
+ type: "URL",
98
+ select: { with: { resource: true } },
99
+ resolve: (row) => row.resource.iri
100
+ }),
101
+ type: t.expose("type", { type: CollectionType }),
102
+ owner: t.relation("ownerActor", {
103
+ nullable: true,
104
+ query: { where: { deleted: { isNull: true } } }
105
+ }),
106
+ declaredTotalItems: t.exposeInt("totalItems", {
107
+ nullable: true,
108
+ description: "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."
109
+ }),
110
+ totalCount: t.int({
111
+ description: "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`.",
112
+ select: { columns: { id: true } },
113
+ resolve: (row, _, ctx) => ctx.db.$count(schema.collectionItems, and$1(eq$1(schema.collectionItems.collectionId, row.id), visibleResource(schema.collectionItems.itemId), readableResource(ctx, schema.collectionItems.itemId)))
114
+ }),
115
+ items: t.connection({
116
+ type: Resource,
117
+ description: "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`.",
118
+ select: { columns: { id: true } },
119
+ resolve: (row, args, ctx) => {
120
+ const positions = /* @__PURE__ */ new Map();
121
+ return resolveCursorConnection({
122
+ args,
123
+ toCursor: (item) => {
124
+ if (!positions.has(item.id)) throw new Error("Missing collection item position.");
125
+ return encodeCollectionCursor({
126
+ position: positions.get(item.id),
127
+ itemId: item.id
128
+ });
129
+ }
130
+ }, async ({ before, after, limit, inverted }) => {
131
+ const parsedBefore = before == null ? void 0 : parseCollectionCursor(before);
132
+ const parsedAfter = after == null ? void 0 : parseCollectionCursor(after);
133
+ const items = await ctx.db.query.collectionItems.findMany({
134
+ where: {
135
+ collectionId: row.id,
136
+ RAW: (table) => and$1(visibleResource(table.itemId), readableResource(ctx, table.itemId), collectionCursorPredicate(table.position, table.itemId, parsedBefore, parsedAfter))
137
+ },
138
+ orderBy: collectionItemsOrder(inverted),
139
+ limit,
140
+ with: { item: true }
141
+ });
142
+ for (const item of items) positions.set(item.itemId, item.position);
143
+ return items.map((item) => item.item);
144
+ });
145
+ }
146
+ })
147
+ })
148
+ });
149
+ const BASE64_PATTERN = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/u;
150
+ function encodeCollectionCursor(cursor) {
151
+ return Buffer.from(JSON.stringify([cursor.position, cursor.itemId])).toString("base64");
152
+ }
153
+ function parseCollectionCursor(cursor) {
154
+ if (cursor === "" || !BASE64_PATTERN.test(cursor)) throw new PothosValidationError("Invalid collection cursor.");
155
+ const decoded = Buffer.from(cursor, "base64");
156
+ if (decoded.toString("base64") !== cursor) throw new PothosValidationError("Invalid collection cursor.");
157
+ let value;
158
+ try {
159
+ value = JSON.parse(decoded.toString("utf8"));
160
+ } catch {
161
+ throw new PothosValidationError("Invalid collection cursor.");
162
+ }
163
+ if (!Array.isArray(value) || value.length !== 2) throw new PothosValidationError("Invalid collection cursor.");
164
+ const [position, itemId] = value;
165
+ if (position !== null && (!Number.isInteger(position) || position < -2147483648 || position > 2147483647) || !validateUuid(itemId)) throw new PothosValidationError("Invalid collection cursor.");
166
+ return {
167
+ position,
168
+ itemId
169
+ };
170
+ }
171
+ function collectionCursorPredicate(positionColumn, itemIdColumn, before, after) {
172
+ return and$1(after == null ? void 0 : after.position == null ? sql`${positionColumn} is null and ${itemIdColumn} > ${after.itemId}` : sql`(
173
+ ${positionColumn} > ${after.position}
174
+ or (${positionColumn} = ${after.position} and ${itemIdColumn} > ${after.itemId})
175
+ or ${positionColumn} is null
176
+ )`, before == null ? void 0 : before.position == null ? sql`(
177
+ ${positionColumn} is not null
178
+ or (${positionColumn} is null and ${itemIdColumn} < ${before.itemId})
179
+ )` : sql`(
180
+ ${positionColumn} < ${before.position}
181
+ or (${positionColumn} = ${before.position} and ${itemIdColumn} < ${before.itemId})
182
+ )`);
183
+ }
184
+ function collectionItemsOrder(inverted) {
185
+ const direction = inverted ? "desc" : "asc";
186
+ return {
187
+ position: direction,
188
+ itemId: direction
189
+ };
190
+ }
191
+ const Implementation = builder.enumType("Implementation", { values: ["MASTODON", "MISSKEY"] });
192
+ const ExpectedClassification = builder.objectRef("ExpectedClassification");
193
+ ExpectedClassification.implement({
194
+ description: "Expected classification; actual access depends on receiver state and policy.",
195
+ fields: (t) => ({
196
+ implementation: t.expose("implementation", { type: Implementation }),
197
+ version: t.exposeString("version"),
198
+ classification: t.exposeString("classification"),
199
+ reason: t.exposeString("reason")
200
+ })
201
+ });
202
+ const ActivityType = builder.enumType("ActivityType", { values: schema.activityTypeEnum.enumValues });
203
+ const Activity = builder.drizzleNode("activities", {
204
+ name: "Activity",
205
+ description: "Represents an ActivityPub activity. An activity of a local actor is readable whatever its addressing. One of a remote actor is readable only when it is addressed to the public, by members of the local instances that received it, and by administrators; otherwise it is left out as if it did not exist.",
206
+ select: {
207
+ columns: { id: true },
208
+ with: { actor: { columns: { deleted: true } } }
209
+ },
210
+ id: { column: (row) => row.id },
211
+ fields: (t) => ({
212
+ resource: t.relation("resource"),
213
+ iri: t.field({
214
+ type: "URL",
215
+ select: { with: { resource: true } },
216
+ resolve: (row) => row.resource.iri
217
+ }),
218
+ type: t.expose("type", { type: ActivityType }),
219
+ actor: t.relation("actor"),
220
+ object: t.field({
221
+ type: Resource,
222
+ nullable: true,
223
+ description: "The resource the activity acts on, or null when there is none or the viewer may not read it.",
224
+ select: { with: { object: true } },
225
+ resolve: async (row, _, ctx) => row.object != null && await isReadableResource(ctx, row.object.id) ? row.object : null
226
+ }),
227
+ expectedClassifications: t.field({
228
+ type: [ExpectedClassification],
229
+ description: "Expected classifications for this activity and its Object. Empty if the object is absent, hidden, or not an Object.",
230
+ select: { columns: { id: true } },
231
+ resolve: async (activity, _, ctx) => {
232
+ const row = await ctx.db.query.activities.findFirst({
233
+ where: { id: activity.id },
234
+ with: activitySelection
235
+ });
236
+ if (row?.objectId == null || !await isReadableResource(ctx, row.objectId)) return [];
237
+ const object = await ctx.db.query.objects.findFirst({
238
+ where: {
239
+ id: row.objectId,
240
+ deleted: { isNull: true },
241
+ actor: { deleted: { isNull: true } }
242
+ },
243
+ with: {
244
+ ...objectSelection,
245
+ actor: { with: {
246
+ resource: true,
247
+ collectionReferences: { with: { collection: { with: { resource: true } } } }
248
+ } }
249
+ }
250
+ });
251
+ if (object == null) return [];
252
+ const addressing = classificationInput(object);
253
+ const input = classificationInput(row);
254
+ const author = classificationAuthor(object.actor);
255
+ return [classifyMastodon(addressing, input, author), classifyMisskey(addressing, input, author)];
256
+ }
257
+ }),
258
+ published: t.expose("published", { type: "DateTime" }),
259
+ document: t.expose("document", {
260
+ type: "JSON",
261
+ nullable: true
262
+ })
263
+ })
264
+ });
265
+ registerAddressingFields("activities");
266
+ /**
267
+ * Excludes deleted actors and objects, including resources authored or
268
+ * owned by deleted actors.
269
+ * @returns A predicate for a resource ID in an outer query.
270
+ */
271
+ function visibleResource(id) {
272
+ return sql`not exists (
273
+ select 1 from ${schema.actors}
274
+ where ${schema.actors.id} = ${id} and ${schema.actors.deleted} is not null
275
+ ) and not exists (
276
+ select 1 from ${schema.objects}
277
+ join ${schema.actors} on ${schema.actors.id} = ${schema.objects.actorId}
278
+ where ${schema.objects.id} = ${id}
279
+ and (${schema.objects.deleted} is not null or ${schema.actors.deleted} is not null)
280
+ ) and not exists (
281
+ select 1 from ${schema.activities}
282
+ join ${schema.actors} on ${schema.actors.id} = ${schema.activities.actorId}
283
+ where ${schema.activities.id} = ${id} and ${schema.actors.deleted} is not null
284
+ ) and not exists (
285
+ select 1 from ${schema.collections}
286
+ join ${schema.actors} on ${schema.actors.id} = ${schema.collections.ownerActorId}
287
+ where ${schema.collections.id} = ${id} and ${schema.actors.deleted} is not null
288
+ )`;
289
+ }
290
+ //#endregion
291
+ //#region src/actor.ts
292
+ const ActorType = builder.enumType("ActorType", { values: actorTypeEnum.enumValues });
293
+ const ACTOR_TYPES_DOC = actorTypeEnum.enumValues.map((t) => `\`${t}\``).join(" | ");
294
+ async function resolveActorCollection(db, actorId, role) {
295
+ const collection = (await db.query.actorCollectionReferences.findFirst({
296
+ where: {
297
+ actorId,
298
+ role
299
+ },
300
+ with: { collection: { with: { ownerActor: { columns: { deleted: true } } } } }
301
+ }))?.collection;
302
+ return collection?.ownerActor?.deleted == null ? collection ?? null : null;
303
+ }
304
+ const USERNAME_DOC = "The username of the `Actor`. A remote actor's is its `preferredUsername` as received, which is null when it has none and need not be unique.";
305
+ const ActorRef = builder.drizzleNode("actors", {
306
+ name: "Actor",
307
+ description: "Represents an `Actor` in the DrFed platform.",
308
+ id: {
309
+ column: ({ id }) => id,
310
+ description: "The unique identifier of the `Actor`."
311
+ },
312
+ fields: (t) => ({
313
+ resource: t.relation("resource"),
314
+ iri: t.field({
315
+ type: "URL",
316
+ select: { with: { resource: true } },
317
+ resolve: (row) => row.resource.iri
318
+ }),
319
+ uuid: t.expose("id", {
320
+ type: "UUID",
321
+ description: "The UUID of the `Actor`."
322
+ }),
323
+ handle: t.field({
324
+ type: "String",
325
+ nullable: true,
326
+ description: "The handle of the `Actor`, its `username` and its `Instance`'s host. For a remote actor, this is not a verified WebFinger address. Null when `username` is.",
327
+ select: {
328
+ columns: { username: true },
329
+ with: { instance: { columns: { host: true } } }
330
+ },
331
+ resolve: ({ instance, username }) => username == null ? null : `@${username}@${instance.host}`
332
+ }),
333
+ type: t.expose("type", {
334
+ type: ActorType,
335
+ description: `The type of the \`Actor\`: ${ACTOR_TYPES_DOC}`
336
+ }),
337
+ username: t.exposeString("username", {
338
+ nullable: true,
339
+ description: USERNAME_DOC
340
+ }),
341
+ instance: t.relation("instance", { description: "The `Instance` that the `Actor` belongs to." }),
342
+ local: t.relation("localActor", {
343
+ nullable: true,
344
+ description: "The local details of the `Actor`, or null if it is remote."
345
+ }),
346
+ inboxUrl: t.expose("inboxUrl", {
347
+ type: "URL",
348
+ description: "The inbox URL of the `Actor`."
349
+ }),
350
+ outbox: t.field({
351
+ type: Collection,
352
+ nullable: true,
353
+ description: "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.",
354
+ select: { columns: { id: true } },
355
+ resolve: (actor, _, ctx) => resolveActorCollection(ctx.db, actor.id, "outbox")
356
+ }),
357
+ avatarUrl: t.expose("avatarUrl", {
358
+ type: "URL",
359
+ description: "The avatar URL of the `Actor`.",
360
+ nullable: true
361
+ }),
362
+ followers: t.field({
363
+ type: Collection,
364
+ nullable: true,
365
+ select: { columns: { id: true } },
366
+ resolve: (actor, _, ctx) => resolveActorCollection(ctx.db, actor.id, "followers")
367
+ }),
368
+ following: t.field({
369
+ type: Collection,
370
+ nullable: true,
371
+ select: { columns: { id: true } },
372
+ resolve: (actor, _, ctx) => resolveActorCollection(ctx.db, actor.id, "following")
373
+ }),
374
+ headerUrl: t.expose("headerUrl", {
375
+ type: "URL",
376
+ description: "The header URL of the `Actor`.",
377
+ nullable: true
378
+ }),
379
+ profileUrl: t.expose("profileUrl", {
380
+ type: "URL",
381
+ description: "The profile URL of the `Actor`.",
382
+ nullable: true
383
+ }),
384
+ featured: t.field({
385
+ type: Collection,
386
+ nullable: true,
387
+ select: { columns: { id: true } },
388
+ resolve: (actor, _, ctx) => resolveActorCollection(ctx.db, actor.id, "featured")
389
+ }),
390
+ created: t.expose("created", {
391
+ type: "DateTime",
392
+ description: "The creation date/time of the `Actor`."
393
+ })
394
+ })
395
+ });
396
+ const Actor = ActorRef;
397
+ ResourceDetail.addTypes([Actor]);
398
+ const LocalActor = builder.drizzleNode("localActors", {
399
+ name: "LocalActor",
400
+ select: {
401
+ columns: { id: true },
402
+ with: { actor: { columns: { deleted: true } } }
403
+ },
404
+ description: "Represents the local details of an `Actor`.",
405
+ id: {
406
+ column: ({ id }) => id,
407
+ description: "The unique identifier of the local actor details."
408
+ },
409
+ fields: (t) => ({
410
+ uuid: t.expose("id", {
411
+ type: "UUID",
412
+ description: "The UUID of the local actor details."
413
+ }),
414
+ avatar: t.exposeString("avatar", {
415
+ nullable: true,
416
+ description: "The profile image of the actor."
417
+ }),
418
+ header: t.exposeString("header", {
419
+ nullable: true,
420
+ description: "The profile banner image of the actor."
421
+ })
422
+ })
423
+ });
424
+ const CreateActorsSuccessRef = builder.objectRef("CreateActorsSuccess");
425
+ CreateActorsSuccessRef.implement({ fields: (t) => ({ actors: t.field({
426
+ type: [ActorRef],
427
+ resolve: ({ actors }) => actors
428
+ }) }) });
429
+ const INVALID_SIZE = "InvalidSize";
430
+ const INSTANCE_NOT_FOUND = "InstanceNotFound";
431
+ const INVALID_INSTANCE_HOST = "InvalidInstanceHost";
432
+ const TOO_MANY_ACTORS = "TooManyActors";
433
+ const CreateActorsErrors = [
434
+ INVALID_SIZE,
435
+ INSTANCE_NOT_FOUND,
436
+ INVALID_INSTANCE_HOST,
437
+ TOO_MANY_ACTORS
438
+ ];
439
+ const CreateActorsErrorType = builder.enumType("CreateActorsErrorType", { values: CreateActorsErrors });
440
+ const CreateActorsErrorRef = builder.objectRef("CreateActorsError");
441
+ CreateActorsErrorRef.implement({
442
+ description: "Represents an error that occurred while creating an `Actor`.",
443
+ fields: (t) => ({
444
+ type: t.expose("type", {
445
+ type: CreateActorsErrorType,
446
+ description: "The type of the error. Use this for programmatic error handling."
447
+ }),
448
+ message: t.exposeString("message", { description: "A human-readable message describing the error. Don't use this for programmatic error handling, use the `type` field instead." })
449
+ })
450
+ });
451
+ const CreateActorsResult = builder.unionType("CreateActorsResult", {
452
+ types: [CreateActorsSuccessRef, CreateActorsErrorRef],
453
+ resolveType(value) {
454
+ if ("message" in value) return CreateActorsErrorRef;
455
+ return CreateActorsSuccessRef;
456
+ }
457
+ });
458
+ builder.mutationFields((t) => ({ generateActors: t.field({
459
+ type: CreateActorsResult,
460
+ description: "Create actors.",
461
+ authScopes: { authenticated: true },
462
+ args: {
463
+ instance: t.arg.globalID({
464
+ for: Instance,
465
+ required: true,
466
+ description: "The ID of the target instance"
467
+ }),
468
+ size: t.arg({
469
+ type: "Int",
470
+ required: true,
471
+ description: "How many actors to generate"
472
+ })
473
+ },
474
+ async resolve(_query, { instance: { id: instanceId }, size }, ctx) {
475
+ if (size < 1) return {
476
+ type: INVALID_SIZE,
477
+ message: `${size} is too small. At least 1 or more.`
478
+ };
479
+ if (ctx.account == null) throw new Error("You must be authenticated to create actors.");
480
+ const { account } = ctx;
481
+ const targetInstanceId = instanceId;
482
+ let createdOrigin;
483
+ const result = await ctx.db.transaction(async (tx) => {
484
+ const [instance] = await tx.select({
485
+ host: schema.instances.host,
486
+ maxActors: schema.localInstances.maxActors
487
+ }).from(schema.instanceMembers).for("update", { of: schema.localInstances }).innerJoin(schema.instances, eq(schema.instanceMembers.instanceId, schema.instances.id)).innerJoin(schema.localInstances, eq(schema.instances.localId, schema.localInstances.id)).where(and(eq(schema.instanceMembers.accountId, account.id), gt(schema.localInstances.expires, Temporal.Now.instant()), eq(schema.instances.id, targetInstanceId), isNotNull(schema.instanceMembers.accepted))).limit(1);
488
+ if (instance == null) return {
489
+ type: INSTANCE_NOT_FOUND,
490
+ message: "Can't find the instance."
491
+ };
492
+ const { host, maxActors } = instance;
493
+ const instanceUrl = `${ctx.rootOrigin.protocol}//${host}`;
494
+ if (!URL.canParse(instanceUrl)) return {
495
+ type: INVALID_INSTANCE_HOST,
496
+ message: `The instance host ${JSON.stringify(host)} cannot be parsed by this server. Contact the server administrator.`
497
+ };
498
+ const currActors = await tx.$count(schema.actors, eq(schema.actors.instanceId, targetInstanceId));
499
+ if (size + currActors > maxActors) return {
500
+ type: TOO_MANY_ACTORS,
501
+ message: `${size} is too big. The maximum number of actors of ${host} is ${maxActors} and the current number of actors is ${currActors}.`
502
+ };
503
+ createdOrigin = new URL(instanceUrl);
504
+ const fedCtx = ctx.federation.createContext(new URL(instanceUrl), void 0);
505
+ const ids = Array.from({ length: size }, () => ({ id: uuidV7() }));
506
+ await tx.insert(schema.localActors).values(ids);
507
+ const createdActors = [];
508
+ for (const { id } of ids) {
509
+ const actor = await promoteResource(tx, fedCtx.getActorUri(id).href, "actor", async (inner, resource) => {
510
+ for (let attempt = 0; attempt < 10; attempt += 1) {
511
+ const [createdActor] = await inner.insert(schema.actors).values(generateActor(resource.id, targetInstanceId, fedCtx)).onConflictDoNothing({
512
+ target: [schema.actors.username, schema.actors.instanceId],
513
+ where: isNotNull(schema.actors.localId)
514
+ }).returning();
515
+ if (createdActor != null) return createdActor;
516
+ }
517
+ throw new Error("Actor insertion returned no row.");
518
+ }, id);
519
+ for (const [role, iri] of [
520
+ ["followers", fedCtx.getFollowersUri(id).href],
521
+ ["following", fedCtx.getFollowingUri(id).href],
522
+ ["featured", fedCtx.getFeaturedUri(id).href],
523
+ ["outbox", fedCtx.getOutboxUri(id).href]
524
+ ]) await promoteResource(tx, iri, "collection", async (inner, resource) => {
525
+ await inner.insert(schema.collections).values({
526
+ id: resource.id,
527
+ type: "OrderedCollection",
528
+ ownerActorId: actor.id
529
+ });
530
+ await inner.insert(schema.actorCollectionReferences).values({
531
+ actorId: actor.id,
532
+ role,
533
+ collectionId: resource.id
534
+ });
535
+ });
536
+ createdActors.push(actor);
537
+ }
538
+ return { actors: createdActors };
539
+ });
540
+ if ("actors" in result && createdOrigin != null) await enqueueActorKeyGeneration(ctx.federation.createContext(createdOrigin, void 0), result.actors.map((actor) => actor.id));
541
+ return result;
542
+ }
543
+ }) }));
544
+ function generateActor(id, instanceId, fedCtx) {
545
+ const username = faker.internet.username().toLowerCase().replace(/[^a-z0-9_]/gu, "_");
546
+ return {
547
+ id,
548
+ localId: id,
549
+ username,
550
+ instanceId,
551
+ type: "Person",
552
+ inboxUrl: fedCtx.getInboxUri(id).href,
553
+ profileUrl: new URL(`/@${username}`, fedCtx.origin).href
554
+ };
555
+ }
556
+ const actorsConnection = drizzleConnectionHelpers(builder, "actors", { query: { orderBy: {
557
+ created: "desc",
558
+ id: "desc"
559
+ } } });
560
+ builder.drizzleObjectField("instances", "actors", (t) => t.connection({
561
+ type: Actor,
562
+ description: "The `Actor`s that belong to the `Instance`.",
563
+ select(args, ctx, nestedSelection) {
564
+ return { with: { actors: actorsConnection.getQuery(args, ctx, nestedSelection) } };
565
+ },
566
+ resolve(instance, args, ctx) {
567
+ return {
568
+ ...actorsConnection.resolve(instance.actors, args, ctx, instance),
569
+ totalCount() {
570
+ return ctx.db.$count(schema.actors, and(eq(schema.actors.instanceId, instance.id), isNull(schema.actors.deleted)));
571
+ }
572
+ };
573
+ }
574
+ }, { fields(fb) {
575
+ return { totalCount: fb.int({
576
+ description: "The total number of `Actor`s that belong to the `Instance`.",
577
+ resolve(connection) {
578
+ return connection.totalCount();
579
+ }
580
+ }) };
581
+ } }, { fields(fb) {
582
+ return {
583
+ created: fb.expose("created", {
584
+ type: "DateTime",
585
+ description: "The date/time when the `Actor` was added to the `Instance`."
586
+ }),
587
+ type: fb.expose("type", {
588
+ type: ActorType,
589
+ description: `The type of the \`Actor\`: ${ACTOR_TYPES_DOC}`
590
+ }),
591
+ username: fb.exposeString("username", {
592
+ nullable: true,
593
+ description: USERNAME_DOC
594
+ })
595
+ };
596
+ } }));
597
+ //#endregion
598
+ export { ResourceDetail as a, ActivityType as i, LocalActor as n, registerAddressingFields as o, Activity as r, Actor as t };
599
+
600
+ //# sourceMappingURL=actor-BJvviz6Q.mjs.map