@fedify/fedify 1.8.1-pr.331.1178 → 1.8.1-pr.332.1179

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 (86) hide show
  1. package/dist/{actor-3n3a3mn9.js → actor-BxoA0YAS.js} +179 -179
  2. package/dist/{actor-FNzWBOLP.js → actor-XdgmhnS2.js} +1 -1
  3. package/dist/{authdocloader-GfBzg16C.js → authdocloader-BVZHcNUr.js} +3 -3
  4. package/dist/{authdocloader-Ca5hhhev.js → authdocloader-InqI_lXP.js} +3 -3
  5. package/dist/{builder-Clm8gcd0.js → builder--IjI02Ox.js} +43 -4
  6. package/dist/{client-Cn1v4IjU.js → client-Crj_oOVS.js} +1 -1
  7. package/dist/compat/mod.d.ts +2 -2
  8. package/dist/compat/transformers.test.js +16 -16
  9. package/dist/{context-B6mUZhs_.d.ts → context-72aRESIE.d.ts} +214 -1
  10. package/dist/{docloader-EkABD3kd.js → docloader-CHd_rHX1.js} +1 -1
  11. package/dist/{esm-DYas5DHL.js → esm-DnLA4gl4.js} +1 -1
  12. package/dist/federation/builder.test.js +5 -5
  13. package/dist/federation/collection.test.js +3 -3
  14. package/dist/federation/handler.test.js +327 -17
  15. package/dist/federation/inbox.test.js +4 -4
  16. package/dist/federation/keycache.test.js +4 -4
  17. package/dist/federation/kv.test.js +3 -3
  18. package/dist/federation/middleware.test.js +19 -18
  19. package/dist/federation/mod.d.ts +2 -2
  20. package/dist/federation/mod.js +10 -10
  21. package/dist/federation/mq.test.js +3 -3
  22. package/dist/federation/retry.test.js +3 -3
  23. package/dist/federation/router.test.js +3 -3
  24. package/dist/federation/send.test.js +10 -10
  25. package/dist/{http-BMoRES3C.js → http-BJEmgkaN.js} +2 -2
  26. package/dist/{http-BjAxnWIu.js → http-kTQne-Vy.js} +3 -3
  27. package/dist/{inbox-CSCse5JS.js → inbox-Cvy4NbLS.js} +1 -1
  28. package/dist/{key-CcIJJoyp.js → key-Bqd_lPUv.js} +2 -2
  29. package/dist/{key-DA72_KFf.js → key-CnAHzdUR.js} +4 -4
  30. package/dist/{key-DzT1bGXW.js → key-DH5TJ47Z.js} +3 -3
  31. package/dist/{key-B8Ddhi4l.js → key-fNDZsrw-.js} +2 -2
  32. package/dist/{keycache-B4X8zg2j.js → keycache-BmNxwMWl.js} +1 -1
  33. package/dist/{keys-Db8BUZdO.js → keys-BQv1XI0z.js} +1 -1
  34. package/dist/{ld-BwliTJit.js → ld-tVEgwW3c.js} +2 -2
  35. package/dist/{lookup-DSIbu5DQ.js → lookup-CzGCa7ll.js} +1 -1
  36. package/dist/{lookup-DYSWakdP.js → lookup-S2xtiVK9.js} +1 -1
  37. package/dist/{middleware-CGmmWG7J.js → middleware-B0SKbJiv.js} +555 -14
  38. package/dist/middleware-CcI2U-o7.js +26 -0
  39. package/dist/{middleware-B5NWowV0.js → middleware-DihQ_X9R.js} +590 -10
  40. package/dist/middleware-ksP_j6kc.js +17 -0
  41. package/dist/{mod-D9qE4iHP.d.ts → mod-OU0GgfW6.d.ts} +1 -1
  42. package/dist/mod.d.ts +3 -3
  43. package/dist/mod.js +10 -10
  44. package/dist/nodeinfo/client.test.js +5 -5
  45. package/dist/nodeinfo/handler.test.js +16 -16
  46. package/dist/nodeinfo/mod.js +2 -2
  47. package/dist/nodeinfo/semver.test.js +3 -3
  48. package/dist/nodeinfo/types.test.js +3 -3
  49. package/dist/{owner-CTaAKlYE.js → owner-DuPxPR5X.js} +2 -2
  50. package/dist/{proof-CaMDg5Wf.js → proof-DLGV7jUF.js} +3 -3
  51. package/dist/{proof-CqInNpez.js → proof-D_vMdizW.js} +2 -2
  52. package/dist/runtime/authdocloader.test.js +9 -9
  53. package/dist/runtime/docloader.test.js +4 -4
  54. package/dist/runtime/key.test.js +5 -5
  55. package/dist/runtime/langstr.test.js +3 -3
  56. package/dist/runtime/mod.js +6 -6
  57. package/dist/runtime/multibase/multibase.test.js +3 -3
  58. package/dist/runtime/url.test.js +3 -3
  59. package/dist/{send-CylRphpj.js → send--AIUpFOl.js} +2 -2
  60. package/dist/sig/http.test.js +8 -8
  61. package/dist/sig/key.test.js +6 -6
  62. package/dist/sig/ld.test.js +7 -7
  63. package/dist/sig/mod.js +6 -6
  64. package/dist/sig/owner.test.js +7 -7
  65. package/dist/sig/proof.test.js +7 -7
  66. package/dist/testing/docloader.test.js +3 -3
  67. package/dist/testing/mod.d.ts +212 -0
  68. package/dist/testing/mod.js +3 -3
  69. package/dist/{testing-BYK226ka.js → testing-dG4K85Rn.js} +4 -3
  70. package/dist/{type-6aat8vwp.js → type-Dn3B2sdm.js} +179 -179
  71. package/dist/{types-BaOxz8EG.js → types-WOQMaDxr.js} +1 -1
  72. package/dist/vocab/actor.test.js +5 -5
  73. package/dist/vocab/lookup.test.js +4 -4
  74. package/dist/vocab/mod.js +4 -4
  75. package/dist/vocab/type.test.js +3 -3
  76. package/dist/vocab/vocab.test.js +4 -4
  77. package/dist/{vocab-3WdS2ySQ.js → vocab-CjmKyqUK.js} +3 -3
  78. package/dist/webfinger/handler.test.js +16 -16
  79. package/dist/webfinger/lookup.test.js +4 -4
  80. package/dist/webfinger/mod.js +2 -2
  81. package/dist/x/cfworkers.test.js +3 -3
  82. package/dist/x/hono.d.ts +1 -1
  83. package/dist/x/sveltekit.d.ts +1 -1
  84. package/package.json +1 -1
  85. package/dist/middleware-7JYs-9eD.js +0 -26
  86. package/dist/middleware-CcZg36yb.js +0 -17
