@hypercerts-org/sdk-core 0.5.0-beta.0 → 0.7.0-beta.0

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 (57) hide show
  1. package/README.md +130 -8
  2. package/dist/index.cjs +93 -15
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.ts +64 -1
  5. package/dist/index.mjs +93 -16
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +9 -5
  8. package/.turbo/turbo-build.log +0 -40
  9. package/.turbo/turbo-test.log +0 -119
  10. package/CHANGELOG.md +0 -62
  11. package/eslint.config.mjs +0 -22
  12. package/rollup.config.js +0 -75
  13. package/src/auth/OAuthClient.ts +0 -497
  14. package/src/core/SDK.ts +0 -410
  15. package/src/core/config.ts +0 -243
  16. package/src/core/errors.ts +0 -257
  17. package/src/core/interfaces.ts +0 -324
  18. package/src/core/types.ts +0 -282
  19. package/src/errors.ts +0 -57
  20. package/src/index.ts +0 -107
  21. package/src/lexicons.ts +0 -64
  22. package/src/repository/BlobOperationsImpl.ts +0 -199
  23. package/src/repository/CollaboratorOperationsImpl.ts +0 -442
  24. package/src/repository/HypercertOperationsImpl.ts +0 -1146
  25. package/src/repository/LexiconRegistry.ts +0 -332
  26. package/src/repository/OrganizationOperationsImpl.ts +0 -282
  27. package/src/repository/ProfileOperationsImpl.ts +0 -281
  28. package/src/repository/RecordOperationsImpl.ts +0 -340
  29. package/src/repository/Repository.ts +0 -482
  30. package/src/repository/interfaces.ts +0 -909
  31. package/src/repository/types.ts +0 -111
  32. package/src/services/hypercerts/types.ts +0 -87
  33. package/src/storage/InMemorySessionStore.ts +0 -127
  34. package/src/storage/InMemoryStateStore.ts +0 -146
  35. package/src/storage.ts +0 -63
  36. package/src/testing/index.ts +0 -67
  37. package/src/testing/mocks.ts +0 -142
  38. package/src/testing/stores.ts +0 -285
  39. package/src/testing.ts +0 -64
  40. package/src/types.ts +0 -86
  41. package/tests/auth/OAuthClient.test.ts +0 -164
  42. package/tests/core/SDK.test.ts +0 -176
  43. package/tests/core/errors.test.ts +0 -81
  44. package/tests/repository/BlobOperationsImpl.test.ts +0 -155
  45. package/tests/repository/CollaboratorOperationsImpl.test.ts +0 -438
  46. package/tests/repository/HypercertOperationsImpl.test.ts +0 -652
  47. package/tests/repository/LexiconRegistry.test.ts +0 -192
  48. package/tests/repository/OrganizationOperationsImpl.test.ts +0 -240
  49. package/tests/repository/ProfileOperationsImpl.test.ts +0 -254
  50. package/tests/repository/RecordOperationsImpl.test.ts +0 -375
  51. package/tests/repository/Repository.test.ts +0 -149
  52. package/tests/utils/fixtures.ts +0 -117
  53. package/tests/utils/mocks.ts +0 -109
  54. package/tests/utils/repository-fixtures.ts +0 -78
  55. package/tsconfig.json +0 -11
  56. package/tsconfig.tsbuildinfo +0 -1
  57. package/vitest.config.ts +0 -30
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/core/errors.ts","../src/storage/InMemorySessionStore.ts","../src/storage/InMemoryStateStore.ts","../src/auth/OAuthClient.ts","../src/repository/LexiconRegistry.ts","../src/repository/RecordOperationsImpl.ts","../src/repository/BlobOperationsImpl.ts","../src/repository/ProfileOperationsImpl.ts","../src/repository/HypercertOperationsImpl.ts","../src/repository/CollaboratorOperationsImpl.ts","../src/repository/OrganizationOperationsImpl.ts","../src/repository/Repository.ts","../src/core/config.ts","../src/core/SDK.ts","../src/core/types.ts"],"sourcesContent":["/**\n * Base error class for all SDK errors.\n *\n * All errors thrown by the Hypercerts SDK extend this class, making it easy\n * to catch and handle SDK-specific errors.\n *\n * @example Catching all SDK errors\n * ```typescript\n * try {\n * await sdk.authorize(\"user.bsky.social\");\n * } catch (error) {\n * if (error instanceof ATProtoSDKError) {\n * console.error(`SDK Error [${error.code}]: ${error.message}`);\n * console.error(`HTTP Status: ${error.status}`);\n * }\n * }\n * ```\n *\n * @example Checking error codes\n * ```typescript\n * try {\n * await repo.records.get(collection, rkey);\n * } catch (error) {\n * if (error instanceof ATProtoSDKError) {\n * switch (error.code) {\n * case \"AUTHENTICATION_ERROR\":\n * // Redirect to login\n * break;\n * case \"VALIDATION_ERROR\":\n * // Show form errors\n * break;\n * case \"NETWORK_ERROR\":\n * // Retry or show offline message\n * break;\n * }\n * }\n * }\n * ```\n */\nexport class ATProtoSDKError extends Error {\n /**\n * Creates a new SDK error.\n *\n * @param message - Human-readable error description\n * @param code - Machine-readable error code for programmatic handling\n * @param status - HTTP status code associated with this error type\n * @param cause - The underlying error that caused this error, if any\n */\n constructor(\n message: string,\n public code: string,\n public status?: number,\n public cause?: unknown,\n ) {\n super(message);\n this.name = \"ATProtoSDKError\";\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\n\n/**\n * Error thrown when authentication fails.\n *\n * This error indicates problems with the OAuth flow, invalid credentials,\n * or failed token exchanges. Common causes:\n * - Invalid authorization code\n * - Expired or invalid state parameter\n * - Revoked or invalid tokens\n * - User denied authorization\n *\n * @example\n * ```typescript\n * try {\n * const session = await sdk.callback(params);\n * } catch (error) {\n * if (error instanceof AuthenticationError) {\n * // Clear any stored state and redirect to login\n * console.error(\"Authentication failed:\", error.message);\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends ATProtoSDKError {\n /**\n * Creates an authentication error.\n *\n * @param message - Description of what went wrong during authentication\n * @param cause - The underlying error (e.g., from the OAuth client)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"AUTHENTICATION_ERROR\", 401, cause);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Error thrown when a session has expired and cannot be refreshed.\n *\n * This typically occurs when:\n * - The refresh token has expired (usually after extended inactivity)\n * - The user has revoked access to your application\n * - The PDS has invalidated all sessions for the user\n *\n * When this error occurs, the user must re-authenticate.\n *\n * @example\n * ```typescript\n * try {\n * const session = await sdk.restoreSession(did);\n * } catch (error) {\n * if (error instanceof SessionExpiredError) {\n * // Clear stored session and prompt user to log in again\n * localStorage.removeItem(\"userDid\");\n * window.location.href = \"/login\";\n * }\n * }\n * ```\n */\nexport class SessionExpiredError extends ATProtoSDKError {\n /**\n * Creates a session expired error.\n *\n * @param message - Description of why the session expired\n * @param cause - The underlying error from the token refresh attempt\n */\n constructor(message: string = \"Session expired\", cause?: unknown) {\n super(message, \"SESSION_EXPIRED\", 401, cause);\n this.name = \"SessionExpiredError\";\n }\n}\n\n/**\n * Error thrown when input validation fails.\n *\n * This error indicates that provided data doesn't meet the required format\n * or constraints. Common causes:\n * - Missing required fields\n * - Invalid URL formats\n * - Invalid DID format\n * - Schema validation failures for records\n * - Invalid configuration values\n *\n * @example\n * ```typescript\n * try {\n * await sdk.authorize(\"\"); // Empty identifier\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.error(\"Invalid input:\", error.message);\n * // Show validation error to user\n * }\n * }\n * ```\n *\n * @example With Zod validation cause\n * ```typescript\n * try {\n * await repo.records.create(collection, record);\n * } catch (error) {\n * if (error instanceof ValidationError && error.cause) {\n * // error.cause may be a ZodError with detailed field errors\n * const zodError = error.cause as ZodError;\n * zodError.errors.forEach(e => {\n * console.error(`Field ${e.path.join(\".\")}: ${e.message}`);\n * });\n * }\n * }\n * ```\n */\nexport class ValidationError extends ATProtoSDKError {\n /**\n * Creates a validation error.\n *\n * @param message - Description of what validation failed\n * @param cause - The underlying validation error (e.g., ZodError)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"VALIDATION_ERROR\", 400, cause);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Error thrown when a network request fails.\n *\n * This error indicates connectivity issues or server unavailability.\n * Common causes:\n * - No internet connection\n * - DNS resolution failure\n * - Server timeout\n * - Server returned 5xx error\n * - TLS/SSL errors\n *\n * These errors are typically transient and may succeed on retry.\n *\n * @example\n * ```typescript\n * try {\n * await repo.records.list(collection);\n * } catch (error) {\n * if (error instanceof NetworkError) {\n * // Implement retry logic or show offline indicator\n * console.error(\"Network error:\", error.message);\n * await retryWithBackoff(() => repo.records.list(collection));\n * }\n * }\n * ```\n */\nexport class NetworkError extends ATProtoSDKError {\n /**\n * Creates a network error.\n *\n * @param message - Description of the network failure\n * @param cause - The underlying error (e.g., fetch error, timeout)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"NETWORK_ERROR\", 503, cause);\n this.name = \"NetworkError\";\n }\n}\n\n/**\n * Error thrown when an SDS-only operation is attempted on a PDS.\n *\n * Certain operations are only available on Shared Data Servers (SDS),\n * such as collaborator management and organization operations.\n * This error is thrown when these operations are attempted on a\n * Personal Data Server (PDS).\n *\n * @example\n * ```typescript\n * const pdsRepo = sdk.repository(session); // Default is PDS\n *\n * try {\n * // This will throw SDSRequiredError\n * await pdsRepo.collaborators.list();\n * } catch (error) {\n * if (error instanceof SDSRequiredError) {\n * // Switch to SDS for this operation\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n * const collaborators = await sdsRepo.collaborators.list();\n * }\n * }\n * ```\n */\nexport class SDSRequiredError extends ATProtoSDKError {\n /**\n * Creates an SDS required error.\n *\n * @param message - Description of which operation requires SDS\n * @param cause - Any underlying error\n */\n constructor(message: string = \"This operation requires a Shared Data Server (SDS)\", cause?: unknown) {\n super(message, \"SDS_REQUIRED\", 400, cause);\n this.name = \"SDSRequiredError\";\n }\n}\n","import type { SessionStore } from \"../core/interfaces.js\";\nimport type { NodeSavedSession } from \"@atproto/oauth-client-node\";\n\n/**\n * In-memory implementation of the SessionStore interface.\n *\n * This store keeps OAuth sessions in memory using a Map. It's intended\n * for development, testing, and simple use cases where session persistence\n * across restarts is not required.\n *\n * @remarks\n * **Warning**: This implementation is **not suitable for production** because:\n * - Sessions are lost when the process restarts\n * - Sessions cannot be shared across multiple server instances\n * - No automatic cleanup of expired sessions\n *\n * For production, implement {@link SessionStore} with a persistent backend:\n * - **Redis**: Good for distributed systems, supports TTL\n * - **PostgreSQL/MySQL**: Good for existing database infrastructure\n * - **MongoDB**: Good for document-based storage\n *\n * @example Basic usage\n * ```typescript\n * import { InMemorySessionStore } from \"@hypercerts-org/sdk/storage\";\n *\n * const sessionStore = new InMemorySessionStore();\n *\n * const sdk = new ATProtoSDK({\n * oauth: { ... },\n * storage: {\n * sessionStore, // Will warn in logs for production\n * },\n * });\n * ```\n *\n * @example Testing usage\n * ```typescript\n * const sessionStore = new InMemorySessionStore();\n *\n * // After tests, clean up\n * sessionStore.clear();\n * ```\n *\n * @see {@link SessionStore} for the interface definition\n * @see {@link InMemoryStateStore} for the corresponding state store\n */\nexport class InMemorySessionStore implements SessionStore {\n /**\n * Internal storage for sessions, keyed by DID.\n * @internal\n */\n private sessions = new Map<string, NodeSavedSession>();\n\n /**\n * Retrieves a session by DID.\n *\n * @param did - The user's Decentralized Identifier\n * @returns Promise resolving to the session, or `undefined` if not found\n *\n * @example\n * ```typescript\n * const session = await sessionStore.get(\"did:plc:abc123\");\n * if (session) {\n * console.log(\"Session found\");\n * }\n * ```\n */\n async get(did: string): Promise<NodeSavedSession | undefined> {\n return this.sessions.get(did);\n }\n\n /**\n * Stores or updates a session.\n *\n * @param did - The user's DID to use as the key\n * @param session - The session data to store\n *\n * @remarks\n * If a session already exists for the DID, it is overwritten.\n *\n * @example\n * ```typescript\n * await sessionStore.set(\"did:plc:abc123\", sessionData);\n * ```\n */\n async set(did: string, session: NodeSavedSession): Promise<void> {\n this.sessions.set(did, session);\n }\n\n /**\n * Deletes a session by DID.\n *\n * @param did - The DID of the session to delete\n *\n * @remarks\n * If no session exists for the DID, this is a no-op.\n *\n * @example\n * ```typescript\n * await sessionStore.del(\"did:plc:abc123\");\n * ```\n */\n async del(did: string): Promise<void> {\n this.sessions.delete(did);\n }\n\n /**\n * Clears all stored sessions.\n *\n * This is primarily useful for testing to ensure a clean state\n * between test runs.\n *\n * @remarks\n * This method is synchronous (not async) for convenience in test cleanup.\n *\n * @example\n * ```typescript\n * // In test teardown\n * afterEach(() => {\n * sessionStore.clear();\n * });\n * ```\n */\n clear(): void {\n this.sessions.clear();\n }\n}\n","import type { StateStore } from \"../core/interfaces.js\";\nimport type { NodeSavedState } from \"@atproto/oauth-client-node\";\n\n/**\n * In-memory implementation of the StateStore interface.\n *\n * This store keeps OAuth state parameters in memory using a Map. State is\n * used during the OAuth authorization flow for CSRF protection and PKCE.\n *\n * @remarks\n * **Warning**: This implementation is **not suitable for production** because:\n * - State is lost when the process restarts (breaking in-progress OAuth flows)\n * - State cannot be shared across multiple server instances\n * - No automatic cleanup of expired state (memory leak potential)\n *\n * For production, implement {@link StateStore} with a persistent backend\n * that supports TTL (time-to-live):\n * - **Redis**: Ideal choice with built-in TTL support\n * - **Database with cleanup job**: PostgreSQL/MySQL with periodic cleanup\n *\n * **State Lifecycle**:\n * 1. Created when user starts OAuth flow (`authorize()`)\n * 2. Retrieved and validated during callback\n * 3. Deleted after successful or failed callback\n * 4. Should expire after ~15 minutes if callback never happens\n *\n * @example Basic usage\n * ```typescript\n * import { InMemoryStateStore } from \"@hypercerts-org/sdk/storage\";\n *\n * const stateStore = new InMemoryStateStore();\n *\n * const sdk = new ATProtoSDK({\n * oauth: { ... },\n * storage: {\n * stateStore, // Will warn in logs for production\n * },\n * });\n * ```\n *\n * @example Testing usage\n * ```typescript\n * const stateStore = new InMemoryStateStore();\n *\n * // After tests, clean up\n * stateStore.clear();\n * ```\n *\n * @see {@link StateStore} for the interface definition\n * @see {@link InMemorySessionStore} for the corresponding session store\n */\nexport class InMemoryStateStore implements StateStore {\n /**\n * Internal storage for OAuth state, keyed by state string.\n * @internal\n */\n private states = new Map<string, NodeSavedState>();\n\n /**\n * Retrieves OAuth state by key.\n *\n * @param key - The state key (random string from authorization URL)\n * @returns Promise resolving to the state, or `undefined` if not found\n *\n * @remarks\n * The key is a cryptographically random string generated during\n * the authorization request. It's included in the callback URL\n * and used to retrieve the associated PKCE verifier and other data.\n *\n * @example\n * ```typescript\n * // During OAuth callback\n * const state = await stateStore.get(params.get(\"state\")!);\n * if (!state) {\n * throw new Error(\"Invalid or expired state\");\n * }\n * ```\n */\n async get(key: string): Promise<NodeSavedState | undefined> {\n return this.states.get(key);\n }\n\n /**\n * Stores OAuth state temporarily.\n *\n * @param key - The state key to use for storage\n * @param state - The OAuth state data (includes PKCE verifier, etc.)\n *\n * @remarks\n * In production implementations, state should be stored with a TTL\n * of approximately 10-15 minutes to prevent stale state accumulation.\n *\n * @example\n * ```typescript\n * // Called internally by OAuthClient during authorize()\n * await stateStore.set(stateKey, {\n * // PKCE code verifier, redirect URI, etc.\n * });\n * ```\n */\n async set(key: string, state: NodeSavedState): Promise<void> {\n this.states.set(key, state);\n }\n\n /**\n * Deletes OAuth state by key.\n *\n * @param key - The state key to delete\n *\n * @remarks\n * Called after the OAuth callback is processed (whether successful or not)\n * to clean up the temporary state.\n *\n * @example\n * ```typescript\n * // After processing callback\n * await stateStore.del(stateKey);\n * ```\n */\n async del(key: string): Promise<void> {\n this.states.delete(key);\n }\n\n /**\n * Clears all stored state.\n *\n * This is primarily useful for testing to ensure a clean state\n * between test runs.\n *\n * @remarks\n * This method is synchronous (not async) for convenience in test cleanup.\n * In production, be careful using this as it will invalidate all\n * in-progress OAuth flows.\n *\n * @example\n * ```typescript\n * // In test teardown\n * afterEach(() => {\n * stateStore.clear();\n * });\n * ```\n */\n clear(): void {\n this.states.clear();\n }\n}\n","import { NodeOAuthClient, JoseKey, type NodeSavedSession } from \"@atproto/oauth-client-node\";\nimport type { SessionStore, StateStore, LoggerInterface } from \"../core/interfaces.js\";\nimport type { ATProtoSDKConfig } from \"../core/config.js\";\nimport { AuthenticationError, NetworkError } from \"../core/errors.js\";\nimport { InMemorySessionStore } from \"../storage/InMemorySessionStore.js\";\nimport { InMemoryStateStore } from \"../storage/InMemoryStateStore.js\";\n\n/**\n * Options for the OAuth authorization flow.\n *\n * @internal\n */\ninterface AuthorizeOptions {\n /**\n * OAuth scope string to request specific permissions.\n * Overrides the default scope from the SDK configuration.\n */\n scope?: string;\n}\n\n/**\n * OAuth 2.0 client for AT Protocol authentication with DPoP support.\n *\n * This class wraps the `@atproto/oauth-client-node` library to provide\n * OAuth 2.0 authentication with the following features:\n *\n * - **DPoP (Demonstrating Proof of Possession)**: Binds tokens to cryptographic keys\n * to prevent token theft and replay attacks\n * - **PKCE (Proof Key for Code Exchange)**: Protects against authorization code interception\n * - **Automatic Token Refresh**: Transparently refreshes expired access tokens\n * - **Session Persistence**: Stores sessions in configurable storage backends\n *\n * @remarks\n * This class is typically used internally by {@link ATProtoSDK}. Direct usage\n * is only needed for advanced scenarios.\n *\n * The client uses lazy initialization - the underlying `NodeOAuthClient` is\n * created asynchronously on first use. This allows the constructor to return\n * synchronously while deferring async key parsing.\n *\n * @example Direct usage (advanced)\n * ```typescript\n * import { OAuthClient } from \"@hypercerts-org/sdk\";\n *\n * const client = new OAuthClient({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: { pds: \"https://bsky.social\" },\n * });\n *\n * // Start authorization\n * const authUrl = await client.authorize(\"user.bsky.social\");\n *\n * // Handle callback\n * const session = await client.callback(new URLSearchParams(callbackUrl.search));\n * ```\n *\n * @see {@link ATProtoSDK} for the recommended high-level API\n * @see https://atproto.com/specs/oauth for AT Protocol OAuth specification\n */\nexport class OAuthClient {\n /** The underlying NodeOAuthClient instance (lazily initialized) */\n private client: NodeOAuthClient | null = null;\n\n /** Promise that resolves to the initialized client */\n private clientPromise: Promise<NodeOAuthClient>;\n\n /** SDK configuration */\n private config: ATProtoSDKConfig;\n\n /** Optional logger for debugging */\n private logger?: LoggerInterface;\n\n /**\n * Creates a new OAuth client.\n *\n * @param config - SDK configuration including OAuth credentials and server URLs\n * @throws {@link AuthenticationError} if the JWK private key is not valid JSON\n *\n * @remarks\n * The constructor validates the JWK format synchronously but defers\n * the actual client initialization to the first API call.\n */\n constructor(config: ATProtoSDKConfig) {\n this.config = config;\n this.logger = config.logger;\n\n // Validate JWK format synchronously (before async initialization)\n try {\n JSON.parse(config.oauth.jwkPrivate);\n } catch (error) {\n throw new AuthenticationError(\"Failed to parse JWK private key. Ensure it is valid JSON.\", error);\n }\n\n // Initialize client lazily (async initialization)\n this.clientPromise = this.initializeClient();\n }\n\n /**\n * Initializes the NodeOAuthClient asynchronously.\n *\n * This method is called lazily on first use. It:\n * 1. Parses the JWK private key(s)\n * 2. Builds OAuth client metadata\n * 3. Creates the underlying NodeOAuthClient\n *\n * @returns Promise resolving to the initialized client\n * @internal\n */\n private async initializeClient(): Promise<NodeOAuthClient> {\n if (this.client) {\n return this.client;\n }\n\n // Parse JWK private key (already validated in constructor)\n const privateJWK = JSON.parse(this.config.oauth.jwkPrivate) as {\n keys: Array<{ kid: string; [key: string]: unknown }>;\n };\n\n // Build client metadata\n const clientMetadata = this.buildClientMetadata();\n\n // Convert JWK keys to JoseKey instances (await here)\n const keyset = await Promise.all(\n privateJWK.keys.map((key) =>\n JoseKey.fromImportable(key as unknown as Parameters<typeof JoseKey.fromImportable>[0], key.kid),\n ),\n );\n\n // Create fetch with timeout\n const fetchWithTimeout = this.createFetchWithTimeout(this.config.timeouts?.pdsMetadata ?? 30000);\n\n // Use provided stores or fall back to in-memory implementations\n const stateStore = this.config.storage?.stateStore ?? new InMemoryStateStore();\n const sessionStore = this.config.storage?.sessionStore ?? new InMemorySessionStore();\n\n this.client = new NodeOAuthClient({\n clientMetadata,\n keyset,\n stateStore: this.createStateStoreAdapter(stateStore),\n sessionStore: this.createSessionStoreAdapter(sessionStore),\n handleResolver: this.config.servers?.pds,\n fetch: this.config.fetch ?? fetchWithTimeout,\n });\n\n return this.client;\n }\n\n /**\n * Gets the OAuth client instance, initializing if needed.\n *\n * @returns Promise resolving to the initialized client\n * @internal\n */\n private async getClient(): Promise<NodeOAuthClient> {\n return this.clientPromise;\n }\n\n /**\n * Builds OAuth client metadata from configuration.\n *\n * The metadata describes your application to the authorization server\n * and must match what's published at your `clientId` URL.\n *\n * @returns OAuth client metadata object\n * @internal\n *\n * @remarks\n * Key metadata fields:\n * - `client_id`: URL to your client metadata JSON\n * - `redirect_uris`: Where to redirect after auth (must match config)\n * - `dpop_bound_access_tokens`: Always true for AT Protocol\n * - `token_endpoint_auth_method`: Uses private_key_jwt for security\n */\n private buildClientMetadata() {\n const clientIdUrl = new URL(this.config.oauth.clientId);\n return {\n client_id: this.config.oauth.clientId,\n client_name: \"ATProto SDK Client\",\n client_uri: clientIdUrl.origin,\n redirect_uris: [this.config.oauth.redirectUri] as [string, ...string[]],\n scope: this.config.oauth.scope,\n grant_types: [\"authorization_code\", \"refresh_token\"] as [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"] as [\"code\"],\n application_type: \"web\" as const,\n token_endpoint_auth_method: \"private_key_jwt\" as const,\n token_endpoint_auth_signing_alg: \"ES256\",\n dpop_bound_access_tokens: true,\n jwks_uri: this.config.oauth.jwksUri,\n } as const;\n }\n\n /**\n * Creates a fetch handler with timeout support.\n *\n * @param timeoutMs - Request timeout in milliseconds\n * @returns A fetch function that aborts after the timeout\n * @internal\n */\n private createFetchWithTimeout(timeoutMs: number): typeof fetch {\n return async (input: RequestInfo | URL, init?: RequestInit) => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(input, {\n ...init,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new NetworkError(`Request timeout after ${timeoutMs}ms`, error);\n }\n throw new NetworkError(\"Network request failed\", error);\n }\n };\n }\n\n /**\n * Creates a state store adapter compatible with NodeOAuthClient.\n *\n * @param store - The StateStore implementation to adapt\n * @returns An adapter compatible with NodeOAuthClient\n * @internal\n */\n private createStateStoreAdapter(store: StateStore): import(\"@atproto/oauth-client-node\").NodeSavedStateStore {\n return {\n get: (key: string) => store.get(key),\n set: (key: string, value: import(\"@atproto/oauth-client-node\").NodeSavedState) => store.set(key, value),\n del: (key: string) => store.del(key),\n };\n }\n\n /**\n * Creates a session store adapter compatible with NodeOAuthClient.\n *\n * @param store - The SessionStore implementation to adapt\n * @returns An adapter compatible with NodeOAuthClient\n * @internal\n */\n private createSessionStoreAdapter(store: SessionStore): import(\"@atproto/oauth-client-node\").NodeSavedSessionStore {\n return {\n get: (did: string) => store.get(did),\n set: (did: string, session: NodeSavedSession) => store.set(did, session),\n del: (did: string) => store.del(did),\n };\n }\n\n /**\n * Initiates the OAuth authorization flow.\n *\n * This method resolves the user's identity from their identifier,\n * generates PKCE codes, creates OAuth state, and returns an\n * authorization URL to redirect the user to.\n *\n * @param identifier - The user's ATProto identifier. Accepts:\n * - Handle (e.g., `\"alice.bsky.social\"`)\n * - DID (e.g., `\"did:plc:abc123...\"`)\n * - PDS URL (e.g., `\"https://bsky.social\"`)\n * @param options - Optional authorization settings\n * @returns A Promise resolving to the authorization URL\n * @throws {@link AuthenticationError} if authorization setup fails\n * @throws {@link NetworkError} if identity resolution fails\n *\n * @example\n * ```typescript\n * // Get authorization URL\n * const authUrl = await client.authorize(\"user.bsky.social\");\n *\n * // Redirect user (in a web app)\n * window.location.href = authUrl;\n *\n * // Or return to client (in an API)\n * res.json({ authUrl });\n * ```\n */\n async authorize(identifier: string, options?: AuthorizeOptions): Promise<string> {\n try {\n this.logger?.debug(\"Initiating OAuth authorization\", { identifier });\n\n const client = await this.getClient();\n const scope = options?.scope ?? this.config.oauth.scope;\n const authUrl = await client.authorize(identifier, { scope });\n\n this.logger?.debug(\"Authorization URL generated\", { identifier });\n // Convert URL to string if needed\n return typeof authUrl === \"string\" ? authUrl : authUrl.toString();\n } catch (error) {\n this.logger?.error(\"Authorization failed\", { identifier, error });\n if (error instanceof NetworkError || error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(\n `Failed to initiate authorization: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Handles the OAuth callback and exchanges the authorization code for tokens.\n *\n * Call this method when the user is redirected back to your application.\n * It validates the state, exchanges the code for tokens, and creates\n * a persistent session.\n *\n * @param params - URL search parameters from the callback. Expected parameters:\n * - `code`: The authorization code\n * - `state`: The state parameter (for CSRF protection)\n * - `iss`: The issuer (authorization server URL)\n * @returns A Promise resolving to the authenticated OAuth session\n * @throws {@link AuthenticationError} if:\n * - The callback contains an OAuth error\n * - The state is invalid or expired\n * - The code exchange fails\n * - Session persistence fails\n *\n * @example\n * ```typescript\n * // In your callback route handler\n * app.get(\"/callback\", async (req, res) => {\n * const params = new URLSearchParams(req.url.split(\"?\")[1]);\n *\n * try {\n * const session = await client.callback(params);\n * // Store DID for session restoration\n * req.session.userDid = session.sub;\n * res.redirect(\"/dashboard\");\n * } catch (error) {\n * res.redirect(\"/login?error=auth_failed\");\n * }\n * });\n * ```\n *\n * @remarks\n * After successful token exchange, this method verifies that the session\n * was properly persisted by attempting to restore it. This ensures the\n * storage backend is working correctly.\n */\n async callback(params: URLSearchParams): Promise<import(\"@atproto/oauth-client\").OAuthSession> {\n try {\n this.logger?.debug(\"Processing OAuth callback\");\n\n // Check for OAuth errors\n const error = params.get(\"error\");\n if (error) {\n const errorDescription = params.get(\"error_description\");\n throw new AuthenticationError(errorDescription || error);\n }\n\n const client = await this.getClient();\n const result = await client.callback(params);\n const session = result.session;\n const did = session.sub;\n\n this.logger?.info(\"OAuth callback successful\", { did });\n\n // Verify session can be restored (validates persistence)\n try {\n const restored = await client.restore(did);\n if (!restored) {\n throw new AuthenticationError(\"OAuth session was not persisted\");\n }\n this.logger?.debug(\"Session verified and restorable\", { did });\n } catch (restoreError) {\n this.logger?.error(\"Failed to verify persisted session\", {\n did,\n error: restoreError,\n });\n throw new AuthenticationError(\"Failed to persist OAuth session\", restoreError);\n }\n\n return session;\n } catch (error) {\n this.logger?.error(\"OAuth callback failed\", { error });\n if (error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(\n `OAuth callback failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Restores an OAuth session by DID.\n *\n * Use this method to restore a previously authenticated session.\n * The method automatically refreshes expired access tokens using\n * the stored refresh token.\n *\n * @param did - The user's Decentralized Identifier (e.g., `\"did:plc:abc123...\"`)\n * @returns A Promise resolving to the session, or `null` if not found\n * @throws {@link AuthenticationError} if session restoration fails (not for missing sessions)\n * @throws {@link NetworkError} if token refresh requires network and fails\n *\n * @example\n * ```typescript\n * // On application startup or request\n * const userDid = req.session.userDid;\n * if (userDid) {\n * const session = await client.restore(userDid);\n * if (session) {\n * // Session restored, user is authenticated\n * req.atprotoSession = session;\n * } else {\n * // No session found, user needs to log in\n * delete req.session.userDid;\n * }\n * }\n * ```\n *\n * @remarks\n * Token refresh is handled automatically by the underlying OAuth client.\n * If the refresh token has expired or been revoked, this method will\n * throw an {@link AuthenticationError}.\n */\n async restore(did: string): Promise<import(\"@atproto/oauth-client\").OAuthSession | null> {\n try {\n this.logger?.debug(\"Restoring session\", { did });\n\n const client = await this.getClient();\n const session = await client.restore(did);\n\n if (session) {\n this.logger?.debug(\"Session restored\", { did });\n } else {\n this.logger?.debug(\"No session found\", { did });\n }\n\n return session;\n } catch (error) {\n this.logger?.error(\"Failed to restore session\", { did, error });\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new AuthenticationError(\n `Failed to restore session: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Revokes an OAuth session.\n *\n * This method invalidates the session's tokens both locally and\n * (if supported) on the authorization server. After revocation,\n * the session cannot be restored.\n *\n * @param did - The user's DID to revoke\n * @throws {@link AuthenticationError} if revocation fails\n *\n * @example\n * ```typescript\n * // Log out endpoint\n * app.post(\"/logout\", async (req, res) => {\n * const userDid = req.session.userDid;\n * if (userDid) {\n * await client.revoke(userDid);\n * delete req.session.userDid;\n * }\n * res.redirect(\"/\");\n * });\n * ```\n *\n * @remarks\n * Even if revocation fails on the server, the local session is\n * removed. The error is thrown to inform you that remote revocation\n * may not have succeeded.\n */\n async revoke(did: string): Promise<void> {\n try {\n this.logger?.debug(\"Revoking session\", { did });\n\n const client = await this.getClient();\n await client.revoke(did);\n\n this.logger?.info(\"Session revoked\", { did });\n } catch (error) {\n this.logger?.error(\"Failed to revoke session\", { did, error });\n throw new AuthenticationError(\n `Failed to revoke session: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n}\n","import type { Agent } from \"@atproto/api\";\nimport type { LexiconDoc } from \"@atproto/lexicon\";\nimport { Lexicons } from \"@atproto/lexicon\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/**\n * Result of validating a record against a lexicon schema.\n */\nexport interface ValidationResult {\n /**\n * Whether the record is valid according to the lexicon schema.\n */\n valid: boolean;\n\n /**\n * Error message if validation failed.\n *\n * Only present when `valid` is `false`.\n */\n error?: string;\n}\n\n/**\n * Registry for managing and validating AT Protocol lexicon schemas.\n *\n * Lexicons are schema definitions that describe the structure of records\n * in the AT Protocol. This registry allows you to:\n *\n * - Register custom lexicons for your application's record types\n * - Validate records against their lexicon schemas\n * - Extend the AT Protocol Agent with custom lexicon support\n *\n * @remarks\n * The SDK automatically registers hypercert lexicons when creating a Repository.\n * You only need to use this class directly if you're working with custom\n * record types.\n *\n * **Lexicon IDs** follow the NSID (Namespaced Identifier) format:\n * `{authority}.{name}` (e.g., `org.hypercerts.hypercert`)\n *\n * @example Registering custom lexicons\n * ```typescript\n * const registry = sdk.getLexiconRegistry();\n *\n * // Register a single lexicon\n * registry.register({\n * lexicon: 1,\n * id: \"org.example.myRecord\",\n * defs: {\n * main: {\n * type: \"record\",\n * key: \"tid\",\n * record: {\n * type: \"object\",\n * required: [\"title\", \"createdAt\"],\n * properties: {\n * title: { type: \"string\" },\n * description: { type: \"string\" },\n * createdAt: { type: \"string\", format: \"datetime\" },\n * },\n * },\n * },\n * },\n * });\n *\n * // Register multiple lexicons at once\n * registry.registerMany([lexicon1, lexicon2, lexicon3]);\n * ```\n *\n * @example Validating records\n * ```typescript\n * const result = registry.validate(\"org.example.myRecord\", {\n * title: \"Test\",\n * createdAt: new Date().toISOString(),\n * });\n *\n * if (!result.valid) {\n * console.error(`Validation failed: ${result.error}`);\n * }\n * ```\n *\n * @see https://atproto.com/specs/lexicon for the Lexicon specification\n */\nexport class LexiconRegistry {\n /** Map of lexicon ID to lexicon document */\n private lexicons = new Map<string, LexiconDoc>();\n\n /** Lexicons collection for validation */\n private lexiconsCollection: Lexicons;\n\n /**\n * Creates a new LexiconRegistry.\n *\n * The registry starts empty. Use {@link register} or {@link registerMany}\n * to add lexicons.\n */\n constructor() {\n this.lexiconsCollection = new Lexicons();\n }\n\n /**\n * Registers a single lexicon schema.\n *\n * @param lexicon - The lexicon document to register\n * @throws {@link ValidationError} if the lexicon doesn't have an `id` field\n *\n * @remarks\n * If a lexicon with the same ID is already registered, it will be\n * replaced with the new definition. This is useful for testing but\n * should generally be avoided in production.\n *\n * @example\n * ```typescript\n * registry.register({\n * lexicon: 1,\n * id: \"org.example.post\",\n * defs: {\n * main: {\n * type: \"record\",\n * key: \"tid\",\n * record: {\n * type: \"object\",\n * required: [\"text\", \"createdAt\"],\n * properties: {\n * text: { type: \"string\", maxLength: 300 },\n * createdAt: { type: \"string\", format: \"datetime\" },\n * },\n * },\n * },\n * },\n * });\n * ```\n */\n register(lexicon: LexiconDoc): void {\n if (!lexicon.id) {\n throw new ValidationError(\"Lexicon must have an 'id' field\");\n }\n\n // Remove existing lexicon if present (to allow overwriting)\n if (this.lexicons.has(lexicon.id)) {\n // Lexicons collection doesn't support removal, so we create a new one\n // This is a limitation - in practice, lexicons shouldn't be overwritten\n // But we allow it for testing and flexibility\n const existingLexicon = this.lexicons.get(lexicon.id);\n if (existingLexicon) {\n // Try to remove from collection (may fail if not supported)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.lexiconsCollection as any).remove?.(lexicon.id);\n } catch {\n // If removal fails, create a new collection\n this.lexiconsCollection = new Lexicons();\n // Re-register all other lexicons\n for (const [id, lex] of this.lexicons.entries()) {\n if (id !== lexicon.id) {\n this.lexiconsCollection.add(lex);\n }\n }\n }\n }\n }\n\n this.lexicons.set(lexicon.id, lexicon);\n this.lexiconsCollection.add(lexicon);\n }\n\n /**\n * Registers multiple lexicons at once.\n *\n * @param lexicons - Array of lexicon documents to register\n *\n * @example\n * ```typescript\n * import { HYPERCERT_LEXICONS } from \"@hypercerts-org/sdk/lexicons\";\n *\n * registry.registerMany(HYPERCERT_LEXICONS);\n * ```\n */\n registerMany(lexicons: LexiconDoc[]): void {\n for (const lexicon of lexicons) {\n this.register(lexicon);\n }\n }\n\n /**\n * Gets a lexicon document by ID.\n *\n * @param id - The lexicon NSID (e.g., \"org.hypercerts.hypercert\")\n * @returns The lexicon document, or `undefined` if not registered\n *\n * @example\n * ```typescript\n * const lexicon = registry.get(\"org.hypercerts.hypercert\");\n * if (lexicon) {\n * console.log(`Found lexicon: ${lexicon.id}`);\n * }\n * ```\n */\n get(id: string): LexiconDoc | undefined {\n return this.lexicons.get(id);\n }\n\n /**\n * Validates a record against a collection's lexicon schema.\n *\n * @param collection - The collection NSID (same as lexicon ID)\n * @param record - The record data to validate\n * @returns Validation result with `valid` boolean and optional `error` message\n *\n * @remarks\n * - If no lexicon is registered for the collection, validation passes\n * (we can't validate against unknown schemas)\n * - Validation checks required fields and type constraints defined\n * in the lexicon schema\n *\n * @example\n * ```typescript\n * const result = registry.validate(\"org.hypercerts.hypercert\", {\n * title: \"My Hypercert\",\n * description: \"Description...\",\n * // ... other fields\n * });\n *\n * if (!result.valid) {\n * throw new Error(`Invalid record: ${result.error}`);\n * }\n * ```\n */\n validate(collection: string, record: unknown): ValidationResult {\n // Check if we have a lexicon registered for this collection\n // Collection format is typically \"namespace.collection\" (e.g., \"app.bsky.feed.post\")\n // Lexicon ID format is the same\n const lexiconId = collection;\n const lexicon = this.lexicons.get(lexiconId);\n if (!lexicon) {\n // No lexicon registered - validation passes (can't validate unknown schemas)\n return { valid: true };\n }\n\n // Check required fields if the lexicon defines them\n const recordDef = lexicon.defs?.record;\n if (recordDef && typeof recordDef === \"object\" && \"record\" in recordDef) {\n const recordSchema = recordDef.record;\n if (typeof recordSchema === \"object\" && \"required\" in recordSchema && Array.isArray(recordSchema.required)) {\n const recordObj = record as Record<string, unknown>;\n for (const requiredField of recordSchema.required) {\n if (typeof requiredField === \"string\" && !(requiredField in recordObj)) {\n return {\n valid: false,\n error: `Missing required field: ${requiredField}`,\n };\n }\n }\n }\n }\n\n try {\n this.lexiconsCollection.assertValidRecord(collection, record);\n return { valid: true };\n } catch (error) {\n // If error indicates lexicon not found, treat as validation pass\n // (the lexicon might exist in Agent's collection but not ours)\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes(\"not found\") || errorMessage.includes(\"Lexicon not found\")) {\n return { valid: true };\n }\n return {\n valid: false,\n error: errorMessage,\n };\n }\n }\n\n /**\n * Adds all registered lexicons to an AT Protocol Agent instance.\n *\n * This allows the Agent to understand custom lexicon types when making\n * API requests.\n *\n * @param agent - The Agent instance to extend\n *\n * @remarks\n * This is called automatically when creating a Repository. You typically\n * don't need to call this directly unless you're using the Agent\n * independently.\n *\n * @internal\n */\n addToAgent(agent: Agent): void {\n // Access the internal lexicons collection and merge our lexicons\n // The Agent's lex property is a Lexicons instance\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const agentLex = (agent as any).lex as Lexicons;\n\n // Add each registered lexicon to the agent\n for (const lexicon of this.lexicons.values()) {\n agentLex.add(lexicon);\n }\n }\n\n /**\n * Gets all registered lexicon IDs.\n *\n * @returns Array of lexicon NSIDs\n *\n * @example\n * ```typescript\n * const ids = registry.getRegisteredIds();\n * console.log(`Registered lexicons: ${ids.join(\", \")}`);\n * ```\n */\n getRegisteredIds(): string[] {\n return Array.from(this.lexicons.keys());\n }\n\n /**\n * Checks if a lexicon is registered.\n *\n * @param id - The lexicon NSID to check\n * @returns `true` if the lexicon is registered\n *\n * @example\n * ```typescript\n * if (registry.has(\"org.hypercerts.hypercert\")) {\n * // Hypercert lexicon is available\n * }\n * ```\n */\n has(id: string): boolean {\n return this.lexicons.has(id);\n }\n}\n","/**\n * RecordOperationsImpl - Low-level record CRUD operations.\n *\n * This module provides the implementation for direct AT Protocol\n * record operations (create, read, update, delete, list).\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError, ValidationError } from \"../core/errors.js\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\nimport type { RecordOperations } from \"./interfaces.js\";\nimport type { CreateResult, UpdateResult, PaginatedList } from \"./types.js\";\n\n/**\n * Implementation of low-level AT Protocol record operations.\n *\n * This class provides direct access to the AT Protocol repository API\n * for CRUD operations on records. It handles:\n *\n * - Lexicon validation before create/update operations\n * - Error mapping to SDK error types\n * - Response normalization\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.records}.\n *\n * All operations are performed against the repository DID specified\n * at construction time. To operate on a different repository, create\n * a new Repository instance using {@link Repository.repo}.\n *\n * @example\n * ```typescript\n * // Access through Repository\n * const repo = sdk.repository(session);\n *\n * // Create a record\n * const { uri, cid } = await repo.records.create({\n * collection: \"org.example.myRecord\",\n * record: { title: \"Hello\", createdAt: new Date().toISOString() },\n * });\n *\n * // Update the record\n * const rkey = uri.split(\"/\").pop()!;\n * await repo.records.update({\n * collection: \"org.example.myRecord\",\n * rkey,\n * record: { title: \"Updated\", createdAt: new Date().toISOString() },\n * });\n * ```\n *\n * @internal\n */\nexport class RecordOperationsImpl implements RecordOperations {\n /**\n * Creates a new RecordOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository to operate on\n * @param lexiconRegistry - Registry for record validation\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private lexiconRegistry: LexiconRegistry,\n ) {}\n\n /**\n * Creates a new record in the specified collection.\n *\n * @param params - Creation parameters\n * @param params.collection - NSID of the collection (e.g., \"org.hypercerts.hypercert\")\n * @param params.record - Record data conforming to the collection's lexicon schema\n * @param params.rkey - Optional record key. If not provided, a TID (timestamp-based ID)\n * is automatically generated by the server.\n * @returns Promise resolving to the created record's URI and CID\n * @throws {@link ValidationError} if the record doesn't conform to the lexicon schema\n * @throws {@link NetworkError} if the API request fails\n *\n * @remarks\n * The record is validated against the collection's lexicon before sending\n * to the server. If no lexicon is registered for the collection, validation\n * is skipped (allowing custom record types).\n *\n * **AT-URI Format**: `at://{did}/{collection}/{rkey}`\n *\n * @example\n * ```typescript\n * const result = await repo.records.create({\n * collection: \"org.hypercerts.hypercert\",\n * record: {\n * title: \"My Hypercert\",\n * description: \"...\",\n * createdAt: new Date().toISOString(),\n * },\n * });\n * console.log(`Created: ${result.uri}`);\n * // Output: Created: at://did:plc:abc123/org.hypercerts.hypercert/xyz789\n * ```\n */\n async create(params: { collection: string; record: unknown; rkey?: string }): Promise<CreateResult> {\n const validation = this.lexiconRegistry.validate(params.collection, params.record);\n if (!validation.valid) {\n throw new ValidationError(`Invalid record for collection ${params.collection}: ${validation.error}`);\n }\n\n try {\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: params.collection,\n record: params.record as Record<string, unknown>,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates an existing record (full replacement).\n *\n * @param params - Update parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key (the last segment of the AT-URI)\n * @param params.record - New record data (completely replaces existing record)\n * @returns Promise resolving to the updated record's URI and new CID\n * @throws {@link ValidationError} if the record doesn't conform to the lexicon schema\n * @throws {@link NetworkError} if the API request fails\n *\n * @remarks\n * This is a full replacement operation, not a partial update. The entire\n * record is replaced with the new data. To preserve existing fields,\n * first fetch the record with {@link get}, modify it, then update.\n *\n * @example\n * ```typescript\n * // Get existing record\n * const existing = await repo.records.get({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n *\n * // Update with modified data\n * const updated = await repo.records.update({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * record: {\n * ...existing.value,\n * title: \"Updated Title\",\n * },\n * });\n * ```\n */\n async update(params: { collection: string; rkey: string; record: unknown }): Promise<UpdateResult> {\n const validation = this.lexiconRegistry.validate(params.collection, params.record);\n if (!validation.valid) {\n throw new ValidationError(`Invalid record for collection ${params.collection}: ${validation.error}`);\n }\n\n try {\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n record: params.record as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a single record by collection and key.\n *\n * @param params - Get parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key\n * @returns Promise resolving to the record's URI, CID, and value\n * @throws {@link NetworkError} if the record is not found or request fails\n *\n * @example\n * ```typescript\n * const record = await repo.records.get({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n *\n * console.log(record.uri); // at://did:plc:abc123/org.hypercerts.hypercert/xyz789\n * console.log(record.cid); // bafyrei...\n * console.log(record.value); // { title: \"...\", description: \"...\", ... }\n * ```\n */\n async get(params: { collection: string; rkey: string }): Promise<{ uri: string; cid: string; value: unknown }> {\n try {\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid ?? \"\", value: result.data.value };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to get record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Lists records in a collection with pagination.\n *\n * @param params - List parameters\n * @param params.collection - NSID of the collection\n * @param params.limit - Maximum number of records to return (server may impose its own limit)\n * @param params.cursor - Pagination cursor from a previous response\n * @returns Promise resolving to paginated list of records\n * @throws {@link NetworkError} if the request fails\n *\n * @remarks\n * Records are returned in reverse chronological order (newest first).\n * Use the `cursor` from the response to fetch subsequent pages.\n *\n * @example Paginating through all records\n * ```typescript\n * let cursor: string | undefined;\n * const allRecords = [];\n *\n * do {\n * const page = await repo.records.list({\n * collection: \"org.hypercerts.hypercert\",\n * limit: 100,\n * cursor,\n * });\n * allRecords.push(...page.records);\n * cursor = page.cursor;\n * } while (cursor);\n *\n * console.log(`Total records: ${allRecords.length}`);\n * ```\n */\n async list(params: {\n collection: string;\n limit?: number;\n cursor?: string;\n }): Promise<PaginatedList<{ uri: string; cid: string; value: unknown }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: params.collection,\n limit: params.limit,\n cursor: params.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list records\");\n }\n\n return {\n records: result.data.records?.map((r) => ({ uri: r.uri, cid: r.cid, value: r.value })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to list records: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Deletes a record from a collection.\n *\n * @param params - Delete parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key to delete\n * @throws {@link NetworkError} if the deletion fails\n *\n * @remarks\n * Deletion is permanent. The record's AT-URI cannot be reused (the same\n * rkey can be used for a new record, but it will have a different CID).\n *\n * @example\n * ```typescript\n * await repo.records.delete({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n * ```\n */\n async delete(params: { collection: string; rkey: string }): Promise<void> {\n try {\n const result = await this.agent.com.atproto.repo.deleteRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to delete record\");\n }\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to delete record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n}\n","/**\n * BlobOperationsImpl - Blob upload and retrieval operations.\n *\n * This module provides the implementation for AT Protocol blob operations,\n * handling binary data like images and files.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError } from \"../core/errors.js\";\nimport type { BlobOperations } from \"./interfaces.js\";\n\n/**\n * Implementation of blob operations for binary data handling.\n *\n * Blobs in AT Protocol are content-addressed binary objects stored\n * separately from records. They are referenced in records using a\n * blob reference object with a CID ($link).\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.blobs}.\n *\n * **Blob Size Limits**: PDS servers typically impose size limits on blobs.\n * Common limits are:\n * - Images: 1MB\n * - Other files: Varies by server configuration\n *\n * **Supported MIME Types**: Any MIME type is technically supported, but\n * servers may reject certain types. Images (JPEG, PNG, GIF, WebP) are\n * universally supported.\n *\n * @example\n * ```typescript\n * // Upload an image blob\n * const imageBlob = new Blob([imageData], { type: \"image/jpeg\" });\n * const { ref, mimeType, size } = await repo.blobs.upload(imageBlob);\n *\n * // Use the ref in a record\n * await repo.records.create({\n * collection: \"org.example.post\",\n * record: {\n * text: \"Check out this image!\",\n * image: ref, // { $link: \"bafyrei...\" }\n * createdAt: new Date().toISOString(),\n * },\n * });\n * ```\n *\n * @internal\n */\nexport class BlobOperationsImpl implements BlobOperations {\n /**\n * Creates a new BlobOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository (used for blob retrieval)\n * @param _serverUrl - Server URL (reserved for future use)\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n ) {}\n\n /**\n * Uploads a blob to the server.\n *\n * @param blob - The blob to upload (File or Blob object)\n * @returns Promise resolving to blob reference and metadata\n * @throws {@link NetworkError} if the upload fails\n *\n * @remarks\n * The returned `ref` object should be used directly in records to\n * reference the blob. The `$link` property contains the blob's CID.\n *\n * **MIME Type Detection**: If the blob has no type, it defaults to\n * `application/octet-stream`. For best results, always specify the\n * correct MIME type when creating the Blob.\n *\n * @example Uploading an image\n * ```typescript\n * // From a File input\n * const file = fileInput.files[0];\n * const { ref } = await repo.blobs.upload(file);\n *\n * // From raw data\n * const imageBlob = new Blob([uint8Array], { type: \"image/png\" });\n * const { ref, mimeType, size } = await repo.blobs.upload(imageBlob);\n *\n * console.log(`Uploaded ${size} bytes of ${mimeType}`);\n * console.log(`CID: ${ref.$link}`);\n * ```\n *\n * @example Using in a hypercert\n * ```typescript\n * const coverImage = new Blob([imageData], { type: \"image/jpeg\" });\n * const { ref } = await repo.blobs.upload(coverImage);\n *\n * // The ref is used directly in the record\n * await repo.hypercerts.create({\n * title: \"My Hypercert\",\n * // ... other fields\n * image: coverImage, // HypercertOperations handles upload internally\n * });\n * ```\n */\n async upload(blob: Blob): Promise<{ ref: { $link: string }; mimeType: string; size: number }> {\n try {\n const arrayBuffer = await blob.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n\n const result = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: blob.type || \"application/octet-stream\",\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to upload blob\");\n }\n\n return {\n ref: { $link: result.data.blob.ref.toString() },\n mimeType: result.data.blob.mimeType,\n size: result.data.blob.size,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to upload blob: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Retrieves a blob by its CID.\n *\n * @param cid - Content Identifier (CID) of the blob, typically from a blob\n * reference's `$link` property\n * @returns Promise resolving to blob data and MIME type\n * @throws {@link NetworkError} if the blob is not found or retrieval fails\n *\n * @remarks\n * The returned data is a Uint8Array which can be converted to other\n * formats as needed (Blob, ArrayBuffer, Base64, etc.).\n *\n * **MIME Type**: The returned MIME type comes from the Content-Type header.\n * If the server doesn't provide one, it defaults to `application/octet-stream`.\n *\n * @example Basic retrieval\n * ```typescript\n * // Get a blob from a record's blob reference\n * const record = await repo.records.get({ collection, rkey });\n * const blobRef = (record.value as any).image;\n *\n * const { data, mimeType } = await repo.blobs.get(blobRef.$link);\n *\n * // Convert to a Blob for use in the browser\n * const blob = new Blob([data], { type: mimeType });\n * const url = URL.createObjectURL(blob);\n * ```\n *\n * @example Displaying an image\n * ```typescript\n * const { data, mimeType } = await repo.blobs.get(imageCid);\n *\n * // Create data URL for <img> src\n * const base64 = btoa(String.fromCharCode(...data));\n * const dataUrl = `data:${mimeType};base64,${base64}`;\n *\n * // Or use object URL\n * const blob = new Blob([data], { type: mimeType });\n * img.src = URL.createObjectURL(blob);\n * ```\n */\n async get(cid: string): Promise<{ data: Uint8Array; mimeType: string }> {\n try {\n const result = await this.agent.com.atproto.sync.getBlob({\n did: this.repoDid,\n cid,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get blob\");\n }\n\n return {\n data: result.data,\n mimeType: result.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get blob: ${error instanceof Error ? error.message : \"Unknown error\"}`, error);\n }\n }\n}\n","/**\n * ProfileOperationsImpl - User profile operations.\n *\n * This module provides the implementation for AT Protocol profile\n * management, including fetching and updating user profiles.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError } from \"../core/errors.js\";\nimport type { ProfileOperations } from \"./interfaces.js\";\nimport type { UpdateResult } from \"./types.js\";\n\n/**\n * Implementation of profile operations for user profile management.\n *\n * Profiles in AT Protocol are stored as records in the `app.bsky.actor.profile`\n * collection with the special rkey \"self\". This class provides a convenient\n * API for reading and updating profile data.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.profile}.\n *\n * **Profile Fields**:\n * - `handle`: Read-only, managed by the PDS\n * - `displayName`: User's display name (max 64 chars typically)\n * - `description`: Profile bio (max 256 chars typically)\n * - `avatar`: Profile picture blob reference\n * - `banner`: Banner image blob reference\n * - `website`: User's website URL (may not be available on all servers)\n *\n * @example\n * ```typescript\n * // Get profile\n * const profile = await repo.profile.get();\n * console.log(`${profile.displayName} (@${profile.handle})`);\n *\n * // Update profile\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"Updated bio\",\n * });\n *\n * // Update with new avatar\n * const avatarBlob = new Blob([imageData], { type: \"image/png\" });\n * await repo.profile.update({ avatar: avatarBlob });\n *\n * // Remove a field\n * await repo.profile.update({ website: null });\n * ```\n *\n * @internal\n */\nexport class ProfileOperationsImpl implements ProfileOperations {\n /**\n * Creates a new ProfileOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository/user\n * @param _serverUrl - Server URL (reserved for future use)\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n ) {}\n\n /**\n * Gets the repository's profile.\n *\n * @returns Promise resolving to profile data\n * @throws {@link NetworkError} if the profile cannot be fetched\n *\n * @remarks\n * This method fetches the full profile using the `getProfile` API,\n * which includes resolved information like follower counts on some\n * servers. For hypercerts SDK usage, the basic profile fields are\n * returned.\n *\n * **Note**: The `website` field may not be available on all AT Protocol\n * servers. Standard Bluesky profiles don't include this field.\n *\n * @example\n * ```typescript\n * const profile = await repo.profile.get();\n *\n * console.log(`Handle: @${profile.handle}`);\n * console.log(`Name: ${profile.displayName || \"(not set)\"}`);\n * console.log(`Bio: ${profile.description || \"(no bio)\"}`);\n *\n * if (profile.avatar) {\n * // Avatar is a URL or blob reference\n * console.log(`Avatar: ${profile.avatar}`);\n * }\n * ```\n */\n async get(): Promise<{\n handle: string;\n displayName?: string;\n description?: string;\n avatar?: string;\n banner?: string;\n website?: string;\n }> {\n try {\n const result = await this.agent.getProfile({ actor: this.repoDid });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get profile\");\n }\n\n return {\n handle: result.data.handle,\n displayName: result.data.displayName,\n description: result.data.description,\n avatar: result.data.avatar,\n banner: result.data.banner,\n // Note: website may not be available in standard profile\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to get profile: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates the repository's profile.\n *\n * @param params - Fields to update. Pass `null` to remove a field.\n * Omitted fields are preserved from the existing profile.\n * @returns Promise resolving to update result with new URI and CID\n * @throws {@link NetworkError} if the update fails\n *\n * @remarks\n * This method performs a read-modify-write operation:\n * 1. Fetches the existing profile record\n * 2. Merges in the provided updates\n * 3. Writes the updated profile back\n *\n * **Image Handling**: When providing `avatar` or `banner` as a Blob,\n * the image is automatically uploaded and the blob reference is stored\n * in the profile.\n *\n * **Field Removal**: Pass `null` to explicitly remove a field. Omitting\n * a field (not including it in params) preserves the existing value.\n *\n * @example Update display name and bio\n * ```typescript\n * await repo.profile.update({\n * displayName: \"Alice\",\n * description: \"Building impact certificates\",\n * });\n * ```\n *\n * @example Update avatar image\n * ```typescript\n * // From a file input\n * const file = document.getElementById(\"avatar\").files[0];\n * await repo.profile.update({ avatar: file });\n *\n * // From raw data\n * const response = await fetch(\"https://example.com/my-avatar.png\");\n * const blob = await response.blob();\n * await repo.profile.update({ avatar: blob });\n * ```\n *\n * @example Remove description\n * ```typescript\n * // Removes the description field entirely\n * await repo.profile.update({ description: null });\n * ```\n *\n * @example Multiple updates at once\n * ```typescript\n * const newAvatar = new Blob([avatarData], { type: \"image/png\" });\n * const newBanner = new Blob([bannerData], { type: \"image/jpeg\" });\n *\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"New bio\",\n * avatar: newAvatar,\n * banner: newBanner,\n * });\n * ```\n */\n async update(params: {\n displayName?: string | null;\n description?: string | null;\n avatar?: Blob | null;\n banner?: Blob | null;\n website?: string | null;\n }): Promise<UpdateResult> {\n try {\n // Get existing profile record\n const existing = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection: \"app.bsky.actor.profile\",\n rkey: \"self\",\n });\n\n const existingProfile = (existing.data.value as Record<string, unknown>) || {};\n\n // Build updated profile\n const updatedProfile: Record<string, unknown> = { ...existingProfile };\n\n if (params.displayName !== undefined) {\n if (params.displayName === null) {\n delete updatedProfile.displayName;\n } else {\n updatedProfile.displayName = params.displayName;\n }\n }\n\n if (params.description !== undefined) {\n if (params.description === null) {\n delete updatedProfile.description;\n } else {\n updatedProfile.description = params.description;\n }\n }\n\n // Handle avatar upload\n if (params.avatar !== undefined) {\n if (params.avatar === null) {\n delete updatedProfile.avatar;\n } else {\n const arrayBuffer = await params.avatar.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.avatar.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n updatedProfile.avatar = uploadResult.data.blob;\n }\n }\n }\n\n // Handle banner upload\n if (params.banner !== undefined) {\n if (params.banner === null) {\n delete updatedProfile.banner;\n } else {\n const arrayBuffer = await params.banner.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.banner.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n updatedProfile.banner = uploadResult.data.blob;\n }\n }\n }\n\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection: \"app.bsky.actor.profile\",\n rkey: \"self\",\n record: updatedProfile,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update profile\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update profile: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n}\n","/**\n * HypercertOperationsImpl - High-level hypercert operations.\n *\n * This module provides the implementation for creating and managing\n * hypercerts, including related records like rights, locations,\n * contributions, measurements, and evaluations.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { EventEmitter } from \"eventemitter3\";\nimport { NetworkError, ValidationError } from \"../core/errors.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\nimport {\n HYPERCERT_COLLECTIONS,\n type BlobRef,\n type HypercertEvidence,\n type HypercertClaim,\n type HypercertRights,\n type HypercertContribution,\n type HypercertMeasurement,\n type HypercertEvaluation,\n type HypercertCollection,\n type HypercertLocation,\n} from \"../services/hypercerts/types.js\";\nimport type {\n HypercertOperations,\n HypercertEvents,\n CreateHypercertParams,\n CreateHypercertResult,\n} from \"./interfaces.js\";\nimport type { CreateResult, UpdateResult, PaginatedList, ListParams, ProgressStep } from \"./types.js\";\n\n/**\n * Implementation of high-level hypercert operations.\n *\n * This class provides a convenient API for creating and managing hypercerts\n * with automatic handling of:\n *\n * - Image upload and blob reference management\n * - Rights record creation and linking\n * - Location attachment with optional GeoJSON support\n * - Contribution tracking\n * - Measurement and evaluation records\n * - Hypercert collections\n *\n * The class extends EventEmitter to provide real-time progress notifications\n * during complex operations.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.hypercerts}.\n *\n * **Record Relationships**:\n * - Hypercert → Rights (required, 1:1)\n * - Hypercert → Location (optional, 1:many)\n * - Hypercert → Contribution (optional, 1:many)\n * - Hypercert → Measurement (optional, 1:many)\n * - Hypercert → Evaluation (optional, 1:many)\n * - Collection → Hypercerts (1:many via claims array)\n *\n * @example Creating a hypercert with progress tracking\n * ```typescript\n * repo.hypercerts.on(\"recordCreated\", ({ uri }) => {\n * console.log(`Hypercert created: ${uri}`);\n * });\n *\n * const result = await repo.hypercerts.create({\n * title: \"Climate Impact\",\n * description: \"Reduced emissions by 100 tons\",\n * workScope: \"Climate\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: { name: \"CC-BY\", type: \"license\", description: \"...\" },\n * onProgress: (step) => console.log(`${step.name}: ${step.status}`),\n * });\n * ```\n *\n * @internal\n */\nexport class HypercertOperationsImpl extends EventEmitter<HypercertEvents> implements HypercertOperations {\n /**\n * Creates a new HypercertOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository to operate on\n * @param _serverUrl - Server URL (reserved for future use)\n * @param lexiconRegistry - Registry for record validation\n * @param logger - Optional logger for debugging\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n private lexiconRegistry: LexiconRegistry,\n private logger?: LoggerInterface,\n ) {\n super();\n }\n\n /**\n * Emits a progress event to the optional progress handler.\n *\n * @param onProgress - Progress callback from create params\n * @param step - Progress step information\n * @internal\n */\n private emitProgress(onProgress: ((step: ProgressStep) => void) | undefined, step: ProgressStep): void {\n if (onProgress) {\n try {\n onProgress(step);\n } catch (err) {\n this.logger?.error(`Error in progress handler: ${err instanceof Error ? err.message : \"Unknown\"}`);\n }\n }\n }\n\n /**\n * Creates a new hypercert with all related records.\n *\n * This method orchestrates the creation of a hypercert and its associated\n * records in the correct order:\n *\n * 1. Upload image (if provided)\n * 2. Create rights record\n * 3. Create hypercert record (referencing rights)\n * 4. Attach location (if provided)\n * 5. Create contributions (if provided)\n *\n * @param params - Creation parameters (see {@link CreateHypercertParams})\n * @returns Promise resolving to URIs and CIDs of all created records\n * @throws {@link ValidationError} if any record fails validation\n * @throws {@link NetworkError} if any API call fails\n *\n * @remarks\n * The operation is not atomic - if a later step fails, earlier records\n * will still exist. The result object will contain URIs for all\n * successfully created records.\n *\n * **Progress Steps**:\n * - `uploadImage`: Image blob upload\n * - `createRights`: Rights record creation\n * - `createHypercert`: Main hypercert record creation\n * - `attachLocation`: Location record creation\n * - `createContributions`: Contribution records creation\n *\n * @example Minimal hypercert\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"My Impact\",\n * description: \"Description of impact work\",\n * workScope: \"Education\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-06-30\",\n * rights: {\n * name: \"Attribution\",\n * type: \"license\",\n * description: \"CC-BY-4.0\",\n * },\n * });\n * ```\n *\n * @example Full hypercert with all options\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"Reforestation Project\",\n * description: \"Planted 10,000 trees...\",\n * shortDescription: \"10K trees planted\",\n * workScope: \"Environment\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: { name: \"Open\", type: \"impact\", description: \"...\" },\n * image: coverImageBlob,\n * location: { value: \"Amazon, Brazil\", name: \"Amazon Basin\" },\n * contributions: [\n * { contributors: [\"did:plc:org1\"], role: \"coordinator\" },\n * { contributors: [\"did:plc:org2\"], role: \"implementer\" },\n * ],\n * evidence: [{ uri: \"https://...\", description: \"Satellite data\" }],\n * onProgress: console.log,\n * });\n * ```\n */\n async create(params: CreateHypercertParams): Promise<CreateHypercertResult> {\n const createdAt = new Date().toISOString();\n const result: CreateHypercertResult = {\n hypercertUri: \"\",\n rightsUri: \"\",\n hypercertCid: \"\",\n rightsCid: \"\",\n };\n\n try {\n // Step 1: Upload image if provided\n let imageBlobRef: BlobRef | undefined;\n if (params.image) {\n this.emitProgress(params.onProgress, { name: \"uploadImage\", status: \"start\" });\n try {\n const arrayBuffer = await params.image.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.image.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n imageBlobRef = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n this.emitProgress(params.onProgress, {\n name: \"uploadImage\",\n status: \"success\",\n data: { size: params.image.size },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"uploadImage\", status: \"error\", error: error as Error });\n throw new NetworkError(\n `Failed to upload image: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n // Step 2: Create rights record\n this.emitProgress(params.onProgress, { name: \"createRights\", status: \"start\" });\n const rightsRecord: Omit<HypercertRights, \"$type\"> = {\n rightsName: params.rights.name,\n rightsType: params.rights.type,\n rightsDescription: params.rights.description,\n createdAt,\n };\n\n const rightsValidation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.RIGHTS, rightsRecord);\n if (!rightsValidation.valid) {\n throw new ValidationError(`Invalid rights record: ${rightsValidation.error}`);\n }\n\n const rightsResult = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.RIGHTS,\n record: rightsRecord as Record<string, unknown>,\n });\n\n if (!rightsResult.success) {\n throw new NetworkError(\"Failed to create rights record\");\n }\n\n result.rightsUri = rightsResult.data.uri;\n result.rightsCid = rightsResult.data.cid;\n this.emit(\"rightsCreated\", { uri: result.rightsUri, cid: result.rightsCid });\n this.emitProgress(params.onProgress, {\n name: \"createRights\",\n status: \"success\",\n data: { uri: result.rightsUri },\n });\n\n // Step 3: Create hypercert record\n this.emitProgress(params.onProgress, { name: \"createHypercert\", status: \"start\" });\n const hypercertRecord: Record<string, unknown> = {\n title: params.title,\n description: params.description,\n workScope: params.workScope,\n workTimeframeFrom: params.workTimeframeFrom,\n workTimeframeTo: params.workTimeframeTo,\n rights: { uri: result.rightsUri, cid: result.rightsCid },\n createdAt,\n };\n\n if (params.shortDescription) {\n hypercertRecord.shortDescription = params.shortDescription;\n }\n\n if (imageBlobRef) {\n hypercertRecord.image = imageBlobRef;\n }\n\n if (params.evidence && params.evidence.length > 0) {\n hypercertRecord.evidence = params.evidence;\n }\n\n const hypercertValidation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CLAIM, hypercertRecord);\n if (!hypercertValidation.valid) {\n throw new ValidationError(`Invalid hypercert record: ${hypercertValidation.error}`);\n }\n\n const hypercertResult = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CLAIM,\n record: hypercertRecord,\n });\n\n if (!hypercertResult.success) {\n throw new NetworkError(\"Failed to create hypercert record\");\n }\n\n result.hypercertUri = hypercertResult.data.uri;\n result.hypercertCid = hypercertResult.data.cid;\n this.emit(\"recordCreated\", { uri: result.hypercertUri, cid: result.hypercertCid });\n this.emitProgress(params.onProgress, {\n name: \"createHypercert\",\n status: \"success\",\n data: { uri: result.hypercertUri },\n });\n\n // Step 4: Attach location if provided\n if (params.location) {\n this.emitProgress(params.onProgress, { name: \"attachLocation\", status: \"start\" });\n try {\n const locationResult = await this.attachLocation(result.hypercertUri, params.location);\n result.locationUri = locationResult.uri;\n this.emitProgress(params.onProgress, {\n name: \"attachLocation\",\n status: \"success\",\n data: { uri: result.locationUri },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"attachLocation\", status: \"error\", error: error as Error });\n this.logger?.warn(`Failed to attach location: ${error instanceof Error ? error.message : \"Unknown\"}`);\n }\n }\n\n // Step 5: Create contributions if provided\n if (params.contributions && params.contributions.length > 0) {\n this.emitProgress(params.onProgress, { name: \"createContributions\", status: \"start\" });\n result.contributionUris = [];\n try {\n for (const contrib of params.contributions) {\n const contribResult = await this.addContribution({\n hypercertUri: result.hypercertUri,\n contributors: contrib.contributors,\n role: contrib.role,\n description: contrib.description,\n });\n result.contributionUris.push(contribResult.uri);\n }\n this.emitProgress(params.onProgress, {\n name: \"createContributions\",\n status: \"success\",\n data: { count: result.contributionUris.length },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"createContributions\", status: \"error\", error: error as Error });\n this.logger?.warn(`Failed to create contributions: ${error instanceof Error ? error.message : \"Unknown\"}`);\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates an existing hypercert record.\n *\n * @param params - Update parameters\n * @param params.uri - AT-URI of the hypercert to update\n * @param params.updates - Partial record with fields to update\n * @param params.image - New image blob, `null` to remove, `undefined` to keep existing\n * @returns Promise resolving to update result\n * @throws {@link ValidationError} if the URI format is invalid or record fails validation\n * @throws {@link NetworkError} if the update fails\n *\n * @remarks\n * This is a partial update - only specified fields are changed.\n * The `createdAt` and `rights` fields cannot be changed.\n *\n * @example Update title and description\n * ```typescript\n * await repo.hypercerts.update({\n * uri: \"at://did:plc:abc/org.hypercerts.hypercert/xyz\",\n * updates: {\n * title: \"Updated Title\",\n * description: \"New description\",\n * },\n * });\n * ```\n *\n * @example Update with new image\n * ```typescript\n * await repo.hypercerts.update({\n * uri: hypercertUri,\n * updates: { title: \"New Title\" },\n * image: newImageBlob,\n * });\n * ```\n *\n * @example Remove image\n * ```typescript\n * await repo.hypercerts.update({\n * uri: hypercertUri,\n * updates: {},\n * image: null, // Explicitly remove image\n * });\n * ```\n */\n async update(params: {\n uri: string;\n updates: Partial<Omit<HypercertClaim, \"$type\" | \"createdAt\" | \"rights\">>;\n image?: Blob | null;\n }): Promise<UpdateResult> {\n try {\n const uriMatch = params.uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${params.uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const existing = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n // The existing record comes from ATProto, use it directly\n // TypeScript ensures type safety through the HypercertClaim interface\n const existingRecord = existing.data.value as HypercertClaim;\n\n const recordForUpdate: Record<string, unknown> = {\n ...existingRecord,\n ...params.updates,\n createdAt: existingRecord.createdAt,\n rights: existingRecord.rights,\n };\n\n // Handle image update\n delete (recordForUpdate as { image?: unknown }).image;\n if (params.image !== undefined) {\n if (params.image === null) {\n // Remove image\n } else {\n const arrayBuffer = await params.image.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.image.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n recordForUpdate.image = {\n $type: \"blob\",\n ref: uploadResult.data.blob.ref,\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n } else if (existingRecord.image) {\n // Preserve existing image\n recordForUpdate.image = existingRecord.image;\n }\n\n const validation = this.lexiconRegistry.validate(collection, recordForUpdate);\n if (!validation.valid) {\n throw new ValidationError(`Invalid hypercert record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection,\n rkey,\n record: recordForUpdate,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update hypercert\");\n }\n\n this.emit(\"recordUpdated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a hypercert by its AT-URI.\n *\n * @param uri - AT-URI of the hypercert (e.g., \"at://did:plc:abc/org.hypercerts.hypercert/xyz\")\n * @returns Promise resolving to hypercert URI, CID, and parsed record\n * @throws {@link ValidationError} if the URI format is invalid or record doesn't match schema\n * @throws {@link NetworkError} if the record cannot be fetched\n *\n * @example\n * ```typescript\n * const { uri, cid, record } = await repo.hypercerts.get(hypercertUri);\n * console.log(`${record.title}: ${record.description}`);\n * ```\n */\n async get(uri: string): Promise<{ uri: string; cid: string; record: HypercertClaim }> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get hypercert\");\n }\n\n // Validate with lexicon registry (more lenient - doesn't require $type)\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CLAIM, result.data.value);\n if (!validation.valid) {\n throw new ValidationError(`Invalid hypercert record format: ${validation.error}`);\n }\n\n return {\n uri: result.data.uri,\n cid: result.data.cid ?? \"\",\n record: result.data.value as HypercertClaim,\n };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Lists hypercerts in the repository with pagination.\n *\n * @param params - Optional pagination parameters\n * @returns Promise resolving to paginated list of hypercerts\n * @throws {@link NetworkError} if the list operation fails\n *\n * @example\n * ```typescript\n * // Get first page\n * const { records, cursor } = await repo.hypercerts.list({ limit: 20 });\n *\n * // Get next page\n * if (cursor) {\n * const nextPage = await repo.hypercerts.list({ limit: 20, cursor });\n * }\n * ```\n */\n async list(params?: ListParams): Promise<PaginatedList<{ uri: string; cid: string; record: HypercertClaim }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CLAIM,\n limit: params?.limit,\n cursor: params?.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list hypercerts\");\n }\n\n return {\n records:\n result.data.records?.map((r) => ({\n uri: r.uri,\n cid: r.cid,\n record: r.value as HypercertClaim,\n })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to list hypercerts: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Deletes a hypercert record.\n *\n * @param uri - AT-URI of the hypercert to delete\n * @throws {@link ValidationError} if the URI format is invalid\n * @throws {@link NetworkError} if the deletion fails\n *\n * @remarks\n * This only deletes the hypercert record itself. Related records\n * (rights, locations, contributions) are not automatically deleted.\n *\n * @example\n * ```typescript\n * await repo.hypercerts.delete(hypercertUri);\n * ```\n */\n async delete(uri: string): Promise<void> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.deleteRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to delete hypercert\");\n }\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to delete hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Attaches a location to an existing hypercert.\n *\n * @param hypercertUri - AT-URI of the hypercert to attach location to\n * @param location - Location data\n * @param location.value - Location value (address, coordinates, or description)\n * @param location.name - Optional human-readable name\n * @param location.description - Optional description\n * @param location.srs - Spatial Reference System (e.g., \"EPSG:4326\")\n * @param location.geojson - Optional GeoJSON blob for precise boundaries\n * @returns Promise resolving to location record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example Simple location\n * ```typescript\n * await repo.hypercerts.attachLocation(hypercertUri, {\n * value: \"San Francisco, CA\",\n * name: \"SF Bay Area\",\n * });\n * ```\n *\n * @example Location with GeoJSON\n * ```typescript\n * const geojsonBlob = new Blob([JSON.stringify(geojson)], {\n * type: \"application/geo+json\"\n * });\n *\n * await repo.hypercerts.attachLocation(hypercertUri, {\n * value: \"Custom Region\",\n * srs: \"EPSG:4326\",\n * geojson: geojsonBlob,\n * });\n * ```\n */\n async attachLocation(\n hypercertUri: string,\n location: { value: string; name?: string; description?: string; srs?: string; geojson?: Blob },\n ): Promise<CreateResult> {\n try {\n // Get hypercert to get CID\n const hypercert = await this.get(hypercertUri);\n const createdAt = new Date().toISOString();\n\n let locationValue: string | BlobRef = location.value;\n if (location.geojson) {\n const arrayBuffer = await location.geojson.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: location.geojson.type || \"application/geo+json\",\n });\n if (uploadResult.success) {\n locationValue = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n\n const locationRecord: Omit<HypercertLocation, \"$type\"> = {\n hypercert: { uri: hypercert.uri, cid: hypercert.cid },\n value: locationValue,\n createdAt,\n name: location.name,\n description: location.description,\n srs: location.srs,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.LOCATION, locationRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid location record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.LOCATION,\n record: locationRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to attach location\");\n }\n\n this.emit(\"locationAttached\", { uri: result.data.uri, cid: result.data.cid, hypercertUri });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to attach location: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Adds evidence to an existing hypercert.\n *\n * @param hypercertUri - AT-URI of the hypercert\n * @param evidence - Array of evidence items to add\n * @returns Promise resolving to update result\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @remarks\n * Evidence is appended to existing evidence, not replaced.\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addEvidence(hypercertUri, [\n * { uri: \"https://example.com/report.pdf\", description: \"Impact report\" },\n * { uri: \"https://example.com/data.csv\", description: \"Raw data\" },\n * ]);\n * ```\n */\n async addEvidence(hypercertUri: string, evidence: HypercertEvidence[]): Promise<UpdateResult> {\n try {\n const existing = await this.get(hypercertUri);\n const existingEvidence = existing.record.evidence || [];\n const updatedEvidence = [...existingEvidence, ...evidence];\n\n const result = await this.update({\n uri: hypercertUri,\n updates: { evidence: updatedEvidence },\n });\n\n this.emit(\"evidenceAdded\", { uri: result.uri, cid: result.cid });\n return result;\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add evidence: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates a contribution record.\n *\n * @param params - Contribution parameters\n * @param params.hypercertUri - Optional hypercert to link (can be standalone)\n * @param params.contributors - Array of contributor DIDs\n * @param params.role - Role of the contributors (e.g., \"coordinator\", \"implementer\")\n * @param params.description - Optional description of the contribution\n * @returns Promise resolving to contribution record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addContribution({\n * hypercertUri: hypercertUri,\n * contributors: [\"did:plc:alice\", \"did:plc:bob\"],\n * role: \"implementer\",\n * description: \"On-ground implementation team\",\n * });\n * ```\n */\n async addContribution(params: {\n hypercertUri?: string;\n contributors: string[];\n role: string;\n description?: string;\n }): Promise<CreateResult> {\n try {\n const createdAt = new Date().toISOString();\n const contributionRecord: Omit<HypercertContribution, \"$type\"> = {\n contributors: params.contributors,\n role: params.role,\n createdAt,\n description: params.description,\n };\n\n if (params.hypercertUri) {\n const hypercert = await this.get(params.hypercertUri);\n contributionRecord.hypercert = { uri: hypercert.uri, cid: hypercert.cid };\n }\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CONTRIBUTION, contributionRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid contribution record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CONTRIBUTION,\n record: contributionRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create contribution\");\n }\n\n this.emit(\"contributionCreated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to add contribution: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Creates a measurement record for a hypercert.\n *\n * Measurements quantify the impact claimed in a hypercert with\n * specific metrics and values.\n *\n * @param params - Measurement parameters\n * @param params.hypercertUri - AT-URI of the hypercert being measured\n * @param params.measurers - DIDs of entities who performed the measurement\n * @param params.metric - Name of the metric (e.g., \"CO2 Reduced\", \"Trees Planted\")\n * @param params.value - Measured value with units (e.g., \"100 tons\", \"10000\")\n * @param params.methodUri - Optional URI describing the measurement methodology\n * @param params.evidenceUris - Optional URIs to supporting evidence\n * @returns Promise resolving to measurement record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addMeasurement({\n * hypercertUri: hypercertUri,\n * measurers: [\"did:plc:auditor\"],\n * metric: \"Carbon Offset\",\n * value: \"150 tons CO2e\",\n * methodUri: \"https://example.com/methodology\",\n * evidenceUris: [\"https://example.com/audit-report\"],\n * });\n * ```\n */\n async addMeasurement(params: {\n hypercertUri: string;\n measurers: string[];\n metric: string;\n value: string;\n methodUri?: string;\n evidenceUris?: string[];\n }): Promise<CreateResult> {\n try {\n const hypercert = await this.get(params.hypercertUri);\n const createdAt = new Date().toISOString();\n\n const measurementRecord: Omit<HypercertMeasurement, \"$type\"> = {\n hypercert: { uri: hypercert.uri, cid: hypercert.cid },\n measurers: params.measurers,\n metric: params.metric,\n value: params.value,\n createdAt,\n measurementMethodURI: params.methodUri,\n evidenceURI: params.evidenceUris,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.MEASUREMENT, measurementRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid measurement record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.MEASUREMENT,\n record: measurementRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create measurement\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add measurement: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates an evaluation record for a hypercert or other subject.\n *\n * Evaluations provide third-party assessments of impact claims.\n *\n * @param params - Evaluation parameters\n * @param params.subjectUri - AT-URI of the record being evaluated\n * @param params.evaluators - DIDs of evaluating entities\n * @param params.summary - Summary of the evaluation findings\n * @returns Promise resolving to evaluation record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addEvaluation({\n * subjectUri: hypercertUri,\n * evaluators: [\"did:plc:evaluator-org\"],\n * summary: \"Verified impact claims through site visit and data analysis\",\n * });\n * ```\n */\n async addEvaluation(params: { subjectUri: string; evaluators: string[]; summary: string }): Promise<CreateResult> {\n try {\n const subject = await this.get(params.subjectUri);\n const createdAt = new Date().toISOString();\n\n const evaluationRecord: Omit<HypercertEvaluation, \"$type\"> = {\n subject: { uri: subject.uri, cid: subject.cid },\n evaluators: params.evaluators,\n summary: params.summary,\n createdAt,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.EVALUATION, evaluationRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid evaluation record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.EVALUATION,\n record: evaluationRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create evaluation\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add evaluation: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates a collection of hypercerts.\n *\n * Collections group related hypercerts with optional weights\n * for relative importance.\n *\n * @param params - Collection parameters\n * @param params.title - Collection title\n * @param params.claims - Array of hypercert references with weights\n * @param params.shortDescription - Optional short description\n * @param params.coverPhoto - Optional cover image blob\n * @returns Promise resolving to collection record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * const collection = await repo.hypercerts.createCollection({\n * title: \"Climate Projects 2024\",\n * shortDescription: \"Our climate impact portfolio\",\n * claims: [\n * { uri: hypercert1Uri, cid: hypercert1Cid, weight: \"0.5\" },\n * { uri: hypercert2Uri, cid: hypercert2Cid, weight: \"0.3\" },\n * { uri: hypercert3Uri, cid: hypercert3Cid, weight: \"0.2\" },\n * ],\n * coverPhoto: coverImageBlob,\n * });\n * ```\n */\n async createCollection(params: {\n title: string;\n claims: Array<{ uri: string; cid: string; weight: string }>;\n shortDescription?: string;\n coverPhoto?: Blob;\n }): Promise<CreateResult> {\n try {\n const createdAt = new Date().toISOString();\n\n let coverPhotoRef: BlobRef | undefined;\n if (params.coverPhoto) {\n const arrayBuffer = await params.coverPhoto.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.coverPhoto.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n coverPhotoRef = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n\n const collectionRecord: Record<string, unknown> = {\n title: params.title,\n claims: params.claims.map((c) => ({ claim: { uri: c.uri, cid: c.cid }, weight: c.weight })),\n createdAt,\n };\n\n if (params.shortDescription) {\n collectionRecord.shortDescription = params.shortDescription;\n }\n\n if (coverPhotoRef) {\n collectionRecord.coverPhoto = coverPhotoRef;\n }\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.COLLECTION, collectionRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid collection record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.COLLECTION,\n record: collectionRecord,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create collection\");\n }\n\n this.emit(\"collectionCreated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create collection: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a collection by its AT-URI.\n *\n * @param uri - AT-URI of the collection\n * @returns Promise resolving to collection URI, CID, and parsed record\n * @throws {@link ValidationError} if the URI format is invalid or record doesn't match schema\n * @throws {@link NetworkError} if the record cannot be fetched\n *\n * @example\n * ```typescript\n * const { record } = await repo.hypercerts.getCollection(collectionUri);\n * console.log(`Collection: ${record.title}`);\n * console.log(`Contains ${record.claims.length} hypercerts`);\n * ```\n */\n async getCollection(uri: string): Promise<{ uri: string; cid: string; record: HypercertCollection }> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get collection\");\n }\n\n // Validate with lexicon registry (more lenient - doesn't require $type)\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.COLLECTION, result.data.value);\n if (!validation.valid) {\n throw new ValidationError(`Invalid collection record format: ${validation.error}`);\n }\n\n return {\n uri: result.data.uri,\n cid: result.data.cid ?? \"\",\n record: result.data.value as HypercertCollection,\n };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get collection: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Lists collections in the repository with pagination.\n *\n * @param params - Optional pagination parameters\n * @returns Promise resolving to paginated list of collections\n * @throws {@link NetworkError} if the list operation fails\n *\n * @example\n * ```typescript\n * const { records } = await repo.hypercerts.listCollections();\n * for (const { record } of records) {\n * console.log(`${record.title}: ${record.claims.length} claims`);\n * }\n * ```\n */\n async listCollections(\n params?: ListParams,\n ): Promise<PaginatedList<{ uri: string; cid: string; record: HypercertCollection }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.COLLECTION,\n limit: params?.limit,\n cursor: params?.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list collections\");\n }\n\n return {\n records:\n result.data.records?.map((r) => ({\n uri: r.uri,\n cid: r.cid,\n record: r.value as HypercertCollection,\n })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to list collections: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n}\n","/**\n * CollaboratorOperationsImpl - SDS collaborator management operations.\n *\n * This module provides the implementation for managing collaborator\n * access on Shared Data Server (SDS) repositories.\n *\n * @packageDocumentation\n */\n\nimport { NetworkError } from \"../core/errors.js\";\nimport type { CollaboratorPermissions, Session } from \"../core/types.js\";\nimport type { CollaboratorOperations } from \"./interfaces.js\";\nimport type { RepositoryRole, RepositoryAccessGrant } from \"./types.js\";\n\n/**\n * Implementation of collaborator operations for SDS access control.\n *\n * This class manages access permissions for shared repositories on\n * Shared Data Servers (SDS). It provides role-based access control\n * with predefined permission sets.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.collaborators} on an SDS-connected repository.\n *\n * **Role Hierarchy**:\n * - `viewer`: Read-only access\n * - `editor`: Read + Create + Update\n * - `admin`: All permissions except ownership transfer\n * - `owner`: Full control including ownership management\n *\n * **SDS API Endpoints Used**:\n * - `com.sds.repo.grantAccess`: Grant access to a user\n * - `com.sds.repo.revokeAccess`: Revoke access from a user\n * - `com.sds.repo.listCollaborators`: List all collaborators\n * - `com.sds.repo.getPermissions`: Get current user's permissions\n * - `com.sds.repo.transferOwnership`: Transfer repository ownership\n *\n * @example\n * ```typescript\n * // Get SDS repository\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Grant editor access\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:new-user\",\n * role: \"editor\",\n * });\n *\n * // List all collaborators\n * const collaborators = await sdsRepo.collaborators.list();\n *\n * // Check specific user\n * const hasAccess = await sdsRepo.collaborators.hasAccess(\"did:plc:someone\");\n * const role = await sdsRepo.collaborators.getRole(\"did:plc:someone\");\n * ```\n *\n * @internal\n */\nexport class CollaboratorOperationsImpl implements CollaboratorOperations {\n /**\n * Creates a new CollaboratorOperationsImpl.\n *\n * @param session - Authenticated OAuth session with fetchHandler\n * @param repoDid - DID of the repository to manage\n * @param serverUrl - SDS server URL\n *\n * @internal\n */\n constructor(\n private session: Session,\n private repoDid: string,\n private serverUrl: string,\n ) {}\n\n /**\n * Converts a role to its corresponding permissions object.\n *\n * @param role - The role to convert\n * @returns Permission flags for the role\n * @internal\n */\n private roleToPermissions(role: RepositoryRole): CollaboratorPermissions {\n switch (role) {\n case \"viewer\":\n return { read: true, create: false, update: false, delete: false, admin: false, owner: false };\n case \"editor\":\n return { read: true, create: true, update: true, delete: false, admin: false, owner: false };\n case \"admin\":\n return { read: true, create: true, update: true, delete: true, admin: true, owner: false };\n case \"owner\":\n return { read: true, create: true, update: true, delete: true, admin: true, owner: true };\n }\n }\n\n /**\n * Determines the role from a permissions object.\n *\n * @param permissions - The permissions to analyze\n * @returns The highest role matching the permissions\n * @internal\n */\n private permissionsToRole(permissions: CollaboratorPermissions): RepositoryRole {\n if (permissions.owner) return \"owner\";\n if (permissions.admin) return \"admin\";\n if (permissions.create || permissions.update) return \"editor\";\n return \"viewer\";\n }\n\n /**\n * Converts a permission string array to a permissions object.\n *\n * The SDS API returns permissions as an array of strings (e.g., [\"read\", \"create\"]).\n * This method converts them to the boolean flag format used by the SDK.\n *\n * @param permissionArray - Array of permission strings from SDS API\n * @returns Permission flags object\n * @internal\n */\n private parsePermissions(permissionArray: string[]): CollaboratorPermissions {\n return {\n read: permissionArray.includes(\"read\"),\n create: permissionArray.includes(\"create\"),\n update: permissionArray.includes(\"update\"),\n delete: permissionArray.includes(\"delete\"),\n admin: permissionArray.includes(\"admin\"),\n owner: permissionArray.includes(\"owner\"),\n };\n }\n\n /**\n * Grants repository access to a user.\n *\n * @param params - Grant parameters\n * @param params.userDid - DID of the user to grant access to\n * @param params.role - Role to assign (determines permissions)\n * @throws {@link NetworkError} if the grant operation fails\n *\n * @remarks\n * If the user already has access, their permissions are updated\n * to the new role.\n *\n * @example\n * ```typescript\n * // Grant viewer access\n * await repo.collaborators.grant({\n * userDid: \"did:plc:viewer-user\",\n * role: \"viewer\",\n * });\n *\n * // Upgrade to editor\n * await repo.collaborators.grant({\n * userDid: \"did:plc:viewer-user\",\n * role: \"editor\",\n * });\n * ```\n */\n async grant(params: { userDid: string; role: RepositoryRole }): Promise<void> {\n const permissions = this.roleToPermissions(params.role);\n\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.grantAccess`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n userDid: params.userDid,\n permissions,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to grant access: ${response.statusText}`);\n }\n }\n\n /**\n * Revokes repository access from a user.\n *\n * @param params - Revoke parameters\n * @param params.userDid - DID of the user to revoke access from\n * @throws {@link NetworkError} if the revoke operation fails\n *\n * @remarks\n * - Cannot revoke access from the repository owner\n * - Revoked access is recorded with a `revokedAt` timestamp\n *\n * @example\n * ```typescript\n * await repo.collaborators.revoke({\n * userDid: \"did:plc:former-collaborator\",\n * });\n * ```\n */\n async revoke(params: { userDid: string }): Promise<void> {\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.revokeAccess`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n userDid: params.userDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to revoke access: ${response.statusText}`);\n }\n }\n\n /**\n * Lists all collaborators on the repository.\n *\n * @param params - Optional pagination parameters\n * @param params.limit - Maximum number of results (1-100, default 50)\n * @param params.cursor - Pagination cursor from previous response\n * @returns Promise resolving to collaborators and optional cursor\n * @throws {@link NetworkError} if the list operation fails\n *\n * @remarks\n * The list includes both active and revoked collaborators.\n * Check `revokedAt` to filter active collaborators.\n *\n * @example\n * ```typescript\n * // Get first page\n * const page1 = await repo.collaborators.list({ limit: 10 });\n * console.log(`Found ${page1.collaborators.length} collaborators`);\n *\n * // Get next page if available\n * if (page1.cursor) {\n * const page2 = await repo.collaborators.list({ limit: 10, cursor: page1.cursor });\n * }\n *\n * // Filter active collaborators\n * const active = page1.collaborators.filter(c => !c.revokedAt);\n * ```\n */\n async list(params?: { limit?: number; cursor?: string }): Promise<{\n collaborators: RepositoryAccessGrant[];\n cursor?: string;\n }> {\n const queryParams = new URLSearchParams({\n repo: this.repoDid,\n });\n\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n\n if (params?.cursor) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.repo.listCollaborators?${queryParams.toString()}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to list collaborators: ${response.statusText}`);\n }\n\n const data = await response.json();\n const collaborators = (data.collaborators || []).map(\n (c: {\n userDid: string;\n permissions: string[]; // SDS API returns string array\n grantedBy: string;\n grantedAt: string;\n revokedAt?: string;\n }) => {\n const permissions = this.parsePermissions(c.permissions);\n return {\n userDid: c.userDid,\n role: this.permissionsToRole(permissions),\n permissions: permissions,\n grantedBy: c.grantedBy,\n grantedAt: c.grantedAt,\n revokedAt: c.revokedAt,\n };\n },\n );\n\n return {\n collaborators,\n cursor: data.cursor,\n };\n }\n\n /**\n * Checks if a user has any access to the repository.\n *\n * @param userDid - DID of the user to check\n * @returns Promise resolving to `true` if user has active access\n *\n * @remarks\n * Returns `false` if:\n * - User was never granted access\n * - User's access was revoked\n * - The list operation fails (error is suppressed)\n *\n * @example\n * ```typescript\n * if (await repo.collaborators.hasAccess(\"did:plc:someone\")) {\n * console.log(\"User has access\");\n * }\n * ```\n */\n async hasAccess(userDid: string): Promise<boolean> {\n try {\n const { collaborators } = await this.list();\n return collaborators.some((c) => c.userDid === userDid && !c.revokedAt);\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the role assigned to a user.\n *\n * @param userDid - DID of the user to check\n * @returns Promise resolving to the user's role, or `null` if no active access\n *\n * @example\n * ```typescript\n * const role = await repo.collaborators.getRole(\"did:plc:someone\");\n * if (role === \"admin\" || role === \"owner\") {\n * // User can manage other collaborators\n * }\n * ```\n */\n async getRole(userDid: string): Promise<RepositoryRole | null> {\n const { collaborators } = await this.list();\n const collab = collaborators.find((c) => c.userDid === userDid && !c.revokedAt);\n return collab?.role ?? null;\n }\n\n /**\n * Gets the current user's permissions for this repository.\n *\n * @returns Promise resolving to the permission flags\n * @throws {@link NetworkError} if the request fails\n *\n * @remarks\n * This is useful for checking what actions the current user can perform\n * before attempting operations that might fail due to insufficient permissions.\n *\n * @example\n * ```typescript\n * const permissions = await repo.collaborators.getPermissions();\n *\n * if (permissions.admin) {\n * // Show admin UI\n * console.log(\"You can manage collaborators\");\n * }\n *\n * if (permissions.create) {\n * console.log(\"You can create records\");\n * }\n * ```\n *\n * @example Conditional UI rendering\n * ```typescript\n * const permissions = await repo.collaborators.getPermissions();\n *\n * // Show/hide UI elements based on permissions\n * const canEdit = permissions.update;\n * const canDelete = permissions.delete;\n * const isAdmin = permissions.admin;\n * const isOwner = permissions.owner;\n * ```\n */\n async getPermissions(): Promise<CollaboratorPermissions> {\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.repo.getPermissions?repo=${encodeURIComponent(this.repoDid)}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to get permissions: ${response.statusText}`);\n }\n\n const data = await response.json();\n return data.permissions as CollaboratorPermissions;\n }\n\n /**\n * Transfers repository ownership to another user.\n *\n * @param params - Transfer parameters\n * @param params.newOwnerDid - DID of the user to transfer ownership to\n * @throws {@link NetworkError} if the transfer fails\n *\n * @remarks\n * **IMPORTANT**: This action is irreversible. Once ownership is transferred:\n * - The new owner gains full control of the repository\n * - Your role will be changed to admin (or specified role)\n * - You cannot transfer ownership back without the new owner's approval\n *\n * **Requirements**:\n * - You must be the current owner\n * - The new owner must have an existing account\n * - The new owner will be notified of the ownership transfer\n *\n * @example\n * ```typescript\n * // Transfer ownership to another user\n * await repo.collaborators.transferOwnership({\n * newOwnerDid: \"did:plc:new-owner\",\n * });\n *\n * console.log(\"Ownership transferred successfully\");\n * // You are now an admin, not the owner\n * ```\n *\n * @example With confirmation\n * ```typescript\n * const confirmTransfer = await askUser(\n * \"Are you sure you want to transfer ownership? This cannot be undone.\"\n * );\n *\n * if (confirmTransfer) {\n * await repo.collaborators.transferOwnership({\n * newOwnerDid: \"did:plc:new-owner\",\n * });\n * }\n * ```\n */\n async transferOwnership(params: { newOwnerDid: string }): Promise<void> {\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.transferOwnership`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n newOwner: params.newOwnerDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to transfer ownership: ${response.statusText}`);\n }\n }\n}\n","/**\n * OrganizationOperationsImpl - SDS organization management operations.\n *\n * This module provides the implementation for creating and managing\n * organizations on Shared Data Server (SDS) instances.\n *\n * @packageDocumentation\n */\n\nimport { NetworkError } from \"../core/errors.js\";\nimport type { CollaboratorPermissions, Session } from \"../core/types.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { OrganizationOperations } from \"./interfaces.js\";\nimport type { OrganizationInfo } from \"./types.js\";\n\n/**\n * Implementation of organization operations for SDS management.\n *\n * Organizations on SDS provide a way to create shared repositories\n * that multiple users can collaborate on. Each organization has:\n *\n * - A unique DID (Decentralized Identifier)\n * - A handle for human-readable identification\n * - An owner and optional collaborators\n * - Its own repository for storing records\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.organizations} on an SDS-connected repository.\n *\n * **SDS API Endpoints Used**:\n * - `com.sds.organization.create`: Create a new organization\n * - `com.sds.organization.list`: List accessible organizations\n *\n * **Access Types**:\n * - `\"owner\"`: User created or owns the organization\n * - `\"collaborator\"`: User was invited with specific permissions\n *\n * @example\n * ```typescript\n * // Get SDS repository\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Create an organization\n * const org = await sdsRepo.organizations.create({\n * name: \"My Team\",\n * description: \"A team for impact projects\",\n * });\n *\n * // List organizations you have access to\n * const orgs = await sdsRepo.organizations.list();\n *\n * // Get specific organization\n * const orgInfo = await sdsRepo.organizations.get(org.did);\n * ```\n *\n * @internal\n */\nexport class OrganizationOperationsImpl implements OrganizationOperations {\n /**\n * Creates a new OrganizationOperationsImpl.\n *\n * @param session - Authenticated OAuth session with fetchHandler\n * @param _repoDid - DID of the user's repository (reserved for future use)\n * @param serverUrl - SDS server URL\n * @param _logger - Optional logger for debugging (reserved for future use)\n *\n * @internal\n */\n constructor(\n private session: Session,\n private _repoDid: string,\n private serverUrl: string,\n private _logger?: LoggerInterface,\n ) {}\n\n /**\n * Creates a new organization.\n *\n * @param params - Organization parameters\n * @param params.name - Display name for the organization\n * @param params.description - Optional description of the organization's purpose\n * @param params.handle - Optional custom handle. If not provided, one is auto-generated.\n * @returns Promise resolving to the created organization info\n * @throws {@link NetworkError} if organization creation fails\n *\n * @remarks\n * The creating user automatically becomes the owner with full permissions.\n *\n * **Handle Format**: Handles are typically formatted as\n * `{name}.sds.{domain}` (e.g., \"my-team.sds.hypercerts.org\").\n * If you provide a custom handle, it must be unique on the SDS.\n *\n * @example Basic organization\n * ```typescript\n * const org = await repo.organizations.create({\n * name: \"Climate Action Team\",\n * });\n * console.log(`Created org: ${org.did}`);\n * ```\n *\n * @example With description and custom handle\n * ```typescript\n * const org = await repo.organizations.create({\n * name: \"Reforestation Initiative\",\n * description: \"Coordinating tree planting projects worldwide\",\n * handle: \"reforestation\",\n * });\n * ```\n */\n async create(params: { name: string; description?: string; handle?: string }): Promise<OrganizationInfo> {\n const userDid = this.session.did || this.session.sub;\n if (!userDid) {\n throw new NetworkError(\"No authenticated user found\");\n }\n\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.organization.create`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n ...params,\n creatorDid: userDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to create organization: ${response.statusText}`);\n }\n\n const data = await response.json();\n return {\n did: data.did,\n handle: data.handle,\n name: data.name,\n description: data.description,\n createdAt: data.createdAt || new Date().toISOString(),\n accessType: data.accessType || \"owner\",\n permissions: data.permissions || {\n read: true,\n create: true,\n update: true,\n delete: true,\n admin: true,\n owner: true,\n },\n };\n }\n\n /**\n * Gets an organization by its DID.\n *\n * @param did - The organization's DID\n * @returns Promise resolving to organization info, or `null` if not found\n *\n * @remarks\n * This method searches through the user's accessible organizations.\n * If the organization exists but the user doesn't have access,\n * it will return `null`.\n *\n * @example\n * ```typescript\n * const org = await repo.organizations.get(\"did:plc:org123\");\n * if (org) {\n * console.log(`Found: ${org.name}`);\n * console.log(`Your role: ${org.accessType}`);\n * } else {\n * console.log(\"Organization not found or no access\");\n * }\n * ```\n */\n async get(did: string): Promise<OrganizationInfo | null> {\n try {\n const { organizations } = await this.list();\n return organizations.find((o) => o.did === did) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Lists organizations the current user has access to.\n *\n * @param params - Optional pagination parameters\n * @param params.limit - Maximum number of results (1-100, default 50)\n * @param params.cursor - Pagination cursor from previous response\n * @returns Promise resolving to organizations and optional cursor\n * @throws {@link NetworkError} if the list operation fails\n *\n * @remarks\n * Returns organizations where the user is either:\n * - The owner\n * - A collaborator with any permission level\n *\n * The `accessType` field indicates the user's relationship to each organization.\n *\n * @example\n * ```typescript\n * // Get first page\n * const page1 = await repo.organizations.list({ limit: 20 });\n * console.log(`Found ${page1.organizations.length} organizations`);\n *\n * // Get next page if available\n * if (page1.cursor) {\n * const page2 = await repo.organizations.list({ limit: 20, cursor: page1.cursor });\n * }\n *\n * // Filter by access type\n * const owned = page1.organizations.filter(o => o.accessType === \"owner\");\n * const shared = page1.organizations.filter(o => o.accessType === \"shared\");\n * ```\n *\n * @example Display organization details\n * ```typescript\n * const { organizations } = await repo.organizations.list();\n *\n * for (const org of organizations) {\n * console.log(`${org.name} (@${org.handle})`);\n * console.log(` DID: ${org.did}`);\n * console.log(` Access: ${org.accessType}`);\n * if (org.description) {\n * console.log(` Description: ${org.description}`);\n * }\n * }\n * ```\n */\n async list(params?: { limit?: number; cursor?: string }): Promise<{\n organizations: OrganizationInfo[];\n cursor?: string;\n }> {\n const userDid = this.session.did || this.session.sub;\n if (!userDid) {\n throw new NetworkError(\"No authenticated user found\");\n }\n\n const queryParams = new URLSearchParams({\n userDid,\n });\n\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n\n if (params?.cursor) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.organization.list?${queryParams.toString()}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to list organizations: ${response.statusText}`);\n }\n\n const data = await response.json();\n const organizations = (data.organizations || []).map(\n (r: {\n did: string;\n handle: string;\n name: string;\n description?: string;\n createdAt?: string;\n accessType: \"owner\" | \"shared\" | \"none\";\n permissions: CollaboratorPermissions;\n }) => ({\n did: r.did,\n handle: r.handle,\n name: r.name,\n description: r.description,\n createdAt: r.createdAt || new Date().toISOString(),\n accessType: r.accessType,\n permissions: r.permissions,\n }),\n );\n\n return {\n organizations,\n cursor: data.cursor,\n };\n }\n}\n","/**\n * Repository - Unified fluent API for ATProto repository operations.\n *\n * This module provides the main interface for interacting with AT Protocol\n * data servers (PDS and SDS) through a consistent, fluent API.\n *\n * @packageDocumentation\n */\n\nimport { Agent } from \"@atproto/api\";\nimport { SDSRequiredError } from \"../core/errors.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { Session } from \"../core/types.js\";\nimport { HYPERCERT_LEXICONS } from \"@hypercerts-org/lexicon\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\n\n// Types\nexport type {\n RepositoryOptions,\n CreateResult,\n UpdateResult,\n PaginatedList,\n ListParams,\n RepositoryRole,\n RepositoryAccessGrant,\n OrganizationInfo,\n ProgressStep,\n} from \"./types.js\";\n\n// Interfaces\nexport type {\n RecordOperations,\n BlobOperations,\n ProfileOperations,\n HypercertOperations,\n HypercertEvents,\n CollaboratorOperations,\n OrganizationOperations,\n CreateHypercertParams,\n CreateHypercertResult,\n} from \"./interfaces.js\";\n\n// Implementations\nimport { RecordOperationsImpl } from \"./RecordOperationsImpl.js\";\nimport { BlobOperationsImpl } from \"./BlobOperationsImpl.js\";\nimport { ProfileOperationsImpl } from \"./ProfileOperationsImpl.js\";\nimport { HypercertOperationsImpl } from \"./HypercertOperationsImpl.js\";\nimport { CollaboratorOperationsImpl } from \"./CollaboratorOperationsImpl.js\";\nimport { OrganizationOperationsImpl } from \"./OrganizationOperationsImpl.js\";\n\nimport type {\n RecordOperations,\n BlobOperations,\n ProfileOperations,\n HypercertOperations,\n CollaboratorOperations,\n OrganizationOperations,\n} from \"./interfaces.js\";\n\n/**\n * Repository provides a fluent API for AT Protocol data operations.\n *\n * This class is the primary interface for working with data in the AT Protocol\n * ecosystem. It provides organized access to:\n *\n * - **Records**: Low-level CRUD operations for any AT Protocol record type\n * - **Blobs**: Binary data upload and retrieval (images, files)\n * - **Profile**: User profile management\n * - **Hypercerts**: High-level hypercert creation and management\n * - **Collaborators**: Access control for shared repositories (SDS only)\n * - **Organizations**: Organization management (SDS only)\n *\n * @remarks\n * The Repository uses lazy initialization for operation handlers - they are\n * created only when first accessed. This improves performance when you only\n * need a subset of operations.\n *\n * **PDS vs SDS:**\n * - **PDS (Personal Data Server)**: User's own data storage. All operations\n * except collaborators and organizations are available.\n * - **SDS (Shared Data Server)**: Collaborative data storage with access\n * control. All operations including collaborators and organizations.\n *\n * @example Basic usage\n * ```typescript\n * // Get a repository from the SDK\n * const repo = sdk.repository(session);\n *\n * // Access user profile\n * const profile = await repo.profile.get();\n *\n * // Create a hypercert\n * const result = await repo.hypercerts.create({\n * title: \"My Impact\",\n * description: \"Description of the impact\",\n * workScope: \"Climate Action\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: {\n * name: \"Attribution\",\n * type: \"license\",\n * description: \"CC-BY-4.0\",\n * },\n * });\n * ```\n *\n * @example Working with a different user's repository\n * ```typescript\n * // Get the current user's repo\n * const myRepo = sdk.repository(session);\n *\n * // Get another user's repo (read-only for most operations)\n * const otherRepo = myRepo.repo(\"did:plc:other-user-did\");\n * const theirProfile = await otherRepo.profile.get();\n * ```\n *\n * @example SDS operations\n * ```typescript\n * // Get SDS repository for collaborator features\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Manage collaborators\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:collaborator\",\n * role: \"editor\",\n * });\n *\n * // List organizations\n * const orgs = await sdsRepo.organizations.list();\n * ```\n *\n * @see {@link ATProtoSDK.repository} for creating Repository instances\n */\nexport class Repository {\n private session: Session;\n private serverUrl: string;\n private repoDid: string;\n private lexiconRegistry: LexiconRegistry;\n private logger?: LoggerInterface;\n private agent: Agent;\n private _isSDS: boolean;\n\n // Lazily initialized operations\n private _records?: RecordOperationsImpl;\n private _blobs?: BlobOperationsImpl;\n private _profile?: ProfileOperationsImpl;\n private _hypercerts?: HypercertOperationsImpl;\n private _collaborators?: CollaboratorOperationsImpl;\n private _organizations?: OrganizationOperationsImpl;\n\n /**\n * Creates a new Repository instance.\n *\n * @param session - Authenticated OAuth session\n * @param serverUrl - Base URL of the AT Protocol server\n * @param repoDid - DID of the repository to operate on\n * @param lexiconRegistry - Registry for lexicon validation\n * @param isSDS - Whether this is a Shared Data Server\n * @param logger - Optional logger for debugging\n *\n * @remarks\n * This constructor is typically not called directly. Use\n * {@link ATProtoSDK.repository} to create Repository instances.\n *\n * @internal\n */\n constructor(\n session: Session,\n serverUrl: string,\n repoDid: string,\n lexiconRegistry: LexiconRegistry,\n isSDS: boolean,\n logger?: LoggerInterface,\n ) {\n this.session = session;\n this.serverUrl = serverUrl;\n this.repoDid = repoDid;\n this.lexiconRegistry = lexiconRegistry;\n this._isSDS = isSDS;\n this.logger = logger;\n\n // Create Agent with OAuth session\n this.agent = new Agent(session);\n this.lexiconRegistry.addToAgent(this.agent);\n\n // Register hypercert lexicons\n this.lexiconRegistry.registerMany(HYPERCERT_LEXICONS);\n }\n\n /**\n * The DID (Decentralized Identifier) of this repository.\n *\n * This is the user or organization that owns the repository data.\n *\n * @example\n * ```typescript\n * console.log(`Working with repo: ${repo.did}`);\n * // Output: Working with repo: did:plc:abc123xyz...\n * ```\n */\n get did(): string {\n return this.repoDid;\n }\n\n /**\n * Whether this repository is on a Shared Data Server (SDS).\n *\n * SDS servers support additional features like collaborators and\n * organizations. Attempting to use these features on a PDS will\n * throw {@link SDSRequiredError}.\n *\n * @example\n * ```typescript\n * if (repo.isSDS) {\n * const collaborators = await repo.collaborators.list();\n * }\n * ```\n */\n get isSDS(): boolean {\n return this._isSDS;\n }\n\n /**\n * Gets the server URL this repository connects to.\n *\n * @returns The base URL of the AT Protocol server\n *\n * @example\n * ```typescript\n * console.log(repo.getServerUrl());\n * // Output: https://bsky.social or https://sds.hypercerts.org\n * ```\n */\n getServerUrl(): string {\n return this.serverUrl;\n }\n\n /**\n * Creates a Repository instance for a different DID on the same server.\n *\n * This allows you to read data from other users' repositories while\n * maintaining your authenticated session.\n *\n * @param did - The DID of the repository to access\n * @returns A new Repository instance for the specified DID\n *\n * @remarks\n * Write operations on another user's repository will typically fail\n * unless you have been granted collaborator access (SDS only).\n *\n * @example\n * ```typescript\n * // Read another user's profile\n * const otherRepo = repo.repo(\"did:plc:other-user\");\n * const profile = await otherRepo.profile.get();\n *\n * // List their public hypercerts\n * const hypercerts = await otherRepo.hypercerts.list();\n * ```\n */\n repo(did: string): Repository {\n return new Repository(this.session, this.serverUrl, did, this.lexiconRegistry, this._isSDS, this.logger);\n }\n\n /**\n * Low-level record operations for CRUD on any AT Protocol record type.\n *\n * Use this for direct access to AT Protocol records when the high-level\n * APIs don't meet your needs.\n *\n * @returns {@link RecordOperations} interface for record CRUD\n *\n * @example\n * ```typescript\n * // Create a custom record\n * const result = await repo.records.create({\n * collection: \"org.example.myRecord\",\n * record: { foo: \"bar\" },\n * });\n *\n * // List records in a collection\n * const list = await repo.records.list({\n * collection: \"org.example.myRecord\",\n * limit: 50,\n * });\n *\n * // Get a specific record\n * const record = await repo.records.get({\n * collection: \"org.example.myRecord\",\n * rkey: \"abc123\",\n * });\n * ```\n */\n get records(): RecordOperations {\n if (!this._records) {\n this._records = new RecordOperationsImpl(this.agent, this.repoDid, this.lexiconRegistry);\n }\n return this._records;\n }\n\n /**\n * Blob operations for uploading and retrieving binary data.\n *\n * Blobs are used for images, files, and other binary content associated\n * with records.\n *\n * @returns {@link BlobOperations} interface for blob management\n *\n * @example\n * ```typescript\n * // Upload an image\n * const imageBlob = new Blob([imageData], { type: \"image/png\" });\n * const uploadResult = await repo.blobs.upload(imageBlob);\n *\n * // The ref can be used in records\n * console.log(uploadResult.ref.$link); // CID of the blob\n *\n * // Retrieve a blob by CID\n * const { data, mimeType } = await repo.blobs.get(cid);\n * ```\n */\n get blobs(): BlobOperations {\n if (!this._blobs) {\n this._blobs = new BlobOperationsImpl(this.agent, this.repoDid, this.serverUrl);\n }\n return this._blobs;\n }\n\n /**\n * Profile operations for managing user profiles.\n *\n * @returns {@link ProfileOperations} interface for profile management\n *\n * @example\n * ```typescript\n * // Get current profile\n * const profile = await repo.profile.get();\n * console.log(profile.displayName);\n *\n * // Update profile\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"Updated bio\",\n * avatar: avatarBlob, // Optional: update avatar image\n * });\n * ```\n */\n get profile(): ProfileOperations {\n if (!this._profile) {\n this._profile = new ProfileOperationsImpl(this.agent, this.repoDid, this.serverUrl);\n }\n return this._profile;\n }\n\n /**\n * High-level hypercert operations.\n *\n * Provides a convenient API for creating and managing hypercerts,\n * including related records like locations, contributions, and evidence.\n *\n * @returns {@link HypercertOperations} interface with EventEmitter capabilities\n *\n * @example Creating a hypercert\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"Climate Action Project\",\n * description: \"Reduced carbon emissions by 1000 tons\",\n * workScope: \"Climate Action\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-06-30\",\n * rights: {\n * name: \"Public Domain\",\n * type: \"license\",\n * description: \"CC0 - No Rights Reserved\",\n * },\n * image: imageBlob, // Optional cover image\n * location: {\n * value: \"San Francisco, CA\",\n * name: \"SF Bay Area\",\n * },\n * });\n * console.log(`Created: ${result.hypercertUri}`);\n * ```\n *\n * @example Listening to events\n * ```typescript\n * repo.hypercerts.on(\"recordCreated\", ({ uri, cid }) => {\n * console.log(`Record created: ${uri}`);\n * });\n * ```\n */\n get hypercerts(): HypercertOperations {\n if (!this._hypercerts) {\n this._hypercerts = new HypercertOperationsImpl(\n this.agent,\n this.repoDid,\n this.serverUrl,\n this.lexiconRegistry,\n this.logger,\n );\n }\n return this._hypercerts;\n }\n\n /**\n * Collaborator operations for managing repository access.\n *\n * **SDS Only**: This property throws {@link SDSRequiredError} if accessed\n * on a PDS repository.\n *\n * @returns {@link CollaboratorOperations} interface for access control\n * @throws {@link SDSRequiredError} if not connected to an SDS server\n *\n * @example\n * ```typescript\n * // Ensure we're on SDS\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Grant editor access\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:new-collaborator\",\n * role: \"editor\",\n * });\n *\n * // List all collaborators\n * const collaborators = await sdsRepo.collaborators.list();\n *\n * // Check access\n * const hasAccess = await sdsRepo.collaborators.hasAccess(\"did:plc:someone\");\n *\n * // Revoke access\n * await sdsRepo.collaborators.revoke({ userDid: \"did:plc:former-collaborator\" });\n * ```\n */\n get collaborators(): CollaboratorOperations {\n if (!this._isSDS) {\n throw new SDSRequiredError(\"Collaborator operations are only available on SDS servers\");\n }\n if (!this._collaborators) {\n this._collaborators = new CollaboratorOperationsImpl(this.session, this.repoDid, this.serverUrl);\n }\n return this._collaborators;\n }\n\n /**\n * Organization operations for creating and managing organizations.\n *\n * **SDS Only**: This property throws {@link SDSRequiredError} if accessed\n * on a PDS repository.\n *\n * @returns {@link OrganizationOperations} interface for organization management\n * @throws {@link SDSRequiredError} if not connected to an SDS server\n *\n * @example\n * ```typescript\n * // Ensure we're on SDS\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Create an organization\n * const org = await sdsRepo.organizations.create({\n * name: \"My Organization\",\n * description: \"A team working on impact certificates\",\n * handle: \"my-org\", // Optional custom handle\n * });\n *\n * // List organizations you have access to\n * const orgs = await sdsRepo.organizations.list();\n *\n * // Get specific organization\n * const orgInfo = await sdsRepo.organizations.get(org.did);\n * ```\n */\n get organizations(): OrganizationOperations {\n if (!this._isSDS) {\n throw new SDSRequiredError(\"Organization operations are only available on SDS servers\");\n }\n if (!this._organizations) {\n this._organizations = new OrganizationOperationsImpl(this.session, this.repoDid, this.serverUrl, this.logger);\n }\n return this._organizations;\n }\n}\n","import { z } from \"zod\";\nimport type { SessionStore, StateStore, CacheInterface, LoggerInterface } from \"./interfaces.js\";\n\n/**\n * Zod schema for OAuth configuration validation.\n *\n * @remarks\n * All URLs must be valid and use HTTPS in production. The `jwkPrivate` field\n * should contain the private key in JWK (JSON Web Key) format as a string.\n */\nexport const OAuthConfigSchema = z.object({\n /**\n * URL to the OAuth client metadata JSON document.\n * This document describes your application to the authorization server.\n *\n * @see https://atproto.com/specs/oauth#client-metadata\n */\n clientId: z.string().url(),\n\n /**\n * URL where users are redirected after authentication.\n * Must match one of the redirect URIs in your client metadata.\n */\n redirectUri: z.string().url(),\n\n /**\n * OAuth scopes to request, space-separated.\n * Common scopes: \"atproto\", \"transition:generic\"\n */\n scope: z.string(),\n\n /**\n * URL to your public JWKS (JSON Web Key Set) endpoint.\n * Used by the authorization server to verify your client's signatures.\n */\n jwksUri: z.string().url(),\n\n /**\n * Private JWK (JSON Web Key) as a JSON string.\n * Used for signing DPoP proofs and client assertions.\n *\n * @remarks\n * This should be kept secret and never exposed to clients.\n * Typically loaded from environment variables or a secrets manager.\n */\n jwkPrivate: z.string(),\n});\n\n/**\n * Zod schema for server URL configuration.\n *\n * @remarks\n * At least one server (PDS or SDS) should be configured for the SDK to be useful.\n */\nexport const ServerConfigSchema = z.object({\n /**\n * Personal Data Server URL - the user's own AT Protocol server.\n * This is the primary server for user data operations.\n *\n * @example \"https://bsky.social\"\n */\n pds: z.string().url().optional(),\n\n /**\n * Shared Data Server URL - for collaborative data storage.\n * Required for collaborator and organization operations.\n *\n * @example \"https://sds.hypercerts.org\"\n */\n sds: z.string().url().optional(),\n});\n\n/**\n * Zod schema for timeout configuration.\n *\n * @remarks\n * All timeout values are in milliseconds.\n */\nexport const TimeoutConfigSchema = z.object({\n /**\n * Timeout for fetching PDS metadata during identity resolution.\n * @default 5000 (5 seconds, set by OAuthClient)\n */\n pdsMetadata: z.number().positive().optional(),\n\n /**\n * Timeout for general API requests to PDS/SDS.\n * @default 30000 (30 seconds)\n */\n apiRequests: z.number().positive().optional(),\n});\n\n/**\n * Zod schema for SDK configuration validation.\n *\n * @remarks\n * This schema validates only the primitive/serializable parts of the configuration.\n * Storage interfaces ({@link SessionStore}, {@link StateStore}) cannot be validated\n * with Zod as they are runtime objects.\n */\nexport const ATProtoSDKConfigSchema = z.object({\n oauth: OAuthConfigSchema,\n servers: ServerConfigSchema.optional(),\n timeouts: TimeoutConfigSchema.optional(),\n});\n\n/**\n * Configuration options for the ATProto SDK.\n *\n * This interface defines all configuration needed to initialize the SDK,\n * including OAuth credentials, server endpoints, and optional customizations.\n *\n * @example Minimal configuration\n * ```typescript\n * const config: ATProtoSDKConfig = {\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: {\n * pds: \"https://bsky.social\",\n * },\n * };\n * ```\n *\n * @example Full configuration with custom storage\n * ```typescript\n * const config: ATProtoSDKConfig = {\n * oauth: { ... },\n * servers: {\n * pds: \"https://bsky.social\",\n * sds: \"https://sds.hypercerts.org\",\n * },\n * storage: {\n * sessionStore: new RedisSessionStore(redisClient),\n * stateStore: new RedisStateStore(redisClient),\n * },\n * timeouts: {\n * pdsMetadata: 5000,\n * apiRequests: 30000,\n * },\n * logger: console,\n * };\n * ```\n */\nexport interface ATProtoSDKConfig {\n /**\n * OAuth 2.0 configuration for authentication.\n *\n * Required fields for the OAuth flow with DPoP (Demonstrating Proof of Possession).\n * Your application must host the client metadata and JWKS endpoints.\n *\n * @see https://atproto.com/specs/oauth for AT Protocol OAuth specification\n */\n oauth: z.infer<typeof OAuthConfigSchema>;\n\n /**\n * Server URLs for PDS and SDS connections.\n *\n * - **PDS**: Personal Data Server - user's own data storage\n * - **SDS**: Shared Data Server - collaborative storage with access control\n */\n servers?: z.infer<typeof ServerConfigSchema>;\n\n /**\n * Storage adapters for persisting OAuth sessions and state.\n *\n * If not provided, in-memory implementations are used automatically.\n * **Warning**: In-memory storage is lost on process restart - use persistent\n * storage (Redis, database, etc.) in production.\n *\n * @example\n * ```typescript\n * storage: {\n * sessionStore: new RedisSessionStore(redis),\n * stateStore: new RedisStateStore(redis),\n * }\n * ```\n */\n storage?: {\n /**\n * Persistent storage for OAuth sessions.\n * Sessions contain access tokens, refresh tokens, and DPoP keys.\n */\n sessionStore?: SessionStore;\n\n /**\n * Temporary storage for OAuth state during the authorization flow.\n * State is short-lived and used for PKCE and CSRF protection.\n */\n stateStore?: StateStore;\n };\n\n /**\n * Custom fetch implementation for HTTP requests.\n *\n * Use this to add custom headers, logging, or to use a different HTTP client.\n * Must be compatible with the standard Fetch API.\n *\n * @example\n * ```typescript\n * fetch: async (url, init) => {\n * console.log(`Fetching: ${url}`);\n * return globalThis.fetch(url, init);\n * }\n * ```\n */\n fetch?: typeof fetch;\n\n /**\n * Timeout configuration for network requests.\n * Values are in milliseconds.\n */\n timeouts?: z.infer<typeof TimeoutConfigSchema>;\n\n /**\n * Cache for profiles, metadata, and other frequently accessed data.\n *\n * Implementing caching can significantly reduce API calls and improve performance.\n * The SDK does not provide a default cache - you must implement {@link CacheInterface}.\n */\n cache?: CacheInterface;\n\n /**\n * Logger for debugging and observability.\n *\n * The logger receives debug, info, warn, and error messages from the SDK.\n * Compatible with `console` or any logger implementing {@link LoggerInterface}.\n *\n * @example\n * ```typescript\n * logger: console\n * // or\n * logger: pino()\n * // or\n * logger: winston.createLogger({ ... })\n * ```\n */\n logger?: LoggerInterface;\n}\n","import { OAuthClient } from \"../auth/OAuthClient.js\";\nimport { LexiconRegistry } from \"../repository/LexiconRegistry.js\";\nimport { Repository } from \"../repository/Repository.js\";\nimport type { RepositoryOptions } from \"../repository/types.js\";\nimport { InMemorySessionStore } from \"../storage/InMemorySessionStore.js\";\nimport { InMemoryStateStore } from \"../storage/InMemoryStateStore.js\";\nimport type { ATProtoSDKConfig } from \"./config.js\";\nimport { ATProtoSDKConfigSchema } from \"./config.js\";\nimport { ValidationError } from \"./errors.js\";\nimport type { Session } from \"./types.js\";\n\n/**\n * Options for the OAuth authorization flow.\n */\nexport interface AuthorizeOptions {\n /**\n * OAuth scope string to request specific permissions.\n * Overrides the default scope configured in {@link ATProtoSDKConfig.oauth.scope}.\n *\n * @example\n * ```typescript\n * // Request read-only access\n * await sdk.authorize(\"user.bsky.social\", { scope: \"atproto\" });\n *\n * // Request full access (default typically includes transition:generic)\n * await sdk.authorize(\"user.bsky.social\", { scope: \"atproto transition:generic\" });\n * ```\n */\n scope?: string;\n}\n\n/**\n * Main ATProto SDK class providing OAuth authentication and repository access.\n *\n * This is the primary entry point for interacting with AT Protocol servers.\n * It handles the OAuth 2.0 flow with DPoP (Demonstrating Proof of Possession)\n * and provides access to repository operations for managing records, blobs,\n * and profiles.\n *\n * @example Basic usage with OAuth flow\n * ```typescript\n * import { ATProtoSDK, InMemorySessionStore, InMemoryStateStore } from \"@hypercerts-org/sdk\";\n *\n * const sdk = new ATProtoSDK({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: {\n * pds: \"https://bsky.social\",\n * sds: \"https://sds.hypercerts.org\",\n * },\n * });\n *\n * // Start OAuth flow - redirect user to this URL\n * const authUrl = await sdk.authorize(\"user.bsky.social\");\n *\n * // After user returns, handle the callback\n * const session = await sdk.callback(new URLSearchParams(window.location.search));\n *\n * // Get a repository to work with data\n * const repo = sdk.repository(session);\n * ```\n *\n * @example Restoring an existing session\n * ```typescript\n * // Restore a previous session by DID\n * const session = await sdk.restoreSession(\"did:plc:abc123...\");\n * if (session) {\n * const repo = sdk.repository(session);\n * // Continue working with the restored session\n * }\n * ```\n *\n * @see {@link ATProtoSDKConfig} for configuration options\n * @see {@link Repository} for data operations\n * @see {@link OAuthClient} for OAuth implementation details\n */\nexport class ATProtoSDK {\n private oauthClient: OAuthClient;\n private config: ATProtoSDKConfig;\n private logger?: ATProtoSDKConfig[\"logger\"];\n private lexiconRegistry: LexiconRegistry;\n\n /**\n * Creates a new ATProto SDK instance.\n *\n * @param config - SDK configuration including OAuth credentials, server URLs, and optional storage adapters\n * @throws {@link ValidationError} if the configuration is invalid (e.g., malformed URLs, missing required fields)\n *\n * @remarks\n * If no storage adapters are provided, in-memory implementations are used.\n * These are suitable for development and testing but **not recommended for production**\n * as sessions will be lost on restart.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses in-memory storage)\n * const sdk = new ATProtoSDK({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: privateKeyJwk,\n * },\n * servers: { pds: \"https://bsky.social\" },\n * });\n * ```\n */\n constructor(config: ATProtoSDKConfig) {\n // Validate configuration\n const validationResult = ATProtoSDKConfigSchema.safeParse(config);\n if (!validationResult.success) {\n throw new ValidationError(`Invalid SDK configuration: ${validationResult.error.message}`, validationResult.error);\n }\n\n // Apply defaults for optional storage\n const configWithDefaults: ATProtoSDKConfig = {\n ...config,\n storage: {\n sessionStore: config.storage?.sessionStore ?? new InMemorySessionStore(),\n stateStore: config.storage?.stateStore ?? new InMemoryStateStore(),\n },\n };\n\n this.config = configWithDefaults;\n this.logger = config.logger;\n\n // Initialize OAuth client\n this.oauthClient = new OAuthClient(configWithDefaults);\n\n // Initialize lexicon registry\n this.lexiconRegistry = new LexiconRegistry();\n\n this.logger?.info(\"ATProto SDK initialized\");\n }\n\n /**\n * Initiates the OAuth authorization flow.\n *\n * This method starts the OAuth 2.0 authorization flow by resolving the user's\n * identity and generating an authorization URL. The user should be redirected\n * to this URL to authenticate.\n *\n * @param identifier - The user's ATProto identifier. Can be:\n * - A handle (e.g., `\"user.bsky.social\"`)\n * - A DID (e.g., `\"did:plc:abc123...\"`)\n * - A PDS URL (e.g., `\"https://bsky.social\"`)\n * @param options - Optional authorization settings\n * @returns A Promise resolving to the authorization URL to redirect the user to\n * @throws {@link ValidationError} if the identifier is empty or invalid\n * @throws {@link NetworkError} if the identity cannot be resolved\n *\n * @example\n * ```typescript\n * // Using a handle\n * const authUrl = await sdk.authorize(\"alice.bsky.social\");\n *\n * // Using a DID directly\n * const authUrl = await sdk.authorize(\"did:plc:abc123xyz\");\n *\n * // With custom scope\n * const authUrl = await sdk.authorize(\"alice.bsky.social\", {\n * scope: \"atproto transition:generic\"\n * });\n *\n * // Redirect user to authUrl\n * window.location.href = authUrl;\n * ```\n */\n async authorize(identifier: string, options?: AuthorizeOptions): Promise<string> {\n if (!identifier || !identifier.trim()) {\n throw new ValidationError(\"ATProto identifier is required\");\n }\n\n return this.oauthClient.authorize(identifier.trim(), options);\n }\n\n /**\n * Handles the OAuth callback and exchanges the authorization code for tokens.\n *\n * Call this method when the user is redirected back to your application\n * after authenticating. It validates the OAuth state, exchanges the\n * authorization code for access/refresh tokens, and creates a session.\n *\n * @param params - URL search parameters from the callback URL\n * @returns A Promise resolving to the authenticated OAuth session\n * @throws {@link AuthenticationError} if the callback parameters are invalid or the code exchange fails\n * @throws {@link ValidationError} if required parameters are missing\n *\n * @example\n * ```typescript\n * // In your callback route handler\n * const params = new URLSearchParams(window.location.search);\n * // params contains: code, state, iss (issuer)\n *\n * const session = await sdk.callback(params);\n * console.log(`Authenticated as ${session.did}`);\n *\n * // Store the DID to restore the session later\n * localStorage.setItem(\"userDid\", session.did);\n * ```\n */\n async callback(params: URLSearchParams): Promise<Session> {\n return this.oauthClient.callback(params);\n }\n\n /**\n * Restores an existing OAuth session by DID.\n *\n * Use this method to restore a previously authenticated session, typically\n * on application startup. The method retrieves the stored session and\n * automatically refreshes expired tokens if needed.\n *\n * @param did - The user's Decentralized Identifier (DID), e.g., `\"did:plc:abc123...\"`\n * @returns A Promise resolving to the restored session, or `null` if no session exists\n * @throws {@link ValidationError} if the DID is empty\n * @throws {@link SessionExpiredError} if the session cannot be refreshed\n *\n * @example\n * ```typescript\n * // On application startup\n * const savedDid = localStorage.getItem(\"userDid\");\n * if (savedDid) {\n * const session = await sdk.restoreSession(savedDid);\n * if (session) {\n * // User is still authenticated\n * const repo = sdk.repository(session);\n * } else {\n * // Session not found, user needs to re-authenticate\n * const authUrl = await sdk.authorize(savedDid);\n * }\n * }\n * ```\n */\n async restoreSession(did: string): Promise<Session | null> {\n if (!did || !did.trim()) {\n throw new ValidationError(\"DID is required\");\n }\n\n return this.oauthClient.restore(did.trim());\n }\n\n /**\n * Revokes an OAuth session, logging the user out.\n *\n * This method invalidates the session's tokens and removes it from storage.\n * After revocation, the session can no longer be used or restored.\n *\n * @param did - The user's DID to revoke the session for\n * @throws {@link ValidationError} if the DID is empty\n *\n * @example\n * ```typescript\n * // Log out the user\n * await sdk.revokeSession(session.did);\n * localStorage.removeItem(\"userDid\");\n * ```\n */\n async revokeSession(did: string): Promise<void> {\n if (!did || !did.trim()) {\n throw new ValidationError(\"DID is required\");\n }\n\n return this.oauthClient.revoke(did.trim());\n }\n\n /**\n * Creates a repository instance for data operations.\n *\n * The repository provides a fluent API for working with AT Protocol data\n * including records, blobs, profiles, and domain-specific operations like\n * hypercerts and collaborators.\n *\n * @param session - An authenticated OAuth session\n * @param options - Repository configuration options\n * @returns A {@link Repository} instance configured for the specified server\n * @throws {@link ValidationError} if the session is invalid or server URL is not configured\n *\n * @remarks\n * - **PDS (Personal Data Server)**: User's own data storage, default for most operations\n * - **SDS (Shared Data Server)**: Shared data storage with collaborator support\n *\n * @example Using default PDS\n * ```typescript\n * const repo = sdk.repository(session);\n * const profile = await repo.profile.get();\n * ```\n *\n * @example Using configured SDS\n * ```typescript\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n * const collaborators = await sdsRepo.collaborators.list();\n * ```\n *\n * @example Using custom server URL\n * ```typescript\n * const customRepo = sdk.repository(session, {\n * serverUrl: \"https://custom.atproto.server\"\n * });\n * ```\n */\n repository(session: Session, options?: RepositoryOptions): Repository {\n if (!session) {\n throw new ValidationError(\"Session is required\");\n }\n\n // Determine server URL\n let serverUrl: string;\n let isSDS = false;\n\n if (options?.serverUrl) {\n // Custom URL provided\n serverUrl = options.serverUrl;\n // Check if it matches configured SDS\n isSDS = this.config.servers?.sds === serverUrl;\n } else if (options?.server === \"sds\") {\n // Use configured SDS\n if (!this.config.servers?.sds) {\n throw new ValidationError(\"SDS server URL not configured\");\n }\n serverUrl = this.config.servers.sds;\n isSDS = true;\n } else if (options?.server === \"pds\" || !options?.server) {\n // Use configured PDS (default)\n if (!this.config.servers?.pds) {\n throw new ValidationError(\"PDS server URL not configured\");\n }\n serverUrl = this.config.servers.pds;\n isSDS = false;\n } else {\n // Custom server string (treat as URL)\n serverUrl = options.server;\n isSDS = this.config.servers?.sds === serverUrl;\n }\n\n // Get repository DID (default to session DID)\n const repoDid = session.did || session.sub;\n\n return new Repository(session, serverUrl, repoDid, this.lexiconRegistry, isSDS, this.logger);\n }\n\n /**\n * Gets the lexicon registry for schema validation.\n *\n * The lexicon registry manages AT Protocol lexicon schemas used for\n * validating record data. You can register custom lexicons to extend\n * the SDK's capabilities.\n *\n * @returns The {@link LexiconRegistry} instance\n *\n * @example\n * ```typescript\n * const registry = sdk.getLexiconRegistry();\n *\n * // Register custom lexicons\n * registry.register(myCustomLexicons);\n *\n * // Check if a lexicon is registered\n * const hasLexicon = registry.has(\"org.example.myRecord\");\n * ```\n */\n getLexiconRegistry(): LexiconRegistry {\n return this.lexiconRegistry;\n }\n\n /**\n * The configured PDS (Personal Data Server) URL.\n *\n * @returns The PDS URL if configured, otherwise `undefined`\n */\n get pdsUrl(): string | undefined {\n return this.config.servers?.pds;\n }\n\n /**\n * The configured SDS (Shared Data Server) URL.\n *\n * @returns The SDS URL if configured, otherwise `undefined`\n */\n get sdsUrl(): string | undefined {\n return this.config.servers?.sds;\n }\n}\n\n/**\n * Factory function to create an ATProto SDK instance.\n *\n * This is a convenience function equivalent to `new ATProtoSDK(config)`.\n *\n * @param config - SDK configuration\n * @returns A new {@link ATProtoSDK} instance\n *\n * @example\n * ```typescript\n * import { createATProtoSDK } from \"@hypercerts-org/sdk\";\n *\n * const sdk = createATProtoSDK({\n * oauth: { ... },\n * servers: { pds: \"https://bsky.social\" },\n * });\n * ```\n */\nexport function createATProtoSDK(config: ATProtoSDKConfig): ATProtoSDK {\n return new ATProtoSDK(config);\n}\n","import type { OAuthSession } from \"@atproto/oauth-client-node\";\nimport { z } from \"zod\";\n\n/**\n * Decentralized Identifier (DID) - a unique, persistent identifier for AT Protocol users.\n *\n * DIDs are the canonical identifier for users in the AT Protocol ecosystem.\n * Unlike handles which can change, DIDs remain constant for the lifetime of an account.\n *\n * @remarks\n * AT Protocol supports multiple DID methods:\n * - `did:plc:` - PLC (Public Ledger of Credentials) DIDs, most common for Bluesky users\n * - `did:web:` - Web DIDs, resolved via HTTPS\n *\n * @example\n * ```typescript\n * const did: DID = \"did:plc:ewvi7nxzyoun6zhxrhs64oiz\";\n * const webDid: DID = \"did:web:example.com\";\n * ```\n *\n * @see https://atproto.com/specs/did for DID specification\n */\nexport type DID = string;\n\n/**\n * OAuth session with DPoP (Demonstrating Proof of Possession) support.\n *\n * This type represents an authenticated user session. It wraps the\n * `@atproto/oauth-client-node` OAuthSession and contains:\n * - Access token for API requests\n * - Refresh token for obtaining new access tokens\n * - DPoP key pair for proof-of-possession\n * - User's DID and other identity information\n *\n * @remarks\n * Sessions are managed by the SDK and automatically refresh when tokens expire.\n * Store the user's DID to restore sessions later with {@link ATProtoSDK.restoreSession}.\n *\n * Key properties from OAuthSession:\n * - `did` or `sub`: The user's DID\n * - `handle`: The user's handle (e.g., \"user.bsky.social\")\n *\n * @example\n * ```typescript\n * const session = await sdk.callback(params);\n *\n * // Access user identity\n * console.log(`Logged in as: ${session.did}`);\n *\n * // Use session for repository operations\n * const repo = sdk.repository(session);\n * ```\n *\n * @see https://atproto.com/specs/oauth for OAuth specification\n */\nexport type Session = OAuthSession;\n\n/**\n * Zod schema for collaborator permissions in SDS repositories.\n *\n * Defines the granular permissions a collaborator can have on a shared repository.\n * Permissions follow a hierarchical model where higher-level permissions\n * typically imply lower-level ones.\n */\nexport const CollaboratorPermissionsSchema = z.object({\n /**\n * Can read/view records in the repository.\n * This is the most basic permission level.\n */\n read: z.boolean(),\n\n /**\n * Can create new records in the repository.\n * Typically implies `read` permission.\n */\n create: z.boolean(),\n\n /**\n * Can modify existing records in the repository.\n * Typically implies `read` and `create` permissions.\n */\n update: z.boolean(),\n\n /**\n * Can delete records from the repository.\n * Typically implies `read`, `create`, and `update` permissions.\n */\n delete: z.boolean(),\n\n /**\n * Can manage collaborators and their permissions.\n * Administrative permission that allows inviting/removing collaborators.\n */\n admin: z.boolean(),\n\n /**\n * Full ownership of the repository.\n * Owners have all permissions and cannot be removed by other admins.\n * There must always be at least one owner.\n */\n owner: z.boolean(),\n});\n\n/**\n * Collaborator permissions for SDS (Shared Data Server) repositories.\n *\n * These permissions control what actions a collaborator can perform\n * on records within a shared repository.\n *\n * @example\n * ```typescript\n * // Read-only collaborator\n * const readOnlyPerms: CollaboratorPermissions = {\n * read: true,\n * create: false,\n * update: false,\n * delete: false,\n * admin: false,\n * owner: false,\n * };\n *\n * // Editor collaborator\n * const editorPerms: CollaboratorPermissions = {\n * read: true,\n * create: true,\n * update: true,\n * delete: false,\n * admin: false,\n * owner: false,\n * };\n *\n * // Admin collaborator\n * const adminPerms: CollaboratorPermissions = {\n * read: true,\n * create: true,\n * update: true,\n * delete: true,\n * admin: true,\n * owner: false,\n * };\n * ```\n */\nexport type CollaboratorPermissions = z.infer<typeof CollaboratorPermissionsSchema>;\n\n/**\n * Zod schema for SDS organization data.\n *\n * Organizations are top-level entities in SDS that can own repositories\n * and have multiple collaborators with different permission levels.\n */\nexport const OrganizationSchema = z.object({\n /**\n * The organization's DID - unique identifier.\n * Format: \"did:plc:...\" or \"did:web:...\"\n */\n did: z.string(),\n\n /**\n * The organization's handle - human-readable identifier.\n * Format: \"orgname.sds.hypercerts.org\" or similar\n */\n handle: z.string(),\n\n /**\n * Display name for the organization.\n */\n name: z.string(),\n\n /**\n * Optional description of the organization's purpose.\n */\n description: z.string().optional(),\n\n /**\n * ISO 8601 timestamp when the organization was created.\n * Format: \"2024-01-15T10:30:00.000Z\"\n */\n createdAt: z.string(),\n\n /**\n * The current user's permissions within this organization.\n */\n permissions: CollaboratorPermissionsSchema,\n\n /**\n * How the current user relates to this organization.\n * - `\"owner\"`: User created or owns the organization\n * - `\"shared\"`: User was invited to collaborate (has permissions)\n * - `\"none\"`: User has no access to this organization\n */\n accessType: z.enum([\"owner\", \"shared\", \"none\"]),\n});\n\n/**\n * SDS Organization entity.\n *\n * Represents an organization on a Shared Data Server. Organizations\n * provide a way to group repositories and manage access for teams.\n *\n * @example\n * ```typescript\n * const org: Organization = {\n * did: \"did:plc:org123abc\",\n * handle: \"my-team.sds.hypercerts.org\",\n * name: \"My Team\",\n * description: \"A team working on impact certificates\",\n * createdAt: \"2024-01-15T10:30:00.000Z\",\n * permissions: {\n * read: true,\n * create: true,\n * update: true,\n * delete: true,\n * admin: true,\n * owner: true,\n * },\n * accessType: \"owner\",\n * };\n * ```\n */\nexport type Organization = z.infer<typeof OrganizationSchema>;\n\n/**\n * Zod schema for collaborator data.\n *\n * Represents a user who has been granted access to a shared repository\n * or organization with specific permissions.\n */\nexport const CollaboratorSchema = z.object({\n /**\n * The collaborator's DID - their unique identifier.\n * Format: \"did:plc:...\" or \"did:web:...\"\n */\n userDid: z.string(),\n\n /**\n * The permissions granted to this collaborator.\n */\n permissions: CollaboratorPermissionsSchema,\n\n /**\n * DID of the user who granted these permissions.\n * Useful for audit trails.\n */\n grantedBy: z.string(),\n\n /**\n * ISO 8601 timestamp when permissions were granted.\n * Format: \"2024-01-15T10:30:00.000Z\"\n */\n grantedAt: z.string(),\n\n /**\n * ISO 8601 timestamp when permissions were revoked, if applicable.\n * Undefined if the collaborator is still active.\n */\n revokedAt: z.string().optional(),\n});\n\n/**\n * Collaborator information for SDS repositories.\n *\n * Represents a user who has been granted access to collaborate on\n * a shared repository or organization.\n *\n * @example\n * ```typescript\n * const collaborator: Collaborator = {\n * userDid: \"did:plc:user456def\",\n * permissions: {\n * read: true,\n * create: true,\n * update: true,\n * delete: false,\n * admin: false,\n * owner: false,\n * },\n * grantedBy: \"did:plc:owner123abc\",\n * grantedAt: \"2024-02-01T14:00:00.000Z\",\n * };\n * ```\n */\nexport type Collaborator = z.infer<typeof CollaboratorSchema>;\n"],"names":["JoseKey","NodeOAuthClient","Lexicons","EventEmitter","HYPERCERT_COLLECTIONS","Agent","HYPERCERT_LEXICONS","z"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCG;AACG,MAAO,eAAgB,SAAQ,KAAK,CAAA;AACxC;;;;;;;AAOG;AACH,IAAA,WAAA,CACE,OAAe,EACR,IAAY,EACZ,MAAe,EACf,KAAe,EAAA;QAEtB,KAAK,CAAC,OAAO,CAAC;QAJP,IAAA,CAAA,IAAI,GAAJ,IAAI;QACJ,IAAA,CAAA,MAAM,GAAN,MAAM;QACN,IAAA,CAAA,KAAK,GAAL,KAAK;AAGZ,QAAA,IAAI,CAAC,IAAI,GAAG,iBAAiB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","../src/storage/InMemorySessionStore.ts","../src/storage/InMemoryStateStore.ts","../src/auth/OAuthClient.ts","../src/repository/LexiconRegistry.ts","../src/agent/ConfigurableAgent.ts","../src/repository/RecordOperationsImpl.ts","../src/repository/BlobOperationsImpl.ts","../src/repository/ProfileOperationsImpl.ts","../src/repository/HypercertOperationsImpl.ts","../src/repository/CollaboratorOperationsImpl.ts","../src/repository/OrganizationOperationsImpl.ts","../src/repository/Repository.ts","../src/core/config.ts","../src/core/SDK.ts","../src/core/types.ts"],"sourcesContent":["/**\n * Base error class for all SDK errors.\n *\n * All errors thrown by the Hypercerts SDK extend this class, making it easy\n * to catch and handle SDK-specific errors.\n *\n * @example Catching all SDK errors\n * ```typescript\n * try {\n * await sdk.authorize(\"user.bsky.social\");\n * } catch (error) {\n * if (error instanceof ATProtoSDKError) {\n * console.error(`SDK Error [${error.code}]: ${error.message}`);\n * console.error(`HTTP Status: ${error.status}`);\n * }\n * }\n * ```\n *\n * @example Checking error codes\n * ```typescript\n * try {\n * await repo.records.get(collection, rkey);\n * } catch (error) {\n * if (error instanceof ATProtoSDKError) {\n * switch (error.code) {\n * case \"AUTHENTICATION_ERROR\":\n * // Redirect to login\n * break;\n * case \"VALIDATION_ERROR\":\n * // Show form errors\n * break;\n * case \"NETWORK_ERROR\":\n * // Retry or show offline message\n * break;\n * }\n * }\n * }\n * ```\n */\nexport class ATProtoSDKError extends Error {\n /**\n * Creates a new SDK error.\n *\n * @param message - Human-readable error description\n * @param code - Machine-readable error code for programmatic handling\n * @param status - HTTP status code associated with this error type\n * @param cause - The underlying error that caused this error, if any\n */\n constructor(\n message: string,\n public code: string,\n public status?: number,\n public cause?: unknown,\n ) {\n super(message);\n this.name = \"ATProtoSDKError\";\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\n\n/**\n * Error thrown when authentication fails.\n *\n * This error indicates problems with the OAuth flow, invalid credentials,\n * or failed token exchanges. Common causes:\n * - Invalid authorization code\n * - Expired or invalid state parameter\n * - Revoked or invalid tokens\n * - User denied authorization\n *\n * @example\n * ```typescript\n * try {\n * const session = await sdk.callback(params);\n * } catch (error) {\n * if (error instanceof AuthenticationError) {\n * // Clear any stored state and redirect to login\n * console.error(\"Authentication failed:\", error.message);\n * }\n * }\n * ```\n */\nexport class AuthenticationError extends ATProtoSDKError {\n /**\n * Creates an authentication error.\n *\n * @param message - Description of what went wrong during authentication\n * @param cause - The underlying error (e.g., from the OAuth client)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"AUTHENTICATION_ERROR\", 401, cause);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Error thrown when a session has expired and cannot be refreshed.\n *\n * This typically occurs when:\n * - The refresh token has expired (usually after extended inactivity)\n * - The user has revoked access to your application\n * - The PDS has invalidated all sessions for the user\n *\n * When this error occurs, the user must re-authenticate.\n *\n * @example\n * ```typescript\n * try {\n * const session = await sdk.restoreSession(did);\n * } catch (error) {\n * if (error instanceof SessionExpiredError) {\n * // Clear stored session and prompt user to log in again\n * localStorage.removeItem(\"userDid\");\n * window.location.href = \"/login\";\n * }\n * }\n * ```\n */\nexport class SessionExpiredError extends ATProtoSDKError {\n /**\n * Creates a session expired error.\n *\n * @param message - Description of why the session expired\n * @param cause - The underlying error from the token refresh attempt\n */\n constructor(message: string = \"Session expired\", cause?: unknown) {\n super(message, \"SESSION_EXPIRED\", 401, cause);\n this.name = \"SessionExpiredError\";\n }\n}\n\n/**\n * Error thrown when input validation fails.\n *\n * This error indicates that provided data doesn't meet the required format\n * or constraints. Common causes:\n * - Missing required fields\n * - Invalid URL formats\n * - Invalid DID format\n * - Schema validation failures for records\n * - Invalid configuration values\n *\n * @example\n * ```typescript\n * try {\n * await sdk.authorize(\"\"); // Empty identifier\n * } catch (error) {\n * if (error instanceof ValidationError) {\n * console.error(\"Invalid input:\", error.message);\n * // Show validation error to user\n * }\n * }\n * ```\n *\n * @example With Zod validation cause\n * ```typescript\n * try {\n * await repo.records.create(collection, record);\n * } catch (error) {\n * if (error instanceof ValidationError && error.cause) {\n * // error.cause may be a ZodError with detailed field errors\n * const zodError = error.cause as ZodError;\n * zodError.errors.forEach(e => {\n * console.error(`Field ${e.path.join(\".\")}: ${e.message}`);\n * });\n * }\n * }\n * ```\n */\nexport class ValidationError extends ATProtoSDKError {\n /**\n * Creates a validation error.\n *\n * @param message - Description of what validation failed\n * @param cause - The underlying validation error (e.g., ZodError)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"VALIDATION_ERROR\", 400, cause);\n this.name = \"ValidationError\";\n }\n}\n\n/**\n * Error thrown when a network request fails.\n *\n * This error indicates connectivity issues or server unavailability.\n * Common causes:\n * - No internet connection\n * - DNS resolution failure\n * - Server timeout\n * - Server returned 5xx error\n * - TLS/SSL errors\n *\n * These errors are typically transient and may succeed on retry.\n *\n * @example\n * ```typescript\n * try {\n * await repo.records.list(collection);\n * } catch (error) {\n * if (error instanceof NetworkError) {\n * // Implement retry logic or show offline indicator\n * console.error(\"Network error:\", error.message);\n * await retryWithBackoff(() => repo.records.list(collection));\n * }\n * }\n * ```\n */\nexport class NetworkError extends ATProtoSDKError {\n /**\n * Creates a network error.\n *\n * @param message - Description of the network failure\n * @param cause - The underlying error (e.g., fetch error, timeout)\n */\n constructor(message: string, cause?: unknown) {\n super(message, \"NETWORK_ERROR\", 503, cause);\n this.name = \"NetworkError\";\n }\n}\n\n/**\n * Error thrown when an SDS-only operation is attempted on a PDS.\n *\n * Certain operations are only available on Shared Data Servers (SDS),\n * such as collaborator management and organization operations.\n * This error is thrown when these operations are attempted on a\n * Personal Data Server (PDS).\n *\n * @example\n * ```typescript\n * const pdsRepo = sdk.repository(session); // Default is PDS\n *\n * try {\n * // This will throw SDSRequiredError\n * await pdsRepo.collaborators.list();\n * } catch (error) {\n * if (error instanceof SDSRequiredError) {\n * // Switch to SDS for this operation\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n * const collaborators = await sdsRepo.collaborators.list();\n * }\n * }\n * ```\n */\nexport class SDSRequiredError extends ATProtoSDKError {\n /**\n * Creates an SDS required error.\n *\n * @param message - Description of which operation requires SDS\n * @param cause - Any underlying error\n */\n constructor(message: string = \"This operation requires a Shared Data Server (SDS)\", cause?: unknown) {\n super(message, \"SDS_REQUIRED\", 400, cause);\n this.name = \"SDSRequiredError\";\n }\n}\n","import type { SessionStore } from \"../core/interfaces.js\";\nimport type { NodeSavedSession } from \"@atproto/oauth-client-node\";\n\n/**\n * In-memory implementation of the SessionStore interface.\n *\n * This store keeps OAuth sessions in memory using a Map. It's intended\n * for development, testing, and simple use cases where session persistence\n * across restarts is not required.\n *\n * @remarks\n * **Warning**: This implementation is **not suitable for production** because:\n * - Sessions are lost when the process restarts\n * - Sessions cannot be shared across multiple server instances\n * - No automatic cleanup of expired sessions\n *\n * For production, implement {@link SessionStore} with a persistent backend:\n * - **Redis**: Good for distributed systems, supports TTL\n * - **PostgreSQL/MySQL**: Good for existing database infrastructure\n * - **MongoDB**: Good for document-based storage\n *\n * @example Basic usage\n * ```typescript\n * import { InMemorySessionStore } from \"@hypercerts-org/sdk/storage\";\n *\n * const sessionStore = new InMemorySessionStore();\n *\n * const sdk = new ATProtoSDK({\n * oauth: { ... },\n * storage: {\n * sessionStore, // Will warn in logs for production\n * },\n * });\n * ```\n *\n * @example Testing usage\n * ```typescript\n * const sessionStore = new InMemorySessionStore();\n *\n * // After tests, clean up\n * sessionStore.clear();\n * ```\n *\n * @see {@link SessionStore} for the interface definition\n * @see {@link InMemoryStateStore} for the corresponding state store\n */\nexport class InMemorySessionStore implements SessionStore {\n /**\n * Internal storage for sessions, keyed by DID.\n * @internal\n */\n private sessions = new Map<string, NodeSavedSession>();\n\n /**\n * Retrieves a session by DID.\n *\n * @param did - The user's Decentralized Identifier\n * @returns Promise resolving to the session, or `undefined` if not found\n *\n * @example\n * ```typescript\n * const session = await sessionStore.get(\"did:plc:abc123\");\n * if (session) {\n * console.log(\"Session found\");\n * }\n * ```\n */\n async get(did: string): Promise<NodeSavedSession | undefined> {\n return this.sessions.get(did);\n }\n\n /**\n * Stores or updates a session.\n *\n * @param did - The user's DID to use as the key\n * @param session - The session data to store\n *\n * @remarks\n * If a session already exists for the DID, it is overwritten.\n *\n * @example\n * ```typescript\n * await sessionStore.set(\"did:plc:abc123\", sessionData);\n * ```\n */\n async set(did: string, session: NodeSavedSession): Promise<void> {\n this.sessions.set(did, session);\n }\n\n /**\n * Deletes a session by DID.\n *\n * @param did - The DID of the session to delete\n *\n * @remarks\n * If no session exists for the DID, this is a no-op.\n *\n * @example\n * ```typescript\n * await sessionStore.del(\"did:plc:abc123\");\n * ```\n */\n async del(did: string): Promise<void> {\n this.sessions.delete(did);\n }\n\n /**\n * Clears all stored sessions.\n *\n * This is primarily useful for testing to ensure a clean state\n * between test runs.\n *\n * @remarks\n * This method is synchronous (not async) for convenience in test cleanup.\n *\n * @example\n * ```typescript\n * // In test teardown\n * afterEach(() => {\n * sessionStore.clear();\n * });\n * ```\n */\n clear(): void {\n this.sessions.clear();\n }\n}\n","import type { StateStore } from \"../core/interfaces.js\";\nimport type { NodeSavedState } from \"@atproto/oauth-client-node\";\n\n/**\n * In-memory implementation of the StateStore interface.\n *\n * This store keeps OAuth state parameters in memory using a Map. State is\n * used during the OAuth authorization flow for CSRF protection and PKCE.\n *\n * @remarks\n * **Warning**: This implementation is **not suitable for production** because:\n * - State is lost when the process restarts (breaking in-progress OAuth flows)\n * - State cannot be shared across multiple server instances\n * - No automatic cleanup of expired state (memory leak potential)\n *\n * For production, implement {@link StateStore} with a persistent backend\n * that supports TTL (time-to-live):\n * - **Redis**: Ideal choice with built-in TTL support\n * - **Database with cleanup job**: PostgreSQL/MySQL with periodic cleanup\n *\n * **State Lifecycle**:\n * 1. Created when user starts OAuth flow (`authorize()`)\n * 2. Retrieved and validated during callback\n * 3. Deleted after successful or failed callback\n * 4. Should expire after ~15 minutes if callback never happens\n *\n * @example Basic usage\n * ```typescript\n * import { InMemoryStateStore } from \"@hypercerts-org/sdk/storage\";\n *\n * const stateStore = new InMemoryStateStore();\n *\n * const sdk = new ATProtoSDK({\n * oauth: { ... },\n * storage: {\n * stateStore, // Will warn in logs for production\n * },\n * });\n * ```\n *\n * @example Testing usage\n * ```typescript\n * const stateStore = new InMemoryStateStore();\n *\n * // After tests, clean up\n * stateStore.clear();\n * ```\n *\n * @see {@link StateStore} for the interface definition\n * @see {@link InMemorySessionStore} for the corresponding session store\n */\nexport class InMemoryStateStore implements StateStore {\n /**\n * Internal storage for OAuth state, keyed by state string.\n * @internal\n */\n private states = new Map<string, NodeSavedState>();\n\n /**\n * Retrieves OAuth state by key.\n *\n * @param key - The state key (random string from authorization URL)\n * @returns Promise resolving to the state, or `undefined` if not found\n *\n * @remarks\n * The key is a cryptographically random string generated during\n * the authorization request. It's included in the callback URL\n * and used to retrieve the associated PKCE verifier and other data.\n *\n * @example\n * ```typescript\n * // During OAuth callback\n * const state = await stateStore.get(params.get(\"state\")!);\n * if (!state) {\n * throw new Error(\"Invalid or expired state\");\n * }\n * ```\n */\n async get(key: string): Promise<NodeSavedState | undefined> {\n return this.states.get(key);\n }\n\n /**\n * Stores OAuth state temporarily.\n *\n * @param key - The state key to use for storage\n * @param state - The OAuth state data (includes PKCE verifier, etc.)\n *\n * @remarks\n * In production implementations, state should be stored with a TTL\n * of approximately 10-15 minutes to prevent stale state accumulation.\n *\n * @example\n * ```typescript\n * // Called internally by OAuthClient during authorize()\n * await stateStore.set(stateKey, {\n * // PKCE code verifier, redirect URI, etc.\n * });\n * ```\n */\n async set(key: string, state: NodeSavedState): Promise<void> {\n this.states.set(key, state);\n }\n\n /**\n * Deletes OAuth state by key.\n *\n * @param key - The state key to delete\n *\n * @remarks\n * Called after the OAuth callback is processed (whether successful or not)\n * to clean up the temporary state.\n *\n * @example\n * ```typescript\n * // After processing callback\n * await stateStore.del(stateKey);\n * ```\n */\n async del(key: string): Promise<void> {\n this.states.delete(key);\n }\n\n /**\n * Clears all stored state.\n *\n * This is primarily useful for testing to ensure a clean state\n * between test runs.\n *\n * @remarks\n * This method is synchronous (not async) for convenience in test cleanup.\n * In production, be careful using this as it will invalidate all\n * in-progress OAuth flows.\n *\n * @example\n * ```typescript\n * // In test teardown\n * afterEach(() => {\n * stateStore.clear();\n * });\n * ```\n */\n clear(): void {\n this.states.clear();\n }\n}\n","import { NodeOAuthClient, JoseKey, type NodeSavedSession } from \"@atproto/oauth-client-node\";\nimport type { SessionStore, StateStore, LoggerInterface } from \"../core/interfaces.js\";\nimport type { ATProtoSDKConfig } from \"../core/config.js\";\nimport { AuthenticationError, NetworkError } from \"../core/errors.js\";\nimport { InMemorySessionStore } from \"../storage/InMemorySessionStore.js\";\nimport { InMemoryStateStore } from \"../storage/InMemoryStateStore.js\";\n\n/**\n * Options for the OAuth authorization flow.\n *\n * @internal\n */\ninterface AuthorizeOptions {\n /**\n * OAuth scope string to request specific permissions.\n * Overrides the default scope from the SDK configuration.\n */\n scope?: string;\n}\n\n/**\n * OAuth 2.0 client for AT Protocol authentication with DPoP support.\n *\n * This class wraps the `@atproto/oauth-client-node` library to provide\n * OAuth 2.0 authentication with the following features:\n *\n * - **DPoP (Demonstrating Proof of Possession)**: Binds tokens to cryptographic keys\n * to prevent token theft and replay attacks\n * - **PKCE (Proof Key for Code Exchange)**: Protects against authorization code interception\n * - **Automatic Token Refresh**: Transparently refreshes expired access tokens\n * - **Session Persistence**: Stores sessions in configurable storage backends\n *\n * @remarks\n * This class is typically used internally by {@link ATProtoSDK}. Direct usage\n * is only needed for advanced scenarios.\n *\n * The client uses lazy initialization - the underlying `NodeOAuthClient` is\n * created asynchronously on first use. This allows the constructor to return\n * synchronously while deferring async key parsing.\n *\n * @example Direct usage (advanced)\n * ```typescript\n * import { OAuthClient } from \"@hypercerts-org/sdk\";\n *\n * const client = new OAuthClient({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: { pds: \"https://bsky.social\" },\n * });\n *\n * // Start authorization\n * const authUrl = await client.authorize(\"user.bsky.social\");\n *\n * // Handle callback\n * const session = await client.callback(new URLSearchParams(callbackUrl.search));\n * ```\n *\n * @see {@link ATProtoSDK} for the recommended high-level API\n * @see https://atproto.com/specs/oauth for AT Protocol OAuth specification\n */\nexport class OAuthClient {\n /** The underlying NodeOAuthClient instance (lazily initialized) */\n private client: NodeOAuthClient | null = null;\n\n /** Promise that resolves to the initialized client */\n private clientPromise: Promise<NodeOAuthClient>;\n\n /** SDK configuration */\n private config: ATProtoSDKConfig;\n\n /** Optional logger for debugging */\n private logger?: LoggerInterface;\n\n /**\n * Creates a new OAuth client.\n *\n * @param config - SDK configuration including OAuth credentials and server URLs\n * @throws {@link AuthenticationError} if the JWK private key is not valid JSON\n *\n * @remarks\n * The constructor validates the JWK format synchronously but defers\n * the actual client initialization to the first API call.\n */\n constructor(config: ATProtoSDKConfig) {\n this.config = config;\n this.logger = config.logger;\n\n // Validate JWK format synchronously (before async initialization)\n try {\n JSON.parse(config.oauth.jwkPrivate);\n } catch (error) {\n throw new AuthenticationError(\"Failed to parse JWK private key. Ensure it is valid JSON.\", error);\n }\n\n // Initialize client lazily (async initialization)\n this.clientPromise = this.initializeClient();\n }\n\n /**\n * Initializes the NodeOAuthClient asynchronously.\n *\n * This method is called lazily on first use. It:\n * 1. Parses the JWK private key(s)\n * 2. Builds OAuth client metadata\n * 3. Creates the underlying NodeOAuthClient\n *\n * @returns Promise resolving to the initialized client\n * @internal\n */\n private async initializeClient(): Promise<NodeOAuthClient> {\n if (this.client) {\n return this.client;\n }\n\n // Parse JWK private key (already validated in constructor)\n const privateJWK = JSON.parse(this.config.oauth.jwkPrivate) as {\n keys: Array<{ kid: string; [key: string]: unknown }>;\n };\n\n // Build client metadata\n const clientMetadata = this.buildClientMetadata();\n\n // Convert JWK keys to JoseKey instances (await here)\n const keyset = await Promise.all(\n privateJWK.keys.map((key) =>\n JoseKey.fromImportable(key as unknown as Parameters<typeof JoseKey.fromImportable>[0], key.kid),\n ),\n );\n\n // Create fetch with timeout\n const fetchWithTimeout = this.createFetchWithTimeout(this.config.timeouts?.pdsMetadata ?? 30000);\n\n // Use provided stores or fall back to in-memory implementations\n const stateStore = this.config.storage?.stateStore ?? new InMemoryStateStore();\n const sessionStore = this.config.storage?.sessionStore ?? new InMemorySessionStore();\n\n this.client = new NodeOAuthClient({\n clientMetadata,\n keyset,\n stateStore: this.createStateStoreAdapter(stateStore),\n sessionStore: this.createSessionStoreAdapter(sessionStore),\n handleResolver: this.config.servers?.pds,\n fetch: this.config.fetch ?? fetchWithTimeout,\n });\n\n return this.client;\n }\n\n /**\n * Gets the OAuth client instance, initializing if needed.\n *\n * @returns Promise resolving to the initialized client\n * @internal\n */\n private async getClient(): Promise<NodeOAuthClient> {\n return this.clientPromise;\n }\n\n /**\n * Builds OAuth client metadata from configuration.\n *\n * The metadata describes your application to the authorization server\n * and must match what's published at your `clientId` URL.\n *\n * @returns OAuth client metadata object\n * @internal\n *\n * @remarks\n * Key metadata fields:\n * - `client_id`: URL to your client metadata JSON\n * - `redirect_uris`: Where to redirect after auth (must match config)\n * - `dpop_bound_access_tokens`: Always true for AT Protocol\n * - `token_endpoint_auth_method`: Uses private_key_jwt for security\n */\n private buildClientMetadata() {\n const clientIdUrl = new URL(this.config.oauth.clientId);\n return {\n client_id: this.config.oauth.clientId,\n client_name: \"ATProto SDK Client\",\n client_uri: clientIdUrl.origin,\n redirect_uris: [this.config.oauth.redirectUri] as [string, ...string[]],\n scope: this.config.oauth.scope,\n grant_types: [\"authorization_code\", \"refresh_token\"] as [\"authorization_code\", \"refresh_token\"],\n response_types: [\"code\"] as [\"code\"],\n application_type: \"web\" as const,\n token_endpoint_auth_method: \"private_key_jwt\" as const,\n token_endpoint_auth_signing_alg: \"ES256\",\n dpop_bound_access_tokens: true,\n jwks_uri: this.config.oauth.jwksUri,\n } as const;\n }\n\n /**\n * Creates a fetch handler with timeout support.\n *\n * @param timeoutMs - Request timeout in milliseconds\n * @returns A fetch function that aborts after the timeout\n * @internal\n */\n private createFetchWithTimeout(timeoutMs: number): typeof fetch {\n return async (input: RequestInfo | URL, init?: RequestInit) => {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const response = await fetch(input, {\n ...init,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new NetworkError(`Request timeout after ${timeoutMs}ms`, error);\n }\n throw new NetworkError(\"Network request failed\", error);\n }\n };\n }\n\n /**\n * Creates a state store adapter compatible with NodeOAuthClient.\n *\n * @param store - The StateStore implementation to adapt\n * @returns An adapter compatible with NodeOAuthClient\n * @internal\n */\n private createStateStoreAdapter(store: StateStore): import(\"@atproto/oauth-client-node\").NodeSavedStateStore {\n return {\n get: (key: string) => store.get(key),\n set: (key: string, value: import(\"@atproto/oauth-client-node\").NodeSavedState) => store.set(key, value),\n del: (key: string) => store.del(key),\n };\n }\n\n /**\n * Creates a session store adapter compatible with NodeOAuthClient.\n *\n * @param store - The SessionStore implementation to adapt\n * @returns An adapter compatible with NodeOAuthClient\n * @internal\n */\n private createSessionStoreAdapter(store: SessionStore): import(\"@atproto/oauth-client-node\").NodeSavedSessionStore {\n return {\n get: (did: string) => store.get(did),\n set: (did: string, session: NodeSavedSession) => store.set(did, session),\n del: (did: string) => store.del(did),\n };\n }\n\n /**\n * Initiates the OAuth authorization flow.\n *\n * This method resolves the user's identity from their identifier,\n * generates PKCE codes, creates OAuth state, and returns an\n * authorization URL to redirect the user to.\n *\n * @param identifier - The user's ATProto identifier. Accepts:\n * - Handle (e.g., `\"alice.bsky.social\"`)\n * - DID (e.g., `\"did:plc:abc123...\"`)\n * - PDS URL (e.g., `\"https://bsky.social\"`)\n * @param options - Optional authorization settings\n * @returns A Promise resolving to the authorization URL\n * @throws {@link AuthenticationError} if authorization setup fails\n * @throws {@link NetworkError} if identity resolution fails\n *\n * @example\n * ```typescript\n * // Get authorization URL\n * const authUrl = await client.authorize(\"user.bsky.social\");\n *\n * // Redirect user (in a web app)\n * window.location.href = authUrl;\n *\n * // Or return to client (in an API)\n * res.json({ authUrl });\n * ```\n */\n async authorize(identifier: string, options?: AuthorizeOptions): Promise<string> {\n try {\n this.logger?.debug(\"Initiating OAuth authorization\", { identifier });\n\n const client = await this.getClient();\n const scope = options?.scope ?? this.config.oauth.scope;\n const authUrl = await client.authorize(identifier, { scope });\n\n this.logger?.debug(\"Authorization URL generated\", { identifier });\n // Convert URL to string if needed\n return typeof authUrl === \"string\" ? authUrl : authUrl.toString();\n } catch (error) {\n this.logger?.error(\"Authorization failed\", { identifier, error });\n if (error instanceof NetworkError || error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(\n `Failed to initiate authorization: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Handles the OAuth callback and exchanges the authorization code for tokens.\n *\n * Call this method when the user is redirected back to your application.\n * It validates the state, exchanges the code for tokens, and creates\n * a persistent session.\n *\n * @param params - URL search parameters from the callback. Expected parameters:\n * - `code`: The authorization code\n * - `state`: The state parameter (for CSRF protection)\n * - `iss`: The issuer (authorization server URL)\n * @returns A Promise resolving to the authenticated OAuth session\n * @throws {@link AuthenticationError} if:\n * - The callback contains an OAuth error\n * - The state is invalid or expired\n * - The code exchange fails\n * - Session persistence fails\n *\n * @example\n * ```typescript\n * // In your callback route handler\n * app.get(\"/callback\", async (req, res) => {\n * const params = new URLSearchParams(req.url.split(\"?\")[1]);\n *\n * try {\n * const session = await client.callback(params);\n * // Store DID for session restoration\n * req.session.userDid = session.sub;\n * res.redirect(\"/dashboard\");\n * } catch (error) {\n * res.redirect(\"/login?error=auth_failed\");\n * }\n * });\n * ```\n *\n * @remarks\n * After successful token exchange, this method verifies that the session\n * was properly persisted by attempting to restore it. This ensures the\n * storage backend is working correctly.\n */\n async callback(params: URLSearchParams): Promise<import(\"@atproto/oauth-client\").OAuthSession> {\n try {\n this.logger?.debug(\"Processing OAuth callback\");\n\n // Check for OAuth errors\n const error = params.get(\"error\");\n if (error) {\n const errorDescription = params.get(\"error_description\");\n throw new AuthenticationError(errorDescription || error);\n }\n\n const client = await this.getClient();\n const result = await client.callback(params);\n const session = result.session;\n const did = session.sub;\n\n this.logger?.info(\"OAuth callback successful\", { did });\n\n // Verify session can be restored (validates persistence)\n try {\n const restored = await client.restore(did);\n if (!restored) {\n throw new AuthenticationError(\"OAuth session was not persisted\");\n }\n this.logger?.debug(\"Session verified and restorable\", { did });\n } catch (restoreError) {\n this.logger?.error(\"Failed to verify persisted session\", {\n did,\n error: restoreError,\n });\n throw new AuthenticationError(\"Failed to persist OAuth session\", restoreError);\n }\n\n return session;\n } catch (error) {\n this.logger?.error(\"OAuth callback failed\", { error });\n if (error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(\n `OAuth callback failed: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Restores an OAuth session by DID.\n *\n * Use this method to restore a previously authenticated session.\n * The method automatically refreshes expired access tokens using\n * the stored refresh token.\n *\n * @param did - The user's Decentralized Identifier (e.g., `\"did:plc:abc123...\"`)\n * @returns A Promise resolving to the session, or `null` if not found\n * @throws {@link AuthenticationError} if session restoration fails (not for missing sessions)\n * @throws {@link NetworkError} if token refresh requires network and fails\n *\n * @example\n * ```typescript\n * // On application startup or request\n * const userDid = req.session.userDid;\n * if (userDid) {\n * const session = await client.restore(userDid);\n * if (session) {\n * // Session restored, user is authenticated\n * req.atprotoSession = session;\n * } else {\n * // No session found, user needs to log in\n * delete req.session.userDid;\n * }\n * }\n * ```\n *\n * @remarks\n * Token refresh is handled automatically by the underlying OAuth client.\n * If the refresh token has expired or been revoked, this method will\n * throw an {@link AuthenticationError}.\n */\n async restore(did: string): Promise<import(\"@atproto/oauth-client\").OAuthSession | null> {\n try {\n this.logger?.debug(\"Restoring session\", { did });\n\n const client = await this.getClient();\n const session = await client.restore(did);\n\n if (session) {\n this.logger?.debug(\"Session restored\", { did });\n } else {\n this.logger?.debug(\"No session found\", { did });\n }\n\n return session;\n } catch (error) {\n this.logger?.error(\"Failed to restore session\", { did, error });\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new AuthenticationError(\n `Failed to restore session: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n\n /**\n * Revokes an OAuth session.\n *\n * This method invalidates the session's tokens both locally and\n * (if supported) on the authorization server. After revocation,\n * the session cannot be restored.\n *\n * @param did - The user's DID to revoke\n * @throws {@link AuthenticationError} if revocation fails\n *\n * @example\n * ```typescript\n * // Log out endpoint\n * app.post(\"/logout\", async (req, res) => {\n * const userDid = req.session.userDid;\n * if (userDid) {\n * await client.revoke(userDid);\n * delete req.session.userDid;\n * }\n * res.redirect(\"/\");\n * });\n * ```\n *\n * @remarks\n * Even if revocation fails on the server, the local session is\n * removed. The error is thrown to inform you that remote revocation\n * may not have succeeded.\n */\n async revoke(did: string): Promise<void> {\n try {\n this.logger?.debug(\"Revoking session\", { did });\n\n const client = await this.getClient();\n await client.revoke(did);\n\n this.logger?.info(\"Session revoked\", { did });\n } catch (error) {\n this.logger?.error(\"Failed to revoke session\", { did, error });\n throw new AuthenticationError(\n `Failed to revoke session: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n }\n}\n","import type { Agent } from \"@atproto/api\";\nimport type { LexiconDoc } from \"@atproto/lexicon\";\nimport { Lexicons } from \"@atproto/lexicon\";\nimport { ValidationError } from \"../core/errors.js\";\n\n/**\n * Result of validating a record against a lexicon schema.\n */\nexport interface ValidationResult {\n /**\n * Whether the record is valid according to the lexicon schema.\n */\n valid: boolean;\n\n /**\n * Error message if validation failed.\n *\n * Only present when `valid` is `false`.\n */\n error?: string;\n}\n\n/**\n * Registry for managing and validating AT Protocol lexicon schemas.\n *\n * Lexicons are schema definitions that describe the structure of records\n * in the AT Protocol. This registry allows you to:\n *\n * - Register custom lexicons for your application's record types\n * - Validate records against their lexicon schemas\n * - Extend the AT Protocol Agent with custom lexicon support\n *\n * @remarks\n * The SDK automatically registers hypercert lexicons when creating a Repository.\n * You only need to use this class directly if you're working with custom\n * record types.\n *\n * **Lexicon IDs** follow the NSID (Namespaced Identifier) format:\n * `{authority}.{name}` (e.g., `org.hypercerts.hypercert`)\n *\n * @example Registering custom lexicons\n * ```typescript\n * const registry = sdk.getLexiconRegistry();\n *\n * // Register a single lexicon\n * registry.register({\n * lexicon: 1,\n * id: \"org.example.myRecord\",\n * defs: {\n * main: {\n * type: \"record\",\n * key: \"tid\",\n * record: {\n * type: \"object\",\n * required: [\"title\", \"createdAt\"],\n * properties: {\n * title: { type: \"string\" },\n * description: { type: \"string\" },\n * createdAt: { type: \"string\", format: \"datetime\" },\n * },\n * },\n * },\n * },\n * });\n *\n * // Register multiple lexicons at once\n * registry.registerMany([lexicon1, lexicon2, lexicon3]);\n * ```\n *\n * @example Validating records\n * ```typescript\n * const result = registry.validate(\"org.example.myRecord\", {\n * title: \"Test\",\n * createdAt: new Date().toISOString(),\n * });\n *\n * if (!result.valid) {\n * console.error(`Validation failed: ${result.error}`);\n * }\n * ```\n *\n * @see https://atproto.com/specs/lexicon for the Lexicon specification\n */\nexport class LexiconRegistry {\n /** Map of lexicon ID to lexicon document */\n private lexicons = new Map<string, LexiconDoc>();\n\n /** Lexicons collection for validation */\n private lexiconsCollection: Lexicons;\n\n /**\n * Creates a new LexiconRegistry.\n *\n * The registry starts empty. Use {@link register} or {@link registerMany}\n * to add lexicons.\n */\n constructor() {\n this.lexiconsCollection = new Lexicons();\n }\n\n /**\n * Registers a single lexicon schema.\n *\n * @param lexicon - The lexicon document to register\n * @throws {@link ValidationError} if the lexicon doesn't have an `id` field\n *\n * @remarks\n * If a lexicon with the same ID is already registered, it will be\n * replaced with the new definition. This is useful for testing but\n * should generally be avoided in production.\n *\n * @example\n * ```typescript\n * registry.register({\n * lexicon: 1,\n * id: \"org.example.post\",\n * defs: {\n * main: {\n * type: \"record\",\n * key: \"tid\",\n * record: {\n * type: \"object\",\n * required: [\"text\", \"createdAt\"],\n * properties: {\n * text: { type: \"string\", maxLength: 300 },\n * createdAt: { type: \"string\", format: \"datetime\" },\n * },\n * },\n * },\n * },\n * });\n * ```\n */\n register(lexicon: LexiconDoc): void {\n if (!lexicon.id) {\n throw new ValidationError(\"Lexicon must have an 'id' field\");\n }\n\n // Remove existing lexicon if present (to allow overwriting)\n if (this.lexicons.has(lexicon.id)) {\n // Lexicons collection doesn't support removal, so we create a new one\n // This is a limitation - in practice, lexicons shouldn't be overwritten\n // But we allow it for testing and flexibility\n const existingLexicon = this.lexicons.get(lexicon.id);\n if (existingLexicon) {\n // Try to remove from collection (may fail if not supported)\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.lexiconsCollection as any).remove?.(lexicon.id);\n } catch {\n // If removal fails, create a new collection\n this.lexiconsCollection = new Lexicons();\n // Re-register all other lexicons\n for (const [id, lex] of this.lexicons.entries()) {\n if (id !== lexicon.id) {\n this.lexiconsCollection.add(lex);\n }\n }\n }\n }\n }\n\n this.lexicons.set(lexicon.id, lexicon);\n this.lexiconsCollection.add(lexicon);\n }\n\n /**\n * Registers multiple lexicons at once.\n *\n * @param lexicons - Array of lexicon documents to register\n *\n * @example\n * ```typescript\n * import { HYPERCERT_LEXICONS } from \"@hypercerts-org/sdk/lexicons\";\n *\n * registry.registerMany(HYPERCERT_LEXICONS);\n * ```\n */\n registerMany(lexicons: LexiconDoc[]): void {\n for (const lexicon of lexicons) {\n this.register(lexicon);\n }\n }\n\n /**\n * Gets a lexicon document by ID.\n *\n * @param id - The lexicon NSID (e.g., \"org.hypercerts.hypercert\")\n * @returns The lexicon document, or `undefined` if not registered\n *\n * @example\n * ```typescript\n * const lexicon = registry.get(\"org.hypercerts.hypercert\");\n * if (lexicon) {\n * console.log(`Found lexicon: ${lexicon.id}`);\n * }\n * ```\n */\n get(id: string): LexiconDoc | undefined {\n return this.lexicons.get(id);\n }\n\n /**\n * Validates a record against a collection's lexicon schema.\n *\n * @param collection - The collection NSID (same as lexicon ID)\n * @param record - The record data to validate\n * @returns Validation result with `valid` boolean and optional `error` message\n *\n * @remarks\n * - If no lexicon is registered for the collection, validation passes\n * (we can't validate against unknown schemas)\n * - Validation checks required fields and type constraints defined\n * in the lexicon schema\n *\n * @example\n * ```typescript\n * const result = registry.validate(\"org.hypercerts.hypercert\", {\n * title: \"My Hypercert\",\n * description: \"Description...\",\n * // ... other fields\n * });\n *\n * if (!result.valid) {\n * throw new Error(`Invalid record: ${result.error}`);\n * }\n * ```\n */\n validate(collection: string, record: unknown): ValidationResult {\n // Check if we have a lexicon registered for this collection\n // Collection format is typically \"namespace.collection\" (e.g., \"app.bsky.feed.post\")\n // Lexicon ID format is the same\n const lexiconId = collection;\n const lexicon = this.lexicons.get(lexiconId);\n if (!lexicon) {\n // No lexicon registered - validation passes (can't validate unknown schemas)\n return { valid: true };\n }\n\n // Check required fields if the lexicon defines them\n const recordDef = lexicon.defs?.record;\n if (recordDef && typeof recordDef === \"object\" && \"record\" in recordDef) {\n const recordSchema = recordDef.record;\n if (typeof recordSchema === \"object\" && \"required\" in recordSchema && Array.isArray(recordSchema.required)) {\n const recordObj = record as Record<string, unknown>;\n for (const requiredField of recordSchema.required) {\n if (typeof requiredField === \"string\" && !(requiredField in recordObj)) {\n return {\n valid: false,\n error: `Missing required field: ${requiredField}`,\n };\n }\n }\n }\n }\n\n try {\n this.lexiconsCollection.assertValidRecord(collection, record);\n return { valid: true };\n } catch (error) {\n // If error indicates lexicon not found, treat as validation pass\n // (the lexicon might exist in Agent's collection but not ours)\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes(\"not found\") || errorMessage.includes(\"Lexicon not found\")) {\n return { valid: true };\n }\n return {\n valid: false,\n error: errorMessage,\n };\n }\n }\n\n /**\n * Adds all registered lexicons to an AT Protocol Agent instance.\n *\n * This allows the Agent to understand custom lexicon types when making\n * API requests.\n *\n * @param agent - The Agent instance to extend\n *\n * @remarks\n * This is called automatically when creating a Repository. You typically\n * don't need to call this directly unless you're using the Agent\n * independently.\n *\n * @internal\n */\n addToAgent(agent: Agent): void {\n // Access the internal lexicons collection and merge our lexicons\n // The Agent's lex property is a Lexicons instance\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const agentLex = (agent as any).lex as Lexicons;\n\n // Add each registered lexicon to the agent\n for (const lexicon of this.lexicons.values()) {\n agentLex.add(lexicon);\n }\n }\n\n /**\n * Gets all registered lexicon IDs.\n *\n * @returns Array of lexicon NSIDs\n *\n * @example\n * ```typescript\n * const ids = registry.getRegisteredIds();\n * console.log(`Registered lexicons: ${ids.join(\", \")}`);\n * ```\n */\n getRegisteredIds(): string[] {\n return Array.from(this.lexicons.keys());\n }\n\n /**\n * Checks if a lexicon is registered.\n *\n * @param id - The lexicon NSID to check\n * @returns `true` if the lexicon is registered\n *\n * @example\n * ```typescript\n * if (registry.has(\"org.hypercerts.hypercert\")) {\n * // Hypercert lexicon is available\n * }\n * ```\n */\n has(id: string): boolean {\n return this.lexicons.has(id);\n }\n}\n","/**\n * ConfigurableAgent - Agent with configurable service URL routing.\n *\n * This module provides an Agent extension that allows routing requests to\n * a specific server URL, overriding the default URL from the OAuth session.\n *\n * @packageDocumentation\n */\n\nimport { Agent } from \"@atproto/api\";\nimport type { Session } from \"../core/types.js\";\n\n/**\n * FetchHandler type - function that makes HTTP requests with authentication.\n * Takes a pathname and request init, returns a Response promise.\n */\ntype FetchHandler = (pathname: string, init: RequestInit) => Promise<Response>;\n\n/**\n * Agent subclass that routes requests to a configurable service URL.\n *\n * The standard Agent uses the service URL embedded in the OAuth session's\n * fetch handler. This class allows overriding that URL to route requests\n * to different servers (e.g., PDS vs SDS, or multiple SDS instances).\n *\n * @remarks\n * This is particularly useful for:\n * - Routing to a Shared Data Server (SDS) while authenticated via PDS\n * - Supporting multiple SDS instances for different organizations\n * - Testing against different server environments\n *\n * @example Basic usage\n * ```typescript\n * const session = await sdk.authorize(\"user.bsky.social\");\n *\n * // Create agent routing to SDS instead of session's default PDS\n * const sdsAgent = new ConfigurableAgent(session, \"https://sds.hypercerts.org\");\n *\n * // All requests will now go to the SDS\n * await sdsAgent.com.atproto.repo.createRecord({...});\n * ```\n *\n * @example Multiple SDS instances\n * ```typescript\n * // Route to organization A's SDS\n * const orgAAgent = new ConfigurableAgent(session, \"https://sds-org-a.example.com\");\n *\n * // Route to organization B's SDS\n * const orgBAgent = new ConfigurableAgent(session, \"https://sds-org-b.example.com\");\n * ```\n */\nexport class ConfigurableAgent extends Agent {\n private customServiceUrl: string;\n\n /**\n * Creates a ConfigurableAgent that routes to a specific service URL.\n *\n * @param session - OAuth session for authentication\n * @param serviceUrl - Base URL of the server to route requests to\n *\n * @remarks\n * The agent wraps the session's fetch handler to intercept requests and\n * prepend the custom service URL instead of using the session's default.\n */\n constructor(session: Session, serviceUrl: string) {\n // Create a custom fetch handler that uses our service URL\n const customFetchHandler: FetchHandler = async (pathname: string, init: RequestInit) => {\n // Construct the full URL with our custom service\n const url = new URL(pathname, serviceUrl).toString();\n\n // Use the session's fetch handler for authentication (DPoP, etc.)\n return session.fetchHandler(url, init);\n };\n\n // Initialize the parent Agent with our custom fetch handler\n super(customFetchHandler);\n\n this.customServiceUrl = serviceUrl;\n }\n\n /**\n * Gets the service URL this agent routes to.\n *\n * @returns The base URL of the configured service\n */\n getServiceUrl(): string {\n return this.customServiceUrl;\n }\n}\n","/**\n * RecordOperationsImpl - Low-level record CRUD operations.\n *\n * This module provides the implementation for direct AT Protocol\n * record operations (create, read, update, delete, list).\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError, ValidationError } from \"../core/errors.js\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\nimport type { RecordOperations } from \"./interfaces.js\";\nimport type { CreateResult, UpdateResult, PaginatedList } from \"./types.js\";\n\n/**\n * Implementation of low-level AT Protocol record operations.\n *\n * This class provides direct access to the AT Protocol repository API\n * for CRUD operations on records. It handles:\n *\n * - Lexicon validation before create/update operations\n * - Error mapping to SDK error types\n * - Response normalization\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.records}.\n *\n * All operations are performed against the repository DID specified\n * at construction time. To operate on a different repository, create\n * a new Repository instance using {@link Repository.repo}.\n *\n * @example\n * ```typescript\n * // Access through Repository\n * const repo = sdk.repository(session);\n *\n * // Create a record\n * const { uri, cid } = await repo.records.create({\n * collection: \"org.example.myRecord\",\n * record: { title: \"Hello\", createdAt: new Date().toISOString() },\n * });\n *\n * // Update the record\n * const rkey = uri.split(\"/\").pop()!;\n * await repo.records.update({\n * collection: \"org.example.myRecord\",\n * rkey,\n * record: { title: \"Updated\", createdAt: new Date().toISOString() },\n * });\n * ```\n *\n * @internal\n */\nexport class RecordOperationsImpl implements RecordOperations {\n /**\n * Creates a new RecordOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository to operate on\n * @param lexiconRegistry - Registry for record validation\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private lexiconRegistry: LexiconRegistry,\n ) {}\n\n /**\n * Creates a new record in the specified collection.\n *\n * @param params - Creation parameters\n * @param params.collection - NSID of the collection (e.g., \"org.hypercerts.hypercert\")\n * @param params.record - Record data conforming to the collection's lexicon schema\n * @param params.rkey - Optional record key. If not provided, a TID (timestamp-based ID)\n * is automatically generated by the server.\n * @returns Promise resolving to the created record's URI and CID\n * @throws {@link ValidationError} if the record doesn't conform to the lexicon schema\n * @throws {@link NetworkError} if the API request fails\n *\n * @remarks\n * The record is validated against the collection's lexicon before sending\n * to the server. If no lexicon is registered for the collection, validation\n * is skipped (allowing custom record types).\n *\n * **AT-URI Format**: `at://{did}/{collection}/{rkey}`\n *\n * @example\n * ```typescript\n * const result = await repo.records.create({\n * collection: \"org.hypercerts.hypercert\",\n * record: {\n * title: \"My Hypercert\",\n * description: \"...\",\n * createdAt: new Date().toISOString(),\n * },\n * });\n * console.log(`Created: ${result.uri}`);\n * // Output: Created: at://did:plc:abc123/org.hypercerts.hypercert/xyz789\n * ```\n */\n async create(params: { collection: string; record: unknown; rkey?: string }): Promise<CreateResult> {\n const validation = this.lexiconRegistry.validate(params.collection, params.record);\n if (!validation.valid) {\n throw new ValidationError(`Invalid record for collection ${params.collection}: ${validation.error}`);\n }\n\n try {\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: params.collection,\n record: params.record as Record<string, unknown>,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates an existing record (full replacement).\n *\n * @param params - Update parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key (the last segment of the AT-URI)\n * @param params.record - New record data (completely replaces existing record)\n * @returns Promise resolving to the updated record's URI and new CID\n * @throws {@link ValidationError} if the record doesn't conform to the lexicon schema\n * @throws {@link NetworkError} if the API request fails\n *\n * @remarks\n * This is a full replacement operation, not a partial update. The entire\n * record is replaced with the new data. To preserve existing fields,\n * first fetch the record with {@link get}, modify it, then update.\n *\n * @example\n * ```typescript\n * // Get existing record\n * const existing = await repo.records.get({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n *\n * // Update with modified data\n * const updated = await repo.records.update({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * record: {\n * ...existing.value,\n * title: \"Updated Title\",\n * },\n * });\n * ```\n */\n async update(params: { collection: string; rkey: string; record: unknown }): Promise<UpdateResult> {\n const validation = this.lexiconRegistry.validate(params.collection, params.record);\n if (!validation.valid) {\n throw new ValidationError(`Invalid record for collection ${params.collection}: ${validation.error}`);\n }\n\n try {\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n record: params.record as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a single record by collection and key.\n *\n * @param params - Get parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key\n * @returns Promise resolving to the record's URI, CID, and value\n * @throws {@link NetworkError} if the record is not found or request fails\n *\n * @example\n * ```typescript\n * const record = await repo.records.get({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n *\n * console.log(record.uri); // at://did:plc:abc123/org.hypercerts.hypercert/xyz789\n * console.log(record.cid); // bafyrei...\n * console.log(record.value); // { title: \"...\", description: \"...\", ... }\n * ```\n */\n async get(params: { collection: string; rkey: string }): Promise<{ uri: string; cid: string; value: unknown }> {\n try {\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get record\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid ?? \"\", value: result.data.value };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to get record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Lists records in a collection with pagination.\n *\n * @param params - List parameters\n * @param params.collection - NSID of the collection\n * @param params.limit - Maximum number of records to return (server may impose its own limit)\n * @param params.cursor - Pagination cursor from a previous response\n * @returns Promise resolving to paginated list of records\n * @throws {@link NetworkError} if the request fails\n *\n * @remarks\n * Records are returned in reverse chronological order (newest first).\n * Use the `cursor` from the response to fetch subsequent pages.\n *\n * @example Paginating through all records\n * ```typescript\n * let cursor: string | undefined;\n * const allRecords = [];\n *\n * do {\n * const page = await repo.records.list({\n * collection: \"org.hypercerts.hypercert\",\n * limit: 100,\n * cursor,\n * });\n * allRecords.push(...page.records);\n * cursor = page.cursor;\n * } while (cursor);\n *\n * console.log(`Total records: ${allRecords.length}`);\n * ```\n */\n async list(params: {\n collection: string;\n limit?: number;\n cursor?: string;\n }): Promise<PaginatedList<{ uri: string; cid: string; value: unknown }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: params.collection,\n limit: params.limit,\n cursor: params.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list records\");\n }\n\n return {\n records: result.data.records?.map((r) => ({ uri: r.uri, cid: r.cid, value: r.value })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to list records: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Deletes a record from a collection.\n *\n * @param params - Delete parameters\n * @param params.collection - NSID of the collection\n * @param params.rkey - Record key to delete\n * @throws {@link NetworkError} if the deletion fails\n *\n * @remarks\n * Deletion is permanent. The record's AT-URI cannot be reused (the same\n * rkey can be used for a new record, but it will have a different CID).\n *\n * @example\n * ```typescript\n * await repo.records.delete({\n * collection: \"org.hypercerts.hypercert\",\n * rkey: \"xyz789\",\n * });\n * ```\n */\n async delete(params: { collection: string; rkey: string }): Promise<void> {\n try {\n const result = await this.agent.com.atproto.repo.deleteRecord({\n repo: this.repoDid,\n collection: params.collection,\n rkey: params.rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to delete record\");\n }\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to delete record: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n}\n","/**\n * BlobOperationsImpl - Blob upload and retrieval operations.\n *\n * This module provides the implementation for AT Protocol blob operations,\n * handling binary data like images and files.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError } from \"../core/errors.js\";\nimport type { BlobOperations } from \"./interfaces.js\";\n\n/**\n * Implementation of blob operations for binary data handling.\n *\n * Blobs in AT Protocol are content-addressed binary objects stored\n * separately from records. They are referenced in records using a\n * blob reference object with a CID ($link).\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.blobs}.\n *\n * **Blob Size Limits**: PDS servers typically impose size limits on blobs.\n * Common limits are:\n * - Images: 1MB\n * - Other files: Varies by server configuration\n *\n * **Supported MIME Types**: Any MIME type is technically supported, but\n * servers may reject certain types. Images (JPEG, PNG, GIF, WebP) are\n * universally supported.\n *\n * @example\n * ```typescript\n * // Upload an image blob\n * const imageBlob = new Blob([imageData], { type: \"image/jpeg\" });\n * const { ref, mimeType, size } = await repo.blobs.upload(imageBlob);\n *\n * // Use the ref in a record\n * await repo.records.create({\n * collection: \"org.example.post\",\n * record: {\n * text: \"Check out this image!\",\n * image: ref, // { $link: \"bafyrei...\" }\n * createdAt: new Date().toISOString(),\n * },\n * });\n * ```\n *\n * @internal\n */\nexport class BlobOperationsImpl implements BlobOperations {\n /**\n * Creates a new BlobOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository (used for blob retrieval)\n * @param _serverUrl - Server URL (reserved for future use)\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n ) {}\n\n /**\n * Uploads a blob to the server.\n *\n * @param blob - The blob to upload (File or Blob object)\n * @returns Promise resolving to blob reference and metadata\n * @throws {@link NetworkError} if the upload fails\n *\n * @remarks\n * The returned `ref` object should be used directly in records to\n * reference the blob. The `$link` property contains the blob's CID.\n *\n * **MIME Type Detection**: If the blob has no type, it defaults to\n * `application/octet-stream`. For best results, always specify the\n * correct MIME type when creating the Blob.\n *\n * @example Uploading an image\n * ```typescript\n * // From a File input\n * const file = fileInput.files[0];\n * const { ref } = await repo.blobs.upload(file);\n *\n * // From raw data\n * const imageBlob = new Blob([uint8Array], { type: \"image/png\" });\n * const { ref, mimeType, size } = await repo.blobs.upload(imageBlob);\n *\n * console.log(`Uploaded ${size} bytes of ${mimeType}`);\n * console.log(`CID: ${ref.$link}`);\n * ```\n *\n * @example Using in a hypercert\n * ```typescript\n * const coverImage = new Blob([imageData], { type: \"image/jpeg\" });\n * const { ref } = await repo.blobs.upload(coverImage);\n *\n * // The ref is used directly in the record\n * await repo.hypercerts.create({\n * title: \"My Hypercert\",\n * // ... other fields\n * image: coverImage, // HypercertOperations handles upload internally\n * });\n * ```\n */\n async upload(blob: Blob): Promise<{ ref: { $link: string }; mimeType: string; size: number }> {\n try {\n const arrayBuffer = await blob.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n\n const result = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: blob.type || \"application/octet-stream\",\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to upload blob\");\n }\n\n return {\n ref: { $link: result.data.blob.ref.toString() },\n mimeType: result.data.blob.mimeType,\n size: result.data.blob.size,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to upload blob: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Retrieves a blob by its CID.\n *\n * @param cid - Content Identifier (CID) of the blob, typically from a blob\n * reference's `$link` property\n * @returns Promise resolving to blob data and MIME type\n * @throws {@link NetworkError} if the blob is not found or retrieval fails\n *\n * @remarks\n * The returned data is a Uint8Array which can be converted to other\n * formats as needed (Blob, ArrayBuffer, Base64, etc.).\n *\n * **MIME Type**: The returned MIME type comes from the Content-Type header.\n * If the server doesn't provide one, it defaults to `application/octet-stream`.\n *\n * @example Basic retrieval\n * ```typescript\n * // Get a blob from a record's blob reference\n * const record = await repo.records.get({ collection, rkey });\n * const blobRef = (record.value as any).image;\n *\n * const { data, mimeType } = await repo.blobs.get(blobRef.$link);\n *\n * // Convert to a Blob for use in the browser\n * const blob = new Blob([data], { type: mimeType });\n * const url = URL.createObjectURL(blob);\n * ```\n *\n * @example Displaying an image\n * ```typescript\n * const { data, mimeType } = await repo.blobs.get(imageCid);\n *\n * // Create data URL for <img> src\n * const base64 = btoa(String.fromCharCode(...data));\n * const dataUrl = `data:${mimeType};base64,${base64}`;\n *\n * // Or use object URL\n * const blob = new Blob([data], { type: mimeType });\n * img.src = URL.createObjectURL(blob);\n * ```\n */\n async get(cid: string): Promise<{ data: Uint8Array; mimeType: string }> {\n try {\n const result = await this.agent.com.atproto.sync.getBlob({\n did: this.repoDid,\n cid,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get blob\");\n }\n\n return {\n data: result.data,\n mimeType: result.headers[\"content-type\"] || \"application/octet-stream\",\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get blob: ${error instanceof Error ? error.message : \"Unknown error\"}`, error);\n }\n }\n}\n","/**\n * ProfileOperationsImpl - User profile operations.\n *\n * This module provides the implementation for AT Protocol profile\n * management, including fetching and updating user profiles.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { NetworkError } from \"../core/errors.js\";\nimport type { ProfileOperations } from \"./interfaces.js\";\nimport type { UpdateResult } from \"./types.js\";\n\n/**\n * Implementation of profile operations for user profile management.\n *\n * Profiles in AT Protocol are stored as records in the `app.bsky.actor.profile`\n * collection with the special rkey \"self\". This class provides a convenient\n * API for reading and updating profile data.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.profile}.\n *\n * **Profile Fields**:\n * - `handle`: Read-only, managed by the PDS\n * - `displayName`: User's display name (max 64 chars typically)\n * - `description`: Profile bio (max 256 chars typically)\n * - `avatar`: Profile picture blob reference\n * - `banner`: Banner image blob reference\n * - `website`: User's website URL (may not be available on all servers)\n *\n * @example\n * ```typescript\n * // Get profile\n * const profile = await repo.profile.get();\n * console.log(`${profile.displayName} (@${profile.handle})`);\n *\n * // Update profile\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"Updated bio\",\n * });\n *\n * // Update with new avatar\n * const avatarBlob = new Blob([imageData], { type: \"image/png\" });\n * await repo.profile.update({ avatar: avatarBlob });\n *\n * // Remove a field\n * await repo.profile.update({ website: null });\n * ```\n *\n * @internal\n */\nexport class ProfileOperationsImpl implements ProfileOperations {\n /**\n * Creates a new ProfileOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository/user\n * @param _serverUrl - Server URL (reserved for future use)\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n ) {}\n\n /**\n * Gets the repository's profile.\n *\n * @returns Promise resolving to profile data\n * @throws {@link NetworkError} if the profile cannot be fetched\n *\n * @remarks\n * This method fetches the full profile using the `getProfile` API,\n * which includes resolved information like follower counts on some\n * servers. For hypercerts SDK usage, the basic profile fields are\n * returned.\n *\n * **Note**: The `website` field may not be available on all AT Protocol\n * servers. Standard Bluesky profiles don't include this field.\n *\n * @example\n * ```typescript\n * const profile = await repo.profile.get();\n *\n * console.log(`Handle: @${profile.handle}`);\n * console.log(`Name: ${profile.displayName || \"(not set)\"}`);\n * console.log(`Bio: ${profile.description || \"(no bio)\"}`);\n *\n * if (profile.avatar) {\n * // Avatar is a URL or blob reference\n * console.log(`Avatar: ${profile.avatar}`);\n * }\n * ```\n */\n async get(): Promise<{\n handle: string;\n displayName?: string;\n description?: string;\n avatar?: string;\n banner?: string;\n website?: string;\n }> {\n try {\n const result = await this.agent.getProfile({ actor: this.repoDid });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get profile\");\n }\n\n return {\n handle: result.data.handle,\n displayName: result.data.displayName,\n description: result.data.description,\n avatar: result.data.avatar,\n banner: result.data.banner,\n // Note: website may not be available in standard profile\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to get profile: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates the repository's profile.\n *\n * @param params - Fields to update. Pass `null` to remove a field.\n * Omitted fields are preserved from the existing profile.\n * @returns Promise resolving to update result with new URI and CID\n * @throws {@link NetworkError} if the update fails\n *\n * @remarks\n * This method performs a read-modify-write operation:\n * 1. Fetches the existing profile record\n * 2. Merges in the provided updates\n * 3. Writes the updated profile back\n *\n * **Image Handling**: When providing `avatar` or `banner` as a Blob,\n * the image is automatically uploaded and the blob reference is stored\n * in the profile.\n *\n * **Field Removal**: Pass `null` to explicitly remove a field. Omitting\n * a field (not including it in params) preserves the existing value.\n *\n * @example Update display name and bio\n * ```typescript\n * await repo.profile.update({\n * displayName: \"Alice\",\n * description: \"Building impact certificates\",\n * });\n * ```\n *\n * @example Update avatar image\n * ```typescript\n * // From a file input\n * const file = document.getElementById(\"avatar\").files[0];\n * await repo.profile.update({ avatar: file });\n *\n * // From raw data\n * const response = await fetch(\"https://example.com/my-avatar.png\");\n * const blob = await response.blob();\n * await repo.profile.update({ avatar: blob });\n * ```\n *\n * @example Remove description\n * ```typescript\n * // Removes the description field entirely\n * await repo.profile.update({ description: null });\n * ```\n *\n * @example Multiple updates at once\n * ```typescript\n * const newAvatar = new Blob([avatarData], { type: \"image/png\" });\n * const newBanner = new Blob([bannerData], { type: \"image/jpeg\" });\n *\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"New bio\",\n * avatar: newAvatar,\n * banner: newBanner,\n * });\n * ```\n */\n async update(params: {\n displayName?: string | null;\n description?: string | null;\n avatar?: Blob | null;\n banner?: Blob | null;\n website?: string | null;\n }): Promise<UpdateResult> {\n try {\n // Get existing profile record\n const existing = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection: \"app.bsky.actor.profile\",\n rkey: \"self\",\n });\n\n const existingProfile = (existing.data.value as Record<string, unknown>) || {};\n\n // Build updated profile\n const updatedProfile: Record<string, unknown> = { ...existingProfile };\n\n if (params.displayName !== undefined) {\n if (params.displayName === null) {\n delete updatedProfile.displayName;\n } else {\n updatedProfile.displayName = params.displayName;\n }\n }\n\n if (params.description !== undefined) {\n if (params.description === null) {\n delete updatedProfile.description;\n } else {\n updatedProfile.description = params.description;\n }\n }\n\n // Handle avatar upload\n if (params.avatar !== undefined) {\n if (params.avatar === null) {\n delete updatedProfile.avatar;\n } else {\n const arrayBuffer = await params.avatar.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.avatar.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n updatedProfile.avatar = uploadResult.data.blob;\n }\n }\n }\n\n // Handle banner upload\n if (params.banner !== undefined) {\n if (params.banner === null) {\n delete updatedProfile.banner;\n } else {\n const arrayBuffer = await params.banner.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.banner.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n updatedProfile.banner = uploadResult.data.blob;\n }\n }\n }\n\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection: \"app.bsky.actor.profile\",\n rkey: \"self\",\n record: updatedProfile,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update profile\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update profile: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error,\n );\n }\n }\n}\n","/**\n * HypercertOperationsImpl - High-level hypercert operations.\n *\n * This module provides the implementation for creating and managing\n * hypercerts, including related records like rights, locations,\n * contributions, measurements, and evaluations.\n *\n * @packageDocumentation\n */\n\nimport type { Agent } from \"@atproto/api\";\nimport { EventEmitter } from \"eventemitter3\";\nimport { NetworkError, ValidationError } from \"../core/errors.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\nimport {\n HYPERCERT_COLLECTIONS,\n type BlobRef,\n type HypercertEvidence,\n type HypercertClaim,\n type HypercertRights,\n type HypercertContribution,\n type HypercertMeasurement,\n type HypercertEvaluation,\n type HypercertCollection,\n type HypercertLocation,\n} from \"../services/hypercerts/types.js\";\nimport type {\n HypercertOperations,\n HypercertEvents,\n CreateHypercertParams,\n CreateHypercertResult,\n} from \"./interfaces.js\";\nimport type { CreateResult, UpdateResult, PaginatedList, ListParams, ProgressStep } from \"./types.js\";\n\n/**\n * Implementation of high-level hypercert operations.\n *\n * This class provides a convenient API for creating and managing hypercerts\n * with automatic handling of:\n *\n * - Image upload and blob reference management\n * - Rights record creation and linking\n * - Location attachment with optional GeoJSON support\n * - Contribution tracking\n * - Measurement and evaluation records\n * - Hypercert collections\n *\n * The class extends EventEmitter to provide real-time progress notifications\n * during complex operations.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.hypercerts}.\n *\n * **Record Relationships**:\n * - Hypercert → Rights (required, 1:1)\n * - Hypercert → Location (optional, 1:many)\n * - Hypercert → Contribution (optional, 1:many)\n * - Hypercert → Measurement (optional, 1:many)\n * - Hypercert → Evaluation (optional, 1:many)\n * - Collection → Hypercerts (1:many via claims array)\n *\n * @example Creating a hypercert with progress tracking\n * ```typescript\n * repo.hypercerts.on(\"recordCreated\", ({ uri }) => {\n * console.log(`Hypercert created: ${uri}`);\n * });\n *\n * const result = await repo.hypercerts.create({\n * title: \"Climate Impact\",\n * description: \"Reduced emissions by 100 tons\",\n * workScope: \"Climate\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: { name: \"CC-BY\", type: \"license\", description: \"...\" },\n * onProgress: (step) => console.log(`${step.name}: ${step.status}`),\n * });\n * ```\n *\n * @internal\n */\nexport class HypercertOperationsImpl extends EventEmitter<HypercertEvents> implements HypercertOperations {\n /**\n * Creates a new HypercertOperationsImpl.\n *\n * @param agent - AT Protocol Agent for making API calls\n * @param repoDid - DID of the repository to operate on\n * @param _serverUrl - Server URL (reserved for future use)\n * @param lexiconRegistry - Registry for record validation\n * @param logger - Optional logger for debugging\n *\n * @internal\n */\n constructor(\n private agent: Agent,\n private repoDid: string,\n private _serverUrl: string,\n private lexiconRegistry: LexiconRegistry,\n private logger?: LoggerInterface,\n ) {\n super();\n }\n\n /**\n * Emits a progress event to the optional progress handler.\n *\n * @param onProgress - Progress callback from create params\n * @param step - Progress step information\n * @internal\n */\n private emitProgress(onProgress: ((step: ProgressStep) => void) | undefined, step: ProgressStep): void {\n if (onProgress) {\n try {\n onProgress(step);\n } catch (err) {\n this.logger?.error(`Error in progress handler: ${err instanceof Error ? err.message : \"Unknown\"}`);\n }\n }\n }\n\n /**\n * Creates a new hypercert with all related records.\n *\n * This method orchestrates the creation of a hypercert and its associated\n * records in the correct order:\n *\n * 1. Upload image (if provided)\n * 2. Create rights record\n * 3. Create hypercert record (referencing rights)\n * 4. Attach location (if provided)\n * 5. Create contributions (if provided)\n *\n * @param params - Creation parameters (see {@link CreateHypercertParams})\n * @returns Promise resolving to URIs and CIDs of all created records\n * @throws {@link ValidationError} if any record fails validation\n * @throws {@link NetworkError} if any API call fails\n *\n * @remarks\n * The operation is not atomic - if a later step fails, earlier records\n * will still exist. The result object will contain URIs for all\n * successfully created records.\n *\n * **Progress Steps**:\n * - `uploadImage`: Image blob upload\n * - `createRights`: Rights record creation\n * - `createHypercert`: Main hypercert record creation\n * - `attachLocation`: Location record creation\n * - `createContributions`: Contribution records creation\n *\n * @example Minimal hypercert\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"My Impact\",\n * description: \"Description of impact work\",\n * workScope: \"Education\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-06-30\",\n * rights: {\n * name: \"Attribution\",\n * type: \"license\",\n * description: \"CC-BY-4.0\",\n * },\n * });\n * ```\n *\n * @example Full hypercert with all options\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"Reforestation Project\",\n * description: \"Planted 10,000 trees...\",\n * shortDescription: \"10K trees planted\",\n * workScope: \"Environment\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: { name: \"Open\", type: \"impact\", description: \"...\" },\n * image: coverImageBlob,\n * location: { value: \"Amazon, Brazil\", name: \"Amazon Basin\" },\n * contributions: [\n * { contributors: [\"did:plc:org1\"], role: \"coordinator\" },\n * { contributors: [\"did:plc:org2\"], role: \"implementer\" },\n * ],\n * evidence: [{ uri: \"https://...\", description: \"Satellite data\" }],\n * onProgress: console.log,\n * });\n * ```\n */\n async create(params: CreateHypercertParams): Promise<CreateHypercertResult> {\n const createdAt = new Date().toISOString();\n const result: CreateHypercertResult = {\n hypercertUri: \"\",\n rightsUri: \"\",\n hypercertCid: \"\",\n rightsCid: \"\",\n };\n\n try {\n // Step 1: Upload image if provided\n let imageBlobRef: BlobRef | undefined;\n if (params.image) {\n this.emitProgress(params.onProgress, { name: \"uploadImage\", status: \"start\" });\n try {\n const arrayBuffer = await params.image.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.image.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n imageBlobRef = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n this.emitProgress(params.onProgress, {\n name: \"uploadImage\",\n status: \"success\",\n data: { size: params.image.size },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"uploadImage\", status: \"error\", error: error as Error });\n throw new NetworkError(\n `Failed to upload image: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n // Step 2: Create rights record\n this.emitProgress(params.onProgress, { name: \"createRights\", status: \"start\" });\n const rightsRecord: Omit<HypercertRights, \"$type\"> = {\n rightsName: params.rights.name,\n rightsType: params.rights.type,\n rightsDescription: params.rights.description,\n createdAt,\n };\n\n const rightsValidation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.RIGHTS, rightsRecord);\n if (!rightsValidation.valid) {\n throw new ValidationError(`Invalid rights record: ${rightsValidation.error}`);\n }\n\n const rightsResult = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.RIGHTS,\n record: rightsRecord as Record<string, unknown>,\n });\n\n if (!rightsResult.success) {\n throw new NetworkError(\"Failed to create rights record\");\n }\n\n result.rightsUri = rightsResult.data.uri;\n result.rightsCid = rightsResult.data.cid;\n this.emit(\"rightsCreated\", { uri: result.rightsUri, cid: result.rightsCid });\n this.emitProgress(params.onProgress, {\n name: \"createRights\",\n status: \"success\",\n data: { uri: result.rightsUri },\n });\n\n // Step 3: Create hypercert record\n this.emitProgress(params.onProgress, { name: \"createHypercert\", status: \"start\" });\n const hypercertRecord: Record<string, unknown> = {\n title: params.title,\n description: params.description,\n workScope: params.workScope,\n workTimeframeFrom: params.workTimeframeFrom,\n workTimeframeTo: params.workTimeframeTo,\n rights: { uri: result.rightsUri, cid: result.rightsCid },\n createdAt,\n };\n\n if (params.shortDescription) {\n hypercertRecord.shortDescription = params.shortDescription;\n }\n\n if (imageBlobRef) {\n hypercertRecord.image = imageBlobRef;\n }\n\n if (params.evidence && params.evidence.length > 0) {\n hypercertRecord.evidence = params.evidence;\n }\n\n const hypercertValidation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CLAIM, hypercertRecord);\n if (!hypercertValidation.valid) {\n throw new ValidationError(`Invalid hypercert record: ${hypercertValidation.error}`);\n }\n\n const hypercertResult = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CLAIM,\n record: hypercertRecord,\n });\n\n if (!hypercertResult.success) {\n throw new NetworkError(\"Failed to create hypercert record\");\n }\n\n result.hypercertUri = hypercertResult.data.uri;\n result.hypercertCid = hypercertResult.data.cid;\n this.emit(\"recordCreated\", { uri: result.hypercertUri, cid: result.hypercertCid });\n this.emitProgress(params.onProgress, {\n name: \"createHypercert\",\n status: \"success\",\n data: { uri: result.hypercertUri },\n });\n\n // Step 4: Attach location if provided\n if (params.location) {\n this.emitProgress(params.onProgress, { name: \"attachLocation\", status: \"start\" });\n try {\n const locationResult = await this.attachLocation(result.hypercertUri, params.location);\n result.locationUri = locationResult.uri;\n this.emitProgress(params.onProgress, {\n name: \"attachLocation\",\n status: \"success\",\n data: { uri: result.locationUri },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"attachLocation\", status: \"error\", error: error as Error });\n this.logger?.warn(`Failed to attach location: ${error instanceof Error ? error.message : \"Unknown\"}`);\n }\n }\n\n // Step 5: Create contributions if provided\n if (params.contributions && params.contributions.length > 0) {\n this.emitProgress(params.onProgress, { name: \"createContributions\", status: \"start\" });\n result.contributionUris = [];\n try {\n for (const contrib of params.contributions) {\n const contribResult = await this.addContribution({\n hypercertUri: result.hypercertUri,\n contributors: contrib.contributors,\n role: contrib.role,\n description: contrib.description,\n });\n result.contributionUris.push(contribResult.uri);\n }\n this.emitProgress(params.onProgress, {\n name: \"createContributions\",\n status: \"success\",\n data: { count: result.contributionUris.length },\n });\n } catch (error) {\n this.emitProgress(params.onProgress, { name: \"createContributions\", status: \"error\", error: error as Error });\n this.logger?.warn(`Failed to create contributions: ${error instanceof Error ? error.message : \"Unknown\"}`);\n }\n }\n\n return result;\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Updates an existing hypercert record.\n *\n * @param params - Update parameters\n * @param params.uri - AT-URI of the hypercert to update\n * @param params.updates - Partial record with fields to update\n * @param params.image - New image blob, `null` to remove, `undefined` to keep existing\n * @returns Promise resolving to update result\n * @throws {@link ValidationError} if the URI format is invalid or record fails validation\n * @throws {@link NetworkError} if the update fails\n *\n * @remarks\n * This is a partial update - only specified fields are changed.\n * The `createdAt` and `rights` fields cannot be changed.\n *\n * @example Update title and description\n * ```typescript\n * await repo.hypercerts.update({\n * uri: \"at://did:plc:abc/org.hypercerts.hypercert/xyz\",\n * updates: {\n * title: \"Updated Title\",\n * description: \"New description\",\n * },\n * });\n * ```\n *\n * @example Update with new image\n * ```typescript\n * await repo.hypercerts.update({\n * uri: hypercertUri,\n * updates: { title: \"New Title\" },\n * image: newImageBlob,\n * });\n * ```\n *\n * @example Remove image\n * ```typescript\n * await repo.hypercerts.update({\n * uri: hypercertUri,\n * updates: {},\n * image: null, // Explicitly remove image\n * });\n * ```\n */\n async update(params: {\n uri: string;\n updates: Partial<Omit<HypercertClaim, \"$type\" | \"createdAt\" | \"rights\">>;\n image?: Blob | null;\n }): Promise<UpdateResult> {\n try {\n const uriMatch = params.uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${params.uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const existing = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n // The existing record comes from ATProto, use it directly\n // TypeScript ensures type safety through the HypercertClaim interface\n const existingRecord = existing.data.value as HypercertClaim;\n\n const recordForUpdate: Record<string, unknown> = {\n ...existingRecord,\n ...params.updates,\n createdAt: existingRecord.createdAt,\n rights: existingRecord.rights,\n };\n\n // Handle image update\n delete (recordForUpdate as { image?: unknown }).image;\n if (params.image !== undefined) {\n if (params.image === null) {\n // Remove image\n } else {\n const arrayBuffer = await params.image.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.image.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n recordForUpdate.image = {\n $type: \"blob\",\n ref: uploadResult.data.blob.ref,\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n } else if (existingRecord.image) {\n // Preserve existing image\n recordForUpdate.image = existingRecord.image;\n }\n\n const validation = this.lexiconRegistry.validate(collection, recordForUpdate);\n if (!validation.valid) {\n throw new ValidationError(`Invalid hypercert record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.putRecord({\n repo: this.repoDid,\n collection,\n rkey,\n record: recordForUpdate,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to update hypercert\");\n }\n\n this.emit(\"recordUpdated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to update hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a hypercert by its AT-URI.\n *\n * @param uri - AT-URI of the hypercert (e.g., \"at://did:plc:abc/org.hypercerts.hypercert/xyz\")\n * @returns Promise resolving to hypercert URI, CID, and parsed record\n * @throws {@link ValidationError} if the URI format is invalid or record doesn't match schema\n * @throws {@link NetworkError} if the record cannot be fetched\n *\n * @example\n * ```typescript\n * const { uri, cid, record } = await repo.hypercerts.get(hypercertUri);\n * console.log(`${record.title}: ${record.description}`);\n * ```\n */\n async get(uri: string): Promise<{ uri: string; cid: string; record: HypercertClaim }> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get hypercert\");\n }\n\n // Validate with lexicon registry (more lenient - doesn't require $type)\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CLAIM, result.data.value);\n if (!validation.valid) {\n throw new ValidationError(`Invalid hypercert record format: ${validation.error}`);\n }\n\n return {\n uri: result.data.uri,\n cid: result.data.cid ?? \"\",\n record: result.data.value as HypercertClaim,\n };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Lists hypercerts in the repository with pagination.\n *\n * @param params - Optional pagination parameters\n * @returns Promise resolving to paginated list of hypercerts\n * @throws {@link NetworkError} if the list operation fails\n *\n * @example\n * ```typescript\n * // Get first page\n * const { records, cursor } = await repo.hypercerts.list({ limit: 20 });\n *\n * // Get next page\n * if (cursor) {\n * const nextPage = await repo.hypercerts.list({ limit: 20, cursor });\n * }\n * ```\n */\n async list(params?: ListParams): Promise<PaginatedList<{ uri: string; cid: string; record: HypercertClaim }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CLAIM,\n limit: params?.limit,\n cursor: params?.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list hypercerts\");\n }\n\n return {\n records:\n result.data.records?.map((r) => ({\n uri: r.uri,\n cid: r.cid,\n record: r.value as HypercertClaim,\n })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to list hypercerts: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Deletes a hypercert record.\n *\n * @param uri - AT-URI of the hypercert to delete\n * @throws {@link ValidationError} if the URI format is invalid\n * @throws {@link NetworkError} if the deletion fails\n *\n * @remarks\n * This only deletes the hypercert record itself. Related records\n * (rights, locations, contributions) are not automatically deleted.\n *\n * @example\n * ```typescript\n * await repo.hypercerts.delete(hypercertUri);\n * ```\n */\n async delete(uri: string): Promise<void> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.deleteRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to delete hypercert\");\n }\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to delete hypercert: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Attaches a location to an existing hypercert.\n *\n * @param hypercertUri - AT-URI of the hypercert to attach location to\n * @param location - Location data\n * @param location.value - Location value (address, coordinates, or description)\n * @param location.name - Optional human-readable name\n * @param location.description - Optional description\n * @param location.srs - Spatial Reference System (e.g., \"EPSG:4326\")\n * @param location.geojson - Optional GeoJSON blob for precise boundaries\n * @returns Promise resolving to location record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example Simple location\n * ```typescript\n * await repo.hypercerts.attachLocation(hypercertUri, {\n * value: \"San Francisco, CA\",\n * name: \"SF Bay Area\",\n * });\n * ```\n *\n * @example Location with GeoJSON\n * ```typescript\n * const geojsonBlob = new Blob([JSON.stringify(geojson)], {\n * type: \"application/geo+json\"\n * });\n *\n * await repo.hypercerts.attachLocation(hypercertUri, {\n * value: \"Custom Region\",\n * srs: \"EPSG:4326\",\n * geojson: geojsonBlob,\n * });\n * ```\n */\n async attachLocation(\n hypercertUri: string,\n location: { value: string; name?: string; description?: string; srs?: string; geojson?: Blob },\n ): Promise<CreateResult> {\n try {\n // Get hypercert to get CID\n const hypercert = await this.get(hypercertUri);\n const createdAt = new Date().toISOString();\n\n let locationValue: string | BlobRef = location.value;\n if (location.geojson) {\n const arrayBuffer = await location.geojson.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: location.geojson.type || \"application/geo+json\",\n });\n if (uploadResult.success) {\n locationValue = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n\n const locationRecord: Omit<HypercertLocation, \"$type\"> = {\n hypercert: { uri: hypercert.uri, cid: hypercert.cid },\n value: locationValue,\n createdAt,\n name: location.name,\n description: location.description,\n srs: location.srs,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.LOCATION, locationRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid location record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.LOCATION,\n record: locationRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to attach location\");\n }\n\n this.emit(\"locationAttached\", { uri: result.data.uri, cid: result.data.cid, hypercertUri });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to attach location: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Adds evidence to an existing hypercert.\n *\n * @param hypercertUri - AT-URI of the hypercert\n * @param evidence - Array of evidence items to add\n * @returns Promise resolving to update result\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @remarks\n * Evidence is appended to existing evidence, not replaced.\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addEvidence(hypercertUri, [\n * { uri: \"https://example.com/report.pdf\", description: \"Impact report\" },\n * { uri: \"https://example.com/data.csv\", description: \"Raw data\" },\n * ]);\n * ```\n */\n async addEvidence(hypercertUri: string, evidence: HypercertEvidence[]): Promise<UpdateResult> {\n try {\n const existing = await this.get(hypercertUri);\n const existingEvidence = existing.record.evidence || [];\n const updatedEvidence = [...existingEvidence, ...evidence];\n\n const result = await this.update({\n uri: hypercertUri,\n updates: { evidence: updatedEvidence },\n });\n\n this.emit(\"evidenceAdded\", { uri: result.uri, cid: result.cid });\n return result;\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add evidence: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates a contribution record.\n *\n * @param params - Contribution parameters\n * @param params.hypercertUri - Optional hypercert to link (can be standalone)\n * @param params.contributors - Array of contributor DIDs\n * @param params.role - Role of the contributors (e.g., \"coordinator\", \"implementer\")\n * @param params.description - Optional description of the contribution\n * @returns Promise resolving to contribution record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addContribution({\n * hypercertUri: hypercertUri,\n * contributors: [\"did:plc:alice\", \"did:plc:bob\"],\n * role: \"implementer\",\n * description: \"On-ground implementation team\",\n * });\n * ```\n */\n async addContribution(params: {\n hypercertUri?: string;\n contributors: string[];\n role: string;\n description?: string;\n }): Promise<CreateResult> {\n try {\n const createdAt = new Date().toISOString();\n const contributionRecord: Omit<HypercertContribution, \"$type\"> = {\n contributors: params.contributors,\n role: params.role,\n createdAt,\n description: params.description,\n };\n\n if (params.hypercertUri) {\n const hypercert = await this.get(params.hypercertUri);\n contributionRecord.hypercert = { uri: hypercert.uri, cid: hypercert.cid };\n }\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.CONTRIBUTION, contributionRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid contribution record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.CONTRIBUTION,\n record: contributionRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create contribution\");\n }\n\n this.emit(\"contributionCreated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to add contribution: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Creates a measurement record for a hypercert.\n *\n * Measurements quantify the impact claimed in a hypercert with\n * specific metrics and values.\n *\n * @param params - Measurement parameters\n * @param params.hypercertUri - AT-URI of the hypercert being measured\n * @param params.measurers - DIDs of entities who performed the measurement\n * @param params.metric - Name of the metric (e.g., \"CO2 Reduced\", \"Trees Planted\")\n * @param params.value - Measured value with units (e.g., \"100 tons\", \"10000\")\n * @param params.methodUri - Optional URI describing the measurement methodology\n * @param params.evidenceUris - Optional URIs to supporting evidence\n * @returns Promise resolving to measurement record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addMeasurement({\n * hypercertUri: hypercertUri,\n * measurers: [\"did:plc:auditor\"],\n * metric: \"Carbon Offset\",\n * value: \"150 tons CO2e\",\n * methodUri: \"https://example.com/methodology\",\n * evidenceUris: [\"https://example.com/audit-report\"],\n * });\n * ```\n */\n async addMeasurement(params: {\n hypercertUri: string;\n measurers: string[];\n metric: string;\n value: string;\n methodUri?: string;\n evidenceUris?: string[];\n }): Promise<CreateResult> {\n try {\n const hypercert = await this.get(params.hypercertUri);\n const createdAt = new Date().toISOString();\n\n const measurementRecord: Omit<HypercertMeasurement, \"$type\"> = {\n hypercert: { uri: hypercert.uri, cid: hypercert.cid },\n measurers: params.measurers,\n metric: params.metric,\n value: params.value,\n createdAt,\n measurementMethodURI: params.methodUri,\n evidenceURI: params.evidenceUris,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.MEASUREMENT, measurementRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid measurement record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.MEASUREMENT,\n record: measurementRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create measurement\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add measurement: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates an evaluation record for a hypercert or other subject.\n *\n * Evaluations provide third-party assessments of impact claims.\n *\n * @param params - Evaluation parameters\n * @param params.subjectUri - AT-URI of the record being evaluated\n * @param params.evaluators - DIDs of evaluating entities\n * @param params.summary - Summary of the evaluation findings\n * @returns Promise resolving to evaluation record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * await repo.hypercerts.addEvaluation({\n * subjectUri: hypercertUri,\n * evaluators: [\"did:plc:evaluator-org\"],\n * summary: \"Verified impact claims through site visit and data analysis\",\n * });\n * ```\n */\n async addEvaluation(params: { subjectUri: string; evaluators: string[]; summary: string }): Promise<CreateResult> {\n try {\n const subject = await this.get(params.subjectUri);\n const createdAt = new Date().toISOString();\n\n const evaluationRecord: Omit<HypercertEvaluation, \"$type\"> = {\n subject: { uri: subject.uri, cid: subject.cid },\n evaluators: params.evaluators,\n summary: params.summary,\n createdAt,\n };\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.EVALUATION, evaluationRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid evaluation record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.EVALUATION,\n record: evaluationRecord as Record<string, unknown>,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create evaluation\");\n }\n\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to add evaluation: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Creates a collection of hypercerts.\n *\n * Collections group related hypercerts with optional weights\n * for relative importance.\n *\n * @param params - Collection parameters\n * @param params.title - Collection title\n * @param params.claims - Array of hypercert references with weights\n * @param params.shortDescription - Optional short description\n * @param params.coverPhoto - Optional cover image blob\n * @returns Promise resolving to collection record URI and CID\n * @throws {@link ValidationError} if validation fails\n * @throws {@link NetworkError} if the operation fails\n *\n * @example\n * ```typescript\n * const collection = await repo.hypercerts.createCollection({\n * title: \"Climate Projects 2024\",\n * shortDescription: \"Our climate impact portfolio\",\n * claims: [\n * { uri: hypercert1Uri, cid: hypercert1Cid, weight: \"0.5\" },\n * { uri: hypercert2Uri, cid: hypercert2Cid, weight: \"0.3\" },\n * { uri: hypercert3Uri, cid: hypercert3Cid, weight: \"0.2\" },\n * ],\n * coverPhoto: coverImageBlob,\n * });\n * ```\n */\n async createCollection(params: {\n title: string;\n claims: Array<{ uri: string; cid: string; weight: string }>;\n shortDescription?: string;\n coverPhoto?: Blob;\n }): Promise<CreateResult> {\n try {\n const createdAt = new Date().toISOString();\n\n let coverPhotoRef: BlobRef | undefined;\n if (params.coverPhoto) {\n const arrayBuffer = await params.coverPhoto.arrayBuffer();\n const uint8Array = new Uint8Array(arrayBuffer);\n const uploadResult = await this.agent.com.atproto.repo.uploadBlob(uint8Array, {\n encoding: params.coverPhoto.type || \"image/jpeg\",\n });\n if (uploadResult.success) {\n coverPhotoRef = {\n $type: \"blob\",\n ref: { $link: uploadResult.data.blob.ref.toString() },\n mimeType: uploadResult.data.blob.mimeType,\n size: uploadResult.data.blob.size,\n };\n }\n }\n\n const collectionRecord: Record<string, unknown> = {\n title: params.title,\n claims: params.claims.map((c) => ({ claim: { uri: c.uri, cid: c.cid }, weight: c.weight })),\n createdAt,\n };\n\n if (params.shortDescription) {\n collectionRecord.shortDescription = params.shortDescription;\n }\n\n if (coverPhotoRef) {\n collectionRecord.coverPhoto = coverPhotoRef;\n }\n\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.COLLECTION, collectionRecord);\n if (!validation.valid) {\n throw new ValidationError(`Invalid collection record: ${validation.error}`);\n }\n\n const result = await this.agent.com.atproto.repo.createRecord({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.COLLECTION,\n record: collectionRecord,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to create collection\");\n }\n\n this.emit(\"collectionCreated\", { uri: result.data.uri, cid: result.data.cid });\n return { uri: result.data.uri, cid: result.data.cid };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to create collection: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n\n /**\n * Gets a collection by its AT-URI.\n *\n * @param uri - AT-URI of the collection\n * @returns Promise resolving to collection URI, CID, and parsed record\n * @throws {@link ValidationError} if the URI format is invalid or record doesn't match schema\n * @throws {@link NetworkError} if the record cannot be fetched\n *\n * @example\n * ```typescript\n * const { record } = await repo.hypercerts.getCollection(collectionUri);\n * console.log(`Collection: ${record.title}`);\n * console.log(`Contains ${record.claims.length} hypercerts`);\n * ```\n */\n async getCollection(uri: string): Promise<{ uri: string; cid: string; record: HypercertCollection }> {\n try {\n const uriMatch = uri.match(/^at:\\/\\/([^/]+)\\/([^/]+)\\/(.+)$/);\n if (!uriMatch) {\n throw new ValidationError(`Invalid URI format: ${uri}`);\n }\n const [, , collection, rkey] = uriMatch;\n\n const result = await this.agent.com.atproto.repo.getRecord({\n repo: this.repoDid,\n collection,\n rkey,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to get collection\");\n }\n\n // Validate with lexicon registry (more lenient - doesn't require $type)\n const validation = this.lexiconRegistry.validate(HYPERCERT_COLLECTIONS.COLLECTION, result.data.value);\n if (!validation.valid) {\n throw new ValidationError(`Invalid collection record format: ${validation.error}`);\n }\n\n return {\n uri: result.data.uri,\n cid: result.data.cid ?? \"\",\n record: result.data.value as HypercertCollection,\n };\n } catch (error) {\n if (error instanceof ValidationError || error instanceof NetworkError) throw error;\n throw new NetworkError(`Failed to get collection: ${error instanceof Error ? error.message : \"Unknown\"}`, error);\n }\n }\n\n /**\n * Lists collections in the repository with pagination.\n *\n * @param params - Optional pagination parameters\n * @returns Promise resolving to paginated list of collections\n * @throws {@link NetworkError} if the list operation fails\n *\n * @example\n * ```typescript\n * const { records } = await repo.hypercerts.listCollections();\n * for (const { record } of records) {\n * console.log(`${record.title}: ${record.claims.length} claims`);\n * }\n * ```\n */\n async listCollections(\n params?: ListParams,\n ): Promise<PaginatedList<{ uri: string; cid: string; record: HypercertCollection }>> {\n try {\n const result = await this.agent.com.atproto.repo.listRecords({\n repo: this.repoDid,\n collection: HYPERCERT_COLLECTIONS.COLLECTION,\n limit: params?.limit,\n cursor: params?.cursor,\n });\n\n if (!result.success) {\n throw new NetworkError(\"Failed to list collections\");\n }\n\n return {\n records:\n result.data.records?.map((r) => ({\n uri: r.uri,\n cid: r.cid,\n record: r.value as HypercertCollection,\n })) || [],\n cursor: result.data.cursor ?? undefined,\n };\n } catch (error) {\n if (error instanceof NetworkError) throw error;\n throw new NetworkError(\n `Failed to list collections: ${error instanceof Error ? error.message : \"Unknown\"}`,\n error,\n );\n }\n }\n}\n","/**\n * CollaboratorOperationsImpl - SDS collaborator management operations.\n *\n * This module provides the implementation for managing collaborator\n * access on Shared Data Server (SDS) repositories.\n *\n * @packageDocumentation\n */\n\nimport { NetworkError } from \"../core/errors.js\";\nimport type { CollaboratorPermissions, Session } from \"../core/types.js\";\nimport type { CollaboratorOperations } from \"./interfaces.js\";\nimport type { RepositoryRole, RepositoryAccessGrant } from \"./types.js\";\n\n/**\n * Implementation of collaborator operations for SDS access control.\n *\n * This class manages access permissions for shared repositories on\n * Shared Data Servers (SDS). It provides role-based access control\n * with predefined permission sets.\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.collaborators} on an SDS-connected repository.\n *\n * **Role Hierarchy**:\n * - `viewer`: Read-only access\n * - `editor`: Read + Create + Update\n * - `admin`: All permissions except ownership transfer\n * - `owner`: Full control including ownership management\n *\n * **SDS API Endpoints Used**:\n * - `com.sds.repo.grantAccess`: Grant access to a user\n * - `com.sds.repo.revokeAccess`: Revoke access from a user\n * - `com.sds.repo.listCollaborators`: List all collaborators\n * - `com.sds.repo.getPermissions`: Get current user's permissions\n * - `com.sds.repo.transferOwnership`: Transfer repository ownership\n *\n * @example\n * ```typescript\n * // Get SDS repository\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Grant editor access\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:new-user\",\n * role: \"editor\",\n * });\n *\n * // List all collaborators\n * const collaborators = await sdsRepo.collaborators.list();\n *\n * // Check specific user\n * const hasAccess = await sdsRepo.collaborators.hasAccess(\"did:plc:someone\");\n * const role = await sdsRepo.collaborators.getRole(\"did:plc:someone\");\n * ```\n *\n * @internal\n */\nexport class CollaboratorOperationsImpl implements CollaboratorOperations {\n /**\n * Creates a new CollaboratorOperationsImpl.\n *\n * @param session - Authenticated OAuth session with fetchHandler\n * @param repoDid - DID of the repository to manage\n * @param serverUrl - SDS server URL\n *\n * @internal\n */\n constructor(\n private session: Session,\n private repoDid: string,\n private serverUrl: string,\n ) {}\n\n /**\n * Converts a role to its corresponding permissions object.\n *\n * @param role - The role to convert\n * @returns Permission flags for the role\n * @internal\n */\n private roleToPermissions(role: RepositoryRole): CollaboratorPermissions {\n switch (role) {\n case \"viewer\":\n return { read: true, create: false, update: false, delete: false, admin: false, owner: false };\n case \"editor\":\n return { read: true, create: true, update: true, delete: false, admin: false, owner: false };\n case \"admin\":\n return { read: true, create: true, update: true, delete: true, admin: true, owner: false };\n case \"owner\":\n return { read: true, create: true, update: true, delete: true, admin: true, owner: true };\n }\n }\n\n /**\n * Determines the role from a permissions object.\n *\n * @param permissions - The permissions to analyze\n * @returns The highest role matching the permissions\n * @internal\n */\n private permissionsToRole(permissions: CollaboratorPermissions): RepositoryRole {\n if (permissions.owner) return \"owner\";\n if (permissions.admin) return \"admin\";\n if (permissions.create || permissions.update) return \"editor\";\n return \"viewer\";\n }\n\n /**\n * Normalizes permissions from SDS API format to SDK format.\n *\n * The SDS API returns permissions as an object with boolean flags\n * (e.g., `{ read: true, create: true, update: false, ... }`).\n * This method ensures all expected fields are present with default values.\n *\n * @param permissions - Permissions object from SDS API\n * @returns Normalized permission flags object\n * @internal\n */\n private parsePermissions(permissions: CollaboratorPermissions): CollaboratorPermissions {\n return {\n read: permissions.read ?? false,\n create: permissions.create ?? false,\n update: permissions.update ?? false,\n delete: permissions.delete ?? false,\n admin: permissions.admin ?? false,\n owner: permissions.owner ?? false,\n };\n }\n\n /**\n * Grants repository access to a user.\n *\n * @param params - Grant parameters\n * @param params.userDid - DID of the user to grant access to\n * @param params.role - Role to assign (determines permissions)\n * @throws {@link NetworkError} if the grant operation fails\n *\n * @remarks\n * If the user already has access, their permissions are updated\n * to the new role.\n *\n * @example\n * ```typescript\n * // Grant viewer access\n * await repo.collaborators.grant({\n * userDid: \"did:plc:viewer-user\",\n * role: \"viewer\",\n * });\n *\n * // Upgrade to editor\n * await repo.collaborators.grant({\n * userDid: \"did:plc:viewer-user\",\n * role: \"editor\",\n * });\n * ```\n */\n async grant(params: { userDid: string; role: RepositoryRole }): Promise<void> {\n const permissions = this.roleToPermissions(params.role);\n\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.grantAccess`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n userDid: params.userDid,\n permissions,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to grant access: ${response.statusText}`);\n }\n }\n\n /**\n * Revokes repository access from a user.\n *\n * @param params - Revoke parameters\n * @param params.userDid - DID of the user to revoke access from\n * @throws {@link NetworkError} if the revoke operation fails\n *\n * @remarks\n * - Cannot revoke access from the repository owner\n * - Revoked access is recorded with a `revokedAt` timestamp\n *\n * @example\n * ```typescript\n * await repo.collaborators.revoke({\n * userDid: \"did:plc:former-collaborator\",\n * });\n * ```\n */\n async revoke(params: { userDid: string }): Promise<void> {\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.revokeAccess`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n userDid: params.userDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to revoke access: ${response.statusText}`);\n }\n }\n\n /**\n * Lists all collaborators on the repository.\n *\n * @param params - Optional pagination parameters\n * @param params.limit - Maximum number of results (1-100, default 50)\n * @param params.cursor - Pagination cursor from previous response\n * @returns Promise resolving to collaborators and optional cursor\n * @throws {@link NetworkError} if the list operation fails\n *\n * @remarks\n * The list includes both active and revoked collaborators.\n * Check `revokedAt` to filter active collaborators.\n *\n * @example\n * ```typescript\n * // Get first page\n * const page1 = await repo.collaborators.list({ limit: 10 });\n * console.log(`Found ${page1.collaborators.length} collaborators`);\n *\n * // Get next page if available\n * if (page1.cursor) {\n * const page2 = await repo.collaborators.list({ limit: 10, cursor: page1.cursor });\n * }\n *\n * // Filter active collaborators\n * const active = page1.collaborators.filter(c => !c.revokedAt);\n * ```\n */\n async list(params?: { limit?: number; cursor?: string }): Promise<{\n collaborators: RepositoryAccessGrant[];\n cursor?: string;\n }> {\n const queryParams = new URLSearchParams({\n repo: this.repoDid,\n });\n\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n\n if (params?.cursor) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.repo.listCollaborators?${queryParams.toString()}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to list collaborators: ${response.statusText}`);\n }\n\n const data = await response.json();\n const collaborators = (data.collaborators || []).map(\n (c: {\n userDid: string;\n permissions: CollaboratorPermissions; // SDS API returns object with boolean flags\n grantedBy: string;\n grantedAt: string;\n revokedAt?: string;\n }) => {\n const permissions = this.parsePermissions(c.permissions);\n return {\n userDid: c.userDid,\n role: this.permissionsToRole(permissions),\n permissions: permissions,\n grantedBy: c.grantedBy,\n grantedAt: c.grantedAt,\n revokedAt: c.revokedAt,\n };\n },\n );\n\n return {\n collaborators,\n cursor: data.cursor,\n };\n }\n\n /**\n * Checks if a user has any access to the repository.\n *\n * @param userDid - DID of the user to check\n * @returns Promise resolving to `true` if user has active access\n *\n * @remarks\n * Returns `false` if:\n * - User was never granted access\n * - User's access was revoked\n * - The list operation fails (error is suppressed)\n *\n * @example\n * ```typescript\n * if (await repo.collaborators.hasAccess(\"did:plc:someone\")) {\n * console.log(\"User has access\");\n * }\n * ```\n */\n async hasAccess(userDid: string): Promise<boolean> {\n try {\n const { collaborators } = await this.list();\n return collaborators.some((c) => c.userDid === userDid && !c.revokedAt);\n } catch {\n return false;\n }\n }\n\n /**\n * Gets the role assigned to a user.\n *\n * @param userDid - DID of the user to check\n * @returns Promise resolving to the user's role, or `null` if no active access\n *\n * @example\n * ```typescript\n * const role = await repo.collaborators.getRole(\"did:plc:someone\");\n * if (role === \"admin\" || role === \"owner\") {\n * // User can manage other collaborators\n * }\n * ```\n */\n async getRole(userDid: string): Promise<RepositoryRole | null> {\n const { collaborators } = await this.list();\n const collab = collaborators.find((c) => c.userDid === userDid && !c.revokedAt);\n return collab?.role ?? null;\n }\n\n /**\n * Gets the current user's permissions for this repository.\n *\n * @returns Promise resolving to the permission flags\n * @throws {@link NetworkError} if the request fails\n *\n * @remarks\n * This is useful for checking what actions the current user can perform\n * before attempting operations that might fail due to insufficient permissions.\n *\n * @example\n * ```typescript\n * const permissions = await repo.collaborators.getPermissions();\n *\n * if (permissions.admin) {\n * // Show admin UI\n * console.log(\"You can manage collaborators\");\n * }\n *\n * if (permissions.create) {\n * console.log(\"You can create records\");\n * }\n * ```\n *\n * @example Conditional UI rendering\n * ```typescript\n * const permissions = await repo.collaborators.getPermissions();\n *\n * // Show/hide UI elements based on permissions\n * const canEdit = permissions.update;\n * const canDelete = permissions.delete;\n * const isAdmin = permissions.admin;\n * const isOwner = permissions.owner;\n * ```\n */\n async getPermissions(): Promise<CollaboratorPermissions> {\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.repo.getPermissions?repo=${encodeURIComponent(this.repoDid)}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to get permissions: ${response.statusText}`);\n }\n\n const data = await response.json();\n return data.permissions as CollaboratorPermissions;\n }\n\n /**\n * Transfers repository ownership to another user.\n *\n * @param params - Transfer parameters\n * @param params.newOwnerDid - DID of the user to transfer ownership to\n * @throws {@link NetworkError} if the transfer fails\n *\n * @remarks\n * **IMPORTANT**: This action is irreversible. Once ownership is transferred:\n * - The new owner gains full control of the repository\n * - Your role will be changed to admin (or specified role)\n * - You cannot transfer ownership back without the new owner's approval\n *\n * **Requirements**:\n * - You must be the current owner\n * - The new owner must have an existing account\n * - The new owner will be notified of the ownership transfer\n *\n * @example\n * ```typescript\n * // Transfer ownership to another user\n * await repo.collaborators.transferOwnership({\n * newOwnerDid: \"did:plc:new-owner\",\n * });\n *\n * console.log(\"Ownership transferred successfully\");\n * // You are now an admin, not the owner\n * ```\n *\n * @example With confirmation\n * ```typescript\n * const confirmTransfer = await askUser(\n * \"Are you sure you want to transfer ownership? This cannot be undone.\"\n * );\n *\n * if (confirmTransfer) {\n * await repo.collaborators.transferOwnership({\n * newOwnerDid: \"did:plc:new-owner\",\n * });\n * }\n * ```\n */\n async transferOwnership(params: { newOwnerDid: string }): Promise<void> {\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.repo.transferOwnership`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n repo: this.repoDid,\n newOwner: params.newOwnerDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to transfer ownership: ${response.statusText}`);\n }\n }\n}\n","/**\n * OrganizationOperationsImpl - SDS organization management operations.\n *\n * This module provides the implementation for creating and managing\n * organizations on Shared Data Server (SDS) instances.\n *\n * @packageDocumentation\n */\n\nimport { NetworkError } from \"../core/errors.js\";\nimport type { CollaboratorPermissions, Session } from \"../core/types.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { OrganizationOperations } from \"./interfaces.js\";\nimport type { OrganizationInfo } from \"./types.js\";\n\n/**\n * Implementation of organization operations for SDS management.\n *\n * Organizations on SDS provide a way to create shared repositories\n * that multiple users can collaborate on. Each organization has:\n *\n * - A unique DID (Decentralized Identifier)\n * - A handle for human-readable identification\n * - An owner and optional collaborators\n * - Its own repository for storing records\n *\n * @remarks\n * This class is typically not instantiated directly. Access it through\n * {@link Repository.organizations} on an SDS-connected repository.\n *\n * **SDS API Endpoints Used**:\n * - `com.sds.organization.create`: Create a new organization\n * - `com.sds.organization.list`: List accessible organizations\n *\n * **Access Types**:\n * - `\"owner\"`: User created or owns the organization\n * - `\"collaborator\"`: User was invited with specific permissions\n *\n * @example\n * ```typescript\n * // Get SDS repository\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Create an organization\n * const org = await sdsRepo.organizations.create({\n * name: \"My Team\",\n * description: \"A team for impact projects\",\n * });\n *\n * // List organizations you have access to\n * const orgs = await sdsRepo.organizations.list();\n *\n * // Get specific organization\n * const orgInfo = await sdsRepo.organizations.get(org.did);\n * ```\n *\n * @internal\n */\nexport class OrganizationOperationsImpl implements OrganizationOperations {\n /**\n * Creates a new OrganizationOperationsImpl.\n *\n * @param session - Authenticated OAuth session with fetchHandler\n * @param _repoDid - DID of the user's repository (reserved for future use)\n * @param serverUrl - SDS server URL\n * @param _logger - Optional logger for debugging (reserved for future use)\n *\n * @internal\n */\n constructor(\n private session: Session,\n private _repoDid: string,\n private serverUrl: string,\n private _logger?: LoggerInterface,\n ) {}\n\n /**\n * Creates a new organization.\n *\n * @param params - Organization parameters\n * @param params.name - Display name for the organization\n * @param params.description - Optional description of the organization's purpose\n * @param params.handle - Optional custom handle. If not provided, one is auto-generated.\n * @returns Promise resolving to the created organization info\n * @throws {@link NetworkError} if organization creation fails\n *\n * @remarks\n * The creating user automatically becomes the owner with full permissions.\n *\n * **Handle Format**: Handles are typically formatted as\n * `{name}.sds.{domain}` (e.g., \"my-team.sds.hypercerts.org\").\n * If you provide a custom handle, it must be unique on the SDS.\n *\n * @example Basic organization\n * ```typescript\n * const org = await repo.organizations.create({\n * name: \"Climate Action Team\",\n * });\n * console.log(`Created org: ${org.did}`);\n * ```\n *\n * @example With description and custom handle\n * ```typescript\n * const org = await repo.organizations.create({\n * name: \"Reforestation Initiative\",\n * description: \"Coordinating tree planting projects worldwide\",\n * handle: \"reforestation\",\n * });\n * ```\n */\n async create(params: { name: string; description?: string; handle?: string }): Promise<OrganizationInfo> {\n const userDid = this.session.did || this.session.sub;\n if (!userDid) {\n throw new NetworkError(\"No authenticated user found\");\n }\n\n const response = await this.session.fetchHandler(`${this.serverUrl}/xrpc/com.sds.organization.create`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n ...params,\n creatorDid: userDid,\n }),\n });\n\n if (!response.ok) {\n throw new NetworkError(`Failed to create organization: ${response.statusText}`);\n }\n\n const data = await response.json();\n return {\n did: data.did,\n handle: data.handle,\n name: data.name,\n description: data.description,\n createdAt: data.createdAt || new Date().toISOString(),\n accessType: data.accessType || \"owner\",\n permissions: data.permissions || {\n read: true,\n create: true,\n update: true,\n delete: true,\n admin: true,\n owner: true,\n },\n };\n }\n\n /**\n * Gets an organization by its DID.\n *\n * @param did - The organization's DID\n * @returns Promise resolving to organization info, or `null` if not found\n *\n * @remarks\n * This method searches through the user's accessible organizations.\n * If the organization exists but the user doesn't have access,\n * it will return `null`.\n *\n * @example\n * ```typescript\n * const org = await repo.organizations.get(\"did:plc:org123\");\n * if (org) {\n * console.log(`Found: ${org.name}`);\n * console.log(`Your role: ${org.accessType}`);\n * } else {\n * console.log(\"Organization not found or no access\");\n * }\n * ```\n */\n async get(did: string): Promise<OrganizationInfo | null> {\n try {\n const { organizations } = await this.list();\n return organizations.find((o) => o.did === did) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Lists organizations the current user has access to.\n *\n * @param params - Optional pagination parameters\n * @param params.limit - Maximum number of results (1-100, default 50)\n * @param params.cursor - Pagination cursor from previous response\n * @returns Promise resolving to organizations and optional cursor\n * @throws {@link NetworkError} if the list operation fails\n *\n * @remarks\n * Returns organizations where the user is either:\n * - The owner\n * - A collaborator with any permission level\n *\n * The `accessType` field indicates the user's relationship to each organization.\n *\n * @example\n * ```typescript\n * // Get first page\n * const page1 = await repo.organizations.list({ limit: 20 });\n * console.log(`Found ${page1.organizations.length} organizations`);\n *\n * // Get next page if available\n * if (page1.cursor) {\n * const page2 = await repo.organizations.list({ limit: 20, cursor: page1.cursor });\n * }\n *\n * // Filter by access type\n * const owned = page1.organizations.filter(o => o.accessType === \"owner\");\n * const shared = page1.organizations.filter(o => o.accessType === \"shared\");\n * ```\n *\n * @example Display organization details\n * ```typescript\n * const { organizations } = await repo.organizations.list();\n *\n * for (const org of organizations) {\n * console.log(`${org.name} (@${org.handle})`);\n * console.log(` DID: ${org.did}`);\n * console.log(` Access: ${org.accessType}`);\n * if (org.description) {\n * console.log(` Description: ${org.description}`);\n * }\n * }\n * ```\n */\n async list(params?: { limit?: number; cursor?: string }): Promise<{\n organizations: OrganizationInfo[];\n cursor?: string;\n }> {\n const userDid = this.session.did || this.session.sub;\n if (!userDid) {\n throw new NetworkError(\"No authenticated user found\");\n }\n\n const queryParams = new URLSearchParams({\n userDid,\n });\n\n if (params?.limit !== undefined) {\n queryParams.set(\"limit\", params.limit.toString());\n }\n\n if (params?.cursor) {\n queryParams.set(\"cursor\", params.cursor);\n }\n\n const response = await this.session.fetchHandler(\n `${this.serverUrl}/xrpc/com.sds.organization.list?${queryParams.toString()}`,\n { method: \"GET\" },\n );\n\n if (!response.ok) {\n throw new NetworkError(`Failed to list organizations: ${response.statusText}`);\n }\n\n const data = await response.json();\n const organizations = (data.organizations || []).map(\n (r: {\n did: string;\n handle: string;\n name: string;\n description?: string;\n createdAt?: string;\n accessType: \"owner\" | \"shared\" | \"none\";\n permissions: CollaboratorPermissions;\n }) => ({\n did: r.did,\n handle: r.handle,\n name: r.name,\n description: r.description,\n createdAt: r.createdAt || new Date().toISOString(),\n accessType: r.accessType,\n permissions: r.permissions,\n }),\n );\n\n return {\n organizations,\n cursor: data.cursor,\n };\n }\n}\n","/**\n * Repository - Unified fluent API for ATProto repository operations.\n *\n * This module provides the main interface for interacting with AT Protocol\n * data servers (PDS and SDS) through a consistent, fluent API.\n *\n * @packageDocumentation\n */\n\nimport { SDSRequiredError } from \"../core/errors.js\";\nimport type { LoggerInterface } from \"../core/interfaces.js\";\nimport type { Session } from \"../core/types.js\";\nimport { HYPERCERT_LEXICONS } from \"@hypercerts-org/lexicon\";\nimport { ConfigurableAgent } from \"../agent/ConfigurableAgent.js\";\nimport type { Agent } from \"@atproto/api\";\nimport type { LexiconRegistry } from \"./LexiconRegistry.js\";\n\n// Types\nexport type {\n RepositoryOptions,\n CreateResult,\n UpdateResult,\n PaginatedList,\n ListParams,\n RepositoryRole,\n RepositoryAccessGrant,\n OrganizationInfo,\n ProgressStep,\n} from \"./types.js\";\n\n// Interfaces\nexport type {\n RecordOperations,\n BlobOperations,\n ProfileOperations,\n HypercertOperations,\n HypercertEvents,\n CollaboratorOperations,\n OrganizationOperations,\n CreateHypercertParams,\n CreateHypercertResult,\n} from \"./interfaces.js\";\n\n// Implementations\nimport { RecordOperationsImpl } from \"./RecordOperationsImpl.js\";\nimport { BlobOperationsImpl } from \"./BlobOperationsImpl.js\";\nimport { ProfileOperationsImpl } from \"./ProfileOperationsImpl.js\";\nimport { HypercertOperationsImpl } from \"./HypercertOperationsImpl.js\";\nimport { CollaboratorOperationsImpl } from \"./CollaboratorOperationsImpl.js\";\nimport { OrganizationOperationsImpl } from \"./OrganizationOperationsImpl.js\";\n\nimport type {\n RecordOperations,\n BlobOperations,\n ProfileOperations,\n HypercertOperations,\n CollaboratorOperations,\n OrganizationOperations,\n} from \"./interfaces.js\";\n\n/**\n * Repository provides a fluent API for AT Protocol data operations.\n *\n * This class is the primary interface for working with data in the AT Protocol\n * ecosystem. It provides organized access to:\n *\n * - **Records**: Low-level CRUD operations for any AT Protocol record type\n * - **Blobs**: Binary data upload and retrieval (images, files)\n * - **Profile**: User profile management\n * - **Hypercerts**: High-level hypercert creation and management\n * - **Collaborators**: Access control for shared repositories (SDS only)\n * - **Organizations**: Organization management (SDS only)\n *\n * @remarks\n * The Repository uses lazy initialization for operation handlers - they are\n * created only when first accessed. This improves performance when you only\n * need a subset of operations.\n *\n * **PDS vs SDS:**\n * - **PDS (Personal Data Server)**: User's own data storage. All operations\n * except collaborators and organizations are available.\n * - **SDS (Shared Data Server)**: Collaborative data storage with access\n * control. All operations including collaborators and organizations.\n *\n * @example Basic usage\n * ```typescript\n * // Get a repository from the SDK\n * const repo = sdk.repository(session);\n *\n * // Access user profile\n * const profile = await repo.profile.get();\n *\n * // Create a hypercert\n * const result = await repo.hypercerts.create({\n * title: \"My Impact\",\n * description: \"Description of the impact\",\n * workScope: \"Climate Action\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-12-31\",\n * rights: {\n * name: \"Attribution\",\n * type: \"license\",\n * description: \"CC-BY-4.0\",\n * },\n * });\n * ```\n *\n * @example Working with a different user's repository\n * ```typescript\n * // Get the current user's repo\n * const myRepo = sdk.repository(session);\n *\n * // Get another user's repo (read-only for most operations)\n * const otherRepo = myRepo.repo(\"did:plc:other-user-did\");\n * const theirProfile = await otherRepo.profile.get();\n * ```\n *\n * @example SDS operations\n * ```typescript\n * // Get SDS repository for collaborator features\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Manage collaborators\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:collaborator\",\n * role: \"editor\",\n * });\n *\n * // List organizations\n * const orgs = await sdsRepo.organizations.list();\n * ```\n *\n * @see {@link ATProtoSDK.repository} for creating Repository instances\n */\nexport class Repository {\n private session: Session;\n private serverUrl: string;\n private repoDid: string;\n private lexiconRegistry: LexiconRegistry;\n private logger?: LoggerInterface;\n private agent: Agent;\n private _isSDS: boolean;\n\n // Lazily initialized operations\n private _records?: RecordOperationsImpl;\n private _blobs?: BlobOperationsImpl;\n private _profile?: ProfileOperationsImpl;\n private _hypercerts?: HypercertOperationsImpl;\n private _collaborators?: CollaboratorOperationsImpl;\n private _organizations?: OrganizationOperationsImpl;\n\n /**\n * Creates a new Repository instance.\n *\n * @param session - Authenticated OAuth session\n * @param serverUrl - Base URL of the AT Protocol server\n * @param repoDid - DID of the repository to operate on\n * @param lexiconRegistry - Registry for lexicon validation\n * @param isSDS - Whether this is a Shared Data Server\n * @param logger - Optional logger for debugging\n *\n * @remarks\n * This constructor is typically not called directly. Use\n * {@link ATProtoSDK.repository} to create Repository instances.\n *\n * @internal\n */\n constructor(\n session: Session,\n serverUrl: string,\n repoDid: string,\n lexiconRegistry: LexiconRegistry,\n isSDS: boolean,\n logger?: LoggerInterface,\n ) {\n this.session = session;\n this.serverUrl = serverUrl;\n this.repoDid = repoDid;\n this.lexiconRegistry = lexiconRegistry;\n this._isSDS = isSDS;\n this.logger = logger;\n\n // Create a ConfigurableAgent that routes requests to the specified server URL\n // This allows routing to PDS, SDS, or any custom server while maintaining\n // the OAuth session's authentication\n this.agent = new ConfigurableAgent(session, serverUrl);\n\n this.lexiconRegistry.addToAgent(this.agent);\n\n // Register hypercert lexicons\n this.lexiconRegistry.registerMany(HYPERCERT_LEXICONS);\n }\n\n /**\n * The DID (Decentralized Identifier) of this repository.\n *\n * This is the user or organization that owns the repository data.\n *\n * @example\n * ```typescript\n * console.log(`Working with repo: ${repo.did}`);\n * // Output: Working with repo: did:plc:abc123xyz...\n * ```\n */\n get did(): string {\n return this.repoDid;\n }\n\n /**\n * Whether this repository is on a Shared Data Server (SDS).\n *\n * SDS servers support additional features like collaborators and\n * organizations. Attempting to use these features on a PDS will\n * throw {@link SDSRequiredError}.\n *\n * @example\n * ```typescript\n * if (repo.isSDS) {\n * const collaborators = await repo.collaborators.list();\n * }\n * ```\n */\n get isSDS(): boolean {\n return this._isSDS;\n }\n\n /**\n * Gets the server URL this repository connects to.\n *\n * @returns The base URL of the AT Protocol server\n *\n * @example\n * ```typescript\n * console.log(repo.getServerUrl());\n * // Output: https://bsky.social or https://sds.hypercerts.org\n * ```\n */\n getServerUrl(): string {\n return this.serverUrl;\n }\n\n /**\n * Creates a Repository instance for a different DID on the same server.\n *\n * This allows you to read data from other users' repositories while\n * maintaining your authenticated session.\n *\n * @param did - The DID of the repository to access\n * @returns A new Repository instance for the specified DID\n *\n * @remarks\n * Write operations on another user's repository will typically fail\n * unless you have been granted collaborator access (SDS only).\n *\n * @example\n * ```typescript\n * // Read another user's profile\n * const otherRepo = repo.repo(\"did:plc:other-user\");\n * const profile = await otherRepo.profile.get();\n *\n * // List their public hypercerts\n * const hypercerts = await otherRepo.hypercerts.list();\n * ```\n */\n repo(did: string): Repository {\n return new Repository(this.session, this.serverUrl, did, this.lexiconRegistry, this._isSDS, this.logger);\n }\n\n /**\n * Low-level record operations for CRUD on any AT Protocol record type.\n *\n * Use this for direct access to AT Protocol records when the high-level\n * APIs don't meet your needs.\n *\n * @returns {@link RecordOperations} interface for record CRUD\n *\n * @example\n * ```typescript\n * // Create a custom record\n * const result = await repo.records.create({\n * collection: \"org.example.myRecord\",\n * record: { foo: \"bar\" },\n * });\n *\n * // List records in a collection\n * const list = await repo.records.list({\n * collection: \"org.example.myRecord\",\n * limit: 50,\n * });\n *\n * // Get a specific record\n * const record = await repo.records.get({\n * collection: \"org.example.myRecord\",\n * rkey: \"abc123\",\n * });\n * ```\n */\n get records(): RecordOperations {\n if (!this._records) {\n this._records = new RecordOperationsImpl(this.agent, this.repoDid, this.lexiconRegistry);\n }\n return this._records;\n }\n\n /**\n * Blob operations for uploading and retrieving binary data.\n *\n * Blobs are used for images, files, and other binary content associated\n * with records.\n *\n * @returns {@link BlobOperations} interface for blob management\n *\n * @example\n * ```typescript\n * // Upload an image\n * const imageBlob = new Blob([imageData], { type: \"image/png\" });\n * const uploadResult = await repo.blobs.upload(imageBlob);\n *\n * // The ref can be used in records\n * console.log(uploadResult.ref.$link); // CID of the blob\n *\n * // Retrieve a blob by CID\n * const { data, mimeType } = await repo.blobs.get(cid);\n * ```\n */\n get blobs(): BlobOperations {\n if (!this._blobs) {\n this._blobs = new BlobOperationsImpl(this.agent, this.repoDid, this.serverUrl);\n }\n return this._blobs;\n }\n\n /**\n * Profile operations for managing user profiles.\n *\n * @returns {@link ProfileOperations} interface for profile management\n *\n * @example\n * ```typescript\n * // Get current profile\n * const profile = await repo.profile.get();\n * console.log(profile.displayName);\n *\n * // Update profile\n * await repo.profile.update({\n * displayName: \"New Name\",\n * description: \"Updated bio\",\n * avatar: avatarBlob, // Optional: update avatar image\n * });\n * ```\n */\n get profile(): ProfileOperations {\n if (!this._profile) {\n this._profile = new ProfileOperationsImpl(this.agent, this.repoDid, this.serverUrl);\n }\n return this._profile;\n }\n\n /**\n * High-level hypercert operations.\n *\n * Provides a convenient API for creating and managing hypercerts,\n * including related records like locations, contributions, and evidence.\n *\n * @returns {@link HypercertOperations} interface with EventEmitter capabilities\n *\n * @example Creating a hypercert\n * ```typescript\n * const result = await repo.hypercerts.create({\n * title: \"Climate Action Project\",\n * description: \"Reduced carbon emissions by 1000 tons\",\n * workScope: \"Climate Action\",\n * workTimeframeFrom: \"2024-01-01\",\n * workTimeframeTo: \"2024-06-30\",\n * rights: {\n * name: \"Public Domain\",\n * type: \"license\",\n * description: \"CC0 - No Rights Reserved\",\n * },\n * image: imageBlob, // Optional cover image\n * location: {\n * value: \"San Francisco, CA\",\n * name: \"SF Bay Area\",\n * },\n * });\n * console.log(`Created: ${result.hypercertUri}`);\n * ```\n *\n * @example Listening to events\n * ```typescript\n * repo.hypercerts.on(\"recordCreated\", ({ uri, cid }) => {\n * console.log(`Record created: ${uri}`);\n * });\n * ```\n */\n get hypercerts(): HypercertOperations {\n if (!this._hypercerts) {\n this._hypercerts = new HypercertOperationsImpl(\n this.agent,\n this.repoDid,\n this.serverUrl,\n this.lexiconRegistry,\n this.logger,\n );\n }\n return this._hypercerts;\n }\n\n /**\n * Collaborator operations for managing repository access.\n *\n * **SDS Only**: This property throws {@link SDSRequiredError} if accessed\n * on a PDS repository.\n *\n * @returns {@link CollaboratorOperations} interface for access control\n * @throws {@link SDSRequiredError} if not connected to an SDS server\n *\n * @example\n * ```typescript\n * // Ensure we're on SDS\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Grant editor access\n * await sdsRepo.collaborators.grant({\n * userDid: \"did:plc:new-collaborator\",\n * role: \"editor\",\n * });\n *\n * // List all collaborators\n * const collaborators = await sdsRepo.collaborators.list();\n *\n * // Check access\n * const hasAccess = await sdsRepo.collaborators.hasAccess(\"did:plc:someone\");\n *\n * // Revoke access\n * await sdsRepo.collaborators.revoke({ userDid: \"did:plc:former-collaborator\" });\n * ```\n */\n get collaborators(): CollaboratorOperations {\n if (!this._isSDS) {\n throw new SDSRequiredError(\"Collaborator operations are only available on SDS servers\");\n }\n if (!this._collaborators) {\n this._collaborators = new CollaboratorOperationsImpl(this.session, this.repoDid, this.serverUrl);\n }\n return this._collaborators;\n }\n\n /**\n * Organization operations for creating and managing organizations.\n *\n * **SDS Only**: This property throws {@link SDSRequiredError} if accessed\n * on a PDS repository.\n *\n * @returns {@link OrganizationOperations} interface for organization management\n * @throws {@link SDSRequiredError} if not connected to an SDS server\n *\n * @example\n * ```typescript\n * // Ensure we're on SDS\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n *\n * // Create an organization\n * const org = await sdsRepo.organizations.create({\n * name: \"My Organization\",\n * description: \"A team working on impact certificates\",\n * handle: \"my-org\", // Optional custom handle\n * });\n *\n * // List organizations you have access to\n * const orgs = await sdsRepo.organizations.list();\n *\n * // Get specific organization\n * const orgInfo = await sdsRepo.organizations.get(org.did);\n * ```\n */\n get organizations(): OrganizationOperations {\n if (!this._isSDS) {\n throw new SDSRequiredError(\"Organization operations are only available on SDS servers\");\n }\n if (!this._organizations) {\n this._organizations = new OrganizationOperationsImpl(this.session, this.repoDid, this.serverUrl, this.logger);\n }\n return this._organizations;\n }\n}\n","import { z } from \"zod\";\nimport type { SessionStore, StateStore, CacheInterface, LoggerInterface } from \"./interfaces.js\";\n\n/**\n * Zod schema for OAuth configuration validation.\n *\n * @remarks\n * All URLs must be valid and use HTTPS in production. The `jwkPrivate` field\n * should contain the private key in JWK (JSON Web Key) format as a string.\n */\nexport const OAuthConfigSchema = z.object({\n /**\n * URL to the OAuth client metadata JSON document.\n * This document describes your application to the authorization server.\n *\n * @see https://atproto.com/specs/oauth#client-metadata\n */\n clientId: z.string().url(),\n\n /**\n * URL where users are redirected after authentication.\n * Must match one of the redirect URIs in your client metadata.\n */\n redirectUri: z.string().url(),\n\n /**\n * OAuth scopes to request, space-separated.\n * Common scopes: \"atproto\", \"transition:generic\"\n */\n scope: z.string(),\n\n /**\n * URL to your public JWKS (JSON Web Key Set) endpoint.\n * Used by the authorization server to verify your client's signatures.\n */\n jwksUri: z.string().url(),\n\n /**\n * Private JWK (JSON Web Key) as a JSON string.\n * Used for signing DPoP proofs and client assertions.\n *\n * @remarks\n * This should be kept secret and never exposed to clients.\n * Typically loaded from environment variables or a secrets manager.\n */\n jwkPrivate: z.string(),\n});\n\n/**\n * Zod schema for server URL configuration.\n *\n * @remarks\n * At least one server (PDS or SDS) should be configured for the SDK to be useful.\n */\nexport const ServerConfigSchema = z.object({\n /**\n * Personal Data Server URL - the user's own AT Protocol server.\n * This is the primary server for user data operations.\n *\n * @example \"https://bsky.social\"\n */\n pds: z.string().url().optional(),\n\n /**\n * Shared Data Server URL - for collaborative data storage.\n * Required for collaborator and organization operations.\n *\n * @example \"https://sds.hypercerts.org\"\n */\n sds: z.string().url().optional(),\n});\n\n/**\n * Zod schema for timeout configuration.\n *\n * @remarks\n * All timeout values are in milliseconds.\n */\nexport const TimeoutConfigSchema = z.object({\n /**\n * Timeout for fetching PDS metadata during identity resolution.\n * @default 5000 (5 seconds, set by OAuthClient)\n */\n pdsMetadata: z.number().positive().optional(),\n\n /**\n * Timeout for general API requests to PDS/SDS.\n * @default 30000 (30 seconds)\n */\n apiRequests: z.number().positive().optional(),\n});\n\n/**\n * Zod schema for SDK configuration validation.\n *\n * @remarks\n * This schema validates only the primitive/serializable parts of the configuration.\n * Storage interfaces ({@link SessionStore}, {@link StateStore}) cannot be validated\n * with Zod as they are runtime objects.\n */\nexport const ATProtoSDKConfigSchema = z.object({\n oauth: OAuthConfigSchema,\n servers: ServerConfigSchema.optional(),\n timeouts: TimeoutConfigSchema.optional(),\n});\n\n/**\n * Configuration options for the ATProto SDK.\n *\n * This interface defines all configuration needed to initialize the SDK,\n * including OAuth credentials, server endpoints, and optional customizations.\n *\n * @example Minimal configuration\n * ```typescript\n * const config: ATProtoSDKConfig = {\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: {\n * pds: \"https://bsky.social\",\n * },\n * };\n * ```\n *\n * @example Full configuration with custom storage\n * ```typescript\n * const config: ATProtoSDKConfig = {\n * oauth: { ... },\n * servers: {\n * pds: \"https://bsky.social\",\n * sds: \"https://sds.hypercerts.org\",\n * },\n * storage: {\n * sessionStore: new RedisSessionStore(redisClient),\n * stateStore: new RedisStateStore(redisClient),\n * },\n * timeouts: {\n * pdsMetadata: 5000,\n * apiRequests: 30000,\n * },\n * logger: console,\n * };\n * ```\n */\nexport interface ATProtoSDKConfig {\n /**\n * OAuth 2.0 configuration for authentication.\n *\n * Required fields for the OAuth flow with DPoP (Demonstrating Proof of Possession).\n * Your application must host the client metadata and JWKS endpoints.\n *\n * @see https://atproto.com/specs/oauth for AT Protocol OAuth specification\n */\n oauth: z.infer<typeof OAuthConfigSchema>;\n\n /**\n * Server URLs for PDS and SDS connections.\n *\n * - **PDS**: Personal Data Server - user's own data storage\n * - **SDS**: Shared Data Server - collaborative storage with access control\n */\n servers?: z.infer<typeof ServerConfigSchema>;\n\n /**\n * Storage adapters for persisting OAuth sessions and state.\n *\n * If not provided, in-memory implementations are used automatically.\n * **Warning**: In-memory storage is lost on process restart - use persistent\n * storage (Redis, database, etc.) in production.\n *\n * @example\n * ```typescript\n * storage: {\n * sessionStore: new RedisSessionStore(redis),\n * stateStore: new RedisStateStore(redis),\n * }\n * ```\n */\n storage?: {\n /**\n * Persistent storage for OAuth sessions.\n * Sessions contain access tokens, refresh tokens, and DPoP keys.\n */\n sessionStore?: SessionStore;\n\n /**\n * Temporary storage for OAuth state during the authorization flow.\n * State is short-lived and used for PKCE and CSRF protection.\n */\n stateStore?: StateStore;\n };\n\n /**\n * Custom fetch implementation for HTTP requests.\n *\n * Use this to add custom headers, logging, or to use a different HTTP client.\n * Must be compatible with the standard Fetch API.\n *\n * @example\n * ```typescript\n * fetch: async (url, init) => {\n * console.log(`Fetching: ${url}`);\n * return globalThis.fetch(url, init);\n * }\n * ```\n */\n fetch?: typeof fetch;\n\n /**\n * Timeout configuration for network requests.\n * Values are in milliseconds.\n */\n timeouts?: z.infer<typeof TimeoutConfigSchema>;\n\n /**\n * Cache for profiles, metadata, and other frequently accessed data.\n *\n * Implementing caching can significantly reduce API calls and improve performance.\n * The SDK does not provide a default cache - you must implement {@link CacheInterface}.\n */\n cache?: CacheInterface;\n\n /**\n * Logger for debugging and observability.\n *\n * The logger receives debug, info, warn, and error messages from the SDK.\n * Compatible with `console` or any logger implementing {@link LoggerInterface}.\n *\n * @example\n * ```typescript\n * logger: console\n * // or\n * logger: pino()\n * // or\n * logger: winston.createLogger({ ... })\n * ```\n */\n logger?: LoggerInterface;\n}\n","import { OAuthClient } from \"../auth/OAuthClient.js\";\nimport { LexiconRegistry } from \"../repository/LexiconRegistry.js\";\nimport { Repository } from \"../repository/Repository.js\";\nimport type { RepositoryOptions } from \"../repository/types.js\";\nimport { InMemorySessionStore } from \"../storage/InMemorySessionStore.js\";\nimport { InMemoryStateStore } from \"../storage/InMemoryStateStore.js\";\nimport type { ATProtoSDKConfig } from \"./config.js\";\nimport { ATProtoSDKConfigSchema } from \"./config.js\";\nimport { ValidationError } from \"./errors.js\";\nimport type { Session } from \"./types.js\";\n\n/**\n * Options for the OAuth authorization flow.\n */\nexport interface AuthorizeOptions {\n /**\n * OAuth scope string to request specific permissions.\n * Overrides the default scope configured in {@link ATProtoSDKConfig.oauth.scope}.\n *\n * @example\n * ```typescript\n * // Request read-only access\n * await sdk.authorize(\"user.bsky.social\", { scope: \"atproto\" });\n *\n * // Request full access (default typically includes transition:generic)\n * await sdk.authorize(\"user.bsky.social\", { scope: \"atproto transition:generic\" });\n * ```\n */\n scope?: string;\n}\n\n/**\n * Main ATProto SDK class providing OAuth authentication and repository access.\n *\n * This is the primary entry point for interacting with AT Protocol servers.\n * It handles the OAuth 2.0 flow with DPoP (Demonstrating Proof of Possession)\n * and provides access to repository operations for managing records, blobs,\n * and profiles.\n *\n * @example Basic usage with OAuth flow\n * ```typescript\n * import { ATProtoSDK, InMemorySessionStore, InMemoryStateStore } from \"@hypercerts-org/sdk\";\n *\n * const sdk = new ATProtoSDK({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto transition:generic\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: process.env.JWK_PRIVATE_KEY!,\n * },\n * servers: {\n * pds: \"https://bsky.social\",\n * sds: \"https://sds.hypercerts.org\",\n * },\n * });\n *\n * // Start OAuth flow - redirect user to this URL\n * const authUrl = await sdk.authorize(\"user.bsky.social\");\n *\n * // After user returns, handle the callback\n * const session = await sdk.callback(new URLSearchParams(window.location.search));\n *\n * // Get a repository to work with data\n * const repo = sdk.repository(session);\n * ```\n *\n * @example Restoring an existing session\n * ```typescript\n * // Restore a previous session by DID\n * const session = await sdk.restoreSession(\"did:plc:abc123...\");\n * if (session) {\n * const repo = sdk.repository(session);\n * // Continue working with the restored session\n * }\n * ```\n *\n * @see {@link ATProtoSDKConfig} for configuration options\n * @see {@link Repository} for data operations\n * @see {@link OAuthClient} for OAuth implementation details\n */\nexport class ATProtoSDK {\n private oauthClient: OAuthClient;\n private config: ATProtoSDKConfig;\n private logger?: ATProtoSDKConfig[\"logger\"];\n private lexiconRegistry: LexiconRegistry;\n\n /**\n * Creates a new ATProto SDK instance.\n *\n * @param config - SDK configuration including OAuth credentials, server URLs, and optional storage adapters\n * @throws {@link ValidationError} if the configuration is invalid (e.g., malformed URLs, missing required fields)\n *\n * @remarks\n * If no storage adapters are provided, in-memory implementations are used.\n * These are suitable for development and testing but **not recommended for production**\n * as sessions will be lost on restart.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses in-memory storage)\n * const sdk = new ATProtoSDK({\n * oauth: {\n * clientId: \"https://my-app.com/client-metadata.json\",\n * redirectUri: \"https://my-app.com/callback\",\n * scope: \"atproto\",\n * jwksUri: \"https://my-app.com/.well-known/jwks.json\",\n * jwkPrivate: privateKeyJwk,\n * },\n * servers: { pds: \"https://bsky.social\" },\n * });\n * ```\n */\n constructor(config: ATProtoSDKConfig) {\n // Validate configuration\n const validationResult = ATProtoSDKConfigSchema.safeParse(config);\n if (!validationResult.success) {\n throw new ValidationError(`Invalid SDK configuration: ${validationResult.error.message}`, validationResult.error);\n }\n\n // Apply defaults for optional storage\n const configWithDefaults: ATProtoSDKConfig = {\n ...config,\n storage: {\n sessionStore: config.storage?.sessionStore ?? new InMemorySessionStore(),\n stateStore: config.storage?.stateStore ?? new InMemoryStateStore(),\n },\n };\n\n this.config = configWithDefaults;\n this.logger = config.logger;\n\n // Initialize OAuth client\n this.oauthClient = new OAuthClient(configWithDefaults);\n\n // Initialize lexicon registry\n this.lexiconRegistry = new LexiconRegistry();\n\n this.logger?.info(\"ATProto SDK initialized\");\n }\n\n /**\n * Initiates the OAuth authorization flow.\n *\n * This method starts the OAuth 2.0 authorization flow by resolving the user's\n * identity and generating an authorization URL. The user should be redirected\n * to this URL to authenticate.\n *\n * @param identifier - The user's ATProto identifier. Can be:\n * - A handle (e.g., `\"user.bsky.social\"`)\n * - A DID (e.g., `\"did:plc:abc123...\"`)\n * - A PDS URL (e.g., `\"https://bsky.social\"`)\n * @param options - Optional authorization settings\n * @returns A Promise resolving to the authorization URL to redirect the user to\n * @throws {@link ValidationError} if the identifier is empty or invalid\n * @throws {@link NetworkError} if the identity cannot be resolved\n *\n * @example\n * ```typescript\n * // Using a handle\n * const authUrl = await sdk.authorize(\"alice.bsky.social\");\n *\n * // Using a DID directly\n * const authUrl = await sdk.authorize(\"did:plc:abc123xyz\");\n *\n * // With custom scope\n * const authUrl = await sdk.authorize(\"alice.bsky.social\", {\n * scope: \"atproto transition:generic\"\n * });\n *\n * // Redirect user to authUrl\n * window.location.href = authUrl;\n * ```\n */\n async authorize(identifier: string, options?: AuthorizeOptions): Promise<string> {\n if (!identifier || !identifier.trim()) {\n throw new ValidationError(\"ATProto identifier is required\");\n }\n\n return this.oauthClient.authorize(identifier.trim(), options);\n }\n\n /**\n * Handles the OAuth callback and exchanges the authorization code for tokens.\n *\n * Call this method when the user is redirected back to your application\n * after authenticating. It validates the OAuth state, exchanges the\n * authorization code for access/refresh tokens, and creates a session.\n *\n * @param params - URL search parameters from the callback URL\n * @returns A Promise resolving to the authenticated OAuth session\n * @throws {@link AuthenticationError} if the callback parameters are invalid or the code exchange fails\n * @throws {@link ValidationError} if required parameters are missing\n *\n * @example\n * ```typescript\n * // In your callback route handler\n * const params = new URLSearchParams(window.location.search);\n * // params contains: code, state, iss (issuer)\n *\n * const session = await sdk.callback(params);\n * console.log(`Authenticated as ${session.did}`);\n *\n * // Store the DID to restore the session later\n * localStorage.setItem(\"userDid\", session.did);\n * ```\n */\n async callback(params: URLSearchParams): Promise<Session> {\n return this.oauthClient.callback(params);\n }\n\n /**\n * Restores an existing OAuth session by DID.\n *\n * Use this method to restore a previously authenticated session, typically\n * on application startup. The method retrieves the stored session and\n * automatically refreshes expired tokens if needed.\n *\n * @param did - The user's Decentralized Identifier (DID), e.g., `\"did:plc:abc123...\"`\n * @returns A Promise resolving to the restored session, or `null` if no session exists\n * @throws {@link ValidationError} if the DID is empty\n * @throws {@link SessionExpiredError} if the session cannot be refreshed\n *\n * @example\n * ```typescript\n * // On application startup\n * const savedDid = localStorage.getItem(\"userDid\");\n * if (savedDid) {\n * const session = await sdk.restoreSession(savedDid);\n * if (session) {\n * // User is still authenticated\n * const repo = sdk.repository(session);\n * } else {\n * // Session not found, user needs to re-authenticate\n * const authUrl = await sdk.authorize(savedDid);\n * }\n * }\n * ```\n */\n async restoreSession(did: string): Promise<Session | null> {\n if (!did || !did.trim()) {\n throw new ValidationError(\"DID is required\");\n }\n\n return this.oauthClient.restore(did.trim());\n }\n\n /**\n * Revokes an OAuth session, logging the user out.\n *\n * This method invalidates the session's tokens and removes it from storage.\n * After revocation, the session can no longer be used or restored.\n *\n * @param did - The user's DID to revoke the session for\n * @throws {@link ValidationError} if the DID is empty\n *\n * @example\n * ```typescript\n * // Log out the user\n * await sdk.revokeSession(session.did);\n * localStorage.removeItem(\"userDid\");\n * ```\n */\n async revokeSession(did: string): Promise<void> {\n if (!did || !did.trim()) {\n throw new ValidationError(\"DID is required\");\n }\n\n return this.oauthClient.revoke(did.trim());\n }\n\n /**\n * Creates a repository instance for data operations.\n *\n * The repository provides a fluent API for working with AT Protocol data\n * including records, blobs, profiles, and domain-specific operations like\n * hypercerts and collaborators.\n *\n * @param session - An authenticated OAuth session\n * @param options - Repository configuration options\n * @returns A {@link Repository} instance configured for the specified server\n * @throws {@link ValidationError} if the session is invalid or server URL is not configured\n *\n * @remarks\n * - **PDS (Personal Data Server)**: User's own data storage, default for most operations\n * - **SDS (Shared Data Server)**: Shared data storage with collaborator support\n *\n * @example Using default PDS\n * ```typescript\n * const repo = sdk.repository(session);\n * const profile = await repo.profile.get();\n * ```\n *\n * @example Using configured SDS\n * ```typescript\n * const sdsRepo = sdk.repository(session, { server: \"sds\" });\n * const collaborators = await sdsRepo.collaborators.list();\n * ```\n *\n * @example Using custom server URL\n * ```typescript\n * const customRepo = sdk.repository(session, {\n * serverUrl: \"https://custom.atproto.server\"\n * });\n * ```\n */\n repository(session: Session, options?: RepositoryOptions): Repository {\n if (!session) {\n throw new ValidationError(\"Session is required\");\n }\n\n // Determine server URL\n let serverUrl: string;\n let isSDS = false;\n\n if (options?.serverUrl) {\n // Custom URL provided\n serverUrl = options.serverUrl;\n // Check if it matches configured SDS\n isSDS = this.config.servers?.sds === serverUrl;\n } else if (options?.server === \"sds\") {\n // Use configured SDS\n if (!this.config.servers?.sds) {\n throw new ValidationError(\"SDS server URL not configured\");\n }\n serverUrl = this.config.servers.sds;\n isSDS = true;\n } else if (options?.server === \"pds\" || !options?.server) {\n // Use configured PDS (default)\n if (!this.config.servers?.pds) {\n throw new ValidationError(\"PDS server URL not configured\");\n }\n serverUrl = this.config.servers.pds;\n isSDS = false;\n } else {\n // Custom server string (treat as URL)\n serverUrl = options.server;\n isSDS = this.config.servers?.sds === serverUrl;\n }\n\n // Get repository DID (default to session DID)\n const repoDid = session.did || session.sub;\n\n return new Repository(session, serverUrl, repoDid, this.lexiconRegistry, isSDS, this.logger);\n }\n\n /**\n * Gets the lexicon registry for schema validation.\n *\n * The lexicon registry manages AT Protocol lexicon schemas used for\n * validating record data. You can register custom lexicons to extend\n * the SDK's capabilities.\n *\n * @returns The {@link LexiconRegistry} instance\n *\n * @example\n * ```typescript\n * const registry = sdk.getLexiconRegistry();\n *\n * // Register custom lexicons\n * registry.register(myCustomLexicons);\n *\n * // Check if a lexicon is registered\n * const hasLexicon = registry.has(\"org.example.myRecord\");\n * ```\n */\n getLexiconRegistry(): LexiconRegistry {\n return this.lexiconRegistry;\n }\n\n /**\n * The configured PDS (Personal Data Server) URL.\n *\n * @returns The PDS URL if configured, otherwise `undefined`\n */\n get pdsUrl(): string | undefined {\n return this.config.servers?.pds;\n }\n\n /**\n * The configured SDS (Shared Data Server) URL.\n *\n * @returns The SDS URL if configured, otherwise `undefined`\n */\n get sdsUrl(): string | undefined {\n return this.config.servers?.sds;\n }\n}\n\n/**\n * Factory function to create an ATProto SDK instance.\n *\n * This is a convenience function equivalent to `new ATProtoSDK(config)`.\n *\n * @param config - SDK configuration\n * @returns A new {@link ATProtoSDK} instance\n *\n * @example\n * ```typescript\n * import { createATProtoSDK } from \"@hypercerts-org/sdk\";\n *\n * const sdk = createATProtoSDK({\n * oauth: { ... },\n * servers: { pds: \"https://bsky.social\" },\n * });\n * ```\n */\nexport function createATProtoSDK(config: ATProtoSDKConfig): ATProtoSDK {\n return new ATProtoSDK(config);\n}\n","import type { OAuthSession } from \"@atproto/oauth-client-node\";\nimport { z } from \"zod\";\n\n/**\n * Decentralized Identifier (DID) - a unique, persistent identifier for AT Protocol users.\n *\n * DIDs are the canonical identifier for users in the AT Protocol ecosystem.\n * Unlike handles which can change, DIDs remain constant for the lifetime of an account.\n *\n * @remarks\n * AT Protocol supports multiple DID methods:\n * - `did:plc:` - PLC (Public Ledger of Credentials) DIDs, most common for Bluesky users\n * - `did:web:` - Web DIDs, resolved via HTTPS\n *\n * @example\n * ```typescript\n * const did: DID = \"did:plc:ewvi7nxzyoun6zhxrhs64oiz\";\n * const webDid: DID = \"did:web:example.com\";\n * ```\n *\n * @see https://atproto.com/specs/did for DID specification\n */\nexport type DID = string;\n\n/**\n * OAuth session with DPoP (Demonstrating Proof of Possession) support.\n *\n * This type represents an authenticated user session. It wraps the\n * `@atproto/oauth-client-node` OAuthSession and contains:\n * - Access token for API requests\n * - Refresh token for obtaining new access tokens\n * - DPoP key pair for proof-of-possession\n * - User's DID and other identity information\n *\n * @remarks\n * Sessions are managed by the SDK and automatically refresh when tokens expire.\n * Store the user's DID to restore sessions later with {@link ATProtoSDK.restoreSession}.\n *\n * Key properties from OAuthSession:\n * - `did` or `sub`: The user's DID\n * - `handle`: The user's handle (e.g., \"user.bsky.social\")\n *\n * @example\n * ```typescript\n * const session = await sdk.callback(params);\n *\n * // Access user identity\n * console.log(`Logged in as: ${session.did}`);\n *\n * // Use session for repository operations\n * const repo = sdk.repository(session);\n * ```\n *\n * @see https://atproto.com/specs/oauth for OAuth specification\n */\nexport type Session = OAuthSession;\n\n/**\n * Zod schema for collaborator permissions in SDS repositories.\n *\n * Defines the granular permissions a collaborator can have on a shared repository.\n * Permissions follow a hierarchical model where higher-level permissions\n * typically imply lower-level ones.\n */\nexport const CollaboratorPermissionsSchema = z.object({\n /**\n * Can read/view records in the repository.\n * This is the most basic permission level.\n */\n read: z.boolean(),\n\n /**\n * Can create new records in the repository.\n * Typically implies `read` permission.\n */\n create: z.boolean(),\n\n /**\n * Can modify existing records in the repository.\n * Typically implies `read` and `create` permissions.\n */\n update: z.boolean(),\n\n /**\n * Can delete records from the repository.\n * Typically implies `read`, `create`, and `update` permissions.\n */\n delete: z.boolean(),\n\n /**\n * Can manage collaborators and their permissions.\n * Administrative permission that allows inviting/removing collaborators.\n */\n admin: z.boolean(),\n\n /**\n * Full ownership of the repository.\n * Owners have all permissions and cannot be removed by other admins.\n * There must always be at least one owner.\n */\n owner: z.boolean(),\n});\n\n/**\n * Collaborator permissions for SDS (Shared Data Server) repositories.\n *\n * These permissions control what actions a collaborator can perform\n * on records within a shared repository.\n *\n * @example\n * ```typescript\n * // Read-only collaborator\n * const readOnlyPerms: CollaboratorPermissions = {\n * read: true,\n * create: false,\n * update: false,\n * delete: false,\n * admin: false,\n * owner: false,\n * };\n *\n * // Editor collaborator\n * const editorPerms: CollaboratorPermissions = {\n * read: true,\n * create: true,\n * update: true,\n * delete: false,\n * admin: false,\n * owner: false,\n * };\n *\n * // Admin collaborator\n * const adminPerms: CollaboratorPermissions = {\n * read: true,\n * create: true,\n * update: true,\n * delete: true,\n * admin: true,\n * owner: false,\n * };\n * ```\n */\nexport type CollaboratorPermissions = z.infer<typeof CollaboratorPermissionsSchema>;\n\n/**\n * Zod schema for SDS organization data.\n *\n * Organizations are top-level entities in SDS that can own repositories\n * and have multiple collaborators with different permission levels.\n */\nexport const OrganizationSchema = z.object({\n /**\n * The organization's DID - unique identifier.\n * Format: \"did:plc:...\" or \"did:web:...\"\n */\n did: z.string(),\n\n /**\n * The organization's handle - human-readable identifier.\n * Format: \"orgname.sds.hypercerts.org\" or similar\n */\n handle: z.string(),\n\n /**\n * Display name for the organization.\n */\n name: z.string(),\n\n /**\n * Optional description of the organization's purpose.\n */\n description: z.string().optional(),\n\n /**\n * ISO 8601 timestamp when the organization was created.\n * Format: \"2024-01-15T10:30:00.000Z\"\n */\n createdAt: z.string(),\n\n /**\n * The current user's permissions within this organization.\n */\n permissions: CollaboratorPermissionsSchema,\n\n /**\n * How the current user relates to this organization.\n * - `\"owner\"`: User created or owns the organization\n * - `\"shared\"`: User was invited to collaborate (has permissions)\n * - `\"none\"`: User has no access to this organization\n */\n accessType: z.enum([\"owner\", \"shared\", \"none\"]),\n});\n\n/**\n * SDS Organization entity.\n *\n * Represents an organization on a Shared Data Server. Organizations\n * provide a way to group repositories and manage access for teams.\n *\n * @example\n * ```typescript\n * const org: Organization = {\n * did: \"did:plc:org123abc\",\n * handle: \"my-team.sds.hypercerts.org\",\n * name: \"My Team\",\n * description: \"A team working on impact certificates\",\n * createdAt: \"2024-01-15T10:30:00.000Z\",\n * permissions: {\n * read: true,\n * create: true,\n * update: true,\n * delete: true,\n * admin: true,\n * owner: true,\n * },\n * accessType: \"owner\",\n * };\n * ```\n */\nexport type Organization = z.infer<typeof OrganizationSchema>;\n\n/**\n * Zod schema for collaborator data.\n *\n * Represents a user who has been granted access to a shared repository\n * or organization with specific permissions.\n */\nexport const CollaboratorSchema = z.object({\n /**\n * The collaborator's DID - their unique identifier.\n * Format: \"did:plc:...\" or \"did:web:...\"\n */\n userDid: z.string(),\n\n /**\n * The permissions granted to this collaborator.\n */\n permissions: CollaboratorPermissionsSchema,\n\n /**\n * DID of the user who granted these permissions.\n * Useful for audit trails.\n */\n grantedBy: z.string(),\n\n /**\n * ISO 8601 timestamp when permissions were granted.\n * Format: \"2024-01-15T10:30:00.000Z\"\n */\n grantedAt: z.string(),\n\n /**\n * ISO 8601 timestamp when permissions were revoked, if applicable.\n * Undefined if the collaborator is still active.\n */\n revokedAt: z.string().optional(),\n});\n\n/**\n * Collaborator information for SDS repositories.\n *\n * Represents a user who has been granted access to collaborate on\n * a shared repository or organization.\n *\n * @example\n * ```typescript\n * const collaborator: Collaborator = {\n * userDid: \"did:plc:user456def\",\n * permissions: {\n * read: true,\n * create: true,\n * update: true,\n * delete: false,\n * admin: false,\n * owner: false,\n * },\n * grantedBy: \"did:plc:owner123abc\",\n * grantedAt: \"2024-02-01T14:00:00.000Z\",\n * };\n * ```\n */\nexport type Collaborator = z.infer<typeof CollaboratorSchema>;\n"],"names":["JoseKey","NodeOAuthClient","Lexicons","Agent","EventEmitter","HYPERCERT_COLLECTIONS","HYPERCERT_LEXICONS","z"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCG;AACG,MAAO,eAAgB,SAAQ,KAAK,CAAA;AACxC;;;;;;;AAOG;AACH,IAAA,WAAA,CACE,OAAe,EACR,IAAY,EACZ,MAAe,EACf,KAAe,EAAA;QAEtB,KAAK,CAAC,OAAO,CAAC;QAJP,IAAA,CAAA,IAAI,GAAJ,IAAI;QACJ,IAAA,CAAA,MAAM,GAAN,MAAM;QACN,IAAA,CAAA,KAAK,GAAL,KAAK;AAGZ,QAAA,IAAI,CAAC,IAAI,GAAG,iBAAiB;QAC7B,KAAK,CAAC,iBAAiB,GAAG,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC;IACnD;AACD;AAED;;;;;;;;;;;;;;;;;;;;;AAqBG;AACG,MAAO,mBAAoB,SAAQ,eAAe,CAAA;AACtD;;;;;AAKG;IACH,WAAA,CAAY,OAAe,EAAE,KAAe,EAAA;QAC1C,KAAK,C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