import { Temporal } from "@js-temporal/polyfill";
import "urlpattern-polyfill";
import { d as name, f as version, i as getDocumentLoader } from "../docloader-C7Hk8BRD.js";
import { $ as Person, A as Flag, B as Like, C as Dislike, D as Endpoints, E as EmojiReact, F as Image, G as Multikey, H as Listen, I as IntransitiveActivity, J as Offer, K as Note, L as Invite, M as Group, N as Hashtag, O as Event, P as Ignore, Q as Page, R as Join, S as DidService, T as Emoji, Tt as getTypeId, U as Mention, V as Link, W as Move, X as OrderedCollectionPage, Y as OrderedCollection, Z as Organization, _ as CollectionPage, _t as View, a as normalizeActorHandle, at as Reject, b as DataIntegrityProof, c as Add, ct as Service, d as Arrive, dt as TentativeReject, et as Place, f as Article, ft as Tombstone, g as Collection, gt as Video, h as ChatMessage, ht as Update, i as isActor, it as Read, j as Follow, k as Export, l as Announce, lt as Source, m as Block, mt as Undo, n as getActorHandle, nt as PropertyValue, o as Accept, ot as Relationship, p as Audio, pt as Travel, q as Object$1, r as getActorTypeName, rt as Question, s as Activity, st as Remove, t as getActorClassByTypeName, tt as Profile, u as Application, ut as TentativeAccept, v as Create, w as Document, x as Delete, y as CryptographicKey, z as Leave } from "../actor-BojFQubG.js";
import { t as lookupWebFinger } from "../lookup-BRKVwJc1.js";
import { getLogger } from "@logtape/logtape";
import { SpanStatusCode, trace } from "@opentelemetry/api";
import { delay } from "es-toolkit";
//#region src/vocab/handle.ts
/**
* Regular expression to match a fediverse handle in the format `@user@server`
* or `user@server`.  The `user` part can contain alphanumeric characters and
* some special characters except `@`.  The `server` part is all characters
* after the `@` symbol in the middle.
*/
const handleRegexp = /^@?((?:[-A-Za-z0-9._~!$&'()*+,;=]|%[A-Fa-f0-9]{2})+)@([^@]+)$/;
/**
* Parses a fediverse handle in the format `@user@server` or `user@server`.
* The `user` part can contain alphanumeric characters and some special
* characters except `@`.  The `server` part is all characters after the `@`
* symbol in the middle.
*
* @example
* ```typescript
* const handle = parseFediverseHandle("@username@example.com");
* console.log(handle?.username); // "username"
* console.log(handle?.host);     // "example.com"
* ```
*
* @param handle - The fediverse handle string to parse.
* @returns A {@link FediverseHandle} object with `username` and `host`
*          if the input is valid; otherwise `null`.
* @since 1.8.0
*/
function parseFediverseHandle(handle) {
	const match = handleRegexp.exec(handle);
	if (match) return {
		username: match[1],
		host: match[2]
	};
	return null;
}
/**
* Checks if a string is a valid fediverse handle in the format `@user@server`
* or `user@server`.  The `user` part can contain alphanumeric characters and
* some special characters except `@`.  The `server` part is all characters
* after the `@` symbol in the middle.
*
* @example
* ```typescript
* console.log(isFediverseHandle("@username@example.com")); // true
* console.log(isFediverseHandle("username@example.com"));  // true
* console.log(isFediverseHandle("@username@"));            // false
* ```
*
* @param handle - The string to test as a fediverse handle.
* @returns `true` if the string matches the fediverse handle pattern;
*          otherwise `false`.
* @since 1.8.0
*/
function isFediverseHandle(handle) {
	return handleRegexp.test(handle);
}
/**
* Converts a fediverse handle in the format `@user@server` or `user@server`
* to an `acct:` URI, which is a URL-like identifier for ActivityPub actors.
*
* @example
* ```typescript
* const identifier = toAcctUrl("@username@example.com");
* console.log(identifier?.href); // "acct:username@example.com"
* ```
*
* @param handle - The fediverse handle string to convert.
* @returns A `URL` object representing the `acct:` URI if conversion succeeds;
*          otherwise `null`.
* @since 1.8.0
*/
function toAcctUrl(handle) {
	const parsed = parseFediverseHandle(handle);
	if (!parsed) return null;
	return new URL(`acct:${parsed.username}@${parsed.host}`);
}
//#endregion
//#region src/vocab/lookup.ts
const logger = getLogger([
	"fedify",
	"vocab",
	"lookup"
]);
/**
* Looks up an ActivityStreams object by its URI (including `acct:` URIs)
* or a fediverse handle (e.g., `@user@server` or `user@server`).
*
* @example
* ``` typescript
* // Look up an actor by its fediverse handle:
* await lookupObject("@hongminhee@fosstodon.org");
* // returning a `Person` object.
*
* // A fediverse handle can omit the leading '@':
* await lookupObject("hongminhee@fosstodon.org");
* // returning a `Person` object.
*
* // A `acct:` URI can be used as well:
* await lookupObject("acct:hongminhee@fosstodon.org");
* // returning a `Person` object.
*
* // Look up an object by its URI:
* await lookupObject("https://todon.eu/@hongminhee/112060633798771581");
* // returning a `Note` object.
*
* // It can be a `URL` object as well:
* await lookupObject(new URL("https://todon.eu/@hongminhee/112060633798771581"));
* // returning a `Note` object.
* ```
*
* @param identifier The URI or fediverse handle to look up.
* @param options Lookup options.
* @returns The object, or `null` if not found.
* @since 0.2.0
*/
async function lookupObject(identifier, options = {}) {
	return await (options.tracerProvider ?? trace.getTracerProvider()).getTracer(name, version).startActiveSpan("activitypub.lookup_object", async (span) => {
		try {
			const result = await lookupObjectInternal(identifier, options);
			if (result == null) span.setStatus({ code: SpanStatusCode.ERROR });
			else {
				if (result.id != null) span.setAttribute("activitypub.object.id", result.id.href);
				span.setAttribute("activitypub.object.type", getTypeId(result).href);
				if (result.replyTargetIds.length > 0) span.setAttribute("activitypub.object.in_reply_to", result.replyTargetIds.map((id) => id.href));
				span.addEvent("activitypub.object.fetched", {
					"activitypub.object.type": getTypeId(result).href,
					"activitypub.object.json": JSON.stringify(await result.toJsonLd(options))
				});
			}
			return result;
		} catch (error) {
			span.recordException(error);
			span.setStatus({
				code: SpanStatusCode.ERROR,
				message: String(error)
			});
			throw error;
		} finally {
			span.end();
		}
	});
}
async function lookupObjectInternal(identifier, options = {}) {
	const documentLoader = options.documentLoader ?? getDocumentLoader({ userAgent: options.userAgent });
	if (typeof identifier === "string") identifier = toAcctUrl(identifier) ?? new URL(identifier);
	let remoteDoc = null;
	if (identifier.protocol === "http:" || identifier.protocol === "https:") try {
		remoteDoc = await documentLoader(identifier.href, { signal: options.signal });
	} catch (error) {
		logger.debug("Failed to fetch remote document:\n{error}", { error });
	}
	if (remoteDoc == null) {
		const jrd = await lookupWebFinger(identifier, {
			userAgent: options.userAgent,
			tracerProvider: options.tracerProvider,
			allowPrivateAddress: "allowPrivateAddress" in options && options.allowPrivateAddress === true,
			signal: options.signal
		});
		if (jrd?.links == null) return null;
		for (const l of jrd.links) {
			if (l.type !== "application/activity+json" && !l.type?.match(/application\/ld\+json;\s*profile="https:\/\/www.w3.org\/ns\/activitystreams"/) || l.rel !== "self" || l.href == null) continue;
			try {
				remoteDoc = await documentLoader(l.href, { signal: options.signal });
				break;
			} catch (error) {
				logger.debug("Failed to fetch remote document:\n{error}", { error });
				continue;
			}
		}
	}
	if (remoteDoc == null) return null;
	let object;
	try {
		object = await Object$1.fromJsonLd(remoteDoc.document, {
			documentLoader,
			contextLoader: options.contextLoader,
			tracerProvider: options.tracerProvider,
			baseUrl: new URL(remoteDoc.documentUrl)
		});
	} catch (error) {
		if (error instanceof TypeError) {
			logger.debug("Failed to parse JSON-LD document: {error}\n{document}", {
				...remoteDoc,
				error
			});
			return null;
		}
		throw error;
	}
	if (options.crossOrigin !== "trust" && object.id != null && object.id.origin !== new URL(remoteDoc.documentUrl).origin) {
		if (options.crossOrigin === "throw") throw new Error(`The object's @id (${object.id.href}) has a different origin than the document URL (${remoteDoc.documentUrl}); refusing to return the object.  If you want to bypass this check and are aware of the security implications, set the crossOrigin option to "trust".`);
		logger.warn("The object's @id ({objectId}) has a different origin than the document URL ({documentUrl}); refusing to return the object.  If you want to bypass this check and are aware of the security implications, set the crossOrigin option to \"trust\".", {
			...remoteDoc,
			objectId: object.id.href
		});
		return null;
	}
	return object;
}
/**
* Traverses a collection, yielding each item in the collection.
* If the collection is paginated, it will fetch the next page
* automatically.
*
* @example
* ``` typescript
* const collection = await lookupObject(collectionUrl);
* if (collection instanceof Collection) {
*   for await (const item of traverseCollection(collection)) {
*     console.log(item.id?.href);
*   }
* }
* ```
*
* @param collection The collection to traverse.
* @param options Options for traversing the collection.
* @returns An async iterable of each item in the collection.
* @since 1.1.0
*/
async function* traverseCollection(collection, options = {}) {
	const interval = Temporal.Duration.from(options.interval ?? { seconds: 0 }).total("millisecond");
	let page = await collection.getFirst(options);
	if (page == null) for await (const item of collection.getItems(options)) yield item;
	else while (page != null) {
		for await (const item of page.getItems(options)) yield item;
		if (interval > 0) await delay(interval);
		page = await page.getNext(options);
	}
}
//#endregion
//#region src/vocab/constants.ts
/**
* The special public collection for [public addressing].  *Do not mutate this
* object.*
*
* [public addressing]: https://www.w3.org/TR/activitypub/#public-addressing
*
* @since 0.7.0
*/
const PUBLIC_COLLECTION = new URL("https://www.w3.org/ns/activitystreams#Public");
//#endregion
export { Accept, Activity, Add, Announce, Application, Arrive, Article, Audio, Block, ChatMessage, Collection, CollectionPage, Create, CryptographicKey, DataIntegrityProof, Delete, DidService, Dislike, Document, Emoji, EmojiReact, Endpoints, Event, Export, Flag, Follow, Group, Hashtag, Ignore, Image, IntransitiveActivity, Invite, Join, Leave, Like, Link, Listen, Mention, Move, Multikey, Note, Object$1 as Object, Offer, OrderedCollection, OrderedCollectionPage, Organization, PUBLIC_COLLECTION, Page, Person, Place, Profile, PropertyValue, Question, Read, Reject, Relationship, Remove, Service, Source, TentativeAccept, TentativeReject, Tombstone, Travel, Undo, Update, Video, View, getActorClassByTypeName, getActorHandle, getActorTypeName, getTypeId, isActor, isFediverseHandle, lookupObject, normalizeActorHandle, parseFediverseHandle, toAcctUrl, traverseCollection };