@@ -3,15 +3,15 @@
3
3
  import { URLPattern } from "urlpattern-polyfill";
4
4
 
5
5
  import { getDefaultActivityTransformers } from "./transformers-ghwJuzGY.js";
6
- import { deno_default, getDocumentLoader, kvCache } from "./docloader-EkABD3kd.js";
7
- import { Activity, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId } from "./actor-3n3a3mn9.js";
8
- import { lookupWebFinger } from "./lookup-DSIbu5DQ.js";
9
- import { exportJwk, importJwk, validateCryptoKey } from "./key-CcIJJoyp.js";
10
- import { doubleKnock, verifyRequest } from "./http-BjAxnWIu.js";
11
- import { detachSignature, doesActorOwnKey, getKeyOwner, hasSignature, signJsonLd, signObject, verifyJsonLd, verifyObject } from "./proof-CaMDg5Wf.js";
12
- import { getNodeInfo, nodeInfoToJson } from "./types-BaOxz8EG.js";
13
- import { getAuthenticatedDocumentLoader } from "./authdocloader-GfBzg16C.js";
14
- import { lookupObject, traverseCollection } from "./vocab-3WdS2ySQ.js";
6
+ import { deno_default, getDocumentLoader, kvCache } from "./docloader-CHd_rHX1.js";
7
+ import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, getTypeId } from "./actor-BxoA0YAS.js";
8
+ import { lookupWebFinger } from "./lookup-CzGCa7ll.js";
9
+ import { exportJwk, importJwk, validateCryptoKey } from "./key-Bqd_lPUv.js";
10
+ import { doubleKnock, verifyRequest } from "./http-kTQne-Vy.js";
11
+ import { detachSignature, doesActorOwnKey, getKeyOwner, hasSignature, signJsonLd, signObject, verifyJsonLd, verifyObject } from "./proof-DLGV7jUF.js";
12
+ import { getNodeInfo, nodeInfoToJson } from "./types-WOQMaDxr.js";
13
+ import { getAuthenticatedDocumentLoader } from "./authdocloader-BVZHcNUr.js";
14
+ import { lookupObject, traverseCollection } from "./vocab-CjmKyqUK.js";
15
15
  import { getLogger, withContext } from "@logtape/logtape";
16
16
  import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
17
17
  import { encodeHex } from "byte-encodings/hex";
@@ -306,13 +306,17 @@ var FederationBuilderImpl = class {
306
306
  inboxListeners;
307
307
  inboxErrorHandler;
308
308
  sharedInboxKeyDispatcher;
309
+ collectionTypeIds;
310
+ collectionCallbacks;
309
311
  constructor() {
310
312
  this.router = new Router$1();
311
313
  this.objectCallbacks = {};
312
314
  this.objectTypeIds = {};
315
+ this.collectionCallbacks = {};
316
+ this.collectionTypeIds = {};
313
317
  }
314
318
  async build(options) {
315
- const { FederationImpl: FederationImpl$1 } = await import("./middleware-CcZg36yb.js");
319
+ const { FederationImpl: FederationImpl$1 } = await import("./middleware-ksP_j6kc.js");
316
320
  const f = new FederationImpl$1(options);
317
321
  const trailingSlashInsensitiveValue = f.router.trailingSlashInsensitive;
318
322
  f.router = this.router.clone();
@@ -756,6 +760,41 @@ var FederationBuilderImpl = class {
756
760
  };
757
761
  return setters;
758
762
  }
763
+ setCollectionDispatcher(name, ...args) {
764
+ return this.#setCustomCollectionDispatcher(name, "collection", ...args);
765
+ }
766
+ setOrderedCollectionDispatcher(name, ...args) {
767
+ return this.#setCustomCollectionDispatcher(name, "orderedCollection", ...args);
768
+ }
769
+ #setCustomCollectionDispatcher(name, collectionType, itemType, path, dispatcher) {
770
+ const routeName = `${collectionType}:${String(name)}`;
771
+ if (this.router.has(routeName)) throw new RouterError(`Collection dispatcher for ${String(name)} already set.`);
772
+ if (this.collectionCallbacks[name] != null) throw new RouterError(`Collection dispatcher for ${String(name)} already set.`);
773
+ const variables = this.router.add(path, routeName);
774
+ if (variables.size < 1) throw new RouterError("Path for collection dispatcher must have at least one variable.");
775
+ const callbacks = { dispatcher };
776
+ this.collectionCallbacks[name] = callbacks;
777
+ this.collectionTypeIds[name] = itemType;
778
+ const setters = {
779
+ setCounter(counter) {
780
+ callbacks.counter = counter;
781
+ return setters;
782
+ },
783
+ setFirstCursor(cursor) {
784
+ callbacks.firstCursor = cursor;
785
+ return setters;
786
+ },
787
+ setLastCursor(cursor) {
788
+ callbacks.lastCursor = cursor;
789
+ return setters;
790
+ },
791
+ authorize(predicate) {
792
+ callbacks.authorizePredicate = predicate;
793
+ return setters;
794
+ }
795
+ };
796
+ return setters;
797
+ }
759
798
  };
760
799
  /**
761
800
  * Creates a new {@link FederationBuilder} instance.
@@ -914,6 +953,13 @@ function acceptsJsonLd(request) {
914
953
  if (types[0] === "text/html" || types[0] === "application/xhtml+xml") return false;
915
954
  return types.includes("application/activity+json") || types.includes("application/ld+json") || types.includes("application/json");
916
955
  }
956
+ /**
957
+ * Handles an actor request.
958
+ * @typeParam TContextData The context data to pass to the context.
959
+ * @param request The HTTP request.
960
+ * @param parameters The parameters for handling the actor.
961
+ * @returns A promise that resolves to an HTTP response.
962
+ */
917
963
  async function handleActor(request, { identifier, context: context$1, actorDispatcher, authorizePredicate, onNotFound, onNotAcceptable, onUnauthorized }) {
918
964
  const logger$1 = getLogger([
919
965
  "fedify",
@@ -957,6 +1003,13 @@ async function handleActor(request, { identifier, context: context$1, actorDispa
957
1003
  Vary: "Accept"
958
1004
  } });
959
1005
  }
1006
+ /**
1007
+ * Handles an object request.
1008
+ * @typeParam TContextData The context data to pass to the context.
1009
+ * @param request The HTTP request.
1010
+ * @param parameters The parameters for handling the object.
1011
+ * @returns A promise that resolves to an HTTP response.
1012
+ */
960
1013
  async function handleObject(request, { values, context: context$1, objectDispatcher, authorizePredicate, onNotFound, onNotAcceptable, onUnauthorized }) {
961
1014
  if (objectDispatcher == null) return await onNotFound(request);
962
1015
  const object = await objectDispatcher(context$1, values);
@@ -989,6 +1042,16 @@ async function handleObject(request, { values, context: context$1, objectDispatc
989
1042
  Vary: "Accept"
990
1043
  } });
991
1044
  }
1045
+ /**
1046
+ * Handles a collection request.
1047
+ * @typeParam TItem The type of items in the collection.
1048
+ * @typeParam TContext The type of the context, extending {@link RequestContext}.
1049
+ * @typeParam TContextData The context data to pass to the `TContext`.
1050
+ * @typeParam TFilter The type of the filter.
1051
+ * @param request The HTTP request.
1052
+ * @param parameters The parameters for handling the collection.
1053
+ * @returns A promise that resolves to an HTTP response.
1054
+ */
992
1055
  async function handleCollection(request, { name, identifier, uriGetter, filter, filterPredicate, context: context$1, collectionCallbacks, tracerProvider, onUnauthorized, onNotFound, onNotAcceptable }) {
993
1056
  const spanName = name.trim().replace(/\s+/g, "_");
994
1057
  tracerProvider = tracerProvider ?? trace.getTracerProvider();
@@ -1130,6 +1193,14 @@ async function handleCollection(request, { name, identifier, uriGetter, filter,
1130
1193
  Vary: "Accept"
1131
1194
  } });
1132
1195
  }
1196
+ /**
1197
+ * Filters collection items based on the provided predicate.
1198
+ * @typeParam TItem The type of items to filter.
1199
+ * @param items The items to filter.
1200
+ * @param collectionName The name of the collection for logging purposes.
1201
+ * @param filterPredicate Optional predicate function to filter items.
1202
+ * @returns The filtered items as Objects, Links, or URLs.
1203
+ */
1133
1204
  function filterCollectionItems(items, collectionName, filterPredicate) {
1134
1205
  const result = [];
1135
1206
  let logged = false;
@@ -1153,6 +1224,13 @@ function filterCollectionItems(items, collectionName, filterPredicate) {
1153
1224
  }
1154
1225
  return result;
1155
1226
  }
1227
+ /**
1228
+ * Handles an inbox request for ActivityPub activities.
1229
+ * @typeParam TContextData The context data to pass to the context.
1230
+ * @param request The HTTP request.
1231
+ * @param options The parameters for handling the inbox.
1232
+ * @returns A promise that resolves to an HTTP response.
1233
+ */
1156
1234
  async function handleInbox(request, options) {
1157
1235
  const tracerProvider = options.tracerProvider ?? trace.getTracerProvider();
1158
1236
  const tracer = tracerProvider.getTracer(deno_default.name, deno_default.version);
@@ -1174,6 +1252,14 @@ async function handleInbox(request, options) {
1174
1252
  }
1175
1253
  });
1176
1254
  }
1255
+ /**
1256
+ * Internal function for handling inbox requests with detailed processing.
1257
+ * @typeParam TContextData The context data to pass to the context.
1258
+ * @param request The HTTP request.
1259
+ * @param options The parameters for handling the inbox.
1260
+ * @param span The OpenTelemetry span for tracing.
1261
+ * @returns A promise that resolves to an HTTP response.
1262
+ */
1177
1263
  async function handleInboxInternal(request, { recipient, context: ctx, inboxContextFactory, kv, kvPrefixes, queue, actorDispatcher, inboxListeners, inboxErrorHandler, onNotFound, signatureTimeWindow, skipSignatureVerification, tracerProvider }, span) {
1178
1264
  const logger$1 = getLogger([
1179
1265
  "fedify",
@@ -1404,6 +1490,447 @@ async function handleInboxInternal(request, { recipient, context: ctx, inboxCont
1404
1490
  });
1405
1491
  }
1406
1492
  /**
1493
+ * Handles a custom collection request.
1494
+ * @typeParam TItem The type of items in the collection.
1495
+ * @typeParam TParams The parameter names of the requested URL.
1496
+ * @typeParam TContext The type of the context, extending {@link RequestContext}.
1497
+ * @typeParam TContextData The context data to pass to the `TContext`.
1498
+ * @param request The HTTP request.
1499
+ * @param handleParams Parameters for handling the collection.
1500
+ * @returns A promise that resolves to an HTTP response.
1501
+ * @since 1.8.0
1502
+ */
1503
+ const handleCustomCollection = exceptWrapper(_handleCustomCollection);
1504
+ async function _handleCustomCollection(request, { name, values, context: context$1, tracerProvider, collectionCallbacks: callbacks, filterPredicate }) {
1505
+ verifyDefined(callbacks);
1506
+ verifyJsonLdRequest(request);
1507
+ await authIfNeeded(context$1, values, callbacks);
1508
+ const cursor = new URL(request.url).searchParams.get("cursor");
1509
+ return await new CustomCollectionHandler(name, values, context$1, callbacks, tracerProvider, Collection, CollectionPage, filterPredicate).fetchCollection(cursor).toJsonLd().then(respondAsActivity);
1510
+ }
1511
+ /**
1512
+ * Handles an ordered collection request.
1513
+ * @typeParam TItem The type of items in the collection.
1514
+ * @typeParam TParams The parameter names of the requested URL.
1515
+ * @typeParam TContext The type of the context, extending {@link RequestContext}.
1516
+ * @typeParam TContextData The context data to pass to the `TContext`.
1517
+ * @param request The HTTP request.
1518
+ * @param handleParams Parameters for handling the collection.
1519
+ * @returns A promise that resolves to an HTTP response.
1520
+ * @since 1.8.0
1521
+ */
1522
+ const handleOrderedCollection = exceptWrapper(_handleOrderedCollection);
1523
+ async function _handleOrderedCollection(request, { name, values, context: context$1, tracerProvider, collectionCallbacks: callbacks, filterPredicate }) {
1524
+ verifyDefined(callbacks);
1525
+ verifyJsonLdRequest(request);
1526
+ await authIfNeeded(context$1, values, callbacks);
1527
+ const cursor = new URL(request.url).searchParams.get("cursor");
1528
+ return await new CustomCollectionHandler(name, values, context$1, callbacks, tracerProvider, OrderedCollection, OrderedCollectionPage, filterPredicate).fetchCollection(cursor).toJsonLd().then(respondAsActivity);
1529
+ }
1530
+ /**
1531
+ * Handling custom collections with support for pagination and filtering.
1532
+ * The main flow is on `getCollection`, `dispatch`.
1533
+ *
1534
+ * @typeParam TItem The type of items in the collection.
1535
+ * @typeParam TParams The parameter names of the requested URL.
1536
+ * @typeParam TContext The type of the context. {@link Context} or {@link RequestContext}.
1537
+ * @typeParam TContextData The context data to pass to the `TContext`.
1538
+ * @typeParam TCollection The type of the collection, extending {@link Collection}.
1539
+ * @typeParam TCollectionPage The type of the collection page, extending {@link CollectionPage}.
1540
+ * @since 1.8.0
1541
+ */
1542
+ var CustomCollectionHandler = class {
1543
+ /**
1544
+ * The tracer for telemetry.
1545
+ * @type {Tracer}
1546
+ */
1547
+ #tracer;
1548
+ /**
1549
+ * The ID of the collection.
1550
+ * @type {URL}
1551
+ */
1552
+ #id;
1553
+ /**
1554
+ * Store total count of items in the collection.
1555
+ * Use `this.totalItems` to access the total items count.
1556
+ * It is a promise because it may require an asynchronous operation to count items.
1557
+ * @type {Promise<number | null> | undefined}
1558
+ */
1559
+ #totalItems = void 0;
1560
+ /**
1561
+ * The first cursor for pagination.
1562
+ * It is a promise because it may require an asynchronous operation to get the first cursor.
1563
+ * @type {Promise<string | null> | undefined}
1564
+ */
1565
+ #dispatcher;
1566
+ #collection = null;
1567
+ /**
1568
+ * Creates a new CustomCollection instance.
1569
+ * @param {string} name The name of the collection.
1570
+ * @param {TParams} values The parameter values for the collection.
1571
+ * @param {TContext} context The request context.
1572
+ * @param {CustomCollectionCallbacks} callbacks The collection callbacks.
1573
+ * @param {TracerProvider} tracerProvider The tracer provider for telemetry.
1574
+ * @param {ConstructorWithTypeId<TCollection>} Collection The Collection constructor.
1575
+ * @param {ConstructorWithTypeId<TCollectionPage>} CollectionPage The CollectionPage constructor.
1576
+ * @param {(item: TItem) => boolean} filterPredicate Optional filter predicate for items.
1577
+ */
1578
+ constructor(name, values, context$1, callbacks, tracerProvider = trace.getTracerProvider(), Collection$1, CollectionPage$1, filterPredicate) {
1579
+ this.name = name;
1580
+ this.values = values;
1581
+ this.context = context$1;
1582
+ this.callbacks = callbacks;
1583
+ this.tracerProvider = tracerProvider;
1584
+ this.Collection = Collection$1;
1585
+ this.CollectionPage = CollectionPage$1;
1586
+ this.filterPredicate = filterPredicate;
1587
+ this.name = this.name.trim().replace(/\s+/g, "_");
1588
+ this.#tracer = this.tracerProvider.getTracer(deno_default.name, deno_default.version);
1589
+ this.#id = new URL(this.context.url);
1590
+ this.#dispatcher = callbacks.dispatcher.bind(callbacks);
1591
+ }
1592
+ /**
1593
+ * Converts the collection to JSON-LD format.
1594
+ * @returns A promise that resolves to the JSON-LD representation.
1595
+ */
1596
+ async toJsonLd() {
1597
+ return (await this.collection).toJsonLd(this.context);
1598
+ }
1599
+ /**
1600
+ * Fetches the collection with optional cursor for pagination.
1601
+ * This method is defined for method chaining and to show processing flow properly.
1602
+ * So it is no problem to call `toJsonLd` directly on the instance.
1603
+ * @param cursor The cursor for pagination, or null for the first page.
1604
+ * @returns The CustomCollection instance for method chaining.
1605
+ */
1606
+ fetchCollection(cursor = null) {
1607
+ this.#collection = this.getCollection(cursor);
1608
+ return this;
1609
+ }
1610
+ /**
1611
+ * Gets the collection or collection page based on the cursor.
1612
+ * @param {string | null} cursor The cursor for pagination, or null for the main collection.
1613
+ * @returns {Promise<TCollection | TCollectionPage>} A promise that resolves to a Collection or CollectionPage.
1614
+ */
1615
+ async getCollection(cursor = null) {
1616
+ if (cursor !== null) {
1617
+ const props$1 = await this.getPageProps(cursor);
1618
+ return new this.CollectionPage(props$1);
1619
+ }
1620
+ const firstCursor = await this.firstCursor;
1621
+ const props = typeof firstCursor === "string" ? await this.getProps(firstCursor) : await this.getPropsWithoutCursor();
1622
+ return new this.Collection(props);
1623
+ }
1624
+ /**
1625
+ * Gets the properties for a collection page.
1626
+ * Returns the page properties including items, previous and next cursors.
1627
+ * @param {string} cursor The cursor for the page.
1628
+ * @returns A promise that resolves to the page properties.
1629
+ */
1630
+ async getPageProps(cursor) {
1631
+ const id = this.#id;
1632
+ const pages = await this.getPages({ cursor });
1633
+ const { prevCursor, nextCursor } = pages;
1634
+ const partOf = new URL(id);
1635
+ partOf.searchParams.delete("cursor");
1636
+ return {
1637
+ id,
1638
+ partOf,
1639
+ items: this.filterItems(pages.items),
1640
+ prev: this.appendToUrl(prevCursor),
1641
+ next: this.appendToUrl(nextCursor)
1642
+ };
1643
+ }
1644
+ /**
1645
+ * Gets the properties for a collection with cursors.
1646
+ * Returns the first cursor and last cursor as URL, along with total items count.
1647
+ * @param {string} firstCursor The first cursor for pagination.
1648
+ * @returns A promise that resolves to the collection properties.
1649
+ */
1650
+ async getProps(firstCursor) {
1651
+ const lastCursor = await this.callbacks.lastCursor?.(this.context, this.values);
1652
+ return {
1653
+ id: this.#id,
1654
+ first: this.appendToUrl(firstCursor),
1655
+ last: this.appendToUrl(lastCursor),
1656
+ totalItems: await this.totalItems
1657
+ };
1658
+ }
1659
+ /**
1660
+ * Gets the properties for a collection of all items and the count.
1661
+ * @returns A promise that resolves to the collection properties.
1662
+ */
1663
+ async getPropsWithoutCursor() {
1664
+ const totalItems = await this.totalItems;
1665
+ const pages = await this.getPages({ totalItems });
1666
+ return {
1667
+ id: this.#id,
1668
+ totalItems,
1669
+ items: this.filterItems(pages.items)
1670
+ };
1671
+ }
1672
+ /**
1673
+ * Gets a page of items from the collection.
1674
+ * Wraps the dispatcher in a span for telemetry.
1675
+ * @param options Options for getting the page, including cursor and total items.
1676
+ * @returns A promise that resolves to the page items.
1677
+ */
1678
+ async getPages({ cursor = null, totalItems = null }) {
1679
+ return await this.#tracer.startActiveSpan(`${this.ATTRS.DISPATCH_COLLECTION} ${this.name}`, this.spanOptions(SpanKind.SERVER, cursor), this.spanPages({
1680
+ cursor,
1681
+ totalItems
1682
+ }));
1683
+ }
1684
+ /**
1685
+ * Creates span options for telemetry.
1686
+ * @param {SpanKind} kind The span kind.
1687
+ * @param {string | null} cursor The optional cursor value.
1688
+ * @returns {SpanOptions}The span options.
1689
+ */
1690
+ spanOptions = (kind, cursor) => ({
1691
+ kind,
1692
+ attributes: {
1693
+ [this.ATTRS.ID]: this.#id.href,
1694
+ [this.ATTRS.TYPE]: this.Collection.typeId.href,
1695
+ ...cursor ? { [this.ATTRS.CURSOR]: cursor } : {}
1696
+ }
1697
+ });
1698
+ /**
1699
+ * Creates a function to wrap the dispatcher so tracing can be applied.
1700
+ * @param params Parameters including cursor and total items.
1701
+ * @returns {(span: Span) => Promise<PageItems<TItem>>} A function that handles the span operation.
1702
+ */
1703
+ spanPages = ({ totalItems = null, cursor = null }) => async (span) => {
1704
+ try {
1705
+ if (totalItems !== null) span.setAttribute(this.ATTRS.TOTAL_ITEMS, totalItems);
1706
+ const page = await this.dispatch(cursor);
1707
+ span.setAttribute(this.ATTRS.ITEMS, page.items.length);
1708
+ return page;
1709
+ } catch (e) {
1710
+ const message = e instanceof Error ? e.message : String(e);
1711
+ span.setStatus({
1712
+ code: SpanStatusCode.ERROR,
1713
+ message
1714
+ });
1715
+ throw e;
1716
+ } finally {
1717
+ span.end();
1718
+ }
1719
+ };
1720
+ /**
1721
+ * Dispatches the collection request to get items.
1722
+ * @param {string | null} cursor The cursor for pagination, or null for the first page.
1723
+ * @returns {Promise<PageItems<TItem>>} A promise that resolves to the page items.
1724
+ */
1725
+ async dispatch(cursor = null) {
1726
+ return await this.#dispatcher(this.context, this.values, cursor) ?? new ItemsNotFoundError().throw();
1727
+ }
1728
+ /**
1729
+ * Filters the items in the collection.
1730
+ * @param {TItem[]} items The items to filter.
1731
+ * @returns {(Object | Link | URL)[]} The filtered items.
1732
+ */
1733
+ filterItems(items) {
1734
+ return filterCollectionItems(items, this.name, this.filterPredicate);
1735
+ }
1736
+ /**
1737
+ * Appends a cursor to the URL if it exists.
1738
+ * @param {string | null | undefined} cursor The cursor to append, or null/undefined.
1739
+ * @returns The URL with cursor appended, or null if cursor is null/undefined.
1740
+ */
1741
+ appendToUrl(cursor) {
1742
+ return appendCursorIfExists(this.context.url, cursor);
1743
+ }
1744
+ /**
1745
+ * Gets the stored collection or collection page.
1746
+ * @returns {Promise<TCollection | TCollectionPage>} A promise that resolves to
1747
+ the collection or collection page.
1748
+ */
1749
+ get collection() {
1750
+ if (this.#collection === null) this.#collection = this.getCollection();
1751
+ return this.#collection;
1752
+ }
1753
+ /**
1754
+ * Gets the total number of items in the collection.
1755
+ * @returns {Promise<number | null>} A promise that
1756
+ resolves to the total items count, or null if not available.
1757
+ */
1758
+ get totalItems() {
1759
+ if (this.#totalItems === void 0) this.totalItems = this.callbacks.counter?.(this.context, this.values);
1760
+ return this.#totalItems;
1761
+ }
1762
+ /**
1763
+ * Sets the total number of items in the collection.
1764
+ * @param value The total items count or a promise that resolves to it.
1765
+ */
1766
+ set totalItems(value) {
1767
+ const toNumber = (value$1) => value$1 == null ? null : Number(value$1);
1768
+ this.#totalItems = value instanceof Promise ? value.then(toNumber) : Promise.resolve(toNumber(value));
1769
+ }
1770
+ /**
1771
+ * Gets the first cursor for pagination.
1772
+ * @returns {Promise<string | null>} A promise that resolves to the first cursor,
1773
+ or null if not available.
1774
+ */
1775
+ get firstCursor() {
1776
+ const cursor = this.callbacks.firstCursor?.(this.context, this.values);
1777
+ return Promise.resolve(cursor ?? null);
1778
+ }
1779
+ /**
1780
+ * Attribute constants for telemetry spans.
1781
+ */
1782
+ ATTRS = {
1783
+ DISPATCH_COLLECTION: "activitypub.dispatch_collection",
1784
+ CURSOR: "fedify.collection.cursor",
1785
+ ID: "activitypub.collection.id",
1786
+ ITEMS: "fedify.collection.items",
1787
+ TOTAL_ITEMS: "activitypub.collection.total_items",
1788
+ TYPE: "activitypub.collection.type"
1789
+ };
1790
+ };
1791
+ /**
1792
+ * A wrapper function that catches specific errors and handles them appropriately.
1793
+ * @typeParam TParams The type of parameters that extend ErrorHandlers.
1794
+ * @param handler The handler function to wrap.
1795
+ * @returns A wrapped handler function that catches and handles specific errors.
1796
+ * @since 1.8.0
1797
+ */
1798
+ function exceptWrapper(handler) {
1799
+ return async (request, handlerParams) => {
1800
+ try {
1801
+ return await handler(request, handlerParams);
1802
+ } catch (error) {
1803
+ const { onNotFound, onNotAcceptable, onUnauthorized } = handlerParams;
1804
+ switch (error?.constructor) {
1805
+ case ItemsNotFoundError: return await onNotFound(request);
1806
+ case NotAcceptableError: return await onNotAcceptable(request);
1807
+ case UnauthorizedError: return await onUnauthorized(request);
1808
+ default: throw error;
1809
+ }
1810
+ }
1811
+ };
1812
+ }
1813
+ /**
1814
+ * Verifies that a value is defined (not undefined).
1815
+ * @typeParam T The type of the value, excluding undefined.
1816
+ * @param callbacks The value to verify.
1817
+ * @throws {ItemsNotFoundError} If the value is undefined.
1818
+ * @since 1.8.0
1819
+ */
1820
+ const verifyDefined = (callbacks) => {
1821
+ if (callbacks === void 0) throw new ItemsNotFoundError();
1822
+ };
1823
+ /**
1824
+ * Verifies that a request accepts JSON-LD content type.
1825
+ * @param request The HTTP request to verify.
1826
+ * @throws {NotAcceptableError} If the request doesn't accept JSON-LD.
1827
+ * @since 1.8.0
1828
+ */
1829
+ const verifyJsonLdRequest = (request) => {
1830
+ if (!acceptsJsonLd(request)) throw new NotAcceptableError();
1831
+ };
1832
+ /**
1833
+ * Performs authorization if needed based on the authorization predicate.
1834
+ * @typeParam TContextData The context data type.
1835
+ * @param {RequestContext<TContextData>} context The request context.
1836
+ * @param {Record<string, string>} values The parameter values.
1837
+ * @param options Options containing the authorization predicate.
1838
+ * @throws {UnauthorizedError} If authorization fails.
1839
+ * @since 1.8.0
1840
+ */
1841
+ const authIfNeeded = async (context$1, values, { authorizePredicate: authorize = void 0 }) => {
1842
+ if (authorize === void 0) return;
1843
+ const key = (await context$1.getSignedKey())?.clone({}, warning.key) ?? null;
1844
+ const keyOwner = (await context$1.getSignedKeyOwner())?.clone({}, warning.keyOwner) ?? null;
1845
+ if (!await authorize(context$1, values, key, keyOwner)) throw new UnauthorizedError();
1846
+ };
1847
+ /** Warning messages for `authIfNeeded`. */
1848
+ const warning = {
1849
+ key: { $warning: {
1850
+ category: [
1851
+ "fedify",
1852
+ "federation",
1853
+ "collection"
1854
+ ],
1855
+ message: "The third parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKey() method. The third parameter will be removed in a future release."
1856
+ } },
1857
+ keyOwner: { $warning: {
1858
+ category: [
1859
+ "fedify",
1860
+ "federation",
1861
+ "collection"
1862
+ ],
1863
+ message: "The fourth parameter of AuthorizePredicate is deprecated in favor of RequestContext.getSignedKeyOwner() method. The fourth parameter will be removed in a future release."
1864
+ } }
1865
+ };
1866
+ /**
1867
+ * Appends a cursor parameter to a URL if the cursor exists.
1868
+ * @typeParam Cursor The type of the cursor (string, null, or undefined).
1869
+ * @param {URL} url The base URL to append the cursor to.
1870
+ * @param {string | null | undefined} cursor The cursor value to append.
1871
+ * @returns The URL with cursor appended if cursor is a string, null otherwise.
1872
+ * @since 1.8.0
1873
+ */
1874
+ const appendCursorIfExists = (url, cursor) => {
1875
+ if (cursor === null || cursor === void 0) return null;
1876
+ const copied = new URL(url);
1877
+ copied.searchParams.set("cursor", cursor);
1878
+ return copied;
1879
+ };
1880
+ /**
1881
+ * Creates an HTTP response for ActivityPub data.
1882
+ * @param {unknown} data The data to serialize as JSON-LD.
1883
+ * @returns {Response} An HTTP response with the data as ActivityPub JSON.
1884
+ * @since 1.8.0
1885
+ */
1886
+ const respondAsActivity = (data) => new Response(JSON.stringify(data), { headers: {
1887
+ "Content-Type": "application/activity+json",
1888
+ Vary: "Accept"
1889
+ } });
1890
+ /**
1891
+ * Base class for handler errors.
1892
+ * @since 1.8.0
1893
+ */
1894
+ var HandlerError = class extends Error {
1895
+ constructor(message) {
1896
+ super(message);
1897
+ }
1898
+ /**
1899
+ * Throws this error.
1900
+ * @returns Never returns, always throws.
1901
+ */
1902
+ throw() {
1903
+ throw this;
1904
+ }
1905
+ };
1906
+ /**
1907
+ * Error thrown when items are not found in a collection.
1908
+ * @since 1.8.0
1909
+ */
1910
+ var ItemsNotFoundError = class extends HandlerError {
1911
+ constructor() {
1912
+ super("Items not found in the collection.");
1913
+ }
1914
+ };
1915
+ /**
1916
+ * Error thrown when the request is not acceptable (e.g., wrong content type).
1917
+ * @since 1.8.0
1918
+ */
1919
+ var NotAcceptableError = class extends HandlerError {
1920
+ constructor() {
1921
+ super("Items not found in the collection.");
1922
+ }
1923
+ };
1924
+ /**
1925
+ * Error thrown when access to a collection is unauthorized.
1926
+ * @since 1.8.0
1927
+ */
1928
+ var UnauthorizedError = class extends HandlerError {
1929
+ constructor() {
1930
+ super("Unauthorized access to the collection.");
1931
+ }
1932
+ };
1933
+ /**
1407
1934
  * Responds with the given object in JSON-LD format.
1408
1935
  *
1409
1936
  * @param object The object to respond with.
@@ -2599,6 +3126,34 @@ var FederationImpl = class extends FederationBuilderImpl {
2599
3126
  onNotFound,
2600
3127
  onNotAcceptable
2601
3128
  });
3129
+ case "collection": {
3130
+ const name = route.name.replace(/^collection:/, "");
3131
+ const callbacks = this.collectionCallbacks[name];
3132
+ return await handleOrderedCollection(request, {
3133
+ name,
3134
+ context: context$1,
3135
+ values: route.values,
3136
+ collectionCallbacks: callbacks,
3137
+ tracerProvider: this.tracerProvider,
3138
+ onUnauthorized,
3139
+ onNotFound,
3140
+ onNotAcceptable
3141
+ });
3142
+ }
3143
+ case "orderedCollection": {
3144
+ const name = route.name.replace(/^orderedCollection:/, "");
3145
+ const callbacks = this.collectionCallbacks[name];
3146
+ return await handleOrderedCollection(request, {
3147
+ name,
3148
+ context: context$1,
3149
+ values: route.values,
3150
+ collectionCallbacks: callbacks,
3151
+ tracerProvider: this.tracerProvider,
3152
+ onUnauthorized,
3153
+ onNotFound,
3154
+ onNotAcceptable
3155
+ });
3156
+ }
2602
3157
  default: {
2603
3158
  const response = onNotFound(request);
2604
3159
  return response instanceof Promise ? await response : response;
@@ -2739,6 +3294,18 @@ var ContextImpl = class ContextImpl {
2739
3294
  if (path == null) throw new RouterError("No featured tags collection path registered.");
2740
3295
  return new URL(path, this.canonicalOrigin);
2741
3296
  }
3297
+ getCollectionUri(name, values) {
3298
+ const customCallbacks = this.federation.collectionCallbacks[name];
3299
+ if (customCallbacks != null) {
3300
+ const collectionRouteName = `collection:${String(name)}`;
3301
+ const orderedCollectionRouteName = `orderedCollection:${String(name)}`;
3302
+ let path = this.federation.router.build(collectionRouteName, values);
3303
+ if (path == null) path = this.federation.router.build(orderedCollectionRouteName, values);
3304
+ if (path == null) throw new RouterError(`No collection dispatcher registered for ${String(name)}.`);
3305
+ return new URL(path, this.canonicalOrigin);
3306
+ }
3307
+ throw new RouterError(`No collection dispatcher registered for ${String(name)}.`);
3308
+ }
2742
3309
  parseUri(uri) {
2743
3310
  if (uri == null) return null;
2744
3311
  if (uri.origin !== this.origin && uri.origin !== this.canonicalOrigin) return null;
@@ -2826,6 +3393,19 @@ var ContextImpl = class ContextImpl {
2826
3393
  return identifier;
2827
3394
  }
2828
3395
  };
3396
+ const collectionRegex = /^(orderedC|c)ollection:(.*)$/;
3397
+ const match = route.name.match(collectionRegex);
3398
+ if (match !== null) {
3399
+ const [, type, name] = match;
3400
+ const cls = this.federation.collectionTypeIds[name];
3401
+ return {
3402
+ type,
3403
+ name,
3404
+ class: cls,
3405
+ typeId: cls.typeId,
3406
+ values: route.values
3407
+ };
3408
+ }
2829
3409
  return null;
2830
3410
  }
2831
3411
  async getActorKeyPairs(identifier) {